diff --git a/DEPS b/DEPS index a89a24f..14045c71 100644 --- a/DEPS +++ b/DEPS
@@ -305,19 +305,19 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling V8 # and whatever else without interference from each other. - 'src_internal_revision': '226326934fb1466c7a57898dbd24c922e173702c', + 'src_internal_revision': 'a745a52bdcff739fdbd370e7fb7da57c8111786e', # 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': '343b249b2cacaa694a07ca7430b1881274417da0', + 'skia_revision': 'a874e29d71c0f6491c733d878204270333e44038', # 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': '324cc1f85e9fb53da25afa270d6353a2167c9c96', + 'v8_revision': 'f2a4a2beba1d4056f6d1e66a16c15d70470c1051', # 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': '98d79260fa0ebfcd5a4d959c9c21bf44071a00e6', + 'angle_revision': 'c8a544dddbae3d1f495e05a36d5c2f4427b4994b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -325,7 +325,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling PDFium # and whatever else without interference from each other. - 'pdfium_revision': 'aae740cc19b3f5244751c768fa5e2550c6a716a2', + 'pdfium_revision': 'a5bb284fd0387fe11def18f1048516fa60313c77', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling BoringSSL # and whatever else without interference from each other. @@ -400,7 +400,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': '45123813f5cb7335dc4a7e5151931dbe451b742c', + 'devtools_frontend_revision': 'e6bdd501b906e79f863decb8ca89598d4b1f317c', # 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. @@ -424,7 +424,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': 'bfb695dd9b62203f1b8fdaf7998e5681c38bd3b9', + 'dawn_revision': 'ff937f71a801fe382ac1c902f830b56719f4e1da', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -468,7 +468,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. - 'cros_components_revision': 'd04234ed17e4e8d2d95dc360b3bc3b0e6b0e3d6d', + 'cros_components_revision': '99998f1608c8b13dab09cdc0585a0f8007211080', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling feed # and whatever else without interference from each other. @@ -824,7 +824,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - '545e490705f01ebb699f788c8eadb47a77a4fa6c', + '68949fa36ab0fb6ad6d4f07bfed5139ecc426c3b', 'condition': 'checkout_android and checkout_src_internal', }, @@ -986,7 +986,7 @@ 'packages': [ { 'package': 'chromium/third_party/androidx', - 'version': 'SVekkV-WsTydJ9quroV_dvN5Q7X7UZ_C4eJ8VstiLzoC', + 'version': 'iIOjnHoOGIGndTMSfxlARsOPYyR9OOsTud-7duKGuFkC', }, ], 'condition': 'checkout_android', @@ -1204,7 +1204,7 @@ # For Linux and Chromium OS. 'src/third_party/cros_system_api': { - 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '1d9711b3bc06c08d92842b3df6f407f7edc029c5', + 'url': Var('chromium_git') + '/chromiumos/platform2/system_api.git' + '@' + '209d5157d57fabac8ab61af5be7c5a4770c80436', 'condition': 'checkout_linux', }, @@ -1224,7 +1224,7 @@ Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + '1c042a68ac0552324f7105843936b0f0218099f2', + 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + '4b78cf0e89fdbdb7f917beab13a7ad62af3f05ef', 'condition': 'checkout_src_internal', }, @@ -1689,7 +1689,7 @@ Var('pdfium_git') + '/pdfium.git' + '@' + Var('pdfium_revision'), 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + '0447454ec8cefdbaa41ec2c67ca7013a83188ac0', + Var('android_git') + '/platform/external/perfetto.git' + '@' + '510b65fa04d733f3bfa9e4c6ea7ff98e0c449637', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1874,7 +1874,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '300768e70537a52889f9e283465b1fbf8679ebfb', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '0967247662f6de824432992a7cc5e154e0fd6c29', + Var('webrtc_git') + '/src.git' + '@' + 'f0907c6f5bcdacf2e180acf4f15c4700f72d6982', # Wuffs' canonical repository is at github.com/google/wuffs, but we use # Skia's mirror of Wuffs, the same as in upstream Skia's DEPS file. @@ -4031,7 +4031,7 @@ 'src/ios_internal': { 'url': Var('chrome_git') + '/chrome/ios_internal.git' + '@' + - 'eb61322a92140850bf94cb6e7a2511743c80ade5', + '12205cac93d6adfbfad832d5c9401fbd1c19fa35', 'condition': 'checkout_ios and checkout_src_internal', },
diff --git a/android_webview/java/src/org/chromium/android_webview/AwMediaIntegrityApiStatusConfig.java b/android_webview/java/src/org/chromium/android_webview/AwMediaIntegrityApiStatusConfig.java index 651d940..afcc60e2 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwMediaIntegrityApiStatusConfig.java +++ b/android_webview/java/src/org/chromium/android_webview/AwMediaIntegrityApiStatusConfig.java
@@ -4,19 +4,26 @@ package org.chromium.android_webview; +import android.net.Uri; + import androidx.annotation.IntDef; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; import java.util.Map; import org.chromium.android_webview.common.Lifetime; /** * Stores configuration for the WebView Media Integrity API. Configuration is used to set permission - * levels for origin sites through defaults and override rules. + * levels for origin sites through defaults and override rules. Origin site URIs are matched against + * these override rules with an {@link AwContentsOriginMatcher}. */ @Lifetime.WebView public class AwMediaIntegrityApiStatusConfig { @@ -33,18 +40,38 @@ int ENABLED = 2; } + // A URI may match multiple origin patterns but we must return the least permissive + // option. Hence we look for matches in the following order. + private static final int[] sStatusByPriority = { + ApiStatus.DISABLED, ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, ApiStatus.ENABLED + }; + private final AwContentsOriginMatcher mRuleValidationMatcher = new AwContentsOriginMatcher(); + private final Map<@ApiStatus Integer, AwContentsOriginMatcher> mPermissionToMatcher; + private @ApiStatus int mDefaultStatus; private Map<String, @ApiStatus Integer> mOverrideRulesToPermission; public AwMediaIntegrityApiStatusConfig() { mDefaultStatus = ApiStatus.ENABLED; mOverrideRulesToPermission = Collections.emptyMap(); + Map<@ApiStatus Integer, AwContentsOriginMatcher> matcherMap = new HashMap<>(); + for (@ApiStatus int status : sStatusByPriority) { + matcherMap.put(status, new AwContentsOriginMatcher()); + } + mPermissionToMatcher = Collections.unmodifiableMap(matcherMap); } - public void setApiStatus( - @ApiStatus int defaultStatus, Map<String, @ApiStatus Integer> permissionConfig) { - mOverrideRulesToPermission = permissionConfig; + public void setApiAvailabilityRules( + @ApiStatus int defaultStatus, Map<String, @ApiStatus Integer> permissionConfig) { mDefaultStatus = defaultStatus; + String[] badRules = + mRuleValidationMatcher.updateRuleList(new ArrayList<>(permissionConfig.keySet())); + if (badRules.length > 0) { + throw new IllegalArgumentException( + "Badly formed rules: " + Arrays.toString(badRules)); + } + mOverrideRulesToPermission = permissionConfig; + populateMatchersForLookup(permissionConfig); } @ApiStatus @@ -55,4 +82,28 @@ public Map<String, @ApiStatus Integer> getOverrideRules() { return mOverrideRulesToPermission; } + + @ApiStatus + public int getStatusForUri(Uri uri) { + for (@ApiStatus int status : sStatusByPriority) { + if (mPermissionToMatcher.get(status).matchesOrigin(uri)) { + return status; + } + } + // Uri does not match any override rules + return mDefaultStatus; + } + + private void populateMatchersForLookup(Map<String, @ApiStatus Integer> permissionConfig) { + Map<Integer, List<String>> newPatterns = new HashMap<>(); + for (int status : sStatusByPriority) { + newPatterns.put(status, new ArrayList()); + } + for (Map.Entry<String, @ApiStatus Integer> entry : permissionConfig.entrySet()) { + newPatterns.get(entry.getValue()).add(entry.getKey()); + } + for (int status : sStatusByPriority) { + mPermissionToMatcher.get(status).updateRuleList(newPatterns.get(status)); + } + } }
diff --git a/android_webview/java/src/org/chromium/android_webview/AwSettings.java b/android_webview/java/src/org/chromium/android_webview/AwSettings.java index 070c4fe..5b0a4655 100644 --- a/android_webview/java/src/org/chromium/android_webview/AwSettings.java +++ b/android_webview/java/src/org/chromium/android_webview/AwSettings.java
@@ -2086,7 +2086,7 @@ public void setWebViewIntegrityApiStatus( @ApiStatus int defaultStatus, Map<String, @ApiStatus Integer> permissionConfig) { synchronized (mAwSettingsLock) { - mIntegrityApiStatusConfig.setApiStatus(defaultStatus, permissionConfig); + mIntegrityApiStatusConfig.setApiAvailabilityRules(defaultStatus, permissionConfig); } }
diff --git a/android_webview/javatests/src/org/chromium/android_webview/test/AwMediaIntegrityApiStatusConfigTest.java b/android_webview/javatests/src/org/chromium/android_webview/test/AwMediaIntegrityApiStatusConfigTest.java index 224ac3ce..bca0aee 100644 --- a/android_webview/javatests/src/org/chromium/android_webview/test/AwMediaIntegrityApiStatusConfigTest.java +++ b/android_webview/javatests/src/org/chromium/android_webview/test/AwMediaIntegrityApiStatusConfigTest.java
@@ -4,9 +4,13 @@ package org.chromium.android_webview.test; +import android.net.Uri; + +import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; import org.junit.Assert; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -18,6 +22,8 @@ /** {@link org.chromium.android_webview.AwMediaIntegrityApiStatusConfig} tests. */ @RunWith(AwJUnit4ClassRunner.class) public class AwMediaIntegrityApiStatusConfigTest { + @Rule public AwActivityTestRule mActivityTestRule = new AwActivityTestRule(); + @Test @SmallTest public void testGetApiStatus_returnsEmptyConfig_whenNotSet() throws Throwable { @@ -32,11 +38,148 @@ public void testGetApiStatus_returnsConfig_whenSetWithRules() throws Throwable { AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); Map<String, @ApiStatus Integer> overrideRules = - Map.of("http://*.webview.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY); + Map.of("http://*.example.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY); @ApiStatus int defaultPermission = ApiStatus.DISABLED; - config.setApiStatus(defaultPermission, overrideRules); + config.setApiAvailabilityRules(defaultPermission, overrideRules); Assert.assertEquals(defaultPermission, config.getDefaultStatus()); Assert.assertEquals(overrideRules, config.getOverrideRules()); } + + @Test + @SmallTest + public void testGetStatusForUri_returnsStatus_whenMatches() throws Throwable { + AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); + Map<String, @ApiStatus Integer> overrideRules = + Map.of( + "http://*.example.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + "http://somesite.com", ApiStatus.ENABLED); + @ApiStatus int defaultPermission = ApiStatus.DISABLED; + config.setApiAvailabilityRules(defaultPermission, overrideRules); + + Assert.assertEquals(defaultPermission, config.getDefaultStatus()); + Assert.assertEquals(overrideRules, config.getOverrideRules()); + Assert.assertEquals( + ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + config.getStatusForUri(Uri.parse("http://sub.example.com"))); + } + + @Test + @SmallTest + public void testGetStatusForUri_returnsDefaultStatus_whenNoMatches() throws Throwable { + AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); + Map<String, @ApiStatus Integer> overrideRules = + Map.of( + "http://*.example.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + "http://somesite.com", ApiStatus.ENABLED); + @ApiStatus int defaultPermission = ApiStatus.DISABLED; + config.setApiAvailabilityRules(defaultPermission, overrideRules); + + Assert.assertEquals(defaultPermission, config.getDefaultStatus()); + Assert.assertEquals(overrideRules, config.getOverrideRules()); + Assert.assertEquals( + defaultPermission, config.getStatusForUri(Uri.parse("http://randomsite.com"))); + } + + @Test + @MediumTest + public void testSetConfigTwice_returnsUpdatedStatus_whenUriMatches() throws Throwable { + AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); + Map<String, @ApiStatus Integer> overrideRules = + Map.of( + "http://*.example.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + "http://somesite.com", ApiStatus.ENABLED); + @ApiStatus int defaultPermission = ApiStatus.DISABLED; + config.setApiAvailabilityRules(defaultPermission, overrideRules); + + Assert.assertEquals(defaultPermission, config.getDefaultStatus()); + Assert.assertEquals(overrideRules, config.getOverrideRules()); + Assert.assertEquals( + ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + config.getStatusForUri(Uri.parse("http://sub.example.com"))); + + Map<String, @ApiStatus Integer> overrideRules2 = + Map.of("http://*.somedomain.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY); + @ApiStatus int defaultPermission2 = ApiStatus.ENABLED; + config.setApiAvailabilityRules(defaultPermission2, overrideRules2); + + Assert.assertEquals(defaultPermission2, config.getDefaultStatus()); + Assert.assertEquals(overrideRules2, config.getOverrideRules()); + Assert.assertEquals( + defaultPermission2, config.getStatusForUri(Uri.parse("http://sub.example.com"))); + Assert.assertEquals( + ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + config.getStatusForUri(Uri.parse("http://sub.somedomain.com"))); + } + + @Test + @SmallTest + public void testSetApiConfig_throwsError_whenGivenInvalidRule() throws Throwable { + AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); + Map<String, @ApiStatus Integer> overrideRules = + Map.of( + "xyz://*.abc.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY); + @ApiStatus int defaultPermission = ApiStatus.DISABLED; + Assert.assertThrows(IllegalArgumentException.class, + () -> config.setApiAvailabilityRules(defaultPermission, overrideRules)); + Assert.assertTrue(config.getOverrideRules().isEmpty()); + + } + + @Test + @SmallTest + public void testSetApiConfig_doesNotOverwritePreviousRules_whenGivenNewInvalidRules() + throws Throwable { + AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); + Map<String, @ApiStatus Integer> overrideRules = + Map.of( + "http://*.example.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY); + @ApiStatus int defaultPermission = ApiStatus.DISABLED; + config.setApiAvailabilityRules(defaultPermission, overrideRules); + Assert.assertEquals(defaultPermission, config.getDefaultStatus()); + Assert.assertEquals(overrideRules, config.getOverrideRules()); + + Map<String, @ApiStatus Integer> overrideRules2 = + Map.of( + // one good rule + "http://*.sub.example.com", ApiStatus.ENABLED, + // one bad rule + "xyz://*.abc.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY); + Assert.assertThrows(IllegalArgumentException.class, + () -> config.setApiAvailabilityRules(defaultPermission, overrideRules2)); + Assert.assertEquals(defaultPermission, config.getDefaultStatus()); + // Previously set rules have not been overwritten + Assert.assertEquals(overrideRules, config.getOverrideRules()); + // Does not even set the good rule from overrideRules2 + Assert.assertFalse(config.getOverrideRules().containsKey("http://*.sub.example.com")); + } + + @Test + @SmallTest + public void testGetStatusForUri_returnsLessPermissiveStatus_whenMultipleMatches() throws Throwable { + AwMediaIntegrityApiStatusConfig config = new AwMediaIntegrityApiStatusConfig(); + Map<String, @ApiStatus Integer> overrideRules = + Map.of( + "http://*.example.com", ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + "http://*.sub.example.com", ApiStatus.ENABLED, + "http://*.other.example.com", ApiStatus.DISABLED, + "http://*.xyz.sub.example.com", ApiStatus.DISABLED); + @ApiStatus int defaultPermission = ApiStatus.ENABLED; + config.setApiAvailabilityRules(defaultPermission, overrideRules); + + Assert.assertEquals(defaultPermission, config.getDefaultStatus()); + Assert.assertEquals(overrideRules, config.getOverrideRules()); + // Choose between ENABLED and ENABLED_WITHOUT_APP_IDENTITY + Assert.assertEquals( + ApiStatus.ENABLED_WITHOUT_APP_IDENTITY, + config.getStatusForUri(Uri.parse("http://random.sub.example.com"))); + // Choose between ENABLED_WITHOUT_APP_IDENTITY and DISABLED + Assert.assertEquals( + ApiStatus.DISABLED, + config.getStatusForUri(Uri.parse("http://random.other.example.com"))); + // Choose between ENABLED, ENABLED_WITHOUT_APP_IDENTITY and DISABLED + Assert.assertEquals( + ApiStatus.DISABLED, + config.getStatusForUri(Uri.parse("http://random.xyz.sub.example.com"))); + } }
diff --git a/ash/accelerators/accelerator_commands.cc b/ash/accelerators/accelerator_commands.cc index f7a8c81..6675ad25 100644 --- a/ash/accelerators/accelerator_commands.cc +++ b/ash/accelerators/accelerator_commands.cc
@@ -66,6 +66,7 @@ #include "ash/wm/screen_pinning_controller.h" #include "ash/wm/snap_group/snap_group.h" #include "ash/wm/snap_group/snap_group_controller.h" +#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/tablet_mode/tablet_mode_multitask_menu_controller.h" #include "ash/wm/tablet_mode/tablet_mode_window_manager.h" #include "ash/wm/window_cycle/window_cycle_controller.h" @@ -185,7 +186,7 @@ int64_t display_id, display::Display::Rotation current) { Shell* shell = Shell::Get(); - DCHECK(shell->tablet_mode_controller()->InTabletMode()); + DCHECK(display::Screen::GetScreen()->InTabletMode()); if (!display::HasInternalDisplay() || display_id != display::Display::InternalDisplayId()) { @@ -262,15 +263,14 @@ void RotateScreenImpl() { auto* shell = Shell::Get(); - const bool in_tablet_mode = - Shell::Get()->tablet_mode_controller()->InTabletMode(); const int64_t display_id = GetDisplayIdForRotation(); const display::ManagedDisplayInfo& display_info = shell->display_manager()->GetDisplayInfo(display_id); const auto active_rotation = display_info.GetActiveRotation(); const auto next_rotation = - in_tablet_mode ? GetNextRotationInTabletMode(display_id, active_rotation) - : GetNextRotationInClamshell(active_rotation); + display::Screen::GetScreen()->InTabletMode() + ? GetNextRotationInTabletMode(display_id, active_rotation) + : GetNextRotationInClamshell(active_rotation); if (active_rotation == next_rotation) return; @@ -601,7 +601,7 @@ if (!window) { return false; } - if (Shell::Get()->tablet_mode_controller()->InTabletMode()) { + if (display::Screen::GetScreen()->InTabletMode()) { // In tablet mode, the window just has to be able to maximize. return WindowState::Get(window)->CanMaximize(); } @@ -1583,10 +1583,11 @@ void ToggleMultitaskMenu() { aura::Window* window = GetTargetWindow(); DCHECK(window); - if (auto* tablet_mode_controller = Shell::Get()->tablet_mode_controller(); - tablet_mode_controller->InTabletMode()) { + if (display::Screen::GetScreen()->InTabletMode()) { auto* multitask_menu_controller = - tablet_mode_controller->tablet_mode_window_manager() + Shell::Get() + ->tablet_mode_controller() + ->tablet_mode_window_manager() ->tablet_mode_multitask_menu_controller(); // Does nothing if the menu is already shown. multitask_menu_controller->ShowMultitaskMenu(window); @@ -1721,7 +1722,7 @@ void WindowSnap(AcceleratorAction action) { Shell* shell = Shell::Get(); - const bool in_tablet = shell->tablet_mode_controller()->InTabletMode(); + const bool in_tablet = display::Screen::GetScreen()->InTabletMode(); const bool in_overview = shell->overview_controller()->InOverviewSession(); if (action == AcceleratorAction::kWindowCycleSnapLeft) { if (in_tablet) {
diff --git a/ash/accelerators/accelerator_controller_impl.cc b/ash/accelerators/accelerator_controller_impl.cc index f54a5ae..5b354c07 100644 --- a/ash/accelerators/accelerator_controller_impl.cc +++ b/ash/accelerators/accelerator_controller_impl.cc
@@ -27,7 +27,6 @@ #include "ash/system/power/power_button_controller.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/screen_pinning_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_state.h" #include "base/check.h" #include "base/containers/contains.h" @@ -43,6 +42,7 @@ #include "ui/base/accelerators/accelerator.h" #include "ui/base/accelerators/accelerator_manager.h" #include "ui/base/ui_base_features.h" +#include "ui/display/screen.h" #include "ui/events/ash/keyboard_layout_util.h" #include "ui/events/event_constants.h" #include "ui/ozone/public/ozone_platform.h" @@ -913,7 +913,7 @@ if ((action == AcceleratorAction::kVolumeDown || action == AcceleratorAction::kVolumeUp) && - Shell::Get()->tablet_mode_controller()->InTabletMode()) { + display::Screen::GetScreen()->InTabletMode()) { if (tablet_volume_controller_.ShouldSwapSideVolumeButtons( accelerator.source_device_id())) action = action == AcceleratorAction::kVolumeDown
diff --git a/ash/accelerators/accelerator_controller_unittest.cc b/ash/accelerators/accelerator_controller_unittest.cc index 455694d..223bf49 100644 --- a/ash/accelerators/accelerator_controller_unittest.cc +++ b/ash/accelerators/accelerator_controller_unittest.cc
@@ -1154,7 +1154,7 @@ // those that requested window rotation locks. TabletModeControllerTestApi().AttachExternalMouse(); EXPECT_TRUE(tablet_mode_controller->is_in_tablet_physical_state()); - EXPECT_FALSE(tablet_mode_controller->InTabletMode()); + EXPECT_FALSE(display::Screen::GetScreen()->InTabletMode()); wm::ActivateWindow(win0.get()); EXPECT_TRUE(screen_orientation_controller->rotation_locked());
diff --git a/ash/accelerators/debug_commands.cc b/ash/accelerators/debug_commands.cc index cb465c7..196624d 100644 --- a/ash/accelerators/debug_commands.cc +++ b/ash/accelerators/debug_commands.cc
@@ -50,6 +50,7 @@ #include "ui/accessibility/ax_tree_id.h" #include "ui/aura/client/aura_constants.h" #include "ui/display/manager/display_manager.h" +#include "ui/display/screen.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/image_skia.h" @@ -213,8 +214,8 @@ } void HandleToggleTabletMode() { - TabletModeController* controller = Shell::Get()->tablet_mode_controller(); - controller->SetEnabledForDev(!controller->InTabletMode()); + Shell::Get()->tablet_mode_controller()->SetEnabledForDev( + !display::Screen::GetScreen()->InTabletMode()); } void HandleToggleVideoConferenceCameraTrayIcon() {
diff --git a/ash/accessibility/accessibility_controller_impl.cc b/ash/accessibility/accessibility_controller_impl.cc index b5b5fa32b..ae7a060 100644 --- a/ash/accessibility/accessibility_controller_impl.cc +++ b/ash/accessibility/accessibility_controller_impl.cc
@@ -54,7 +54,6 @@ #include "ash/system/power/backlights_forced_off_setter.h" #include "ash/system/power/power_status.h" #include "ash/system/power/scoped_backlights_forced_off.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/memory/raw_ptr_exclusion.h" @@ -77,6 +76,8 @@ #include "ui/aura/window.h" #include "ui/base/cursor/cursor_size.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/display/screen.h" +#include "ui/display/tablet_state.h" #include "ui/message_center/message_center.h" #include "ui/message_center/public/cpp/notifier_id.h" #include "ui/strings/grit/ui_strings.h" @@ -464,7 +465,7 @@ text = l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_SWITCH_ACCESS_ENABLED); catalog_name = NotificationCatalogName::kSwitchAccessEnabled; } else { - bool is_tablet = Shell::Get()->tablet_mode_controller()->InTabletMode(); + bool is_tablet = display::Screen::GetScreen()->InTabletMode(); title = l10n_util::GetStringUTF16( type == A11yNotificationType::kSpokenFeedbackBrailleEnabled @@ -971,7 +972,7 @@ AccessibilityControllerImpl::AccessibilityControllerImpl() : autoclick_delay_(AutoclickController::GetDefaultAutoclickDelay()) { Shell::Get()->session_controller()->AddObserver(this); - Shell::Get()->tablet_mode_controller()->AddObserver(this); + display::Screen::GetScreen()->AddObserver(this); CreateAccessibilityFeatures(); accessibility_notification_controller_ = @@ -1279,7 +1280,7 @@ } void AccessibilityControllerImpl::Shutdown() { - Shell::Get()->tablet_mode_controller()->RemoveObserver(this); + display::Screen::GetScreen()->RemoveObserver(this); Shell::Get()->session_controller()->RemoveObserver(this); // Clean up any child windows and widgets that might be animating out. @@ -2085,18 +2086,17 @@ skip_switch_access_notification_ = true; } -void AccessibilityControllerImpl::OnTabletModeStarted() { - if (spoken_feedback().enabled()) - ShowAccessibilityNotification( - A11yNotificationWrapper(A11yNotificationType::kSpokenFeedbackEnabled, - std::vector<std::u16string>())); -} - -void AccessibilityControllerImpl::OnTabletModeEnded() { - if (spoken_feedback().enabled()) - ShowAccessibilityNotification( - A11yNotificationWrapper(A11yNotificationType::kSpokenFeedbackEnabled, - std::vector<std::u16string>())); +void AccessibilityControllerImpl::OnDisplayTabletStateChanged( + display::TabletState state) { + if (spoken_feedback().enabled()) { + // Show accessibility notification when tablet mode transition is completed. + if (state == display::TabletState::kInTabletMode || + state == display::TabletState::kInClamshellMode) { + ShowAccessibilityNotification( + A11yNotificationWrapper(A11yNotificationType::kSpokenFeedbackEnabled, + std::vector<std::u16string>())); + } + } } void AccessibilityControllerImpl::ObservePrefs(PrefService* prefs) {
diff --git a/ash/accessibility/accessibility_controller_impl.h b/ash/accessibility/accessibility_controller_impl.h index 5ba5c3ff..363eb55 100644 --- a/ash/accessibility/accessibility_controller_impl.h +++ b/ash/accessibility/accessibility_controller_impl.h
@@ -13,12 +13,12 @@ #include "ash/constants/ash_constants.h" #include "ash/public/cpp/accessibility_controller.h" #include "ash/public/cpp/session/session_observer.h" -#include "ash/public/cpp/tablet_mode_observer.h" #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/time/time.h" +#include "ui/display/display_observer.h" class PrefChangeRegistrar; class PrefRegistrySimple; @@ -34,6 +34,10 @@ } // namespace mojom } // namespace ax +namespace display { +enum class TabletState; +} // namespace display + namespace gfx { class Point; class PointF; @@ -90,7 +94,7 @@ // Uses preferences to communicate with chrome to support mash. class ASH_EXPORT AccessibilityControllerImpl : public AccessibilityController, public SessionObserver, - public TabletModeObserver { + public display::DisplayObserver { public: // Common interface for all features. class Feature { @@ -541,9 +545,8 @@ // Propagates the state of |feature| according to |feature->enabled()|. void OnFeatureChanged(A11yFeatureType feature); - // TabletModeObserver: - void OnTabletModeStarted() override; - void OnTabletModeEnded() override; + // display::DisplayObserver: + void OnDisplayTabletStateChanged(display::TabletState state) override; // Observes either the signin screen prefs or active user prefs and loads // initial settings.
diff --git a/ash/accessibility/chromevox/key_accessibility_enabler.cc b/ash/accessibility/chromevox/key_accessibility_enabler.cc index 6cebd56..f32714a 100644 --- a/ash/accessibility/chromevox/key_accessibility_enabler.cc +++ b/ash/accessibility/chromevox/key_accessibility_enabler.cc
@@ -7,7 +7,7 @@ #include "ash/accessibility/chromevox/spoken_feedback_enabler.h" #include "ash/shell.h" #include "ash/system/power/power_button_screenshot_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" +#include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #include "ui/events/event.h" @@ -25,15 +25,17 @@ void KeyAccessibilityEnabler::OnKeyEvent(ui::KeyEvent* event) { if ((event->type() != ui::ET_KEY_PRESSED && event->type() != ui::ET_KEY_RELEASED) || - !Shell::Get()->tablet_mode_controller()->InTabletMode()) + !display::Screen::GetScreen()->InTabletMode()) { return; + } - if (event->key_code() == ui::VKEY_VOLUME_DOWN) + if (event->key_code() == ui::VKEY_VOLUME_DOWN) { vol_down_pressed_ = event->type() == ui::ET_KEY_PRESSED; - else if (event->key_code() == ui::VKEY_VOLUME_UP) + } else if (event->key_code() == ui::VKEY_VOLUME_UP) { vol_up_pressed_ = event->type() == ui::ET_KEY_PRESSED; - else + } else { other_key_pressed_ = event->type() == ui::ET_KEY_PRESSED; + } if (vol_down_pressed_ && vol_up_pressed_ && !other_key_pressed_) { if (!spoken_feedback_enabler_.get()) { @@ -42,8 +44,9 @@ } if (ui::EventTimeForNow() - first_time_both_volume_keys_pressed_ > - PowerButtonScreenshotController::kScreenshotChordDelay) + PowerButtonScreenshotController::kScreenshotChordDelay) { event->StopPropagation(); + } } else if (spoken_feedback_enabler_.get()) { spoken_feedback_enabler_.reset(); }
diff --git a/ash/accessibility/chromevox/touch_exploration_controller.cc b/ash/accessibility/chromevox/touch_exploration_controller.cc index 2c9b0fe7..7721c24 100644 --- a/ash/accessibility/chromevox/touch_exploration_controller.cc +++ b/ash/accessibility/chromevox/touch_exploration_controller.cc
@@ -13,7 +13,6 @@ #include "ash/public/cpp/shell_window_ids.h" #include "ash/shell.h" #include "ash/wm/container_finder.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/functional/bind.h" #include "base/logging.h" #include "base/ranges/algorithm.h" @@ -24,6 +23,7 @@ #include "ui/aura/window_event_dispatcher.h" #include "ui/aura/window_targeter.h" #include "ui/aura/window_tree_host.h" +#include "ui/display/screen.h" #include "ui/events/event.h" #include "ui/events/event_processor.h" #include "ui/events/event_utils.h" @@ -1230,7 +1230,7 @@ int edge = FindEdgesWithinInset(event.location(), kMaxDistanceFromEdge); return edge & RIGHT_EDGE && edge != BOTTOM_RIGHT_CORNER && (!Shell::HasInstance() || - Shell::Get()->tablet_mode_controller()->InTabletMode() || + display::Screen::GetScreen()->InTabletMode() || Shell::Get() ->accessibility_controller() ->enable_chromevox_volume_slide_gesture());
diff --git a/ash/accessibility/magnifier/docked_magnifier_controller_unittest.cc b/ash/accessibility/magnifier/docked_magnifier_controller_unittest.cc index c5f85e6..db9af38 100644 --- a/ash/accessibility/magnifier/docked_magnifier_controller_unittest.cc +++ b/ash/accessibility/magnifier/docked_magnifier_controller_unittest.cc
@@ -553,7 +553,7 @@ TEST_F(DockedMagnifierTest, DisplaysWorkAreasSingleSplitView) { // Verify that we're in tablet mode. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); - EXPECT_TRUE(Shell::Get()->tablet_mode_controller()->InTabletMode()); + EXPECT_TRUE(display::Screen::GetScreen()->InTabletMode()); std::unique_ptr<aura::Window> window = TestWindowBuilder() @@ -602,7 +602,7 @@ TEST_F(DockedMagnifierTest, DisplaysWorkAreasDoubleSplitView) { // Verify that we're in tablet mode. Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); - EXPECT_TRUE(Shell::Get()->tablet_mode_controller()->InTabletMode()); + EXPECT_TRUE(display::Screen::GetScreen()->InTabletMode()); std::unique_ptr<aura::Window> window1 = TestWindowBuilder()
diff --git a/ash/ambient/metrics/ambient_animation_metrics_recorder_unittest.cc b/ash/ambient/metrics/ambient_animation_metrics_recorder_unittest.cc index 6de9534..6398c278 100644 --- a/ash/ambient/metrics/ambient_animation_metrics_recorder_unittest.cc +++ b/ash/ambient/metrics/ambient_animation_metrics_recorder_unittest.cc
@@ -13,7 +13,6 @@ #include "ash/shell.h" #include "ash/test/ash_test_base.h" #include "ash/webui/personalization_app/mojom/personalization_app.mojom-shared.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/strings/strcat.h" #include "base/strings/string_piece.h" #include "base/test/metrics/histogram_tester.h"
diff --git a/ash/app_list/app_list_controller_impl.cc b/ash/app_list/app_list_controller_impl.cc index a5436aa..2a0dd71 100644 --- a/ash/app_list/app_list_controller_impl.cc +++ b/ash/app_list/app_list_controller_impl.cc
@@ -57,7 +57,6 @@ #include "ash/wm/overview/overview_controller.h" #include "ash/wm/overview/overview_session.h" #include "ash/wm/splitview/split_view_controller.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "base/barrier_closure.h" @@ -77,6 +76,7 @@ #include "ui/compositor/compositor.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animation_sequence.h" +#include "ui/display/display_observer.h" #include "ui/display/manager/display_manager.h" #include "ui/display/screen.h" #include "ui/display/util/display_util.h" @@ -189,10 +189,6 @@ return !windows_to_minimize.empty(); } -bool IsTabletMode() { - return Shell::Get()->tablet_mode_controller()->InTabletMode(); -} - TabletModeAnimationTransition CalculateAnimationTransitionForMetrics( HomeLauncherAnimationTrigger trigger, bool launcher_should_show) { @@ -282,10 +278,10 @@ OnSessionStateChanged(session_controller->GetSessionState()); Shell* shell = Shell::Get(); - shell->tablet_mode_controller()->AddObserver(this); shell->wallpaper_controller()->AddObserver(this); shell->AddShellObserver(this); shell->overview_controller()->AddObserver(this); + display::Screen::GetScreen()->AddObserver(this); keyboard::KeyboardUIController::Get()->AddObserver(this); AssistantState::Get()->AddObserver(this); shell->window_tree_host_manager()->AddObserver(this); @@ -401,8 +397,9 @@ } aura::Window* AppListControllerImpl::GetWindow() { - if (IsTabletMode()) + if (IsInTabletMode()) { return fullscreen_presenter_->GetWindow(); + } return bubble_presenter_->GetWindow(); } @@ -427,7 +424,7 @@ if (IsKioskSession()) return; - if (!IsTabletMode()) { + if (!IsInTabletMode()) { DismissAppList(); return; } @@ -446,7 +443,7 @@ if (state == session_manager::SessionState::ACTIVE) has_session_started_ = true; - const bool in_clamshell = !IsTabletMode(); + const bool in_clamshell = !IsInTabletMode(); if (state != session_manager::SessionState::ACTIVE || IsKioskSession()) { if (in_clamshell) DismissAppList(); @@ -479,7 +476,7 @@ return; ash::ReportPrefSortOrderOnSessionStart(client_->GetPermanentSortingOrder(), - IsTabletMode()); + IsInTabletMode()); auto* prefs = Shell::Get()->session_controller()->GetUserPrefServiceForUser(account_id); @@ -508,13 +505,13 @@ last_open_source_ = show_source; if (should_record_metrics) - LogAppListShowSource(show_source, !IsTabletMode()); + LogAppListShowSource(show_source, !IsInTabletMode()); // Checking `should_record_metrics` is redundant here, since this helper // function never logs metrics when the app list was shown by tablet mode. MaybeLogWelcomeTourInteraction(show_source); - if (IsTabletMode()) { + if (IsInTabletMode()) { fullscreen_presenter_->Show(AppListViewState::kFullscreenAllApps, display_id, event_time_stamp, show_source); return; @@ -546,7 +543,7 @@ // Adapt the bubble app list to the new sorting order. NOTE: the bubble app // list is visible only in clamshell mode. Therefore do not animate in tablet // mode. - const bool is_tablet_mode = IsTabletMode(); + const bool is_tablet_mode = IsInTabletMode(); bubble_presenter_->UpdateForNewSortingOrder( new_order, !is_tablet_mode && animate, is_tablet_mode ? base::NullCallback() @@ -573,7 +570,7 @@ if (IsKioskSession()) return SHELF_ACTION_APP_LIST_DISMISSED; - if (IsTabletMode()) { + if (IsInTabletMode()) { bool handled = GoHome(display_id); // Perform the "back" action for the app list. @@ -603,7 +600,7 @@ if (IsKioskSession()) return false; - DCHECK(Shell::Get()->tablet_mode_controller()->InTabletMode()); + DCHECK(IsInTabletMode()); if (fullscreen_presenter_->IsShowingEmbeddedAssistantUI()) fullscreen_presenter_->ShowEmbeddedAssistantUI(false); @@ -705,12 +702,14 @@ } bool AppListControllerImpl::ShouldHomeLauncherBeVisible() const { - if (!IsTabletMode() || IsKioskSession()) + if (!IsInTabletMode() || IsKioskSession()) { return false; + } if (home_launcher_transition_state_ == - HomeLauncherTransitionState::kMostlyShown) + HomeLauncherTransitionState::kMostlyShown) { return true; + } return !Shell::Get()->overview_controller()->InOverviewSession() && !GetTopVisibleWindow(); @@ -719,8 +718,9 @@ void AppListControllerImpl::OnShelfAlignmentChanged( aura::Window* root_window, ShelfAlignment old_alignment) { - if (!IsTabletMode()) + if (!IsInTabletMode()) { DismissAppList(); + } } void AppListControllerImpl::OnShellDestroying() { @@ -742,7 +742,7 @@ UpdateForOverviewModeChange(/*show_home_launcher=*/false, animate); - if (IsTabletMode()) { + if (IsInTabletMode()) { const int64_t display_id = last_visible_display_id_; OnVisibilityWillChange(false /*shown*/, display_id); } else { @@ -752,8 +752,9 @@ void AppListControllerImpl::OnOverviewModeStartingAnimationComplete( bool canceled) { - if (!IsTabletMode()) + if (!IsInTabletMode()) { return; + } // If overview start was canceled, overview end animations are about to start. // Preemptively update the target app list visibility. @@ -784,8 +785,9 @@ UpdateHomeScreenVisibility(); } - if (!IsTabletMode()) + if (!IsInTabletMode()) { return; + } // Overview state might end during home launcher transition - if that is the // case, respect the final state set by in-progress home launcher transition. @@ -797,8 +799,10 @@ } void AppListControllerImpl::OnOverviewModeEnded() { - if (!IsTabletMode()) + if (!IsInTabletMode()) { return; + } + // Overview state might end during home launcher transition - if that is the // case, respect the final state set by in-progress home launcher transition. if (home_launcher_transition_state_ != HomeLauncherTransitionState::kFinished) @@ -834,9 +838,10 @@ UpdateHomeScreenVisibility(); } -void AppListControllerImpl::OnTabletModeStarted() { - if (IsKioskSession()) +void AppListControllerImpl::OnChangedToInTabletMode() { + if (IsKioskSession()) { return; + } // Reset the keyboard traversal mode to prevent using the value saved in // clamshell mode. @@ -863,11 +868,12 @@ // window will be shown over the app list view. // Ensure the app list visibility is properly updated if the app list is // hidden behind a window at this point. - if (last_target_visible_ && !ShouldHomeLauncherBeVisible()) + if (last_target_visible_ && !ShouldHomeLauncherBeVisible()) { OnVisibilityChanged(false, last_visible_display_id_); + } } -void AppListControllerImpl::OnTabletModeEnded() { +void AppListControllerImpl::OnChangedToInClamshellMode() { // Reset the keyboard traversal mode to prevent using the value saved last // time in tablet mode. SetKeyboardTraversalMode(false); @@ -884,6 +890,22 @@ DismissAppList(); } +void AppListControllerImpl::OnDisplayTabletStateChanged( + display::TabletState state) { + switch (state) { + case display::TabletState::kEnteringTabletMode: + case display::TabletState::kExitingTabletMode: + // Do nothing when the tablet state is still in the process of transition. + break; + case display::TabletState::kInTabletMode: + OnChangedToInTabletMode(); + break; + case display::TabletState::kInClamshellMode: + OnChangedToInClamshellMode(); + break; + } +} + void AppListControllerImpl::OnWallpaperPreviewStarted() { in_wallpaper_preview_ = true; UpdateHomeScreenVisibility(); @@ -927,8 +949,9 @@ // expected if it's enabled and we're still in tablet mode. // https://crbug.com/900956. const bool should_be_shown = - IsTabletMode() && Shell::Get()->session_controller()->GetSessionState() == - session_manager::SessionState::ACTIVE; + IsInTabletMode() && + Shell::Get()->session_controller()->GetSessionState() == + session_manager::SessionState::ACTIVE; if (!should_be_shown || should_be_shown == fullscreen_presenter_->GetTargetVisibility()) { @@ -970,7 +993,7 @@ AppListShowSource::kAssistantEntryPoint, base::TimeTicks(), /*should_record_metrics=*/true); } - if (!IsTabletMode()) { + if (!IsInTabletMode()) { bubble_presenter_->ShowEmbeddedAssistantUI(); } else { if (!fullscreen_presenter_->IsShowingEmbeddedAssistantUI() || @@ -991,7 +1014,7 @@ // When Launcher is closing, we do not want to call // |ShowEmbeddedAssistantUI(false)|, which will show previous state page // in Launcher and make the UI flash. - if (IsTabletMode()) { + if (IsInTabletMode()) { absl::optional<ContentsView::ScopedSetActiveStateAnimationDisabler> set_active_state_animation_disabler; // When taking a screenshot by Assistant, we do not want to animate to @@ -1137,7 +1160,7 @@ RecordAppListAppLaunched( AppListLaunchedFrom::kLaunchedFromShelf, recorded_app_list_view_state_.value_or(GetAppListViewState()), - IsTabletMode(), recorded_app_list_visibility_.value_or(last_visible_)); + IsInTabletMode(), recorded_app_list_visibility_.value_or(last_visible_)); recorded_app_list_view_state_ = absl::nullopt; recorded_app_list_visibility_ = absl::nullopt; } @@ -1199,7 +1222,7 @@ } } - const bool is_tablet_mode = IsTabletMode(); + const bool is_tablet_mode = IsInTabletMode(); switch (launched_from) { case AppListLaunchedFrom::kLaunchedFromSearchBox: switch (launch_type) { @@ -1276,7 +1299,7 @@ AppListLaunchedFrom launched_from) { RecordAppLaunched(launched_from); - const bool is_tablet_mode = IsTabletMode(); + const bool is_tablet_mode = IsInTabletMode(); switch (launched_from) { case AppListLaunchedFrom::kLaunchedFromGrid: RecordLauncherWorkflowMetrics(AppListUserAction::kAppLaunchFromAppsGrid, @@ -1455,7 +1478,7 @@ void AppListControllerImpl::GetAppLaunchedMetricParams( AppLaunchedMetricParams* metric_params) { metric_params->app_list_view_state = GetAppListViewState(); - metric_params->is_tablet_mode = IsTabletMode(); + metric_params->is_tablet_mode = IsInTabletMode(); metric_params->app_list_shown = last_visible_; metric_params->launcher_show_timestamp = last_show_timestamp_; } @@ -1504,14 +1527,14 @@ return ShelfConfig::Get()->GetTabletModeShelfInsetsAndRecordUMA(); } -bool AppListControllerImpl::IsInTabletMode() { - return Shell::Get()->tablet_mode_controller()->InTabletMode(); +bool AppListControllerImpl::IsInTabletMode() const { + return display::Screen::GetScreen()->InTabletMode(); } void AppListControllerImpl::RecordAppLaunched( AppListLaunchedFrom launched_from) { - RecordAppListAppLaunched(launched_from, GetAppListViewState(), IsTabletMode(), - last_visible_); + RecordAppListAppLaunched(launched_from, GetAppListViewState(), + IsInTabletMode(), last_visible_); } void AppListControllerImpl::AddObserver(AppListControllerObserver* observer) { @@ -1549,7 +1572,7 @@ // HomeLauncher is only visible when no other app windows are visible, // unless we are in the process of animating to (or dragging) the home // launcher. - if (IsTabletMode()) { + if (IsInTabletMode()) { UpdateTrackedAppWindow(); if (tracked_app_window_) @@ -1644,8 +1667,8 @@ // HomeLauncher is only visible when no other app windows are visible, // unless we are in the process of animating to (or dragging) the home // launcher. - if (IsTabletMode() && home_launcher_transition_state_ == - HomeLauncherTransitionState::kFinished) { + if (IsInTabletMode() && home_launcher_transition_state_ == + HomeLauncherTransitionState::kFinished) { real_target_visibility &= !GetTopVisibleWindow(); } @@ -1696,7 +1719,7 @@ } int64_t AppListControllerImpl::GetDisplayIdToShowAppListOn() { - if (IsTabletMode() && !Shell::Get()->display_manager()->IsInUnifiedMode()) { + if (IsInTabletMode() && !Shell::Get()->display_manager()->IsInUnifiedMode()) { return display::HasInternalDisplay() ? display::Display::InternalDisplayId() : display::Screen::GetScreen()->GetPrimaryDisplay().id(); @@ -1708,8 +1731,9 @@ } void AppListControllerImpl::ResetHomeLauncherIfShown() { - if (!IsTabletMode() || !fullscreen_presenter_->IsVisibleDeprecated()) + if (!IsInTabletMode() || !fullscreen_presenter_->IsVisibleDeprecated()) { return; + } auto* const keyboard_controller = keyboard::KeyboardUIController::Get(); if (keyboard_controller->IsKeyboardVisible()) @@ -1722,7 +1746,7 @@ } void AppListControllerImpl::ShowHomeScreen(AppListShowSource show_source) { - DCHECK(Shell::Get()->tablet_mode_controller()->InTabletMode()); + DCHECK(IsInTabletMode()); if (!Shell::Get()->session_controller()->IsActiveUserSessionStarted() || IsKioskSession()) @@ -1744,8 +1768,9 @@ } void AppListControllerImpl::UpdateHomeScreenVisibility() { - if (!IsTabletMode()) + if (!IsInTabletMode()) { return; + } aura::Window* window = GetHomeScreenWindow(); if (!window) @@ -1765,11 +1790,12 @@ if (!window) return false; - auto* shell = Shell::Get(); - if (!shell->tablet_mode_controller()->InTabletMode()) + if (!IsInTabletMode()) { return false; - if (shell->overview_controller()->InOverviewSession()) + } + if (Shell::Get()->overview_controller()->InOverviewSession()) { return false; + } return !SplitViewController::Get(window)->InSplitViewMode(); } @@ -1832,7 +1858,7 @@ // Release focus if the launcher is moving behind apps, and there is app // window showing. Note that the app list can be shown behind apps in // tablet mode only. - if (IsTabletMode() && !ShouldHomeLauncherBeVisible()) { + if (IsInTabletMode() && !ShouldHomeLauncherBeVisible()) { WindowState* const window_state = WindowState::Get(window); if (window_state->IsActive()) window_state->Deactivate(); @@ -1872,10 +1898,10 @@ shell->window_tree_host_manager()->RemoveObserver(this); AssistantState::Get()->RemoveObserver(this); keyboard::KeyboardUIController::Get()->RemoveObserver(this); + display::Screen::GetScreen()->RemoveObserver(this); shell->overview_controller()->RemoveObserver(this); shell->RemoveShellObserver(this); shell->wallpaper_controller()->RemoveObserver(this); - shell->tablet_mode_controller()->RemoveObserver(this); shell->session_controller()->RemoveObserver(this); FeatureDiscoveryDurationReporter::GetInstance()->RemoveObserver(this); @@ -1883,7 +1909,7 @@ } bool AppListControllerImpl::IsHomeScreenVisible() { - return IsTabletMode() && IsVisible(); + return IsInTabletMode() && IsVisible(); } void AppListControllerImpl::OnWindowDragStarted() {
diff --git a/ash/app_list/app_list_controller_impl.h b/ash/app_list/app_list_controller_impl.h index 04d195b..29e2448 100644 --- a/ash/app_list/app_list_controller_impl.h +++ b/ash/app_list/app_list_controller_impl.h
@@ -26,7 +26,6 @@ #include "ash/public/cpp/keyboard/keyboard_controller_observer.h" #include "ash/public/cpp/session/session_observer.h" #include "ash/public/cpp/shelf_types.h" -#include "ash/public/cpp/tablet_mode_observer.h" #include "ash/public/cpp/wallpaper/wallpaper_controller_observer.h" #include "ash/shelf/shelf_layout_manager.h" #include "ash/shell_observer.h" @@ -41,10 +40,15 @@ #include "base/time/time.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/aura/window_observer.h" +#include "ui/display/display_observer.h" #include "ui/display/types/display_constants.h" class PrefRegistrySimple; +namespace display { +enum class TabletState; +} // namespace display + namespace ash { class AppListBadgeController; @@ -67,7 +71,7 @@ public ShellObserver, public OverviewObserver, public SplitViewObserver, - public TabletModeObserver, + public display::DisplayObserver, public KeyboardControllerObserver, public WallpaperControllerObserver, public AssistantStateObserver, @@ -206,7 +210,7 @@ void OnViewStateChanged(AppListViewState state) override; int GetShelfSize() override; int GetSystemShelfInsetsInTabletMode() override; - bool IsInTabletMode() override; + bool IsInTabletMode() const override; // Notifies observers of AppList visibility changes. void OnVisibilityChanged(bool visible, int64_t display_id); @@ -228,9 +232,8 @@ void OnSplitViewStateChanged(SplitViewController::State previous_state, SplitViewController::State state) override; - // TabletModeObserver: - void OnTabletModeStarted() override; - void OnTabletModeEnded() override; + // display::DisplayObserver: + void OnDisplayTabletStateChanged(display::TabletState state) override; // KeyboardControllerObserver: void OnKeyboardVisibilityChanged(bool is_visible) override; @@ -409,6 +412,11 @@ // FeatureDiscoveryDurationReporter::ReporterObserver: void OnReporterActivated() override; + // Called when display tablet state is changed to kInTabletMode or + // kInClamshellMode. + void OnChangedToInTabletMode(); + void OnChangedToInClamshellMode(); + // Gets the container which should contain the fullscreen launcher. int GetFullscreenLauncherContainerId() const;
diff --git a/ash/app_list/app_list_controller_impl_unittest.cc b/ash/app_list/app_list_controller_impl_unittest.cc index 79e73ca..e9a7f21 100644 --- a/ash/app_list/app_list_controller_impl_unittest.cc +++ b/ash/app_list/app_list_controller_impl_unittest.cc
@@ -57,6 +57,7 @@ #include "ui/compositor/layer.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/test/layer_animation_stopped_waiter.h" +#include "ui/display/screen.h" #include "ui/events/test/event_generator.h" #include "ui/message_center/message_center.h" #include "ui/message_center/views/message_popup_view.h" @@ -74,7 +75,7 @@ } bool IsTabletMode() { - return Shell::Get()->tablet_mode_controller()->InTabletMode(); + return display::Screen::GetScreen()->InTabletMode(); } AppListModel* GetAppListModel() { @@ -1172,11 +1173,12 @@ auto* controller = Shell::Get()->app_list_controller(); EnableTabletMode(); - controller->OnTabletModeStarted(); + controller->OnDisplayTabletStateChanged(display::TabletState::kInTabletMode); EXPECT_FALSE(controller->IsVisible()); Shell::Get()->tablet_mode_controller()->SetEnabledForTest(false); - controller->OnTabletModeEnded(); + controller->OnDisplayTabletStateChanged( + display::TabletState::kInClamshellMode); EXPECT_FALSE(controller->bubble_presenter_for_test()->IsShowing()); EXPECT_FALSE(controller->IsVisible());
diff --git a/ash/app_list/app_list_metrics_unittest.cc b/ash/app_list/app_list_metrics_unittest.cc index db814b0..d7bd942 100644 --- a/ash/app_list/app_list_metrics_unittest.cc +++ b/ash/app_list/app_list_metrics_unittest.cc
@@ -41,7 +41,9 @@ #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" +#include "ui/display/display_observer.h" #include "ui/display/screen.h" +#include "ui/display/tablet_state.h" namespace ash { @@ -53,7 +55,8 @@ // item is selected. When |wait_for_tablet_mode_| is set, the delegate will wait // for tablet mode animation start to run the callback that activates the // window. -class TestShelfItemDelegate : public ShelfItemDelegate, TabletModeObserver { +class TestShelfItemDelegate : public ShelfItemDelegate, + display::DisplayObserver { public: explicit TestShelfItemDelegate(const ShelfID& shelf_id) : ShelfItemDelegate(shelf_id) {} @@ -62,10 +65,14 @@ : ShelfItemDelegate(shelf_id), wait_for_tablet_mode_(wait_for_tablet_mode) { if (wait_for_tablet_mode_) { - Shell::Get()->tablet_mode_controller()->AddObserver(this); + display::Screen::GetScreen()->AddObserver(this); } } + ~TestShelfItemDelegate() override { + display::Screen::GetScreen()->RemoveObserver(this); + } + void ItemSelected(std::unique_ptr<ui::Event> event, int64_t display_id, ash::ShelfLaunchSource source, @@ -83,17 +90,13 @@ int64_t display_id) override {} void Close() override {} - void OnTabletModeStarting() override { - if (!callback_) { + void OnDisplayTabletStateChanged(display::TabletState state) override { + if (!callback_ || state != display::TabletState::kEnteringTabletMode) { return; } std::move(callback_).Run(SHELF_ACTION_WINDOW_ACTIVATED, {}); } - void OnTabletControllerDestroyed() override { - Shell::Get()->tablet_mode_controller()->RemoveObserver(this); - } - private: bool wait_for_tablet_mode_ = false; ItemSelectedCallback callback_;
diff --git a/ash/app_list/app_list_test_view_delegate.cc b/ash/app_list/app_list_test_view_delegate.cc index ae7820c..bdd31e91 100644 --- a/ash/app_list/app_list_test_view_delegate.cc +++ b/ash/app_list/app_list_test_view_delegate.cc
@@ -202,7 +202,7 @@ return true; } -bool AppListTestViewDelegate::IsInTabletMode() { +bool AppListTestViewDelegate::IsInTabletMode() const { return is_tablet_mode_; }
diff --git a/ash/app_list/app_list_test_view_delegate.h b/ash/app_list/app_list_test_view_delegate.h index 4098d90..f17e180 100644 --- a/ash/app_list/app_list_test_view_delegate.h +++ b/ash/app_list/app_list_test_view_delegate.h
@@ -104,7 +104,7 @@ int GetShelfSize() override; int GetSystemShelfInsetsInTabletMode() override; bool AppListTargetVisibility() const override; - bool IsInTabletMode() override; + bool IsInTabletMode() const override; AppListNotifier* GetNotifier() override; std::unique_ptr<ScopedIphSession> CreateLauncherSearchIphSession() override; void LoadIcon(const std::string& app_id) override {}
diff --git a/ash/app_list/app_list_view_delegate.h b/ash/app_list/app_list_view_delegate.h index 675ffff..16c38700 100644 --- a/ash/app_list/app_list_view_delegate.h +++ b/ash/app_list/app_list_view_delegate.h
@@ -183,7 +183,7 @@ virtual int GetSystemShelfInsetsInTabletMode() = 0; // Returns whether tablet mode is currently enabled. - virtual bool IsInTabletMode() = 0; + virtual bool IsInTabletMode() const = 0; // Loads the icon of an app item identified by `app_id`. virtual void LoadIcon(const std::string& app_id) = 0;
diff --git a/ash/app_list/views/app_list_nudge_controller_unittest.cc b/ash/app_list/views/app_list_nudge_controller_unittest.cc index 0c0d5ea..96a0e75 100644 --- a/ash/app_list/views/app_list_nudge_controller_unittest.cc +++ b/ash/app_list/views/app_list_nudge_controller_unittest.cc
@@ -19,6 +19,7 @@ #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/functional/callback.h" #include "base/test/task_environment.h" +#include "ui/display/screen.h" #include "ui/views/controls/button/label_button.h" #include "ui/wm/core/window_util.h" @@ -27,7 +28,7 @@ namespace { bool IsTabletMode() { - return Shell::Get()->tablet_mode_controller()->InTabletMode(); + return display::Screen::GetScreen()->InTabletMode(); } // Returns the number of times the nudge has been shown. Note that the count
diff --git a/ash/app_list/views/assistant/assistant_page_view.cc b/ash/app_list/views/assistant/assistant_page_view.cc index 2658066..7bbbfd03 100644 --- a/ash/app_list/views/assistant/assistant_page_view.cc +++ b/ash/app_list/views/assistant/assistant_page_view.cc
@@ -37,6 +37,8 @@ #include "ui/compositor/layer_type.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/compositor_extra/shadow.h" +#include "ui/display/screen.h" +#include "ui/display/tablet_state.h" #include "ui/gfx/geometry/transform_util.h" #include "ui/views/layout/layout_manager_base.h" @@ -154,8 +156,7 @@ if (AssistantUiController::Get()) // May be |nullptr| in tests. AssistantUiController::Get()->GetModel()->AddObserver(this); - if (Shell::HasInstance()) // Shell might not has an instance in tests. - tablet_mode_observation_.Observe(Shell::Get()->tablet_mode_controller()); + display_observation_.Observe(display::Screen::GetScreen()); } AssistantPageView::~AssistantPageView() { @@ -383,12 +384,19 @@ } } -void AssistantPageView::OnTabletModeStarted() { - UpdateBackground(/*in_tablet_mode=*/true); -} - -void AssistantPageView::OnTabletModeEnded() { - UpdateBackground(/*in_tablet_mode=*/false); +void AssistantPageView::OnDisplayTabletStateChanged( + display::TabletState state) { + switch (state) { + case display::TabletState::kEnteringTabletMode: + case display::TabletState::kExitingTabletMode: + // Do nothing when the tablet mode is in process of changing. + break; + case display::TabletState::kInTabletMode: + UpdateBackground(/*in_tablet_mode=*/true); + break; + case display::TabletState::kInClamshellMode: + UpdateBackground(/*in_tablet_mode=*/false); + } } void AssistantPageView::OnThemeChanged() {
diff --git a/ash/app_list/views/assistant/assistant_page_view.h b/ash/app_list/views/assistant/assistant_page_view.h index 7a09bf6..ded09ea0 100644 --- a/ash/app_list/views/assistant/assistant_page_view.h +++ b/ash/app_list/views/assistant/assistant_page_view.h
@@ -13,12 +13,16 @@ #include "ash/public/cpp/app_list/app_list_types.h" #include "ash/public/cpp/assistant/controller/assistant_controller.h" #include "ash/public/cpp/assistant/controller/assistant_controller_observer.h" -#include "ash/public/cpp/tablet_mode_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/memory/raw_ptr.h" #include "base/scoped_observation.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/metadata/metadata_header_macros.h" +#include "ui/display/display_observer.h" +#include "ui/display/screen.h" + +namespace display { +enum class TableState; +} // namespace display namespace ash { @@ -30,7 +34,7 @@ class ASH_EXPORT AssistantPageView : public AppListPage, public AssistantControllerObserver, public AssistantUiModelObserver, - public TabletModeObserver { + public display::DisplayObserver { public: METADATA_HEADER(AssistantPageView); @@ -70,9 +74,8 @@ absl::optional<AssistantEntryPoint> entry_point, absl::optional<AssistantExitPoint> exit_point) override; - // TabletModeObserver: - void OnTabletModeStarted() override; - void OnTabletModeEnded() override; + // display::DisplayObserver: + void OnDisplayTabletStateChanged(display::TabletState state) override; // views::View: void OnThemeChanged() override; @@ -93,8 +96,8 @@ base::ScopedObservation<AssistantController, AssistantControllerObserver> assistant_controller_observation_{this}; - base::ScopedObservation<TabletModeController, TabletModeObserver> - tablet_mode_observation_{this}; + base::ScopedObservation<display::Screen, display::DisplayObserver> + display_observation_{this}; }; } // namespace ash
diff --git a/ash/app_list/views/assistant/assistant_test_api_impl.cc b/ash/app_list/views/assistant/assistant_test_api_impl.cc index d4a148c..1beb99e 100644 --- a/ash/app_list/views/assistant/assistant_test_api_impl.cc +++ b/ash/app_list/views/assistant/assistant_test_api_impl.cc
@@ -25,6 +25,7 @@ #include "components/prefs/pref_service.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" +#include "ui/display/screen.h" #include "ui/events/test/event_generator.h" #include "ui/views/controls/textfield/textfield.h" @@ -55,7 +56,7 @@ } bool AssistantTestApiImpl::IsVisible() { - if (!TabletMode::Get()->InTabletMode()) { + if (!display::Screen::GetScreen()->InTabletMode()) { return Shell::Get()->app_list_controller()->IsVisible() && GetAppListBubbleView()->assistant_page_->GetVisible(); } @@ -74,7 +75,7 @@ } views::View* AssistantTestApiImpl::page_view() { - if (!TabletMode::Get()->InTabletMode()) { + if (!display::Screen::GetScreen()->InTabletMode()) { auto* bubble_view = GetAppListBubbleView(); DCHECK(bubble_view) << "App list is not showing. Display the assistant UI first.";
diff --git a/ash/app_list/views/continue_section_view_unittest.cc b/ash/app_list/views/continue_section_view_unittest.cc index 73987bf..253fdfd 100644 --- a/ash/app_list/views/continue_section_view_unittest.cc +++ b/ash/app_list/views/continue_section_view_unittest.cc
@@ -40,6 +40,7 @@ #include "ui/compositor/layer.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/compositor/test/layer_animation_stopped_waiter.h" +#include "ui/display/screen.h" #include "ui/events/event.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/views/animation/ink_drop.h" @@ -131,8 +132,9 @@ } ContinueSectionView* GetContinueSectionView() { - if (Shell::Get()->tablet_mode_controller()->InTabletMode()) + if (display::Screen::GetScreen()->InTabletMode()) { return GetAppListTestHelper()->GetFullscreenContinueSectionView(); + } return GetAppListTestHelper()->GetBubbleContinueSectionView(); } @@ -141,14 +143,16 @@ } views::View* GetRecentAppsView() { - if (Shell::Get()->tablet_mode_controller()->InTabletMode()) + if (display::Screen::GetScreen()->InTabletMode()) { return GetAppListTestHelper()->GetFullscreenRecentAppsView(); + } return GetAppListTestHelper()->GetBubbleRecentAppsView(); } views::View* GetAppsGridView() { - if (Shell::Get()->tablet_mode_controller()->InTabletMode()) + if (display::Screen::GetScreen()->InTabletMode()) { return GetAppListTestHelper()->GetRootPagedAppsGridView(); + } return GetAppListTestHelper()->GetScrollableAppsGridView(); } @@ -191,8 +195,9 @@ } SearchBoxView* GetSearchBoxView() { - if (Shell::Get()->tablet_mode_controller()->InTabletMode()) + if (display::Screen::GetScreen()->InTabletMode()) { return GetAppListTestHelper()->GetSearchBoxView(); + } return GetAppListTestHelper()->GetBubbleSearchBoxView(); } @@ -342,7 +347,7 @@ } AppListToastContainerView* GetToastContainerView() { - if (!Shell::Get()->tablet_mode_controller()->InTabletMode()) { + if (!display::Screen::GetScreen()->InTabletMode()) { return GetAppListTestHelper() ->GetBubbleAppsPage() ->toast_container_for_test();
diff --git a/ash/assistant/assistant_interaction_controller_impl.cc b/ash/assistant/assistant_interaction_controller_impl.cc index 14755dc..5e0a802 100644 --- a/ash/assistant/assistant_interaction_controller_impl.cc +++ b/ash/assistant/assistant_interaction_controller_impl.cc
@@ -39,6 +39,8 @@ #include "net/base/url_util.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/l10n/l10n_util.h" +#include "ui/display/screen.h" +#include "ui/display/tablet_state.h" namespace ash { @@ -52,13 +54,9 @@ // Helpers --------------------------------------------------------------------- -ash::TabletModeController* GetTabletModeController() { - return Shell::Get()->tablet_mode_controller(); -} - // Returns true if device is in tablet mode, false otherwise. bool IsTabletMode() { - return GetTabletModeController()->InTabletMode(); + return display::Screen::GetScreen()->InTabletMode(); } bool launch_with_mic_open() { @@ -89,7 +87,7 @@ model_.AddObserver(this); assistant_controller_observation_.Observe(AssistantController::Get()); - tablet_mode_controller_observation_.Observe(GetTabletModeController()); + display_observation_.Observe(display::Screen::GetScreen()); } AssistantInteractionControllerImpl::~AssistantInteractionControllerImpl() { @@ -528,15 +526,14 @@ query_source); } -void AssistantInteractionControllerImpl::OnTabletModeStarted() { - OnTabletModeChanged(); -} +void AssistantInteractionControllerImpl::OnDisplayTabletStateChanged( + display::TabletState state) { + // Ignore the state in the process of changing the tablet state. + if (state == display::TabletState::kEnteringTabletMode || + state == display::TabletState::kExitingTabletMode) { + return; + } -void AssistantInteractionControllerImpl::OnTabletModeEnded() { - OnTabletModeChanged(); -} - -void AssistantInteractionControllerImpl::OnTabletModeChanged() { // The default input modality is different for tablet and normal mode. // Change input modality to the new default input modality. if (!HasActiveInteraction() && !IsVisible())
diff --git a/ash/assistant/assistant_interaction_controller_impl.h b/ash/assistant/assistant_interaction_controller_impl.h index 9a6bf6a..edc781b 100644 --- a/ash/assistant/assistant_interaction_controller_impl.h +++ b/ash/assistant/assistant_interaction_controller_impl.h
@@ -17,16 +17,20 @@ #include "ash/public/cpp/assistant/controller/assistant_controller.h" #include "ash/public/cpp/assistant/controller/assistant_controller_observer.h" #include "ash/public/cpp/assistant/controller/assistant_interaction_controller.h" -#include "ash/public/cpp/tablet_mode_observer.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "chromeos/ash/services/assistant/public/cpp/assistant_service.h" #include "mojo/public/cpp/bindings/receiver.h" +#include "ui/display/display_observer.h" +#include "ui/display/screen.h" class PrefRegistrySimple; +namespace display { +enum class TabletState; +} // namespace display + namespace ash { class AssistantControllerImpl; @@ -39,7 +43,7 @@ public AssistantInteractionModelObserver, public AssistantUiModelObserver, public AssistantViewDelegateObserver, - public TabletModeObserver { + public display::DisplayObserver { public: using AssistantInteractionMetadata = assistant::AssistantInteractionMetadata; using AssistantInteractionResolution = @@ -119,12 +123,10 @@ void OnSuggestionPressed( const base::UnguessableToken& suggestion_id) override; - // TabletModeObserver: - void OnTabletModeStarted() override; - void OnTabletModeEnded() override; + // display::DisplayObserver: + void OnDisplayTabletStateChanged(display::TabletState state) override; private: - void OnTabletModeChanged(); bool HasActiveInteraction() const; void OnUiVisible(AssistantEntryPoint entry_point); void StartVoiceInteraction(); @@ -146,8 +148,8 @@ base::ScopedObservation<AssistantController, AssistantControllerObserver> assistant_controller_observation_{this}; - base::ScopedObservation<TabletModeController, TabletModeObserver> - tablet_mode_controller_observation_{this}; + base::ScopedObservation<display::Screen, display::DisplayObserver> + display_observation_{this}; base::WeakPtrFactory<AssistantInteractionControllerImpl> weak_factory_{this}; };
diff --git a/ash/assistant/assistant_view_delegate_impl.cc b/ash/assistant/assistant_view_delegate_impl.cc index f41ffd0a..b2d1e6d3 100644 --- a/ash/assistant/assistant_view_delegate_impl.cc +++ b/ash/assistant/assistant_view_delegate_impl.cc
@@ -18,10 +18,10 @@ #include "ash/public/cpp/session/user_info.h" #include "ash/session/session_controller_impl.h" #include "ash/shell.h" -#include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/command_line.h" #include "chromeos/ash/services/assistant/public/cpp/features.h" #include "chromeos/ash/services/assistant/public/cpp/switches.h" +#include "ui/display/screen.h" namespace ash { @@ -79,7 +79,7 @@ } bool AssistantViewDelegateImpl::IsTabletMode() const { - return Shell::Get()->tablet_mode_controller()->InTabletMode(); + return display::Screen::GetScreen()->InTabletMode(); } void AssistantViewDelegateImpl::OnDialogPlateButtonPressed(
diff --git a/ash/assistant/ui/DEPS b/ash/assistant/ui/DEPS index 392a46a..b28d5de 100644 --- a/ash/assistant/ui/DEPS +++ b/ash/assistant/ui/DEPS
@@ -61,7 +61,6 @@ "+ash/shell.h", "+ash/test/ash_test_base.h", "+ash/test/ash_test_views_delegate.h", - "+ash/wm/tablet_mode/tablet_mode_controller.h", "+base/test/scoped_feature_list.h", "+cc/test/pixel_comparator.h", "+chromeos/ash/services/assistant/test_support/mock_assistant.h",
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 3910217..47c21f5c 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -2587,7 +2587,7 @@ // Enable storing a newly created owner key in the private slot. BASE_FEATURE(kStoreOwnerKeyInPrivateSlot, "StoreOwnerKeyInPrivateSlot", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); // Enables battery indicator for styluses in the palette tray BASE_FEATURE(kStylusBatteryStatus,
diff --git a/ash/system/media/media_notification_provider.h b/ash/system/media/media_notification_provider.h index fda4ca2..03ff1df 100644 --- a/ash/system/media/media_notification_provider.h +++ b/ash/system/media/media_notification_provider.h
@@ -60,6 +60,7 @@ virtual std::unique_ptr<views::View> GetMediaNotificationListView( int separator_thickness, bool should_clip_height, + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id = "") = 0; // Used for ash to notify the bubble is closing.
diff --git a/ash/system/media/media_tray.cc b/ash/system/media/media_tray.cc index 16497a0..82910fe 100644 --- a/ash/system/media/media_tray.cc +++ b/ash/system/media/media_tray.cc
@@ -27,6 +27,7 @@ #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram_functions.h" +#include "components/global_media_controls/public/constants.h" #include "components/media_message_center/notification_theme.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_registry_simple.h" @@ -395,10 +396,15 @@ title_view->SetPaintToLayer(); title_view->layer()->SetFillsBoundsOpaquely(false); pin_button_ = title_view->pin_button(); + global_media_controls::GlobalMediaControlsEntryPoint entry_point = + item_id.empty() + ? global_media_controls::GlobalMediaControlsEntryPoint::kSystemTray + : global_media_controls::GlobalMediaControlsEntryPoint::kPresentation; content_view_ = bubble_view->AddChildView( MediaNotificationProvider::Get()->GetMediaNotificationListView( - kMenuSeparatorWidth, /*should_clip_height=*/true, item_id)); + kMenuSeparatorWidth, /*should_clip_height=*/true, entry_point, + item_id)); if (base::FeatureList::IsEnabled(media::kGlobalMediaControlsCrOSUpdatedUI)) { bubble_view->SetPreferredWidth(kWideTrayMenuWidth); content_view_->SetBorder(views::CreateEmptyBorder(
diff --git a/ash/system/media/media_tray_unittest.cc b/ash/system/media/media_tray_unittest.cc index 26c365f..d2d5a1e 100644 --- a/ash/system/media/media_tray_unittest.cc +++ b/ash/system/media/media_tray_unittest.cc
@@ -165,8 +165,8 @@ // Tap the media tray should show the bubble, and media tray should // be active. GetMediaNotificationlistview also should be called for // getting active notifications. - EXPECT_CALL(*provider(), - GetMediaNotificationListView(_, /*should_clip_height=*/true, _)); + EXPECT_CALL(*provider(), GetMediaNotificationListView( + _, /*should_clip_height=*/true, _, _)); GestureTapOn(media_tray()); EXPECT_NE(GetBubbleWrapper(), nullptr); EXPECT_TRUE(media_tray()->is_active()); @@ -359,7 +359,7 @@ // We start with no bubble view. EXPECT_EQ(nullptr, media_tray()->GetBubbleView()); - EXPECT_CALL(*provider(), GetMediaNotificationListView(_, _, "")); + EXPECT_CALL(*provider(), GetMediaNotificationListView(_, _, _, "")); media_tray()->ShowBubble(); EXPECT_NE(nullptr, media_tray()->GetBubbleView()); } @@ -369,7 +369,7 @@ EXPECT_EQ(nullptr, media_tray()->GetBubbleView()); const std::string item_id = "my-item-id"; - EXPECT_CALL(*provider(), GetMediaNotificationListView(_, _, item_id)); + EXPECT_CALL(*provider(), GetMediaNotificationListView(_, _, _, item_id)); media_tray()->ShowBubbleWithItem(item_id); EXPECT_NE(nullptr, media_tray()->GetBubbleView()); }
diff --git a/ash/system/media/mock_media_notification_provider.cc b/ash/system/media/mock_media_notification_provider.cc index 0cb3df6..d84b1b66 100644 --- a/ash/system/media/mock_media_notification_provider.cc +++ b/ash/system/media/mock_media_notification_provider.cc
@@ -14,8 +14,8 @@ : old_provider_(MediaNotificationProvider::Get()) { MediaNotificationProvider::Set(this); - ON_CALL(*this, GetMediaNotificationListView(_, _, _)) - .WillByDefault([](auto, auto, const auto&) { + ON_CALL(*this, GetMediaNotificationListView) + .WillByDefault([](auto, auto, auto, const auto&) { return std::make_unique<views::View>(); }); }
diff --git a/ash/system/media/mock_media_notification_provider.h b/ash/system/media/mock_media_notification_provider.h index e89e247..e671434 100644 --- a/ash/system/media/mock_media_notification_provider.h +++ b/ash/system/media/mock_media_notification_provider.h
@@ -25,7 +25,10 @@ // MediaNotificationProvider: MOCK_METHOD((std::unique_ptr<views::View>), GetMediaNotificationListView, - (int, bool, const std::string&)); + (int, + bool, + global_media_controls::GlobalMediaControlsEntryPoint, + const std::string&)); MOCK_METHOD(void, OnBubbleClosing, ()); MOCK_METHOD(global_media_controls::MediaItemManager*, GetMediaItemManager,
diff --git a/ash/system/media/quick_settings_media_view_controller.cc b/ash/system/media/quick_settings_media_view_controller.cc index 33db27a1..ecb1154d 100644 --- a/ash/system/media/quick_settings_media_view_controller.cc +++ b/ash/system/media/quick_settings_media_view_controller.cc
@@ -10,12 +10,15 @@ #include "ash/system/media/media_notification_provider.h" #include "ash/system/media/quick_settings_media_view.h" #include "ash/system/unified/unified_system_tray_controller.h" +#include "components/global_media_controls/public/constants.h" #include "components/global_media_controls/public/media_item_manager.h" #include "components/global_media_controls/public/media_session_item_producer.h" #include "components/global_media_controls/public/views/media_item_ui_view.h" #include "services/media_session/public/cpp/media_session_service.h" #include "ui/views/view.h" +using global_media_controls::GlobalMediaControlsEntryPoint; + namespace ash { QuickSettingsMediaViewController::QuickSettingsMediaViewController( @@ -101,7 +104,8 @@ void QuickSettingsMediaViewController::OnMediaItemUIClicked( const std::string& id) { - tray_controller_->ShowMediaControlsDetailedView(); + tray_controller_->ShowMediaControlsDetailedView( + GlobalMediaControlsEntryPoint::kQuickSettingsMiniPlayer); } void QuickSettingsMediaViewController::OnMediaItemUIDestroyed( @@ -111,7 +115,8 @@ void QuickSettingsMediaViewController::OnMediaItemUIShowDevices( const std::string& id) { - tray_controller_->ShowMediaControlsDetailedView(id); + tray_controller_->ShowMediaControlsDetailedView( + GlobalMediaControlsEntryPoint::kQuickSettingsMiniPlayerCastButton, id); } ///////////////////////////////////////////////////////////////////////////////
diff --git a/ash/system/media/unified_media_controls_detailed_view_controller.cc b/ash/system/media/unified_media_controls_detailed_view_controller.cc index ce8c83b..bc2841a 100644 --- a/ash/system/media/unified_media_controls_detailed_view_controller.cc +++ b/ash/system/media/unified_media_controls_detailed_view_controller.cc
@@ -13,6 +13,7 @@ #include "ash/system/tray/detailed_view_delegate.h" #include "ash/system/tray/tray_constants.h" #include "base/metrics/histogram_functions.h" +#include "components/global_media_controls/public/constants.h" #include "components/media_message_center/notification_theme.h" #include "ui/base/l10n/l10n_util.h" @@ -25,9 +26,11 @@ UnifiedMediaControlsDetailedViewController:: UnifiedMediaControlsDetailedViewController( UnifiedSystemTrayController* tray_controller, + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id) : detailed_view_delegate_( std::make_unique<DetailedViewDelegate>(tray_controller)), + entry_point_(entry_point), show_devices_for_item_id_(show_devices_for_item_id) {} UnifiedMediaControlsDetailedViewController:: @@ -61,11 +64,10 @@ "Media.CrosGlobalMediaControls.RepeatUsageInQuickSetting", detailed_view_has_shown_); detailed_view_has_shown_ = true; - return std::make_unique<UnifiedMediaControlsDetailedView>( detailed_view_delegate_.get(), MediaNotificationProvider::Get()->GetMediaNotificationListView( - kMenuSeparatorWidth, /*should_clip_height=*/false, + kMenuSeparatorWidth, /*should_clip_height=*/false, entry_point_, show_devices_for_item_id_)); }
diff --git a/ash/system/media/unified_media_controls_detailed_view_controller.h b/ash/system/media/unified_media_controls_detailed_view_controller.h index ec9f0a17..e6ba229 100644 --- a/ash/system/media/unified_media_controls_detailed_view_controller.h +++ b/ash/system/media/unified_media_controls_detailed_view_controller.h
@@ -9,6 +9,7 @@ #include "ash/ash_export.h" #include "ash/system/unified/detailed_view_controller.h" +#include "components/global_media_controls/public/constants.h" namespace ash { @@ -22,8 +23,9 @@ // If `show_devices_for_item_id` is not empty, when the // MediaNotificationListView shows the MediaItemUIView for this ID, it will // expand the casting device list too. - explicit UnifiedMediaControlsDetailedViewController( + UnifiedMediaControlsDetailedViewController( UnifiedSystemTrayController* tray_controller, + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id = ""); ~UnifiedMediaControlsDetailedViewController() override; @@ -35,9 +37,8 @@ friend class UnifiedMediaControlsDetailedViewControllerTest; static bool detailed_view_has_shown_; - const std::unique_ptr<DetailedViewDelegate> detailed_view_delegate_; - + const global_media_controls::GlobalMediaControlsEntryPoint entry_point_; const std::string show_devices_for_item_id_; };
diff --git a/ash/system/media/unified_media_controls_detailed_view_controller_unittest.cc b/ash/system/media/unified_media_controls_detailed_view_controller_unittest.cc index 1a1d477..91677455 100644 --- a/ash/system/media/unified_media_controls_detailed_view_controller_unittest.cc +++ b/ash/system/media/unified_media_controls_detailed_view_controller_unittest.cc
@@ -74,8 +74,8 @@ // We should get a MediaNotificationProvider::GetMediaNotificationListView // call when creating the detailed view. - EXPECT_CALL(*provider(), - GetMediaNotificationListView(_, /*should_clip_height=*/false, _)); + EXPECT_CALL(*provider(), GetMediaNotificationListView( + _, /*should_clip_height=*/false, _, _)); system_tray_controller()->OnMediaControlsViewClicked(); EXPECT_NE(system_tray_controller()->detailed_view_controller(), nullptr);
diff --git a/ash/system/unified/unified_system_tray_controller.cc b/ash/system/unified/unified_system_tray_controller.cc index d8d54f7..e5b6cd4 100644 --- a/ash/system/unified/unified_system_tray_controller.cc +++ b/ash/system/unified/unified_system_tray_controller.cc
@@ -72,6 +72,7 @@ #include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/user_metrics.h" +#include "components/global_media_controls/public/constants.h" #include "media/base/media_switches.h" #include "media/capture/video/chromeos/video_capture_features_chromeos.h" #include "ui/accessibility/ax_enums.mojom.h" @@ -80,6 +81,8 @@ #include "ui/events/event.h" #include "ui/views/widget/widget.h" +using global_media_controls::GlobalMediaControlsEntryPoint; + namespace ash { // TODO(amehfooz): Add histograms for pagination metrics in system tray. @@ -315,9 +318,10 @@ } void UnifiedSystemTrayController::ShowMediaControlsDetailedView( + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id) { ShowDetailedView(std::make_unique<UnifiedMediaControlsDetailedViewController>( - this, show_devices_for_item_id)); + this, entry_point, show_devices_for_item_id)); } void UnifiedSystemTrayController::TransitionToMainView(bool restore_focus) { @@ -368,7 +372,8 @@ } void UnifiedSystemTrayController::OnMediaControlsViewClicked() { - ShowMediaControlsDetailedView(); + ShowMediaControlsDetailedView( + GlobalMediaControlsEntryPoint::kQuickSettingsMiniPlayer); } void UnifiedSystemTrayController::SetShowMediaView(bool show_media_view) {
diff --git a/ash/system/unified/unified_system_tray_controller.h b/ash/system/unified/unified_system_tray_controller.h index fd471a6..84a41b5 100644 --- a/ash/system/unified/unified_system_tray_controller.h +++ b/ash/system/unified/unified_system_tray_controller.h
@@ -16,6 +16,7 @@ #include "ash/system/unified/unified_system_tray_model.h" #include "base/memory/raw_ptr.h" #include "base/memory/scoped_refptr.h" +#include "components/global_media_controls/public/constants.h" namespace views { class View; @@ -109,6 +110,7 @@ void ShowNotifierSettingsView(); // Show the detailed view of media controls. Called from the view. void ShowMediaControlsDetailedView( + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id = ""); // Show the detailed view of Calendar. Called from the view. void ShowCalendarView(calendar_metrics::CalendarViewShowSource show_source,
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java index f802079..a7cb628 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/page_info/PageInfoViewTest.java
@@ -1078,7 +1078,6 @@ @Test @MediumTest @Feature({"RenderTest"}) - @DisabledTest(message = "crbug.com/1498268") public void testShowAdPersonalizationInfoSubPageV4() throws IOException { loadUrlAndOpenPageInfo( mTestServerRule.getServer().getURLWithHostName("example.com", sSimpleHtml));
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 3896fdde..bac2935 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -6635,8 +6635,8 @@ <message name="IDS_SUB_APPS_INSTALL_DIALOG_DESCRIPTION" desc="Description of a dialog that lets the user approve the install of one or more sub apps. [ICU Syntax]"> {NUM_SUB_APP_INSTALLS, plural, - =1 {"<ph name="APP_NAME">{APP_NAME}<ex>Citrix</ex></ph>" (<ph name="DOMAIN">{DOMAIN}<ex>citrix.com</ex></ph>) would like to install the following app on this device:} - other {"<ph name="APP_NAME">{APP_NAME}<ex>Citrix</ex></ph>" (<ph name="DOMAIN">{DOMAIN}<ex>citrix.com</ex></ph>) would like to install the following apps on this device:} + =1 {"<ph name="APP_NAME">{APP_NAME}<ex>Citrix</ex></ph>" would like to install the following app on this device:} + other {"<ph name="APP_NAME">{APP_NAME}<ex>Citrix</ex></ph>" would like to install the following apps on this device:} } </message>
diff --git a/chrome/app/generated_resources_grd/IDS_SUB_APPS_INSTALL_DIALOG_DESCRIPTION.png.sha1 b/chrome/app/generated_resources_grd/IDS_SUB_APPS_INSTALL_DIALOG_DESCRIPTION.png.sha1 index cecfbc5d..2c98894b 100644 --- a/chrome/app/generated_resources_grd/IDS_SUB_APPS_INSTALL_DIALOG_DESCRIPTION.png.sha1 +++ b/chrome/app/generated_resources_grd/IDS_SUB_APPS_INSTALL_DIALOG_DESCRIPTION.png.sha1
@@ -1 +1 @@ -936e2f97413b9fef83576bb5b62ce44a1bd90037 \ No newline at end of file +71f56f440704022fb4ce78a2724582f9a41debf5
diff --git a/chrome/browser/apps/app_service/menu_util.cc b/chrome/browser/apps/app_service/menu_util.cc index 42cc968..efd3774 100644 --- a/chrome/browser/apps/app_service/menu_util.cc +++ b/chrome/browser/apps/app_service/menu_util.cc
@@ -20,6 +20,8 @@ #include "chrome/common/chrome_features.h" #include "chrome/grit/generated_resources.h" #include "components/policy/core/common/policy_pref_names.h" +#include "components/services/app_service/public/cpp/app_registry_cache.h" +#include "components/services/app_service/public/cpp/app_update.h" #include "content/public/common/content_features.h" #include "third_party/blink/public/common/features.h" #include "ui/base/l10n/l10n_util.h" @@ -131,9 +133,16 @@ return false; } - return apps::AppServiceProxyFactory::GetForProfile(profile) - ->InstanceRegistry() - .ContainsAppId(app_id); + bool can_close = true; + apps::AppServiceProxyFactory::GetForProfile(profile) + ->AppRegistryCache() + .ForOneApp(app_id, [&can_close](const apps::AppUpdate& update) { + can_close = update.AllowClose().value_or(true); + }); + + return can_close && apps::AppServiceProxyFactory::GetForProfile(profile) + ->InstanceRegistry() + .ContainsAppId(app_id); } void PopulateLaunchNewItemFromMenuItem(const MenuItemPtr& menu_item,
diff --git a/chrome/browser/apps/app_service/publishers/web_apps_crosapi.cc b/chrome/browser/apps/app_service/publishers/web_apps_crosapi.cc index 7dd811a..deacdb88 100644 --- a/chrome/browser/apps/app_service/publishers/web_apps_crosapi.cc +++ b/chrome/browser/apps/app_service/publishers/web_apps_crosapi.cc
@@ -190,10 +190,8 @@ } } - if (menu_type == MenuType::kShelf) { - if (proxy_->InstanceRegistry().ContainsAppId(app_id)) { - AddCommandItem(ash::MENU_CLOSE, IDS_SHELF_CONTEXT_MENU_CLOSE, menu_items); - } + if (ShouldAddCloseItem(app_id, menu_type, proxy_->profile())) { + AddCommandItem(ash::MENU_CLOSE, IDS_SHELF_CONTEXT_MENU_CLOSE, menu_items); } if (can_use_uninstall) {
diff --git a/chrome/browser/ash/crosapi/BUILD.gn b/chrome/browser/ash/crosapi/BUILD.gn index 86d0418..8d98af7c 100644 --- a/chrome/browser/ash/crosapi/BUILD.gn +++ b/chrome/browser/ash/crosapi/BUILD.gn
@@ -362,6 +362,7 @@ "//components/eye_dropper", "//components/feature_engagement", "//components/flags_ui", + "//components/global_media_controls", "//components/keyed_service/content", "//components/language/core/browser:browser", "//components/live_caption:utils",
diff --git a/chrome/browser/ash/crosapi/media_ui_ash.cc b/chrome/browser/ash/crosapi/media_ui_ash.cc index 9a560aa..cf1e4046 100644 --- a/chrome/browser/ash/crosapi/media_ui_ash.cc +++ b/chrome/browser/ash/crosapi/media_ui_ash.cc
@@ -12,6 +12,7 @@ #include "ash/system/unified/unified_system_tray.h" #include "ash/system/unified/unified_system_tray_bubble.h" #include "ash/system/unified/unified_system_tray_controller.h" +#include "components/global_media_controls/public/constants.h" namespace crosapi { @@ -52,7 +53,9 @@ tray->ShowBubble(); tray->bubble() ->unified_system_tray_controller() - ->ShowMediaControlsDetailedView(item_id); + ->ShowMediaControlsDetailedView( + global_media_controls::GlobalMediaControlsEntryPoint::kPresentation, + item_id); } }
diff --git a/chrome/browser/ash/file_manager/file_manager_browsertest.cc b/chrome/browser/ash/file_manager/file_manager_browsertest.cc index 452573e..3ebf8d6a 100644 --- a/chrome/browser/ash/file_manager/file_manager_browsertest.cc +++ b/chrome/browser/ash/file_manager/file_manager_browsertest.cc
@@ -1083,7 +1083,8 @@ TestCase("driveDirtyItemsShouldBeDisplayedAsQueued"), TestCase("openDriveDocWhenOffline").EnableBulkPinning(), TestCase("completedSyncStatusDismissesAfter300Ms"), - TestCase("driveOutOfOrganizationSpaceBanner") + TestCase("driveOutOfOrganizationSpaceBanner"), + TestCase("copyDirectoryWithEncryptedFile") // TODO(b/189173190): Enable // TestCase("driveEnableDocsOfflineDialog"), // TODO(b/189173190): Enable
diff --git a/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc b/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc index cfc3f4f..ca9f367e 100644 --- a/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc +++ b/chrome/browser/ash/file_manager/file_manager_browsertest_base.cc
@@ -114,6 +114,7 @@ #include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/common/chrome_features.h" +#include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/api/file_manager_private.h" #include "chrome/common/pref_names.h" @@ -158,6 +159,7 @@ #include "google_apis/drive/drive_api_parser.h" #include "media/base/media_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "storage/browser/file_system/copy_or_move_operation_delegate.h" #include "storage/browser/file_system/external_mount_points.h" #include "storage/browser/file_system/file_system_context.h" #include "testing/gmock/include/gmock/gmock.h" @@ -2585,6 +2587,9 @@ file_tasks_observer_.reset(); select_factory_ = nullptr; ui::SelectFileDialog::SetFactory(nullptr); + if (error_url_.is_valid()) { + storage::CopyOrMoveOperationDelegate::SetErrorUrlForTest(nullptr); + } } void FileManagerBrowserTestBase::TearDown() { @@ -3932,6 +3937,25 @@ return; } + if (name == "mockDriveReadFailure") { + const std::string path = "v2/root/" + *value.FindString("path"); + base::FilePath user_data_directory; + base::PathService::Get(chrome::DIR_USER_DATA, &user_data_directory); + error_url_ = storage::FileSystemURL::CreateForTest( + blink::StorageKey::CreateFirstParty(url::Origin::Create( + GURL("chrome://file-manager/external/" + path))), + /*mount_type*/ storage::kFileSystemTypeExternal, + /*virtual_path*/ base::FilePath(path), + /*mount_filesystem_id*/ {}, + /*cracked_type*/ storage::kFileSystemTypeDriveFs, + /*cracked_path*/ + user_data_directory.Append(base::FilePath("user/drive/" + path)), + /*filesystem_id*/ "v2", + /*mount_option*/ {}); + storage::CopyOrMoveOperationDelegate::SetErrorUrlForTest(&error_url_); + return; + } + if (HandleGuestOsCommands(name, value, output)) { return; }
diff --git a/chrome/browser/ash/file_manager/file_manager_browsertest_base.h b/chrome/browser/ash/file_manager/file_manager_browsertest_base.h index 8104526..e959f5b 100644 --- a/chrome/browser/ash/file_manager/file_manager_browsertest_base.h +++ b/chrome/browser/ash/file_manager/file_manager_browsertest_base.h
@@ -24,6 +24,7 @@ #include "chrome/test/base/devtools_listener.h" #include "components/webapps/common/web_app_id.h" #include "content/public/browser/devtools_agent_host_observer.h" +#include "storage/browser/file_system/file_system_url.h" class NotificationDisplayServiceTester; class SelectFileDialogExtensionTestFactory; @@ -374,6 +375,8 @@ base::FilePath devtools_code_coverage_dir_; DevToolsAgentMap devtools_agent_; uint32_t process_id_ = 0; + + storage::FileSystemURL error_url_; }; std::ostream& operator<<(std::ostream& out, GuestMode mode);
diff --git a/chrome/browser/ash/file_manager/file_manager_jstest.cc b/chrome/browser/ash/file_manager/file_manager_jstest.cc index 0b577f3..241641d2 100644 --- a/chrome/browser/ash/file_manager/file_manager_jstest.cc +++ b/chrome/browser/ash/file_manager/file_manager_jstest.cc
@@ -431,7 +431,14 @@ RunTestURL("containers/cloud_panel_container_unittest.js"); } -IN_PROC_BROWSER_TEST_F(FileManagerJsTest, DirectoryTreeContainer) { +// TODO(b/312121966): Flaky on linux-chromeos-dbg, Linux ChromiumOS MSan +// Tests and Linux Chromium OS ASan LSan Tests. +#if !defined(NDEBUG) || defined(MEMORY_SANITIZER) || defined(ADDRESS_SANITIZER) +#define MAYBE_DirectoryTreeContainer DISABLED_DirectoryTreeContainer +#else +#define MAYBE_DirectoryTreeContainer DirectoryTreeContainer +#endif +IN_PROC_BROWSER_TEST_F(FileManagerJsTest, MAYBE_DirectoryTreeContainer) { RunTestURL("containers/directory_tree_container_unittest.js"); }
diff --git a/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.cc b/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.cc index 8d6220c3..cf13bd7 100644 --- a/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.cc +++ b/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.cc
@@ -4,10 +4,34 @@ #include "chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.h" -#include "ash/constants/ash_switches.h" +#include "chrome/browser/ash/login/app_mode/test/web_kiosk_base_test.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" namespace ash { +namespace { +std::unique_ptr<net::test_server::HttpResponse> ServeSimpleHtmlPage( + const net::test_server::HttpRequest& request) { + auto response = std::make_unique<net::test_server::BasicHttpResponse>(); + response->set_code(net::HTTP_OK); + response->set_content_type("text/html"); + response->set_content( + "<!DOCTYPE html>" + "<html lang=\"en\">" + "<head><title>Test Page</title></head>" + "<body>A simple kiosk web page.</body>" + "</html>"); + return response; +} + +} // namespace + +void WebKioskLacrosBaseTest::SetUpOnMainThread() { + InitializeWebAppServer(); + WebKioskBaseTest::SetUpOnMainThread(); +} + void WebKioskLacrosBaseTest::SetUpInProcessBrowserTestFixture() { if (kiosk_ash_starter_.HasLacrosArgument()) { kiosk_ash_starter_.PrepareEnvironmentForKioskLacros(); @@ -23,4 +47,11 @@ WebKioskBaseTest::PreRunTestOnMainThread(); } +void WebKioskLacrosBaseTest::InitializeWebAppServer() { + web_app_server_.RegisterRequestHandler( + base::BindRepeating(&ServeSimpleHtmlPage)); + ASSERT_TRUE(web_app_server_handle_ = web_app_server_.StartAndReturnHandle()); + SetAppInstallUrl(web_app_server_.base_url().spec()); +} + } // namespace ash
diff --git a/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.h b/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.h index 507d3f5d..decb9210 100644 --- a/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.h +++ b/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_base_test.h
@@ -7,18 +7,26 @@ #include "chrome/browser/ash/login/app_mode/test/kiosk_ash_browser_test_starter.h" #include "chrome/browser/ash/login/app_mode/test/web_kiosk_base_test.h" +#include "net/test/embedded_test_server/embedded_test_server.h" namespace ash { // Base class for Ash-side of the web kiosk when Lacros is enabled. class WebKioskLacrosBaseTest : public WebKioskBaseTest { public: + void SetUpOnMainThread() override; void SetUpInProcessBrowserTestFixture() override; void PreRunTestOnMainThread() override; protected: KioskAshBrowserTestStarter kiosk_ash_starter_; + + private: + void InitializeWebAppServer(); + + net::test_server::EmbeddedTestServer web_app_server_; + net::test_server::EmbeddedTestServerHandle web_app_server_handle_; }; } // namespace ash
diff --git a/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_browsertest.cc b/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_browsertest.cc index 0114f71..3ed88d9 100644 --- a/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_browsertest.cc +++ b/chrome/browser/ash/login/app_mode/test/web_kiosk_lacros_browsertest.cc
@@ -24,8 +24,7 @@ EXPECT_TRUE(crosapi::BrowserManager::Get()->IsRunning()); } -// TODO(crbug.com/1501438): Reenable the test. -IN_PROC_BROWSER_TEST_F(WebKioskLacrosTest, DISABLED_RecoverFromLacrosCrash) { +IN_PROC_BROWSER_TEST_F(WebKioskLacrosTest, RecoverFromLacrosCrash) { if (!kiosk_ash_starter_.HasLacrosArgument()) { return; }
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_model_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_model_delegate.cc index 3465a5c..33857b37 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_model_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_model_delegate.cc
@@ -28,8 +28,7 @@ #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS) -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" -#include "components/supervised_user/core/browser/supervised_user_service.h" +#include "components/supervised_user/core/browser/supervised_user_preferences.h" #endif #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) @@ -214,14 +213,8 @@ bool ChromeBrowsingDataModelDelegate::IsCookieDeletionDisabled( const GURL& url) { #if BUILDFLAG(ENABLE_SUPERVISED_USERS) - supervised_user::SupervisedUserService* supervised_user_service = - SupervisedUserServiceFactory::GetForBrowserContext(profile_); - if (!supervised_user_service) { - // For some Profiles (e.g. Incognito), SupervisedUserService is not - // created. - return false; - } - return supervised_user_service->IsCookieDeletionDisabled(url); + CHECK(profile_); + return supervised_user::IsCookieDeletionDisabled(url, *profile_->GetPrefs()); #elif BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS_ASH) if (profile_->IsChild()) { auto* client = permissions::PermissionsClient::Get();
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc index 01b18f8..05b83b1 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate_unittest.cc
@@ -122,9 +122,9 @@ #include "components/omnibox/common/omnibox_features.h" #include "components/os_crypt/sync/os_crypt_mocker.h" #include "components/password_manager/core/browser/features/password_features.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" -#include "components/password_manager/core/browser/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_store/password_store_consumer.h" #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "components/payments/content/mock_payment_manifest_web_data_service.h"
diff --git a/chrome/browser/browsing_data/cookies_tree_model.cc b/chrome/browser/browsing_data/cookies_tree_model.cc index d4c4760..6f48a846 100644 --- a/chrome/browser/browsing_data/cookies_tree_model.cc +++ b/chrome/browser/browsing_data/cookies_tree_model.cc
@@ -67,9 +67,9 @@ #endif #if BUILDFLAG(ENABLE_SUPERVISED_USERS) -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" -#include "components/supervised_user/core/browser/supervised_user_service.h" +#include "components/supervised_user/core/browser/supervised_user_preferences.h" #endif + namespace { struct NodeTitleComparator { @@ -1702,16 +1702,9 @@ supervised_user::kClearingCookiesKeepsSupervisedUsersSignedIn)) { #if BUILDFLAG(ENABLE_SUPERVISED_USERS) return base::BindRepeating( - [](content::BrowserContext* browser_context, const GURL& url) { - supervised_user::SupervisedUserService* supervised_user_service = - SupervisedUserServiceFactory::GetForBrowserContext( - browser_context); - if (!supervised_user_service) { - // For some Profiles (eg. Incognito), SupervisedUserService is not - // created. - return false; - } - return supervised_user_service->IsCookieDeletionDisabled(url); + [](Profile* profile, const GURL& url) { + return profile && supervised_user::IsCookieDeletionDisabled( + url, *profile->GetPrefs()); }, profile); #else
diff --git a/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc b/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc index 4f0fe51..163cc3642 100644 --- a/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc +++ b/chrome/browser/browsing_data/counters/downloads_counter_browsertest.cc
@@ -59,6 +59,9 @@ void TearDownOnMainThread() override { history_->RemoveObserver(this); + history_ = nullptr; + otr_manager_ = nullptr; + manager_ = nullptr; } // Adding and removing download items. --------------------------------------- @@ -106,8 +109,8 @@ download::DownloadItem::DownloadState state, download::DownloadDangerType danger, download::DownloadInterruptReason reason) { - std::string guid = AddDownloadInternal( - state, danger, reason, GURL(), std::string(), false); + std::string guid = AddDownloadInternal(state, danger, reason, GURL(), + std::string(), false); guids_to_add_.insert(guid); return guid; } @@ -164,32 +167,38 @@ void OnDownloadStored(download::DownloadItem* item, const history::DownloadRow& info) override { // Ignore any updates on items that we have already processed. - if (guids_to_add_.find(item->GetGuid()) == guids_to_add_.end()) + if (guids_to_add_.find(item->GetGuid()) == guids_to_add_.end()) { return; + } // DownloadHistory updates us before the item is actually written on // the history thread. Ignore this and wait until the item is actually // persisted. - if (!DownloadHistory::IsPersisted(item)) + if (!DownloadHistory::IsPersisted(item)) { return; + } guids_to_add_.erase(item->GetGuid()); - if (run_loop_ && guids_to_add_.empty()) + if (run_loop_ && guids_to_add_.empty()) { run_loop_->Quit(); + } } void OnDownloadsRemoved(const DownloadHistory::IdSet& ids) override { - for (uint32_t id : ids) + for (uint32_t id : ids) { ASSERT_EQ(1u, ids_to_remove_.erase(id)); + } - if (run_loop_ && ids_to_remove_.empty()) + if (run_loop_ && ids_to_remove_.empty()) { run_loop_->Quit(); + } } void WaitForDownloadHistory() { - if (guids_to_add_.empty() && ids_to_remove_.empty()) + if (guids_to_add_.empty() && ids_to_remove_.empty()) { return; + } DCHECK(!run_loop_ || !run_loop_->running()); run_loop_ = std::make_unique<base::RunLoop>(); @@ -228,9 +237,9 @@ // a set of IDs. std::set<uint32_t> ids_to_remove_; - raw_ptr<content::DownloadManager, DanglingUntriaged> manager_; - raw_ptr<content::DownloadManager, DanglingUntriaged> otr_manager_; - raw_ptr<DownloadHistory, DanglingUntriaged> history_; + raw_ptr<content::DownloadManager> manager_ = nullptr; + raw_ptr<content::DownloadManager> otr_manager_ = nullptr; + raw_ptr<DownloadHistory> history_ = nullptr; base::Time time_; int items_count_;
diff --git a/chrome/browser/chromeos/app_mode/kiosk_app_service_launcher_unittest.cc b/chrome/browser/chromeos/app_mode/kiosk_app_service_launcher_unittest.cc index 1a629bf..0adf31f 100644 --- a/chrome/browser/chromeos/app_mode/kiosk_app_service_launcher_unittest.cc +++ b/chrome/browser/chromeos/app_mode/kiosk_app_service_launcher_unittest.cc
@@ -81,6 +81,7 @@ void TearDown() override { publisher_.reset(); launcher_.reset(); + app_service_ = nullptr; BrowserWithTestWindowTest::TearDown(); } @@ -97,8 +98,7 @@ } apps::AppServiceTest app_service_test_; - raw_ptr<apps::AppServiceProxy, DanglingUntriaged | ExperimentalAsh> - app_service_ = nullptr; + raw_ptr<apps::AppServiceProxy, ExperimentalAsh> app_service_ = nullptr; std::unique_ptr<FakePublisher> publisher_; std::unique_ptr<KioskAppServiceLauncher> launcher_;
diff --git a/chrome/browser/chromeos/cros_apps/BUILD.gn b/chrome/browser/chromeos/cros_apps/BUILD.gn index eda3f67d..b435c5f4 100644 --- a/chrome/browser/chromeos/cros_apps/BUILD.gn +++ b/chrome/browser/chromeos/cros_apps/BUILD.gn
@@ -17,6 +17,7 @@ ] deps = [ + "//chrome/browser/chromeos/cros_apps/api", "//chrome/browser/profiles:profile", "//chromeos/constants:constants", "//components/keyed_service/content", @@ -35,23 +36,7 @@ public_deps = [ "//content/test:test_support" ] } -source_set("browser_tests") { - testonly = true - defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] - - sources = [ "cros_apps_tab_helper_browsertest.cc" ] - - deps = [ - ":test_support", - "//chrome/test:test_support", - "//chromeos/constants", - ] -} - group("all_browser_tests") { testonly = true - deps = [ - "//chrome/browser/chromeos/cros_apps:browser_tests", - "//chrome/browser/chromeos/cros_apps/api:browser_tests", - ] + deps = [ "//chrome/browser/chromeos/cros_apps/api:browser_tests" ] }
diff --git a/chrome/browser/chromeos/cros_apps/api/BUILD.gn b/chrome/browser/chromeos/cros_apps/api/BUILD.gn index 313c9fe..1b90b6ad 100644 --- a/chrome/browser/chromeos/cros_apps/api/BUILD.gn +++ b/chrome/browser/chromeos/cros_apps/api/BUILD.gn
@@ -10,8 +10,8 @@ testonly = true sources = [ + "cros_apps_api_access_control_browsertest.cc", "cros_apps_blink_runtime_feature_browsertest.cc", - "cros_apps_chromeos_apitest.cc", ] defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] @@ -19,10 +19,36 @@ deps = [ "//chrome/browser/chromeos/cros_apps:test_support", "//chrome/browser/chromeos/cros_apps/api/test:apitest_support", + "//chrome/browser/profiles:profile", "//chrome/browser/ui", + "//chrome/common", "//chromeos/constants", "//content/test:browsertest_support", "//content/test:test_support", "//testing/gtest", ] } + +source_set("api") { + sources = [ + "cros_apps_api_info.cc", + "cros_apps_api_info.h", + "cros_apps_api_infos.cc", + "cros_apps_api_infos.h", + "cros_apps_api_mutable_registry.cc", + "cros_apps_api_mutable_registry.h", + "cros_apps_api_registry.cc", + "cros_apps_api_registry.h", + "cros_apps_api_utils.cc", + "cros_apps_api_utils.h", + ] + + deps = [ + "//chrome/browser/profiles:profile", + "//chrome/common", + "//chromeos/constants:constants", + "//content/public/browser", + "//content/public/common", + "//services/network/public/cpp", + ] +}
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_access_control_browsertest.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_access_control_browsertest.cc new file mode 100644 index 0000000..2ad9a25 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_access_control_browsertest.cc
@@ -0,0 +1,350 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/scoped_feature_list.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h" +#include "chrome/browser/chromeos/cros_apps/cros_apps_test_utils.h" +#include "chrome/browser/profiles/profile.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 "chromeos/constants/chromeos_features.h" +#include "content/public/browser/navigation_handle.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "net/dns/mock_host_resolver.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_context.h" +#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h" + +class CrosAppsApiAccessControlBrowsertestBase : public InProcessBrowserTest { + public: + CrosAppsApiAccessControlBrowsertestBase() { + features_.InitAndEnableFeature({chromeos::features::kBlinkExtension}); + } + + CrosAppsApiAccessControlBrowsertestBase( + const CrosAppsApiAccessControlBrowsertestBase&) = delete; + CrosAppsApiAccessControlBrowsertestBase& operator=( + const CrosAppsApiAccessControlBrowsertestBase&) = delete; + + ~CrosAppsApiAccessControlBrowsertestBase() override = default; + + void SetUpOnMainThread() override { + net::EmbeddedTestServer::ServerCertificateConfig cert_config; + cert_config.dns_names = {std::string(kFooHost), std::string(kBarHost)}; + https_server_.SetSSLConfig(cert_config); + https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir()); + ASSERT_TRUE(https_server_.Start()); + + host_resolver()->AddRule("*", "127.0.0.1"); + } + + net::EmbeddedTestServer& test_server() { return https_server_; } + + protected: + void SetUpTestApi(const std::vector<url::Origin>& allowlisted_origins, + const std::initializer_list< + const std::reference_wrapper<const base::Feature>>& + required_features) { + CrosAppsApiMutableRegistry::GetInstance(browser()->profile()) + .AddOrReplaceForTesting(std::move( + CrosAppsApiInfo( + blink::mojom::RuntimeFeature::kBlinkExtensionDiagnostics, + &blink::RuntimeFeatureStateContext:: + SetBlinkExtensionDiagnosticsEnabled) + .AddAllowlistedOrigins(allowlisted_origins) + .SetRequiredFeatures(required_features))); + } + + bool IsTestApiExposed(const content::ToRenderFrameHost& to_rfh) { + return IsIdentifierDefined(to_rfh, "chromeos.diagnostics").ExtractBool(); + } + + bool IsChromeOSGlobalExposed(const content::ToRenderFrameHost& to_rfh) { + return IsIdentifierDefined(to_rfh, "chromeos").ExtractBool(); + } + + static constexpr char kFooHost[] = "foo.com"; + static constexpr char kBarHost[] = "bar.com"; + GURL KDataUrl = GURL("data:text/html,<body></body>"); + + private: + net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS}; + base::test::ScopedFeatureList features_; +}; + +// Test fixture with no base::Feature flags enabled. Mostly used for tests where +// the API doesn't require any feature flags. +using CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest = + CrosAppsApiAccessControlBrowsertestBase; + +IN_PROC_BROWSER_TEST_F(CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest, + EmptyAllowlistDoesNotEnableApi) { + SetUpTestApi(/*allowlisted_origins=*/{}, /*required_features=*/{}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/iframe.html"))); + // Main frame doesn't get the API. + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); + + // Child frame doesn't get the API. + auto* child_frame = + content::ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0); + ASSERT_TRUE(child_frame); + EXPECT_FALSE(IsChromeOSGlobalExposed(child_frame)); +} + +IN_PROC_BROWSER_TEST_F(CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest, + OnlyAllowlistedOriginHasApi) { + SetUpTestApi( + /*allowlisted_origins=*/{test_server().GetOrigin(kFooHost)}, + /*required_features=*/{}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The allowlisted origin get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/empty.html"))); + EXPECT_TRUE(IsTestApiExposed(web_contents)); + + // The non-allowlisted origin doesn't get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kBarHost, "/empty.html"))); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); +} + +IN_PROC_BROWSER_TEST_F(CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest, + OnlyEnableApiInMainFrame) { + SetUpTestApi( + /*allowlisted_origins=*/{test_server().GetOrigin(kFooHost)}, + /*required_features=*/{}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The allowlisted origin's top-level frame get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/iframe.html"))); + EXPECT_TRUE(IsTestApiExposed(web_contents)); + + // The allowlisted origin's child frame doesn't get the API. + auto* child_frame = + content::ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0); + ASSERT_TRUE(child_frame); + EXPECT_FALSE(IsChromeOSGlobalExposed(child_frame)); +} + +IN_PROC_BROWSER_TEST_F(CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest, + AllowlistedOriginIsGatedByBaseFeature) { + SetUpTestApi( + /*allowlisted_origin*/ {test_server().GetOrigin(kFooHost)}, + /*required_features=*/{chromeos::features::kBlinkExtensionDiagnostics}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The allowlisted origin doesn't get the API when the API is gated by a + // base::Feature that's not enabled. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/empty.html"))); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); + + // The non-allowlisted origin doesn't get the API when the test API is gated + // by a base::Feature that's not enabled. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kBarHost, "/empty.html"))); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); +} + +IN_PROC_BROWSER_TEST_F(CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest, + DataUrlDoesNotHaveApi) { + SetUpTestApi( + /*allowlisted_origins=*/{test_server().GetOrigin(kFooHost)}, + /*required_features=*/{}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // Pages with an data: scheme shouldn't get the API. + ASSERT_TRUE(NavigateToURL(web_contents, KDataUrl)); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); +} + +IN_PROC_BROWSER_TEST_F(CrosAppsApiAccessControlWithNoFeatureFlagsBrowsertest, + BlobUrlDoesNotHaveApi) { + const auto kAllowlistedOrigin = test_server().GetOrigin(kFooHost); + SetUpTestApi( + /*allowlisted_origins=*/{kAllowlistedOrigin}, + /*required_features=*/{}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/empty.html"))); + ASSERT_TRUE(IsTestApiExposed(web_contents)); + + // Create a blob: URL that can be opened in another WebContents. + GURL blob_url = + GURL(content::EvalJs( + web_contents, + "URL.createObjectURL(new Blob(['<html><body></body></html>']));") + .ExtractString()); + ASSERT_TRUE(kAllowlistedOrigin.IsSameOriginWith(blob_url)); + + // Navigate to the blob URL in a new WebContents. + browser()->tab_strip_model()->AppendWebContents( + content::WebContents::Create( + content::WebContents::CreateParams(browser()->profile())), + /*foreground=*/true); + auto* blob_web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(NavigateToURL(blob_web_contents, blob_url)); + ASSERT_EQ(kAllowlistedOrigin, + blob_web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()); + + // Verify the API isn't enabled. + EXPECT_FALSE(IsChromeOSGlobalExposed(blob_web_contents)); +} + +// Test fixture that enabled the base::Feature corresponding to the test API. +// Mostly used for tests where the API requires a feature flag. +class CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest + : public CrosAppsApiAccessControlBrowsertestBase { + public: + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest() { + features_.InitAndEnableFeature( + chromeos::features::kBlinkExtensionDiagnostics); + } + + ~CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest() override = + default; + + protected: + base::test::ScopedFeatureList features_; +}; + +IN_PROC_BROWSER_TEST_F( + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest, + EmptyAllowlistDoesNotEnableApi) { + SetUpTestApi( + /*allowlisted_origins=*/{}, + /*required_features=*/{chromeos::features::kBlinkExtensionDiagnostics}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The top-level frame doesn't get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/iframe.html"))); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); + + // The child frame doesn't get the API. + auto* child_frame = + content::ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0); + ASSERT_TRUE(child_frame); + EXPECT_FALSE(IsChromeOSGlobalExposed(child_frame)); +} + +IN_PROC_BROWSER_TEST_F( + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest, + DataUrlDoesNotHaveApi) { + SetUpTestApi( + /*allowlisted_origins=*/{test_server().GetOrigin(kFooHost)}, + /*required_features=*/{chromeos::features::kBlinkExtensionDiagnostics}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // Page with an data: scheme doesn't get the API. + ASSERT_TRUE(NavigateToURL(web_contents, KDataUrl)); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); +} + +IN_PROC_BROWSER_TEST_F( + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest, + BlobUrlDoesNotHaveApi) { + const auto kAllowlistedOrigin = test_server().GetOrigin(kFooHost); + SetUpTestApi( + /*allowlisted_origins=*/{kAllowlistedOrigin}, + /*required_features=*/{chromeos::features::kBlinkExtensionDiagnostics}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/empty.html"))); + ASSERT_TRUE(IsTestApiExposed(web_contents)); + + // Create a blob: URL that can be opened in another WebContents. + GURL blob_url = + GURL(content::EvalJs( + web_contents, + "URL.createObjectURL(new Blob(['<html><body></body></html>']));") + .ExtractString()); + ASSERT_TRUE(kAllowlistedOrigin.IsSameOriginWith(blob_url)); + + // Navigate to the blob URL in a new WebContents. + browser()->tab_strip_model()->AppendWebContents( + content::WebContents::Create( + content::WebContents::CreateParams(browser()->profile())), + /*foreground=*/true); + auto* blob_web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(NavigateToURL(blob_web_contents, blob_url)); + ASSERT_EQ(kAllowlistedOrigin, + blob_web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()); + + // Verify the API isn't enabled. + EXPECT_FALSE(IsChromeOSGlobalExposed(blob_web_contents)); +} + +IN_PROC_BROWSER_TEST_F( + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest, + OnlyAllowlistedOriginHasApi) { + SetUpTestApi( + /*allowlisted_origins=*/{test_server().GetOrigin(kFooHost)}, + /*required_features=*/{chromeos::features::kBlinkExtensionDiagnostics}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The allowlisted origin get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/empty.html"))); + EXPECT_TRUE(IsTestApiExposed(web_contents)); + + // The non-allowlisted origin doesn't get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kBarHost, "/empty.html"))); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); +} + +IN_PROC_BROWSER_TEST_F( + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest, + OnlyEnableApiInMainFrame) { + SetUpTestApi( + /*allowlisted_origins=*/{test_server().GetOrigin(kFooHost)}, + /*required_features=*/{chromeos::features::kBlinkExtensionDiagnostics}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The allowlisted origin's top-level frame get the API. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/iframe.html"))); + EXPECT_TRUE(IsTestApiExposed(web_contents)); + + // The allowlisted origin's child frame doesn't get the API. + auto* child_frame = + content::ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0); + ASSERT_TRUE(child_frame); + EXPECT_FALSE(IsChromeOSGlobalExposed(child_frame)); +} + +IN_PROC_BROWSER_TEST_F( + CrosAppsApiAccessControlWithEnabledTestBaseFeatureBrowsertest, + ApiWithoutBaseFeatureRequirement) { + SetUpTestApi(/*allowlisted_origins=*/{}, /*required_features=*/{}); + + auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); + + // The API isn't enabled. + ASSERT_TRUE(NavigateToURL(web_contents, + test_server().GetURL(kFooHost, "/empty.html"))); + EXPECT_FALSE(IsChromeOSGlobalExposed(web_contents)); +}
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.cc new file mode 100644 index 0000000..8890c72 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.cc
@@ -0,0 +1,65 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <iterator> +#include <string_view> +#include <utility> + +#include "base/check.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.h" +#include "url/gurl.h" +#include "url/origin.h" + +CrosAppsApiInfo::CrosAppsApiInfo(blink::mojom::RuntimeFeature blink_feature, + EnableBlinkRuntimeFeatureFunction enable_fn) + : blink_feature_(blink_feature), + enable_blink_runtime_feature_fn_(enable_fn) {} + +CrosAppsApiInfo::CrosAppsApiInfo(CrosAppsApiInfo&&) = default; + +CrosAppsApiInfo& CrosAppsApiInfo::operator=(CrosAppsApiInfo&&) = default; + +CrosAppsApiInfo::~CrosAppsApiInfo() = default; + +CrosAppsApiInfo& CrosAppsApiInfo::AddAllowlistedOrigins( + std::initializer_list<std::string_view> additions) { + std::vector<url::Origin> new_origins; + new_origins.reserve(additions.size()); + + base::ranges::transform( + additions, std::back_inserter(new_origins), [](std::string_view str) { + auto ret = url::Origin::Create(GURL(str)); + CHECK(!ret.opaque()) + << "Matching origin (" << str << ") must be non-opaque."; + return ret; + }); + + AddAllowlistedOrigins(std::move(new_origins)); + return *this; +} + +CrosAppsApiInfo& CrosAppsApiInfo::AddAllowlistedOrigins( + const std::vector<url::Origin>& additions) { + for (const auto& origin : additions) { + CHECK(!origin.opaque()); + } + // For-loop with insert() is O(N^2) because we use a flat_set. + // Instead, merge two vectors then sort. + std::vector<url::Origin> merged_origins; + merged_origins.reserve(allowed_origins_.size() + additions.size()); + + base::ranges::copy(allowed_origins_, std::back_inserter(merged_origins)); + base::ranges::copy(additions, std::back_inserter(merged_origins)); + + allowed_origins_ = std::move(merged_origins); + return *this; +} + +CrosAppsApiInfo& CrosAppsApiInfo::SetRequiredFeatures( + std::initializer_list<const std::reference_wrapper<const base::Feature>> + features) { + required_features_ = decltype(required_features_)(features); + return *this; +}
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h new file mode 100644 index 0000000..968c4d5 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h
@@ -0,0 +1,86 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_INFO_H_ +#define CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_INFO_H_ + +#include <functional> +#include <initializer_list> +#include <string_view> +#include <vector> + +#include "base/containers/flat_set.h" +#include "base/feature_list.h" +#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_context.h" +#include "third_party/blink/public/mojom/runtime_feature_state//runtime_feature.mojom-forward.h" +#include "url/origin.h" + +// CrosAppsApiInfo carries information about a ChromeOS Apps API that's required +// for the rest of ChromeOS Apps system to function. +class CrosAppsApiInfo { + public: + using EnableBlinkRuntimeFeatureFunction = + void (blink::RuntimeFeatureStateContext::*)(bool); + + CrosAppsApiInfo(blink::mojom::RuntimeFeature blink_feature, + EnableBlinkRuntimeFeatureFunction enable_fn); + + CrosAppsApiInfo(const CrosAppsApiInfo&) = delete; + CrosAppsApiInfo& operator=(const CrosAppsApiInfo&) = delete; + + CrosAppsApiInfo(CrosAppsApiInfo&&); + CrosAppsApiInfo& operator=(CrosAppsApiInfo&&); + + ~CrosAppsApiInfo(); + + // `AddAllowlistedOrigins` adds `origins` to the list of origins where the API + // will be enabled. + CrosAppsApiInfo& AddAllowlistedOrigins( + std::initializer_list<std::string_view> origins); + CrosAppsApiInfo& AddAllowlistedOrigins( + const std::vector<url::Origin>& origins); + + // `SetRequiredFeatures` sets the list of `base::Feature`s that all need to be + // enabled for the API to be enabled. + // + // If `features` is an empty list (or this method isn't called), it means the + // API isn't gated behind any feature, and will be enabled if other conditions + // match (e.g. the origin is allowlisted). + CrosAppsApiInfo& SetRequiredFeatures( + std::initializer_list<const std::reference_wrapper<const base::Feature>> + features); + + // Returns the enum that represents the blink runtime feature of this API. + blink::mojom::RuntimeFeature blink_feature() const { return blink_feature_; } + + // Returns the function that should be called on RuntimeFeatureStateContext to + // enable the Blink runtime feature. + EnableBlinkRuntimeFeatureFunction enable_blink_runtime_feature_fn() const { + return enable_blink_runtime_feature_fn_; + } + + // Returns the list of origins that could have access to the API. + const base::flat_set<url::Origin>& allowed_origins() const { + return allowed_origins_; + } + + // Returns the list of `base::Feature`s that must all be enabled for the API + // to be enabled. + const std::vector<const std::reference_wrapper<const base::Feature>>& + required_features() const { + return required_features_; + } + + private: + blink::mojom::RuntimeFeature blink_feature_; + // TODO(b/309556977): Remove enablement function when Runtime Feature State + // supports a generic SetEnabled() method. + EnableBlinkRuntimeFeatureFunction enable_blink_runtime_feature_fn_; + + base::flat_set<url::Origin> allowed_origins_; + std::vector<const std::reference_wrapper<const base::Feature>> + required_features_; +}; + +#endif // CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_INFO_H_
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.cc new file mode 100644 index 0000000..efc1085 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.cc
@@ -0,0 +1,38 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.h" + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h" +#include "chromeos/constants/chromeos_features.h" +#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_context.h" +#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h" + +// TODO(b/309556977): Replace macro with something better once Runtime Feature +// State supports a generic SetEnabled() method. +#define DEFINE_CROS_APPS_API(api_list, name) \ + (list.emplace(list.end(), blink::mojom::RuntimeFeature::k##name, \ + CrosAppsApiInfo( \ + blink::mojom::RuntimeFeature::k##name, \ + &blink::RuntimeFeatureStateContext::Set##name##Enabled)) \ + ->second) + +std::vector<std::pair<blink::mojom::RuntimeFeature, CrosAppsApiInfo>> +CreateDefaultCrosAppsApiInfo() { + std::vector<std::pair<blink::mojom::RuntimeFeature, CrosAppsApiInfo>> list; + + DEFINE_CROS_APPS_API(list, BlinkExtensionDiagnostics) + .SetRequiredFeatures({chromeos::features::kBlinkExtensionDiagnostics}) + .AddAllowlistedOrigins({ + // Externally visible prototype hosting website. + "https://serve-dot-zipline.appspot.com/" + // System info viewer isolated app. + "isolated-app://" + "uwsszrmaowqmxw4f262x5jozzhe5bc4tefqfa5lado674o462aoaaaic/", + }); + + return list; +} + +#undef DEFINE_CROS_APPS_API
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.h b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.h new file mode 100644 index 0000000..a179021 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.h
@@ -0,0 +1,18 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_INFOS_H_ +#define CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_INFOS_H_ + +#include <utility> +#include <vector> + +#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom-forward.h" + +class CrosAppsApiInfo; + +std::vector<std::pair<blink::mojom::RuntimeFeature, CrosAppsApiInfo>> +CreateDefaultCrosAppsApiInfo(); + +#endif // CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_INFOS_H_
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.cc new file mode 100644 index 0000000..be57985 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.cc
@@ -0,0 +1,107 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h" + +#include <memory> + +#include "base/check_is_test.h" +#include "base/feature_list.h" +#include "base/ranges/algorithm.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_infos.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.h" +#include "chrome/browser/profiles/profile.h" +#include "content/public/browser/navigation_handle.h" +#include "url/gurl.h" +#include "url/origin.h" +#include "url/url_constants.h" + +const void* kUserDataKey = &kUserDataKey; + +// static +CrosAppsApiMutableRegistry& CrosAppsApiMutableRegistry::GetInstance( + Profile* profile) { + if (!profile->GetUserData(&kUserDataKey)) { + profile->SetUserData( + kUserDataKey, std::make_unique<CrosAppsApiMutableRegistry>(PassKey())); + } + + return *static_cast<CrosAppsApiMutableRegistry*>( + profile->GetUserData(&kUserDataKey)); +} + +CrosAppsApiMutableRegistry::~CrosAppsApiMutableRegistry() = default; + +CrosAppsApiMutableRegistry::CrosAppsApiMutableRegistry(PassKey) + : apis_(CreateDefaultCrosAppsApiInfo()) {} + +bool CrosAppsApiMutableRegistry::IsApiEnabledFor( + const CrosAppsApiInfo& api_info, + content::NavigationHandle* navigation_handle) const { + if (!navigation_handle->IsInPrimaryMainFrame()) { + // Only main frames can have access to APIs. + return false; + } + + const auto& url = navigation_handle->GetURL(); + + if (!IsUrlEligibleForCrosAppsApis(url)) { + return false; + } + + // TODO(b/311528206): Decide if this scheme check should be removed. + // + // The following schemes because they share the same origin as their creator + // (i.e. the App), and could cause problem during origin matching. + // + // The app could inadvertently create these URLs that serves third-party (from + // the App's perspective) untrustworthy content. Said third-party content + // probably shouldn't be treated as same origin as the app. + if (url.SchemeIs(url::kBlobScheme) || url.SchemeIs(url::kFileSystemScheme)) { + return false; + } + + const bool are_required_features_enabled = base::ranges::all_of( + api_info.required_features(), [](const auto& base_feature) { + return base::FeatureList::IsEnabled(base_feature); + }); + + if (!are_required_features_enabled) { + return false; + } + + const bool is_allowlisted_origin = base::ranges::any_of( + api_info.allowed_origins(), + [&url](const auto& origin) { return origin.IsSameOriginWith(url); }); + + if (!is_allowlisted_origin) { + return false; + } + + return true; +} + +std::vector<CrosAppsApiInfo::EnableBlinkRuntimeFeatureFunction> +CrosAppsApiMutableRegistry::GetBlinkFeatureEnablementFunctionsFor( + content::NavigationHandle* navigation_handle) const { + std::vector<CrosAppsApiInfo::EnableBlinkRuntimeFeatureFunction> fns; + fns.reserve(apis_.size()); + + for (const auto& [_, api] : apis_) { + if (IsApiEnabledFor(api, navigation_handle)) { + fns.push_back(api.enable_blink_runtime_feature_fn()); + } + } + + return fns; +} + +void CrosAppsApiMutableRegistry::AddOrReplaceForTesting( + CrosAppsApiInfo api_info) { + CHECK_IS_TEST(); + + auto key = api_info.blink_feature(); + apis_.insert_or_assign(key, std::move(api_info)); +}
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h new file mode 100644 index 0000000..5dbf7ff --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h
@@ -0,0 +1,45 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_MUTABLE_REGISTRY_H_ +#define CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_MUTABLE_REGISTRY_H_ + +#include "base/containers/flat_map.h" +#include "base/supports_user_data.h" +#include "base/types/pass_key.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.h" + +class Profile; +class CrosAppsApiInfo; + +// CrosAppsApiMutableRegistry stores and maintains information about ChromeOS +// Apps APIs, and implements the CrosAppsApiRegistry interface. +// +// Most caller should use CrosAppsApiRegistry instead. This class is intended +// for callers that really need to modify the API registry (e.g. performing +// browsertest setup). +class CrosAppsApiMutableRegistry : public CrosAppsApiRegistry, + public base::SupportsUserData::Data { + public: + static CrosAppsApiMutableRegistry& GetInstance(Profile* profile); + + using PassKey = base::PassKey<CrosAppsApiMutableRegistry>; + explicit CrosAppsApiMutableRegistry(PassKey passkey); + ~CrosAppsApiMutableRegistry() override; + + bool IsApiEnabledFor(const CrosAppsApiInfo& api_info, + content::NavigationHandle* navigation_handle) const; + void AddOrReplaceForTesting(CrosAppsApiInfo api_info); + + // CrosAppsApiRegistry: + std::vector<CrosAppsApiInfo::EnableBlinkRuntimeFeatureFunction> + GetBlinkFeatureEnablementFunctionsFor( + content::NavigationHandle* navigation_handle) const override; + + private: + base::flat_map<blink::mojom::RuntimeFeature, CrosAppsApiInfo> apis_; +}; + +#endif // CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_MUTABLE_REGISTRY_H_
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.cc new file mode 100644 index 0000000..e70a96f6 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.cc
@@ -0,0 +1,11 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.h" + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h" + +const CrosAppsApiRegistry& CrosAppsApiRegistry::GetInstance(Profile* profile) { + return CrosAppsApiMutableRegistry::GetInstance(profile); +}
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.h b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.h new file mode 100644 index 0000000..f24c30ff --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.h
@@ -0,0 +1,40 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_REGISTRY_H_ +#define CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_REGISTRY_H_ + +#include <string_view> + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h" +#include "third_party/blink/public/common/runtime_feature_state/runtime_feature_state_context.h" +#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom-forward.h" + +class Profile; +namespace content { +class NavigationHandle; +} + +// CrosAppsApiRegistry provides an read-only interface to query access control +// information about ChromeOS Apps APIs. +// +// To perform security checks, use helper methods in CrosAppsApiAccessControl. +// To modify the registry, use CrosAppsApiMutableRegistry. +class CrosAppsApiRegistry { + public: + static const CrosAppsApiRegistry& GetInstance(Profile* profile); + + // Return a list of functions that should be called on + // RuntimeFeatureStateContext to enable the blink runtime features for a given + // `navigation_handle`. + // + // Calling the returned functions on the RuntimeFeatureStateContext associated + // with `navigation_handle` will enable the ChromeOS Apps APIs that should be + // enabled for the navigation_handle`. + virtual std::vector<CrosAppsApiInfo::EnableBlinkRuntimeFeatureFunction> + GetBlinkFeatureEnablementFunctionsFor( + content::NavigationHandle* navigation_handle) const = 0; +}; + +#endif // CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_REGISTRY_H_
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.cc new file mode 100644 index 0000000..dfe6d41 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.cc
@@ -0,0 +1,12 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.h" + +#include "services/network/public/cpp/is_potentially_trustworthy.h" +#include "url/gurl.h" + +bool IsUrlEligibleForCrosAppsApis(const GURL& url) { + return network::IsUrlPotentiallyTrustworthy(url); +}
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.h b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.h new file mode 100644 index 0000000..cd8a0474 --- /dev/null +++ b/chrome/browser/chromeos/cros_apps/api/cros_apps_api_utils.h
@@ -0,0 +1,13 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_UTILS_H_ +#define CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_UTILS_H_ + +class GURL; + +// Returns whether `url` is eligible for ChromeOS Apps APIs. +bool IsUrlEligibleForCrosAppsApis(const GURL& url); + +#endif // CHROME_BROWSER_CHROMEOS_CROS_APPS_API_CROS_APPS_API_UTILS_H_
diff --git a/chrome/browser/chromeos/cros_apps/api/cros_apps_chromeos_apitest.cc b/chrome/browser/chromeos/cros_apps/api/cros_apps_chromeos_apitest.cc deleted file mode 100644 index 72e24690..0000000 --- a/chrome/browser/chromeos/cros_apps/api/cros_apps_chromeos_apitest.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/chromeos/cros_apps/api/test/cros_apps_apitest.h" -#include "chrome/browser/ui/browser.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "testing/gtest/include/gtest/gtest.h" - -using CrosAppsChromeosApiTest = CrosAppsApiTest; - -IN_PROC_BROWSER_TEST_F(CrosAppsChromeosApiTest, ChromeosExists) { - content::WebContents* web_contents = - browser()->tab_strip_model()->GetActiveWebContents(); - - EXPECT_EQ(true, content::EvalJs(web_contents, - "typeof window.chromeos !== 'undefined';")); -}
diff --git a/chrome/browser/chromeos/cros_apps/api/test/BUILD.gn b/chrome/browser/chromeos/cros_apps/api/test/BUILD.gn index d5c3b11c..cefa576d 100644 --- a/chrome/browser/chromeos/cros_apps/api/test/BUILD.gn +++ b/chrome/browser/chromeos/cros_apps/api/test/BUILD.gn
@@ -17,7 +17,9 @@ deps = [ "//chromeos/constants" ] public_deps = [ + "//chrome/browser/chromeos/cros_apps/api", "//chrome/test:test_support_ui", "//testing/gtest", + "//third_party/blink/public/mojom/runtime_feature_state", ] }
diff --git a/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper.cc b/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper.cc index 2210ccc..3532a887 100644 --- a/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper.cc +++ b/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper.cc
@@ -6,6 +6,9 @@ #include <memory> +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_info.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_registry.h" +#include "chrome/browser/profiles/profile.h" #include "chromeos/constants/chromeos_features.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/web_contents.h" @@ -34,21 +37,22 @@ void CrosAppsTabHelper::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { - if (!navigation_handle->IsInPrimaryMainFrame()) { + Profile* profile = Profile::FromBrowserContext( + navigation_handle->GetWebContents()->GetBrowserContext()); + + auto enable_fns = + CrosAppsApiRegistry::GetInstance(profile) + .GetBlinkFeatureEnablementFunctionsFor(navigation_handle); + + if (enable_fns.empty()) { return; } - // TODO(b/295267987): Check `navigation_handle` is for a ChromeOS Apps and - // set features accordingly. - - if (chromeos::features::IsBlinkExtensionEnabled()) { - navigation_handle->GetMutableRuntimeFeatureStateContext() - .SetBlinkExtensionChromeOSEnabled(true); - } - - if (chromeos::features::IsBlinkExtensionDiagnosticsEnabled()) { - navigation_handle->GetMutableRuntimeFeatureStateContext() - .SetBlinkExtensionDiagnosticsEnabled(true); + auto& runtime_feature_state_context = + navigation_handle->GetMutableRuntimeFeatureStateContext(); + runtime_feature_state_context.SetBlinkExtensionChromeOSEnabled(true); + for (const auto& enable_fn : enable_fns) { + (runtime_feature_state_context.*enable_fn)(true); } }
diff --git a/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper_browsertest.cc b/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper_browsertest.cc deleted file mode 100644 index 0a2284f..0000000 --- a/chrome/browser/chromeos/cros_apps/cros_apps_tab_helper_browsertest.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/test/scoped_feature_list.h" -#include "chrome/browser/chromeos/cros_apps/cros_apps_test_utils.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 "chromeos/constants/chromeos_features.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/browser_test.h" -#include "content/public/test/browser_test_utils.h" -#include "net/test/embedded_test_server/embedded_test_server.h" -#include "testing/gtest/include/gtest/gtest.h" - -class CrosAppsTabHelperBrowserTest : public InProcessBrowserTest { - public: - CrosAppsTabHelperBrowserTest() { - scoped_feature_list_.InitWithFeatures({chromeos::features::kBlinkExtension}, - {}); - } - CrosAppsTabHelperBrowserTest(const CrosAppsTabHelperBrowserTest&) = delete; - CrosAppsTabHelperBrowserTest& operator=(const CrosAppsTabHelperBrowserTest&) = - delete; - ~CrosAppsTabHelperBrowserTest() override = default; - - void SetUpOnMainThread() override { - ASSERT_TRUE(embedded_test_server()->Start()); - } - - private: - base::test::ScopedFeatureList scoped_feature_list_; -}; - -IN_PROC_BROWSER_TEST_F(CrosAppsTabHelperBrowserTest, EnableFeatureInMainFrame) { - ASSERT_TRUE(chromeos::features::IsBlinkExtensionEnabled()); - - auto* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - NavigateToURLBlockUntilNavigationsComplete( - web_contents, embedded_test_server()->GetURL("/iframe.html"), - /*num_of_navigations*/ 1); - - EXPECT_EQ(true, IsIdentifierDefined(web_contents, "window.chromeos")); - auto* child_frame = - content::ChildFrameAt(web_contents->GetPrimaryMainFrame(), 0); - ASSERT_TRUE(child_frame); - EXPECT_EQ(false, IsIdentifierDefined(child_frame, "window.chromeos")); -}
diff --git a/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc b/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc index 80c04f0..c958b3d 100644 --- a/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc +++ b/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc
@@ -23,8 +23,8 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/test_browser_window.h" #include "chrome/test/base/testing_browser_process.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/sessions/content/session_tab_helper.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_entry.h"
diff --git a/chrome/browser/lacros/cros_apps/api/diagnostics/cros_apps_diagnostics_apitest.cc b/chrome/browser/lacros/cros_apps/api/diagnostics/cros_apps_diagnostics_apitest.cc index 181443b..b7ce083 100644 --- a/chrome/browser/lacros/cros_apps/api/diagnostics/cros_apps_diagnostics_apitest.cc +++ b/chrome/browser/lacros/cros_apps/api/diagnostics/cros_apps_diagnostics_apitest.cc
@@ -7,25 +7,44 @@ #include "base/system/sys_info.h" #include "base/test/test_future.h" #include "base/threading/thread_restrictions.h" +#include "chrome/browser/chromeos/cros_apps/api/cros_apps_api_mutable_registry.h" #include "chrome/browser/chromeos/cros_apps/api/test/cros_apps_apitest.h" #include "chrome/browser/chromeos/telemetry/fake_probe_service.h" #include "chrome/browser/ui/browser.h" +#include "chrome/test/base/ui_test_utils.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/lacros/lacros_service.h" #include "content/public/browser/network_service_instance.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/content_switches.h" #include "content/public/test/browser_test.h" #include "services/network/public/mojom/network_service.mojom.h" #include "testing/gtest/include/gtest/gtest.h" class CrosAppsDiagnosticsApiTest : public CrosAppsApiTest { public: - CrosAppsDiagnosticsApiTest() : CrosAppsApiTest() { + CrosAppsDiagnosticsApiTest() { scoped_feature_list_.InitAndEnableFeature( chromeos::features::kBlinkExtensionDiagnostics); } + void SetUpOnMainThread() override { + CrosAppsApiTest::SetUpOnMainThread(); + + ASSERT_TRUE(embedded_test_server()->Start()); + + CrosAppsApiMutableRegistry::GetInstance(browser()->profile()) + .AddOrReplaceForTesting(std::move( + CrosAppsApiInfo( + blink::mojom::RuntimeFeature::kBlinkExtensionDiagnostics, + &blink::RuntimeFeatureStateContext:: + SetBlinkExtensionDiagnosticsEnabled) + .AddAllowlistedOrigins({embedded_test_server()->GetOrigin()}))); + + ASSERT_TRUE( + NavigateToURL(browser()->tab_strip_model()->GetActiveWebContents(), + embedded_test_server()->GetURL("/empty.html"))); + } + protected: void SetProbeServiceForTesting( std::unique_ptr<chromeos::FakeProbeService> service) {
diff --git a/chrome/browser/lacros/lacros_extension_apps_publisher.cc b/chrome/browser/lacros/lacros_extension_apps_publisher.cc index b1012b9af..c6fb72b 100644 --- a/chrome/browser/lacros/lacros_extension_apps_publisher.cc +++ b/chrome/browser/lacros/lacros_extension_apps_publisher.cc
@@ -340,6 +340,8 @@ app->allow_uninstall = (policy->UserMayModifySettings(extension, nullptr) && !policy->MustRemainInstalled(extension, nullptr)); + app->allow_close = true; + // Add file_handlers for either of the following: // a) Chrome Apps and quickoffice. // b) Web File Handlers or file_browser_handler for Extensions.
diff --git a/chrome/browser/password_manager/android/built_in_backend_to_android_backend_migrator_unittest.cc b/chrome/browser/password_manager/android/built_in_backend_to_android_backend_migrator_unittest.cc index c7a6a3a..b1ac122 100644 --- a/chrome/browser/password_manager/android/built_in_backend_to_android_backend_migrator_unittest.cc +++ b/chrome/browser/password_manager/android/built_in_backend_to_android_backend_migrator_unittest.cc
@@ -12,8 +12,8 @@ #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include "components/password_manager/core/browser/password_store/mock_password_store_backend.h" #include "components/password_manager/core/browser/password_store/password_store_backend.h" #include "components/password_manager/core/common/password_manager_features.h"
diff --git a/chrome/browser/password_manager/android/password_accessory_controller_impl_unittest.cc b/chrome/browser/password_manager/android/password_accessory_controller_impl_unittest.cc index 4bb6c1f..4410c691 100644 --- a/chrome/browser/password_manager/android/password_accessory_controller_impl_unittest.cc +++ b/chrome/browser/password_manager/android/password_accessory_controller_impl_unittest.cc
@@ -32,11 +32,11 @@ #include "components/password_manager/content/browser/content_password_manager_driver_factory.h" #include "components/password_manager/core/browser/credential_cache.h" #include "components/password_manager/core/browser/features/password_features.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/mock_webauthn_credentials_delegate.h" #include "components/password_manager/core/browser/origin_credential_store.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/test_password_store.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h"
diff --git a/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc b/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc index f56f6b6..e145b92 100644 --- a/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc +++ b/chrome/browser/password_manager/android/password_generation_controller_impl_unittest.cc
@@ -26,11 +26,11 @@ #include "components/autofill/core/browser/ui/accessory_sheet_enums.h" #include "components/autofill/core/common/password_generation_util.h" #include "components/password_manager/content/browser/content_password_manager_driver.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_autofill_manager.h" #include "components/password_manager/core/browser/password_generation_frame_helper.h" #include "components/password_manager/core/browser/password_manager.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h" #include "components/password_manager/core/common/password_manager_features.h"
diff --git a/chrome/browser/password_manager/android/password_migration_warning_startup_launcher_unittest.cc b/chrome/browser/password_manager/android/password_migration_warning_startup_launcher_unittest.cc index f0d7e8e..1f3ce8a3 100644 --- a/chrome/browser/password_manager/android/password_migration_warning_startup_launcher_unittest.cc +++ b/chrome/browser/password_manager/android/password_migration_warning_startup_launcher_unittest.cc
@@ -12,7 +12,7 @@ #include "chrome/browser/password_manager/password_manager_test_util.h" #include "chrome/test/base/chrome_render_view_host_test_harness.h" #include "chrome/test/base/testing_profile.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "components/password_manager/core/browser/password_store/test_password_store.h" #include "components/password_manager/core/common/password_manager_features.h"
diff --git a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc index 3293330..5b701559 100644 --- a/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc +++ b/chrome/browser/password_manager/chrome_password_manager_client_unittest.cc
@@ -50,10 +50,10 @@ #include "components/password_manager/core/browser/credential_cache.h" #include "components/password_manager/core/browser/credentials_filter.h" #include "components/password_manager/core/browser/mock_password_manager_settings_service.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/password_store_consumer.h" #include "components/safe_browsing/buildflags.h" #include "components/safe_browsing/core/common/features.h"
diff --git a/chrome/browser/password_manager/password_manager_captured_sites_interactive_uitest.cc b/chrome/browser/password_manager/password_manager_captured_sites_interactive_uitest.cc index 0fcfabb..9a0c021b 100644 --- a/chrome/browser/password_manager/password_manager_captured_sites_interactive_uitest.cc +++ b/chrome/browser/password_manager/password_manager_captured_sites_interactive_uitest.cc
@@ -20,9 +20,9 @@ #include "chrome/browser/ui/tab_dialogs.h" #include "components/autofill/core/common/autofill_features.h" #include "components/autofill/core/common/autofill_switches.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/safe_browsing/core/common/safe_browsing_prefs.h" #include "components/sync/test/test_sync_service.h"
diff --git a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc index 3caa5bf8..bff7a30 100644 --- a/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc +++ b/chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.cc
@@ -486,6 +486,11 @@ #include "chrome/browser/offline_pages/request_coordinator_factory.h" #endif +#if BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE) +// A ChromeOS build for a dev linux machine. +#include "chrome/browser/smart_card/fake_smart_card_device_service_factory.h" +#endif + namespace chrome { void AddProfilesExtraParts(ChromeBrowserMainParts* main_parts) { @@ -770,6 +775,11 @@ #if BUILDFLAG(ENABLE_SESSION_SERVICE) ExitTypeServiceFactory::GetInstance(); #endif +#if BUILDFLAG(IS_CHROMEOS) && !BUILDFLAG(IS_CHROMEOS_DEVICE) + // A ChromeOS build for a dev linux machine. + // Makes manual testing possible. + FakeSmartCardDeviceServiceFactory::GetInstance(); +#endif #if BUILDFLAG(IS_ANDROID) FastCheckoutCapabilitiesFetcherFactory::GetInstance(); #endif
diff --git a/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc b/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc index e524650c..fe62d8f 100644 --- a/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc +++ b/chrome/browser/renderer_context_menu/render_view_context_menu_unittest.cc
@@ -56,8 +56,8 @@ #include "components/feed/feed_feature_list.h" #include "components/lens/buildflags.h" #include "components/lens/lens_features.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/policy/core/common/policy_pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h"
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc index c385a3fc..3a8aa69d 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_browsertest.cc
@@ -26,12 +26,12 @@ #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" #include "components/password_manager/core/browser/hash_password_manager.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_reuse_manager.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include "components/password_manager/core/browser/ui/password_check_referrer.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/password_manager/core/common/password_manager_pref_names.h"
diff --git a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc index 4edce5d..a56c1a2a 100644 --- a/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc +++ b/chrome/browser/safe_browsing/chrome_password_protection_service_unittest.cc
@@ -35,10 +35,10 @@ #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/password_manager/core/browser/features/password_features.h" #include "components/password_manager/core/browser/hash_password_manager.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_reuse_detector.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/safe_browsing/content/browser/password_protection/password_protection_commit_deferring_condition.h"
diff --git a/chrome/browser/smart_card/BUILD.gn b/chrome/browser/smart_card/BUILD.gn index d57bb94..2cec83b 100644 --- a/chrome/browser/smart_card/BUILD.gn +++ b/chrome/browser/smart_card/BUILD.gn
@@ -2,14 +2,31 @@ # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. +import("//build/config/chromeos/args.gni") + source_set("smart_card") { if (is_chromeos) { sources = [ "chromeos_smart_card_delegate.cc", "chromeos_smart_card_delegate.h", + "get_smart_card_context_factory.cc", + "get_smart_card_context_factory.h", ] + + if (!is_chromeos_device) { + # When making a chromeos build for a dev linux machine, use a fake smart + # card device service to make manual testing during development possible. + sources += [ + "fake_smart_card_device_service.cc", + "fake_smart_card_device_service.h", + "fake_smart_card_device_service_factory.cc", + "fake_smart_card_device_service_factory.h", + ] + } + deps = [ "//chrome/browser/chromeos/extensions/smart_card_provider_private", + "//chrome/browser/profiles:profile", "//content/public/browser:browser", ] }
diff --git a/chrome/browser/smart_card/chromeos_smart_card_delegate.cc b/chrome/browser/smart_card/chromeos_smart_card_delegate.cc index 92d1c575..c8888a7 100644 --- a/chrome/browser/smart_card/chromeos_smart_card_delegate.cc +++ b/chrome/browser/smart_card/chromeos_smart_card_delegate.cc
@@ -3,15 +3,14 @@ // found in the LICENSE file. #include "chrome/browser/smart_card/chromeos_smart_card_delegate.h" -#include "chrome/browser/chromeos/extensions/smart_card_provider_private/smart_card_provider_private_api.h" +#include "chrome/browser/smart_card/get_smart_card_context_factory.h" ChromeOsSmartCardDelegate::ChromeOsSmartCardDelegate() = default; mojo::PendingRemote<device::mojom::SmartCardContextFactory> ChromeOsSmartCardDelegate::GetSmartCardContextFactory( content::BrowserContext& browser_context) { - return extensions::SmartCardProviderPrivateAPI::Get(browser_context) - .GetSmartCardContextFactory(); + return ::GetSmartCardContextFactory(browser_context); } bool ChromeOsSmartCardDelegate::HasReaderPermission(
diff --git a/chrome/browser/smart_card/fake_smart_card_device_service.cc b/chrome/browser/smart_card/fake_smart_card_device_service.cc new file mode 100644 index 0000000..5348655 --- /dev/null +++ b/chrome/browser/smart_card/fake_smart_card_device_service.cc
@@ -0,0 +1,211 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/smart_card/fake_smart_card_device_service.h" +#include "base/containers/map_util.h" + +namespace { +using device::mojom::SmartCardConnectResult; +using device::mojom::SmartCardContext; +using device::mojom::SmartCardCreateContextResult; +using device::mojom::SmartCardCreateContextResultPtr; +using device::mojom::SmartCardError; +using device::mojom::SmartCardListReadersResult; +using device::mojom::SmartCardReaderStateFlags; +using device::mojom::SmartCardReaderStateIn; +using device::mojom::SmartCardReaderStateInPtr; +using device::mojom::SmartCardReaderStateOut; +using device::mojom::SmartCardReaderStateOutPtr; +using device::mojom::SmartCardResult; +using device::mojom::SmartCardStatusChangeResult; +using device::mojom::SmartCardSuccess; + +constexpr char kFooReader[] = "Foo Reader"; +constexpr char kAcmeReader[] = "Acme Reader"; + +bool StateHasChanged(const SmartCardReaderStateOut& state_out, + const SmartCardReaderStateIn& state_in) { + // Try the easy cases first: + + if (state_in.current_state->unaware) { + return true; + } + + if (state_in.current_count != state_out.event_count) { + return true; + } + + // And only then go for a full diff: + const SmartCardReaderStateFlags& flags_in = *state_in.current_state; + const SmartCardReaderStateFlags& flags_out = *state_out.event_state; + // clang-format off + return flags_in.unknown != flags_out.unknown || + flags_in.unavailable != flags_out.unavailable || + flags_in.empty != flags_out.empty || + flags_in.present != flags_out.present || + flags_in.exclusive != flags_out.exclusive || + flags_in.inuse != flags_out.inuse || + flags_in.mute != flags_out.mute || + flags_in.unpowered != flags_out.unpowered; + // clang-format on +} +} // anonymous namespace + +struct FakeSmartCardDeviceService::ReaderState { + bool unknown; + bool unavailable; + bool empty; + bool present; + bool exclusive; + bool inuse; + bool mute; + bool unpowered; + + uint16_t event_count; +}; + +struct FakeSmartCardDeviceService::PendingStatusChange { + PendingStatusChange(std::vector<SmartCardReaderStateInPtr> reader_states, + SmartCardContext::GetStatusChangeCallback callback) + : reader_states(std::move(reader_states)), + callback(std::move(callback)) {} + + ~PendingStatusChange() = default; + + std::vector<SmartCardReaderStateInPtr> reader_states; + SmartCardContext::GetStatusChangeCallback callback; +}; + +FakeSmartCardDeviceService::FakeSmartCardDeviceService() { + readers_[kFooReader] = {.empty = true}; + readers_[kAcmeReader] = {.present = true}; +} + +FakeSmartCardDeviceService::~FakeSmartCardDeviceService() = default; + +mojo::PendingRemote<device::mojom::SmartCardContextFactory> +FakeSmartCardDeviceService::GetSmartCardContextFactory() { + mojo::PendingRemote<device::mojom::SmartCardContextFactory> pending_remote; + context_factory_receivers_.Add( + this, pending_remote.InitWithNewPipeAndPassReceiver()); + return pending_remote; +} + +void FakeSmartCardDeviceService::CreateContext(CreateContextCallback callback) { + mojo::PendingRemote<SmartCardContext> context_remote; + context_receivers_.Add(this, context_remote.InitWithNewPipeAndPassReceiver()); + + std::move(callback).Run( + SmartCardCreateContextResult::NewContext(std::move(context_remote))); +} + +void FakeSmartCardDeviceService::ListReaders(ListReadersCallback callback) { + std::vector<std::string> names; + for (const auto& [name, state] : readers_) { + names.push_back(name); + } + std::move(callback).Run(SmartCardListReadersResult::NewReaders(names)); +} + +void FakeSmartCardDeviceService::GetStatusChange( + base::TimeDelta timeout, + std::vector<device::mojom::SmartCardReaderStateInPtr> reader_states, + GetStatusChangeCallback callback) { + pending_status_changes_.push_back(std::make_unique<PendingStatusChange>( + std::move(reader_states), std::move(callback))); + + TryResolvePendingStatusChanges(); +} + +void FakeSmartCardDeviceService::Cancel(CancelCallback callback) { + auto pending_list = std::move(pending_status_changes_); + for (auto& pending_change : pending_list) { + std::move(pending_change->callback) + .Run(SmartCardStatusChangeResult::NewError(SmartCardError::kCancelled)); + } + + std::move(callback).Run(SmartCardResult::NewSuccess(SmartCardSuccess::kOk)); +} + +void FakeSmartCardDeviceService::Connect( + const std::string& reader, + device::mojom::SmartCardShareMode share_mode, + device::mojom::SmartCardProtocolsPtr preferred_protocols, + ConnectCallback callback) { + std::move(callback).Run( + SmartCardConnectResult::NewError(SmartCardError::kUnresponsiveCard)); +} + +void FakeSmartCardDeviceService::TryResolvePendingStatusChanges() { + std::erase_if(pending_status_changes_, + [this](std::unique_ptr<PendingStatusChange>& p) { + return TryResolve(*p); + }); +} + +bool FakeSmartCardDeviceService::TryResolve( + PendingStatusChange& pending_status_change) { + std::vector<device::mojom::SmartCardReaderStateOutPtr> states_out; + + bool state_changed = false; + + for (const SmartCardReaderStateInPtr& state_in : + pending_status_change.reader_states) { + if (state_in->current_state->ignore) { + continue; + } + + const ReaderState* reader_state = + base::FindOrNull(readers_, state_in->reader); + auto state_out = SmartCardReaderStateOut::New(); + + if (reader_state) { + FillStateOut(*state_out, *state_in, *reader_state); + state_changed = state_out->event_state->changed; + } else { + // Inform that this reader is unknown. + auto flags = SmartCardReaderStateFlags::New(); + flags->unknown = true; + state_out->reader = state_in->reader; + state_out->event_state = std::move(flags); + state_changed = true; + } + + states_out.push_back(std::move(state_out)); + } + + if (state_changed) { + // We only finish an outstanding GetStatusChange() request if the current + // state of the readers is different from any of requests input states. + std::move(pending_status_change.callback) + .Run(SmartCardStatusChangeResult::NewReaderStates( + std::move(states_out))); + return true; + } + + return false; +} + +// static +void FakeSmartCardDeviceService::FillStateOut( + SmartCardReaderStateOut& state_out, + const SmartCardReaderStateIn& state_in, + const ReaderState& reader_state) { + state_out.reader = state_in.reader; + + state_out.event_state = SmartCardReaderStateFlags::New(); + + state_out.event_state->unknown = reader_state.unknown; + state_out.event_state->unavailable = reader_state.unavailable; + state_out.event_state->empty = reader_state.empty; + state_out.event_state->present = reader_state.present; + state_out.event_state->exclusive = reader_state.exclusive; + state_out.event_state->inuse = reader_state.inuse; + state_out.event_state->mute = reader_state.mute; + state_out.event_state->unpowered = reader_state.unpowered; + + state_out.event_count = reader_state.event_count; + + state_out.event_state->changed = StateHasChanged(state_out, state_in); +}
diff --git a/chrome/browser/smart_card/fake_smart_card_device_service.h b/chrome/browser/smart_card/fake_smart_card_device_service.h new file mode 100644 index 0000000..a14d92e --- /dev/null +++ b/chrome/browser/smart_card/fake_smart_card_device_service.h
@@ -0,0 +1,59 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_SMART_CARD_FAKE_SMART_CARD_DEVICE_SERVICE_H_ +#define CHROME_BROWSER_SMART_CARD_FAKE_SMART_CARD_DEVICE_SERVICE_H_ + +#include "components/keyed_service/core/keyed_service.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "services/device/public/mojom/smart_card.mojom.h" + +class FakeSmartCardDeviceService + : public KeyedService, + public device::mojom::SmartCardContextFactory, + public device::mojom::SmartCardContext { + public: + FakeSmartCardDeviceService(); + ~FakeSmartCardDeviceService() override; + + // device::mojom::SmartCardContextFactory overrides: + void CreateContext(CreateContextCallback) override; + + mojo::PendingRemote<device::mojom::SmartCardContextFactory> + GetSmartCardContextFactory(); + + private: + struct PendingStatusChange; + struct ReaderState; + + // device::mojom::SmartCardContext overrides: + void ListReaders(ListReadersCallback callback) override; + void GetStatusChange( + base::TimeDelta timeout, + std::vector<device::mojom::SmartCardReaderStateInPtr> reader_states, + GetStatusChangeCallback callback) override; + void Cancel(CancelCallback callback) override; + void Connect(const std::string& reader, + device::mojom::SmartCardShareMode share_mode, + device::mojom::SmartCardProtocolsPtr preferred_protocols, + ConnectCallback callback) override; + + void TryResolvePendingStatusChanges(); + bool TryResolve(PendingStatusChange& pending_status_change); + static void FillStateOut( + device::mojom::SmartCardReaderStateOut& state_out, + const device::mojom::SmartCardReaderStateIn& state_in, + const ReaderState& reader_state); + + mojo::ReceiverSet<device::mojom::SmartCardContextFactory> + context_factory_receivers_; + + mojo::ReceiverSet<device::mojom::SmartCardContext> context_receivers_; + + base::flat_map<std::string, ReaderState> readers_; + + std::vector<std::unique_ptr<PendingStatusChange>> pending_status_changes_; +}; + +#endif // CHROME_BROWSER_SMART_CARD_FAKE_SMART_CARD_DEVICE_SERVICE_H_
diff --git a/chrome/browser/smart_card/fake_smart_card_device_service_factory.cc b/chrome/browser/smart_card/fake_smart_card_device_service_factory.cc new file mode 100644 index 0000000..c3c67b79 --- /dev/null +++ b/chrome/browser/smart_card/fake_smart_card_device_service_factory.cc
@@ -0,0 +1,39 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/smart_card/fake_smart_card_device_service_factory.h" +#include "base/check_deref.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/smart_card/fake_smart_card_device_service.h" + +// static +FakeSmartCardDeviceServiceFactory& +FakeSmartCardDeviceServiceFactory::GetInstance() { + static base::NoDestructor<FakeSmartCardDeviceServiceFactory> factory; + return *factory; +} + +// static +FakeSmartCardDeviceService& FakeSmartCardDeviceServiceFactory::GetForProfile( + Profile& profile) { + auto* service = static_cast<FakeSmartCardDeviceService*>( + GetInstance().GetServiceForBrowserContext(&profile, /*create=*/true)); + return CHECK_DEREF(service); +} + +FakeSmartCardDeviceServiceFactory::FakeSmartCardDeviceServiceFactory() + : ProfileKeyedServiceFactory( + "FakeSmartCardDeviceService", + ProfileSelections::Builder() + .WithRegular(ProfileSelection::kOwnInstance) + .Build()) {} + +FakeSmartCardDeviceServiceFactory::~FakeSmartCardDeviceServiceFactory() = + default; + +std::unique_ptr<KeyedService> +FakeSmartCardDeviceServiceFactory::BuildServiceInstanceForBrowserContext( + content::BrowserContext* context) const { + return std::make_unique<FakeSmartCardDeviceService>(); +}
diff --git a/chrome/browser/smart_card/fake_smart_card_device_service_factory.h b/chrome/browser/smart_card/fake_smart_card_device_service_factory.h new file mode 100644 index 0000000..e874be4c --- /dev/null +++ b/chrome/browser/smart_card/fake_smart_card_device_service_factory.h
@@ -0,0 +1,29 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_SMART_CARD_FAKE_SMART_CARD_DEVICE_SERVICE_FACTORY_H_ +#define CHROME_BROWSER_SMART_CARD_FAKE_SMART_CARD_DEVICE_SERVICE_FACTORY_H_ + +#include "base/no_destructor.h" +#include "chrome/browser/profiles/profile_keyed_service_factory.h" + +class FakeSmartCardDeviceService; + +class FakeSmartCardDeviceServiceFactory : public ProfileKeyedServiceFactory { + public: + static FakeSmartCardDeviceService& GetForProfile(Profile& profile); + static FakeSmartCardDeviceServiceFactory& GetInstance(); + + private: + friend base::NoDestructor<FakeSmartCardDeviceServiceFactory>; + + FakeSmartCardDeviceServiceFactory(); + ~FakeSmartCardDeviceServiceFactory() override; + + // BrowserContextKeyedServiceFactory: + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( + content::BrowserContext* profile) const override; +}; + +#endif // CHROME_BROWSER_SMART_CARD_FAKE_SMART_CARD_DEVICE_SERVICE_FACTORY_H_
diff --git a/chrome/browser/smart_card/get_smart_card_context_factory.cc b/chrome/browser/smart_card/get_smart_card_context_factory.cc new file mode 100644 index 0000000..c0aabe1 --- /dev/null +++ b/chrome/browser/smart_card/get_smart_card_context_factory.cc
@@ -0,0 +1,29 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/smart_card/get_smart_card_context_factory.h" + +#if BUILDFLAG(IS_CHROMEOS_DEVICE) +#include "chrome/browser/chromeos/extensions/smart_card_provider_private/smart_card_provider_private_api.h" +#else +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/smart_card/fake_smart_card_device_service.h" +#include "chrome/browser/smart_card/fake_smart_card_device_service_factory.h" +#endif // BUILDFLAG(IS_CHROMEOS_DEVICE) + +mojo::PendingRemote<device::mojom::SmartCardContextFactory> +GetSmartCardContextFactory(content::BrowserContext& browser_context) { +#if BUILDFLAG(IS_CHROMEOS_DEVICE) + // Get the smart card (PC/SC) service from a provider extension. + return extensions::SmartCardProviderPrivateAPI::Get(browser_context) + .GetSmartCardContextFactory(); +#else + // Emulate the smart card (PC/SC) service when running a ChromeOS build on + // Linux. This makes make manual testing of features like permission prompt + // and system tray indicator possible in a developer's machine. + return FakeSmartCardDeviceServiceFactory::GetForProfile( + *Profile::FromBrowserContext(&browser_context)) + .GetSmartCardContextFactory(); +#endif // BUILDFLAG(IS_CHROMEOS_DEVICE) +}
diff --git a/chrome/browser/smart_card/get_smart_card_context_factory.h b/chrome/browser/smart_card/get_smart_card_context_factory.h new file mode 100644 index 0000000..413d94b2 --- /dev/null +++ b/chrome/browser/smart_card/get_smart_card_context_factory.h
@@ -0,0 +1,18 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_SMART_CARD_GET_SMART_CARD_CONTEXT_FACTORY_H_ +#define CHROME_BROWSER_SMART_CARD_GET_SMART_CARD_CONTEXT_FACTORY_H_ + +#include "mojo/public/cpp/bindings/pending_receiver.h" +#include "services/device/public/mojom/smart_card.mojom-forward.h" + +namespace content { +class BrowserContext; +} + +mojo::PendingRemote<device::mojom::SmartCardContextFactory> +GetSmartCardContextFactory(content::BrowserContext& browser_context); + +#endif // CHROME_BROWSER_SMART_CARD_GET_SMART_CARD_CONTEXT_FACTORY_H_
diff --git a/chrome/browser/sync/test/integration/single_client_incoming_password_sharing_invitation_test.cc b/chrome/browser/sync/test/integration/single_client_incoming_password_sharing_invitation_test.cc index 4e3e4e0..df7f638 100644 --- a/chrome/browser/sync/test/integration/single_client_incoming_password_sharing_invitation_test.cc +++ b/chrome/browser/sync/test/integration/single_client_incoming_password_sharing_invitation_test.cc
@@ -84,17 +84,21 @@ PasswordSharingInvitationData CreateUnencryptedInvitationData() { PasswordSharingInvitationData password_invitation_data; - PasswordSharingInvitationData::PasswordData* password_data = - password_invitation_data.mutable_password_data(); + PasswordSharingInvitationData::PasswordGroupData* password_group_data = + password_invitation_data.mutable_password_group_data(); - password_data->set_password_value(kPasswordValue); - password_data->set_signon_realm(kSignonRealm); - password_data->set_origin(kOrigin); - password_data->set_username_element(kUsernameElement); - password_data->set_username_value(kUsernameValue); - password_data->set_password_element(kPasswordElement); - password_data->set_display_name(kPasswordDisplayName); - password_data->set_avatar_url(kPasswordAvatarUrl); + password_group_data->set_username_value(kUsernameValue); + password_group_data->set_password_value(kPasswordValue); + + sync_pb::PasswordSharingInvitationData::PasswordGroupElementData* + element_data = password_group_data->add_element_data(); + + element_data->set_signon_realm(kSignonRealm); + element_data->set_origin(kOrigin); + element_data->set_username_element(kUsernameElement); + element_data->set_password_element(kPasswordElement); + element_data->set_display_name(kPasswordDisplayName); + element_data->set_avatar_url(kPasswordAvatarUrl); return password_invitation_data; }
diff --git a/chrome/browser/translate/translate_service.cc b/chrome/browser/translate/translate_service.cc index 64085311..9900b98 100644 --- a/chrome/browser/translate/translate_service.cc +++ b/chrome/browser/translate/translate_service.cc
@@ -71,6 +71,8 @@ // static void TranslateService::Shutdown() { translate::TranslateDownloadManager::GetInstance()->Shutdown(); + delete g_translate_service; + g_translate_service = nullptr; } // static @@ -90,7 +92,7 @@ // static void TranslateService::ShutdownForTesting() { - translate::TranslateDownloadManager::GetInstance()->Shutdown(); + TranslateService::Shutdown(); } void TranslateService::OnResourceRequestsAllowed() {
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 205c709f..d64de5b 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -2578,6 +2578,7 @@ "ash/device_scheduled_reboot/reboot_notification_controller.h", "ash/device_scheduled_reboot/scheduled_reboot_dialog.cc", "ash/device_scheduled_reboot/scheduled_reboot_dialog.h", + "ash/download_status/display_client.cc", "ash/download_status/display_client.h", "ash/download_status/display_manager.cc", "ash/download_status/display_manager.h", @@ -2585,6 +2586,8 @@ "ash/download_status/display_metadata.h", "ash/download_status/holding_space_display_client.cc", "ash/download_status/holding_space_display_client.h", + "ash/download_status/notification_display_client.cc", + "ash/download_status/notification_display_client.h", "ash/fwupd_download_client_impl.cc", "ash/fwupd_download_client_impl.h", "ash/game_dashboard/chrome_game_dashboard_delegate.cc", @@ -4389,6 +4392,8 @@ "views/frame/immersive_mode_controller_mac.h", "views/frame/immersive_mode_controller_mac.mm", "views/frame/native_browser_frame_factory_mac.mm", + "views/passwords/password_relaunch_chrome_view.cc", + "views/passwords/password_relaunch_chrome_view.h", "views/tab_contents/chrome_web_contents_view_delegate_views_mac.h", "views/tab_contents/chrome_web_contents_view_delegate_views_mac.mm", "webui/help/version_updater_mac.h",
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java index de2a723..de289b4 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediator.java
@@ -21,6 +21,7 @@ import org.chromium.base.supplier.OneshotSupplier; import org.chromium.base.supplier.Supplier; +import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.merchant_viewer.MerchantTrustSignalsCoordinator; import org.chromium.chrome.browser.omnibox.LocationBarDataProvider; import org.chromium.chrome.browser.omnibox.R; @@ -45,6 +46,8 @@ import org.chromium.components.content_settings.CookieControlsBridge; import org.chromium.components.content_settings.CookieControlsObserver; import org.chromium.components.content_settings.CookieControlsStatus; +import org.chromium.components.feature_engagement.FeatureConstants; +import org.chromium.components.feature_engagement.Tracker; import org.chromium.components.page_info.PageInfoController; import org.chromium.components.permissions.PermissionDialogController; import org.chromium.components.search_engines.TemplateUrlService; @@ -656,7 +659,7 @@ mBlockingStatus3pcd = blockingStatus; } - private void animateCookieControlsIcon() { + private void animateCookieControlsIcon(Runnable onAnimationFinished) { resetCustomIconsStatus(); boolean isIncognito = mLocationBarDataProvider.isIncognito(); @@ -676,6 +679,7 @@ if (mCookieControlsBridge != null) { mCookieControlsBridge.onEntryPointAnimated(); } + onAnimationFinished.run(); }); // Set the timer to switch the icon back afterwards. @@ -816,21 +820,30 @@ if (profile == null) { return; } - if (UserPrefs.get(profile).getInteger(Pref.TRACKING_PROTECTION_ONBOARDING_ACK_ACTION) - == 0) { - return; - } if (mPageSecurityLevel != ConnectionSecurityLevel.SECURE) { return; } if (mBlockingStatus3pcd != CookieBlocking3pcdStatus.NOT_IN3PCD) { if (mCookieBlockingStatus != CookieControlsStatus.ENABLED) return; - mPageInfoIPHController.showCookieControlsReminderIPH( - getIPHTimeout(), R.string.cookie_controls_reminder_iph_message); + + if (UserPrefs.get(profile).getInteger(Pref.TRACKING_PROTECTION_ONBOARDING_ACK_ACTION) + == 0) { + return; + } + + Tracker tracker = TrackerFactory.getTrackerForProfile(profile); + if (!tracker.wouldTriggerHelpUI(FeatureConstants.COOKIE_CONTROLS_3PCD_FEATURE)) return; + + animateCookieControlsIcon( + () -> + mPageInfoIPHController.showCookieControlsReminderIPH( + getIPHTimeout(), + R.string.cookie_controls_reminder_iph_message)); } else if (mHighConfidenceBreakageReceived) { - mPageInfoIPHController.showCookieControlsIPH( - getIPHTimeout(), R.string.cookie_controls_iph_message); - animateCookieControlsIcon(); + animateCookieControlsIcon( + () -> + mPageInfoIPHController.showCookieControlsIPH( + getIPHTimeout(), R.string.cookie_controls_iph_message)); mHighConfidenceBreakageReceived = false; } }
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediatorUnitTest.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediatorUnitTest.java index 2ce1f1f..20a8819 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediatorUnitTest.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/status/StatusMediatorUnitTest.java
@@ -40,6 +40,7 @@ import org.chromium.base.supplier.OneshotSupplierImpl; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.base.test.util.JniMocker; +import org.chromium.chrome.browser.feature_engagement.TrackerFactory; import org.chromium.chrome.browser.merchant_viewer.MerchantTrustSignalsCoordinator; import org.chromium.chrome.browser.omnibox.LocationBarDataProvider; import org.chromium.chrome.browser.omnibox.NewTabPageDelegate; @@ -58,6 +59,7 @@ import org.chromium.components.content_settings.CookieControlsBridge; import org.chromium.components.content_settings.CookieControlsBridgeJni; import org.chromium.components.content_settings.CookieControlsStatus; +import org.chromium.components.feature_engagement.Tracker; import org.chromium.components.permissions.PermissionDialogController; import org.chromium.components.prefs.PrefService; import org.chromium.components.search_engines.TemplateUrlService; @@ -100,6 +102,7 @@ private @Mock StatusView mStatusView; @Mock UserPrefsJni mMockUserPrefsJni; @Mock private PrefService mPrefs; + @Mock private Tracker mTracker; Context mContext; Resources mResources; @@ -134,12 +137,15 @@ mJniMocker.mock(UserPrefsJni.TEST_HOOKS, mMockUserPrefsJni); doReturn(mPrefs).when(mMockUserPrefsJni).get(mProfile); + TrackerFactory.setTrackerForTests(mTracker); + setupStatusMediator(/* isTablet= */ false); } @After public void tearDown() { mWindowAndroid.destroy(); + TrackerFactory.setTrackerForTests(null); } private void setupStatusMediator(boolean isTablet) { @@ -595,7 +601,7 @@ @Test @SmallTest - public void testCookieControlsIcon_animateOnPageStoppedLoading() { + public void iphCookieControls_animateOnPageStoppedLoading() { setupCookieControlsTest(); Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); @@ -619,11 +625,29 @@ Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); } + @Test + @SmallTest + public void iphCookieControls_onboardingNoticeNotYetAcked() { + setupCookieControlsTest(); + + // No interaction with the Tracking Protection onboarding notice yet. + doReturn(0).when(mPrefs).getInteger(Pref.TRACKING_PROTECTION_ONBOARDING_ACK_ACTION); + + mMediator.onBreakageConfidenceLevelChanged(CookieControlsBreakageConfidenceLevel.HIGH); + mMediator.onPageLoadStopped(); + Assert.assertEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); + + mModel.get(StatusProperties.STATUS_ICON_RESOURCE).getAnimationFinishedCallback().run(); + verify(mPageInfoIPHController, times(1)).showCookieControlsIPH(anyInt(), anyInt()); + verify(mCookieControlsBridge, times(1)).onEntryPointAnimated(); + } + private void setupCookieControlsTest() { mMediator.setUrlHasFocus(true); mMediator.updateVerboseStatus(ConnectionSecurityLevel.SECURE, false, false); mMediator.setCookieControlsBridge(mCookieControlsBridge); doReturn(2).when(mPrefs).getInteger(Pref.TRACKING_PROTECTION_ONBOARDING_ACK_ACTION); + doReturn(true).when(mTracker).wouldTriggerHelpUI(any()); } @Test @@ -638,8 +662,12 @@ /* expiration= */ 0); Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); - // IPH should be shown mMediator.onPageLoadStopped(); + // Cookie controls icon should be shown. + Assert.assertEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); + mModel.get(StatusProperties.STATUS_ICON_RESOURCE).getAnimationFinishedCallback().run(); + + // IPH should be shown. verify(mPageInfoIPHController, times(1)).showCookieControlsReminderIPH(anyInt(), anyInt()); } @@ -656,8 +684,12 @@ CookieBlocking3pcdStatus.LIMITED, /* expiration= */ 0); - // IPH should NOT be shown mMediator.onPageLoadStopped(); + + // Cookie controls icon should NOT be shown. + Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); + + // IPH should NOT be shown. verify(mPageInfoIPHController, never()).showCookieControlsReminderIPH(anyInt(), anyInt()); } @@ -675,8 +707,12 @@ CookieBlocking3pcdStatus.LIMITED, /* expiration= */ 0); - // IPH should NOT be shown mMediator.onPageLoadStopped(); + + // Cookie controls icon should NOT be shown. + Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); + + // IPH should NOT be shown. verify(mPageInfoIPHController, never()).showCookieControlsReminderIPH(anyInt(), anyInt()); } @@ -692,8 +728,12 @@ /* expiration= */ 0); Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); - // IPH should NOT be shown mMediator.onPageLoadStopped(); + + // Cookie controls icon should NOT be shown. + Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); + + // IPH should NOT be shown. verify(mPageInfoIPHController, never()).showCookieControlsReminderIPH(anyInt(), anyInt()); } @@ -709,8 +749,11 @@ /* expiration= */ 0); Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); - // IPH should NOT be shown mMediator.onPageLoadStopped(); + + // Cookie controls icon should NOT be shown. + Assert.assertNotEquals(COOKIE_CONTROLS_ICON, getIconIdentifierForTesting()); + // IPH should NOT be shown. verify(mPageInfoIPHController, never()).showCookieControlsReminderIPH(anyInt(), anyInt()); }
diff --git a/chrome/browser/ui/ash/download_status/display_client.cc b/chrome/browser/ui/ash/download_status/display_client.cc new file mode 100644 index 0000000..bb57e23 --- /dev/null +++ b/chrome/browser/ui/ash/download_status/display_client.cc
@@ -0,0 +1,24 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/ash/download_status/display_client.h" + +#include "base/check.h" +#include "chrome/browser/profiles/profile.h" + +namespace ash::download_status { + +DisplayClient::DisplayClient(Profile* profile) : profile_(profile) { + CHECK(profile_); + profile_observation_.Observe(profile_); +} + +DisplayClient::~DisplayClient() = default; + +void DisplayClient::OnProfileWillBeDestroyed(Profile* profile) { + profile_observation_.Reset(); + profile_ = nullptr; +} + +} // namespace ash::download_status
diff --git a/chrome/browser/ui/ash/download_status/display_client.h b/chrome/browser/ui/ash/download_status/display_client.h index b9f5b18..9f46fa8 100644 --- a/chrome/browser/ui/ash/download_status/display_client.h +++ b/chrome/browser/ui/ash/download_status/display_client.h
@@ -7,14 +7,23 @@ #include <string> +#include "base/memory/raw_ptr.h" +#include "base/scoped_observation.h" +#include "chrome/browser/profiles/profile_observer.h" + +class Profile; + namespace ash::download_status { struct DisplayMetadata; // The virtual base class of Ash classes that display download updates. -class DisplayClient { +class DisplayClient : public ProfileObserver { public: - virtual ~DisplayClient() = default; + explicit DisplayClient(Profile* profile); + DisplayClient(const DisplayClient&) = delete; + DisplayClient& operator=(const DisplayClient&) = delete; + ~DisplayClient() override; // Adds or updates the displayed download specified by `guid` with the given // display metadata. @@ -23,6 +32,19 @@ // Removes the displayed download specified by `guid`. virtual void Remove(const std::string& guid) = 0; + + protected: + Profile* profile() { return profile_; } + + private: + // ProfileObserver: + void OnProfileWillBeDestroyed(Profile* profile) override; + + // Reset when `OnProfileWillBeDestroyed()` is called to prevent the dangling + // pointer issue. + raw_ptr<Profile> profile_ = nullptr; + + base::ScopedObservation<Profile, ProfileObserver> profile_observation_{this}; }; } // namespace ash::download_status
diff --git a/chrome/browser/ui/ash/download_status/display_manager.cc b/chrome/browser/ui/ash/download_status/display_manager.cc index 91ce0e5..0769eea 100644 --- a/chrome/browser/ui/ash/download_status/display_manager.cc +++ b/chrome/browser/ui/ash/download_status/display_manager.cc
@@ -12,6 +12,7 @@ #include "chrome/browser/ui/ash/download_status/display_client.h" #include "chrome/browser/ui/ash/download_status/display_metadata.h" #include "chrome/browser/ui/ash/download_status/holding_space_display_client.h" +#include "chrome/browser/ui/ash/download_status/notification_display_client.h" #include "chromeos/crosapi/mojom/download_controller.mojom.h" #include "chromeos/crosapi/mojom/download_status_updater.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -145,6 +146,7 @@ CHECK(features::IsSysUiDownloadsIntegrationV2Enabled()); clients_.push_back(std::make_unique<HoldingSpaceDisplayClient>(profile)); + clients_.push_back(std::make_unique<NotificationDisplayClient>(profile)); } DisplayManager::~DisplayManager() = default;
diff --git a/chrome/browser/ui/ash/download_status/display_manager.h b/chrome/browser/ui/ash/download_status/display_manager.h index fce6e48..93ac336 100644 --- a/chrome/browser/ui/ash/download_status/display_manager.h +++ b/chrome/browser/ui/ash/download_status/display_manager.h
@@ -45,7 +45,6 @@ // Responsible for displaying download updates. // All clients are ready when `DisplayManager` is created to ensure // consistency in the received display metadata among clients. - // TODO(http://b/279831939): Add the client for download notifications. std::vector<std::unique_ptr<DisplayClient>> clients_; };
diff --git a/chrome/browser/ui/ash/download_status/holding_space_display_client.cc b/chrome/browser/ui/ash/download_status/holding_space_display_client.cc index fb15f70..f5652bed 100644 --- a/chrome/browser/ui/ash/download_status/holding_space_display_client.cc +++ b/chrome/browser/ui/ash/download_status/holding_space_display_client.cc
@@ -19,11 +19,8 @@ namespace ash::download_status { HoldingSpaceDisplayClient::HoldingSpaceDisplayClient(Profile* profile) - : profile_(profile) { + : DisplayClient(profile) { CHECK(features::IsSysUiDownloadsIntegrationV2Enabled()); - CHECK(profile_); - - profile_observation_.Observe(profile); } HoldingSpaceDisplayClient::~HoldingSpaceDisplayClient() = default; @@ -35,7 +32,7 @@ auto item_id_by_guid = item_ids_by_guids_.find(guid); HoldingSpaceKeyedService* const service = - HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(profile_); + HoldingSpaceKeyedServiceFactory::GetInstance()->GetService(profile()); const HoldingSpaceProgress progress(display_metadata.received_bytes, display_metadata.total_bytes); @@ -79,15 +76,10 @@ if (auto iter = item_ids_by_guids_.find(guid); iter != item_ids_by_guids_.end()) { HoldingSpaceKeyedServiceFactory::GetInstance() - ->GetService(profile_) + ->GetService(profile()) ->RemoveItem(iter->second); item_ids_by_guids_.erase(iter); } } -void HoldingSpaceDisplayClient::OnProfileWillBeDestroyed(Profile* profile) { - profile_observation_.Reset(); - profile_ = nullptr; -} - } // namespace ash::download_status
diff --git a/chrome/browser/ui/ash/download_status/holding_space_display_client.h b/chrome/browser/ui/ash/download_status/holding_space_display_client.h index 524f6e59..e3d1933 100644 --- a/chrome/browser/ui/ash/download_status/holding_space_display_client.h +++ b/chrome/browser/ui/ash/download_status/holding_space_display_client.h
@@ -8,9 +8,6 @@ #include <map> #include <string> -#include "base/memory/raw_ptr.h" -#include "base/scoped_observation.h" -#include "chrome/browser/profiles/profile_observer.h" #include "chrome/browser/ui/ash/download_status/display_client.h" class Profile; @@ -21,7 +18,7 @@ // The client to display downloads in holding space. Created only when the // downloads integration V2 feature is enabled. -class HoldingSpaceDisplayClient : public DisplayClient, public ProfileObserver { +class HoldingSpaceDisplayClient : public DisplayClient { public: explicit HoldingSpaceDisplayClient(Profile* profile); HoldingSpaceDisplayClient(const HoldingSpaceDisplayClient&) = delete; @@ -35,21 +32,12 @@ const DisplayMetadata& display_metadata) override; void Remove(const std::string& guid) override; - // ProfileObserver: - void OnProfileWillBeDestroyed(Profile* profile) override; - - // Reset when `OnProfileWillBeDestroyed()` is called to prevent the dangling - // pointer issue. - raw_ptr<Profile> profile_ = nullptr; - // GUID to holding space item ID mappings. // Adds a mapping when displaying a new download. // Removes a mapping when: // 1. A displayed download is removed; OR // 2. An in-progress download completes. std::map<std::string, std::string> item_ids_by_guids_; - - base::ScopedObservation<Profile, ProfileObserver> profile_observation_{this}; }; } // namespace ash::download_status
diff --git a/chrome/browser/ui/ash/download_status/notification_display_client.cc b/chrome/browser/ui/ash/download_status/notification_display_client.cc new file mode 100644 index 0000000..71c07eb5 --- /dev/null +++ b/chrome/browser/ui/ash/download_status/notification_display_client.cc
@@ -0,0 +1,92 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/ash/download_status/notification_display_client.h" + +#include "ash/constants/ash_features.h" +#include "ash/constants/notifier_catalogs.h" +#include "base/check.h" +#include "base/memory/scoped_refptr.h" +#include "base/strings/strcat.h" +#include "chrome/app/vector_icons/vector_icons.h" +#include "chrome/browser/notifications/notification_display_service.h" +#include "chrome/browser/notifications/notification_handler.h" +#include "chrome/browser/ui/ash/download_status/display_metadata.h" +#include "chrome/grit/generated_resources.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/models/image_model.h" +#include "ui/message_center/public/cpp/notification.h" +#include "ui/message_center/public/cpp/notification_delegate.h" +#include "ui/message_center/public/cpp/notifier_id.h" +#include "url/gurl.h" + +namespace ash::download_status { + +namespace { + +// Constants ------------------------------------------------------------------- + +constexpr char kNotificationNotifierId[] = + "chrome://downloads/notification/id-notifier"; + +constexpr char kNotificationOrigin[] = "chrome://downloads"; + +// Helpers --------------------------------------------------------------------- + +// NOTE: This function returns a non-empty string indicating the notification +// text, but does not guarantee the presence of a notification. +std::string GetNotificationIdFromGuid(const std::string& guid) { + return base::StrCat({kNotificationNotifierId, "/", guid}); +} + +} // namespace + +NotificationDisplayClient::NotificationDisplayClient(Profile* profile) + : DisplayClient(profile) { + CHECK(features::IsSysUiDownloadsIntegrationV2Enabled()); +} + +NotificationDisplayClient::~NotificationDisplayClient() = default; + +void NotificationDisplayClient::AddOrUpdate( + const std::string& guid, + const DisplayMetadata& display_metadata) { + // TODO(http://b/310691284): Avoid showing a notification if it has been + // closed. + + message_center::RichNotificationData rich_notification_data; + rich_notification_data.should_make_spoken_feedback_for_popup_updates = false; + rich_notification_data.vector_small_image = &kNotificationDownloadIcon; + + // TODO(http://b/310691284): Initialize `notification` with + // `display_metadata`. + message_center::Notification notification( + message_center::NOTIFICATION_TYPE_PROGRESS, + GetNotificationIdFromGuid(guid), + /*title=*/std::u16string(), + /*message=*/std::u16string(), + /*icon=*/ui::ImageModel(), + /*display_source=*/ + l10n_util::GetStringUTF16(IDS_DOWNLOAD_NOTIFICATION_DISPLAY_SOURCE), + GURL(kNotificationOrigin), + message_center::NotifierId( + message_center::NotifierType::SYSTEM_COMPONENT, + kNotificationNotifierId, + NotificationCatalogName::kDownloadNotification), + rich_notification_data, + base::MakeRefCounted<message_center::NotificationDelegate>()); + notification.set_fullscreen_visibility( + message_center::FullscreenVisibility::OVER_USER); + + NotificationDisplayService::GetForProfile(profile())->Display( + NotificationHandler::Type::TRANSIENT, notification, + /*metadata=*/nullptr); +} + +void NotificationDisplayClient::Remove(const std::string& guid) { + NotificationDisplayService::GetForProfile(profile())->Close( + NotificationHandler::Type::TRANSIENT, GetNotificationIdFromGuid(guid)); +} + +} // namespace ash::download_status
diff --git a/chrome/browser/ui/ash/download_status/notification_display_client.h b/chrome/browser/ui/ash/download_status/notification_display_client.h new file mode 100644 index 0000000..d8cd8598 --- /dev/null +++ b/chrome/browser/ui/ash/download_status/notification_display_client.h
@@ -0,0 +1,37 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_ASH_DOWNLOAD_STATUS_NOTIFICATION_DISPLAY_CLIENT_H_ +#define CHROME_BROWSER_UI_ASH_DOWNLOAD_STATUS_NOTIFICATION_DISPLAY_CLIENT_H_ + +#include <string> + +#include "chrome/browser/ui/ash/download_status/display_client.h" + +class Profile; + +namespace ash::download_status { + +struct DisplayMetadata; + +// The client to display download notifications. Created only when the downloads +// integration V2 feature is enabled. +class NotificationDisplayClient : public DisplayClient { + public: + explicit NotificationDisplayClient(Profile* profile); + NotificationDisplayClient(const NotificationDisplayClient&) = delete; + NotificationDisplayClient& operator=(const NotificationDisplayClient&) = + delete; + ~NotificationDisplayClient() override; + + private: + // DisplayClient: + void AddOrUpdate(const std::string& guid, + const DisplayMetadata& display_metadata) override; + void Remove(const std::string& guid) override; +}; + +} // namespace ash::download_status + +#endif // CHROME_BROWSER_UI_ASH_DOWNLOAD_STATUS_NOTIFICATION_DISPLAY_CLIENT_H_
diff --git a/chrome/browser/ui/ash/download_status/notification_display_client_browsertest.cc b/chrome/browser/ui/ash/download_status/notification_display_client_browsertest.cc new file mode 100644 index 0000000..afc4e32 --- /dev/null +++ b/chrome/browser/ui/ash/download_status/notification_display_client_browsertest.cc
@@ -0,0 +1,178 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <set> +#include <string> +#include <utility> + +#include "ash/constants/ash_features.h" +#include "base/scoped_observation.h" +#include "base/test/bind.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/test_future.h" +#include "chrome/browser/ash/crosapi/crosapi_ash.h" +#include "chrome/browser/ash/crosapi/crosapi_manager.h" +#include "chrome/browser/notifications/notification_display_service.h" +#include "chrome/browser/notifications/notification_display_service_factory.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/ash/download_status/display_test_util.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chromeos/crosapi/mojom/download_status_updater.mojom.h" +#include "content/public/test/browser_test.h" +#include "mojo/public/cpp/bindings/remote.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "ui/message_center/public/cpp/notification.h" + +namespace ash::download_status { + +namespace { + +// Alias ----------------------------------------------------------------------- + +using ::testing::Contains; +using ::testing::Mock; +using ::testing::Not; +using ::testing::WithArg; + +// MockNotificationDisplayServiceObserver -------------------------------------- + +// NOTE: When a download notification is closed, `OnNotificationClosed()` is not +// called because the notification's handler type is `TRANSIENT`. +class MockNotificationDisplayServiceObserver + : public NotificationDisplayService::Observer { + public: + MOCK_METHOD(void, + OnNotificationDisplayed, + (const message_center::Notification&, + const NotificationCommon::Metadata*), + (override)); + MOCK_METHOD(void, OnNotificationClosed, (const std::string&), (override)); + MOCK_METHOD(void, + OnNotificationDisplayServiceDestroyed, + (NotificationDisplayService * service), + (override)); +}; + +// Helpers --------------------------------------------------------------------- + +NotificationDisplayService* GetNotificationDisplayService() { + return NotificationDisplayServiceFactory::GetInstance()->GetForProfile( + ProfileManager::GetActiveUserProfile()); +} + +// Returns the IDs of the displayed notifications. +std::set<std::string> GetDisplayedNotificationIds() { + base::test::TestFuture<std::set<std::string>> future; + GetNotificationDisplayService()->GetDisplayed( + base::BindLambdaForTesting([&future](std::set<std::string> ids, bool) { + future.SetValue(std::move(ids)); + })); + return future.Get(); +} + +} // namespace + +class NotificationDisplayClientBrowserTest : public InProcessBrowserTest { + public: + NotificationDisplayClientBrowserTest() { + scoped_feature_list_.InitAndEnableFeature( + features::kSysUiDownloadsIntegrationV2); + } + + // Updates download through the download status updater. + void Update(crosapi::mojom::DownloadStatusPtr status) { + download_status_updater_remote_->Update(std::move(status)); + download_status_updater_remote_.FlushForTesting(); + } + + MockNotificationDisplayServiceObserver& service_observer() { + return service_observer_; + } + + private: + // InProcessBrowserTest: + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + + crosapi::CrosapiManager::Get()->crosapi_ash()->BindDownloadStatusUpdater( + download_status_updater_remote_.BindNewPipeAndPassReceiver()); + service_observation_.Observe(GetNotificationDisplayService()); + } + + void TearDownOnMainThread() override { + service_observation_.Reset(); + InProcessBrowserTest::TearDownOnMainThread(); + } + + base::test::ScopedFeatureList scoped_feature_list_; + mojo::Remote<crosapi::mojom::DownloadStatusUpdater> + download_status_updater_remote_; + MockNotificationDisplayServiceObserver service_observer_; + base::ScopedObservation<NotificationDisplayService, + NotificationDisplayService::Observer> + service_observation_{&service_observer_}; +}; + +// Verifies that when an in-progress download is cancelled, its notification +// should be removed. +IN_PROC_BROWSER_TEST_F(NotificationDisplayClientBrowserTest, CancelDownload) { + std::string notification_id; + EXPECT_CALL(service_observer(), OnNotificationDisplayed) + .WillOnce(WithArg<0>( + [¬ification_id](const message_center::Notification& notification) { + notification_id = notification.id(); + })); + crosapi::mojom::DownloadStatusPtr download = CreateInProgressDownloadStatus( + ProfileManager::GetActiveUserProfile(), /*received_bytes=*/0, + /*target_bytes=*/1024); + Update(download->Clone()); + Mock::VerifyAndClearExpectations(&service_observer()); + + download->state = crosapi::mojom::DownloadState::kCancelled; + Update(download->Clone()); + EXPECT_THAT(GetDisplayedNotificationIds(), Not(Contains(notification_id))); +} + +// Verifies that when an in-progress download completes, its notification should +// still show. +IN_PROC_BROWSER_TEST_F(NotificationDisplayClientBrowserTest, CompleteDownload) { + std::string notification_id; + EXPECT_CALL(service_observer(), OnNotificationDisplayed) + .WillOnce(WithArg<0>( + [¬ification_id](const message_center::Notification& notification) { + notification_id = notification.id(); + })); + crosapi::mojom::DownloadStatusPtr download = CreateInProgressDownloadStatus( + ProfileManager::GetActiveUserProfile(), /*received_bytes=*/0, + /*target_bytes=*/1024); + Update(download->Clone()); + Mock::VerifyAndClearExpectations(&service_observer()); + + download->state = crosapi::mojom::DownloadState::kComplete; + Update(download->Clone()); + EXPECT_THAT(GetDisplayedNotificationIds(), Contains(notification_id)); +} + +// Verifies that when an in-progress download is interrupted, its notification +// should be removed. +IN_PROC_BROWSER_TEST_F(NotificationDisplayClientBrowserTest, + InterruptDownload) { + std::string notification_id; + EXPECT_CALL(service_observer(), OnNotificationDisplayed) + .WillOnce(WithArg<0>( + [¬ification_id](const message_center::Notification& notification) { + notification_id = notification.id(); + })); + crosapi::mojom::DownloadStatusPtr download = CreateInProgressDownloadStatus( + ProfileManager::GetActiveUserProfile(), /*received_bytes=*/0, + /*target_bytes=*/1024); + Update(download->Clone()); + Mock::VerifyAndClearExpectations(&service_observer()); + + download->state = crosapi::mojom::DownloadState::kInterrupted; + Update(download->Clone()); + EXPECT_THAT(GetDisplayedNotificationIds(), Not(Contains(notification_id))); +} + +} // namespace ash::download_status
diff --git a/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.cc b/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.cc index f38e7cb..6fe4a9a 100644 --- a/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.cc +++ b/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.cc
@@ -110,6 +110,7 @@ MediaNotificationProviderImpl::GetMediaNotificationListView( int separator_thickness, bool should_clip_height, + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id) { CHECK(item_manager_); CHECK(color_theme_); @@ -119,17 +120,8 @@ color_theme_->separator_color, separator_thickness), should_clip_height); media_item_ui_list_view_ = media_item_ui_list_view->GetWeakPtr(); + entry_point_ = entry_point; show_devices_for_item_id_ = show_devices_for_item_id; - if (show_devices_for_item_id.empty()) { - entry_point_ = - global_media_controls::GlobalMediaControlsEntryPoint::kSystemTray; - } else { - // TODO(crbug.com/1501668): Entries via the Cast button in the quick - // settings mini player also hits this else-branch, being miscounted in the - // histogram below. - entry_point_ = - global_media_controls::GlobalMediaControlsEntryPoint::kPresentation; - } item_manager_->SetDialogDelegate(this); base::UmaHistogramEnumeration("Media.GlobalMediaControls.EntryPoint", entry_point_);
diff --git a/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.h b/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.h index 02772686..2e6b788b 100644 --- a/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.h +++ b/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl.h
@@ -58,6 +58,7 @@ std::unique_ptr<views::View> GetMediaNotificationListView( int separator_thickness, bool should_clip_height, + global_media_controls::GlobalMediaControlsEntryPoint entry_point, const std::string& show_devices_for_item_id) override; void OnBubbleClosing() override; void SetColorTheme(
diff --git a/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl_unittest.cc b/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl_unittest.cc index bac9c63..d1d349ee 100644 --- a/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl_unittest.cc +++ b/chrome/browser/ui/ash/global_media_controls/media_notification_provider_impl_unittest.cc
@@ -180,6 +180,7 @@ CreateNotificationListView() { auto view = provider_->GetMediaNotificationListView( 1, /*should_clip_height=*/true, + global_media_controls::GlobalMediaControlsEntryPoint::kSystemTray, /*show_devices_for_item_id=*/""); return base::WrapUnique( static_cast<global_media_controls::MediaItemUIListView*>( @@ -290,6 +291,7 @@ // items. list_view_ = provider_->GetMediaNotificationListView( 1, /*should_clip_height=*/true, + global_media_controls::GlobalMediaControlsEntryPoint::kSystemTray, /*show_devices_for_item_id=*/""); }
diff --git a/chrome/browser/ui/autofill/autofill_context_menu_manager.cc b/chrome/browser/ui/autofill/autofill_context_menu_manager.cc index b148c95..1a468638 100644 --- a/chrome/browser/ui/autofill/autofill_context_menu_manager.cc +++ b/chrome/browser/ui/autofill/autofill_context_menu_manager.cc
@@ -191,13 +191,12 @@ } if (command_id == IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS) { - ExecuteFallbackForAutocompleteUnrecognizedCommand(manager); + ExecuteFallbackForAddressesCommand(manager); return; } if (command_id == IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_PAYMENTS) { - // TODO(crbug.com/1493361): Render payments suggestions. - NOTIMPLEMENTED(); + ExecuteFallbackForPaymentsCommand(manager); return; } } @@ -220,9 +219,8 @@ LoadTriggerFormAndFieldLogs(manager, frame_token, params_))); } -void AutofillContextMenuManager:: - ExecuteFallbackForAutocompleteUnrecognizedCommand( - AutofillManager& manager) { +void AutofillContextMenuManager::ExecuteFallbackForAddressesCommand( + AutofillManager& manager) { auto& driver = static_cast<ContentAutofillDriver&>(manager.driver()); if (!ShouldAddAddressManualFallbackForAutocompleteUnrecognized(driver)) { // Do nothing if the target field is not on address form field with @@ -247,6 +245,15 @@ ->ShouldSuppressSuggestionsAndFillingByDefault()); } +void AutofillContextMenuManager::ExecuteFallbackForPaymentsCommand( + AutofillManager& manager) { + auto& driver = static_cast<ContentAutofillDriver&>(manager.driver()); + driver.browser_events().RendererShouldTriggerSuggestions( + FieldGlobalId(driver.GetFrameToken(), + FieldRendererId(params_.field_renderer_id)), + AutofillSuggestionTriggerSource::kManualFallbackPayments); +} + void AutofillContextMenuManager::MaybeAddAutofillManualFallbackItems( ContentAutofillDriver& driver) { if (!ShouldShowAutofillContextMenu(params_)) {
diff --git a/chrome/browser/ui/autofill/autofill_context_menu_manager.h b/chrome/browser/ui/autofill/autofill_context_menu_manager.h index f052ede..2f15e9f 100644 --- a/chrome/browser/ui/autofill/autofill_context_menu_manager.h +++ b/chrome/browser/ui/autofill/autofill_context_menu_manager.h
@@ -82,10 +82,13 @@ // user. void LogManualFallbackContextMenuEntryShown(ContentAutofillDriver& driver); - // Triggers Autofill suggestions on the field that the context menu was - // opened on. - void ExecuteFallbackForAutocompleteUnrecognizedCommand( - AutofillManager& manager); + // Triggers Autofill address suggestions on the field that the context menu + // was opened on. + void ExecuteFallbackForAddressesCommand(AutofillManager& manager); + + // Triggers Autofill payments suggestions on the field that the context menu + // was opened on. + void ExecuteFallbackForPaymentsCommand(AutofillManager& manager); // Gets the `AutofillField` described by the `params_` from the `manager`. // The `frame_token` is used to map from the `params_` renderer id to a global
diff --git a/chrome/browser/ui/autofill/autofill_context_menu_manager_browsertest.cc b/chrome/browser/ui/autofill/autofill_context_menu_manager_browsertest.cc index 70ccc74..536b77a 100644 --- a/chrome/browser/ui/autofill/autofill_context_menu_manager_browsertest.cc +++ b/chrome/browser/ui/autofill/autofill_context_menu_manager_browsertest.cc
@@ -604,13 +604,31 @@ EXPECT_THAT(menu_model(), AddressAndPaymentsFallbacksAdded()); } -// Tests that when the manual fallback entry for the unclassified fields is -// selected, suggestions are not triggered. -IN_PROC_BROWSER_TEST_F(UnclassifiedFieldsTest, - UnclassifiedFormShown_ManualFallbackOptionsAreNoOps) { +// Tests that when the address manual fallback entry for the unclassified fields +// is selected, suggestions are not triggered. +IN_PROC_BROWSER_TEST_F( + UnclassifiedFieldsTest, + UnclassifiedFormShown_AddressFallbackTriggersSuggestion) { AddAutofillProfile(test::GetFullProfile()); + FormData form = CreateAndAttachUnclassifiedForm(); + autofill_context_menu_manager()->set_params_for_testing( + CreateContextMenuParams(form.unique_renderer_id, + form.fields[0].unique_renderer_id)); + autofill_context_menu_manager()->AppendItems(); + + // Expect that when the entry is selected, suggestions are not triggered. + EXPECT_CALL(*driver(), RendererShouldTriggerSuggestions).Times(0); + autofill_context_menu_manager()->ExecuteCommand( + IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS); +} + +// Tests that when the payments manual fallback entry for the unclassified +// fields is selected, suggestions are triggered with correct field global id +// and suggestions trigger source. +IN_PROC_BROWSER_TEST_F(UnclassifiedFieldsTest, + UnclassifiedFormShown_PaymentsFallbackTriggersFallback) { AddCreditCard(test::GetCreditCard()); - FormData form = CreateAndAttachAutocompleteUnrecognizedForm(); + FormData form = CreateAndAttachUnclassifiedForm(); autofill_context_menu_manager()->set_params_for_testing( CreateContextMenuParams(form.unique_renderer_id, form.fields[0].unique_renderer_id)); @@ -618,9 +636,12 @@ // Expect that when the entry is selected, suggestions are triggered from that // field. - EXPECT_CALL(*driver(), RendererShouldTriggerSuggestions).Times(0); - autofill_context_menu_manager()->ExecuteCommand( - IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_ADDRESS); + EXPECT_CALL( + *driver(), + RendererShouldTriggerSuggestions( + FieldGlobalId{LocalFrameToken(main_rfh()->GetFrameToken().value()), + form.fields[0].unique_renderer_id}, + AutofillSuggestionTriggerSource::kManualFallbackPayments)); autofill_context_menu_manager()->ExecuteCommand( IDC_CONTENT_CONTEXT_AUTOFILL_FALLBACK_PAYMENTS); }
diff --git a/chrome/browser/ui/hats/OWNERS b/chrome/browser/ui/hats/OWNERS index 0203085..0b6574d5 100644 --- a/chrome/browser/ui/hats/OWNERS +++ b/chrome/browser/ui/hats/OWNERS
@@ -1,5 +1,3 @@ -feuunk@chromium.org msramek@chromium.org sauski@google.com -eokoyomon@chromium.org fjacky@chromium.org
diff --git a/chrome/browser/ui/passwords/bubble_controllers/manage_passwords_bubble_controller_unittest.cc b/chrome/browser/ui/passwords/bubble_controllers/manage_passwords_bubble_controller_unittest.cc index 4a09997..dd7c1ddb 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/manage_passwords_bubble_controller_unittest.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/manage_passwords_bubble_controller_unittest.cc
@@ -17,10 +17,10 @@ #include "chrome/browser/sync/sync_service_factory.h" #include "chrome/browser/ui/passwords/passwords_model_delegate_mock.h" #include "chrome/test/base/testing_profile.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/signin/public/identity_manager/identity_test_utils.h" #include "components/sync/test/test_sync_service.h"
diff --git a/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.cc b/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.cc index dce39ca0..691b33d9 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.cc
@@ -4,11 +4,15 @@ #include "chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h" +#include "components/password_manager/core/browser/password_form_metrics_recorder.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" +namespace metrics_util = password_manager::metrics_util; +namespace pwm_prefs = password_manager::prefs; + namespace { constexpr int kMaxNumberOfTimesBubbleIsShown = 3; @@ -27,7 +31,7 @@ PrefService* prefs) : PasswordBubbleControllerBase( std::move(delegate), - password_manager::metrics_util::AUTOMATIC_RELAUNCH_CHROME_BUBBLE), + metrics_util::AUTOMATIC_RELAUNCH_CHROME_BUBBLE), prefs_(prefs) {} RelaunchChromeBubbleController::~RelaunchChromeBubbleController() { @@ -68,13 +72,27 @@ } void RelaunchChromeBubbleController::OnAccepted() { + dismissal_reason_ = metrics_util::CLICKED_ACCEPT; delegate_->RelaunchChrome(); } void RelaunchChromeBubbleController::OnCanceled() { + if (prefs_->GetInteger(pwm_prefs::kRelaunchChromeBubbleDismissedCounter) < + kMaxNumberOfTimesBubbleIsShown) { + dismissal_reason_ = metrics_util::CLICKED_CANCEL; + } else { + dismissal_reason_ = metrics_util::CLICKED_NEVER; + } + prefs_->SetInteger( - password_manager::prefs::kRelaunchChromeBubbleDismissedCounter, - prefs_->GetInteger( - password_manager::prefs::kRelaunchChromeBubbleDismissedCounter) + - 1); + pwm_prefs::kRelaunchChromeBubbleDismissedCounter, + prefs_->GetInteger(pwm_prefs::kRelaunchChromeBubbleDismissedCounter) + 1); +} + +void RelaunchChromeBubbleController::ReportInteractions() { + password_manager::metrics_util::LogGeneralUIDismissalReason( + dismissal_reason_); + base::UmaHistogramBoolean( + "PasswordBubble.RelaunchChromeBubble.RestartButtonInBubbleClicked", + dismissal_reason_ == metrics_util::CLICKED_ACCEPT); }
diff --git a/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h b/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h index 65ab6a3..a2d274d0 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h +++ b/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h
@@ -7,6 +7,7 @@ #include "chrome/browser/ui/passwords/bubble_controllers/password_bubble_controller_base.h" #include "chrome/browser/ui/passwords/passwords_model_delegate.h" +#include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/prefs/pref_service.h" // This controller manages the relaunch Chrome bubble, which is shown while @@ -30,7 +31,10 @@ private: // PasswordBubbleControllerBase: - void ReportInteractions() override {} + void ReportInteractions() override; + + password_manager::metrics_util::UIDismissalReason dismissal_reason_ = + password_manager::metrics_util::NO_DIRECT_INTERACTION; raw_ptr<PrefService> prefs_; };
diff --git a/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller_unittest.cc b/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller_unittest.cc index c2151037..c3336885 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller_unittest.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller_unittest.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h" +#include "base/test/metrics/histogram_tester.h" #include "chrome/browser/ui/passwords/passwords_model_delegate_mock.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_registry_simple.h" @@ -11,6 +12,11 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +namespace { +constexpr char kAcceptHistogram[] = + "PasswordBubble.RelaunchChromeBubble.RestartButtonInBubbleClicked"; +} + class RelaunchChromeBubbleControllerTest : public ::testing::Test { public: RelaunchChromeBubbleControllerTest() { @@ -36,12 +42,35 @@ EXPECT_TRUE(testing::Mock::VerifyAndClearExpectations(delegate())); } + void ResetController() { controller_.reset(); } + + void CancelAndClose() { + controller()->OnCanceled(); + controller()->OnBubbleClosing(); + ResetController(); + } + + void CreateCancelAndClose() { + CreateController(); + CancelAndClose(); + } + private: std::unique_ptr<PasswordsModelDelegateMock> mock_delegate_; std::unique_ptr<TestingPrefServiceSimple> test_pref_service_; std::unique_ptr<RelaunchChromeBubbleController> controller_; }; +TEST_F(RelaunchChromeBubbleControllerTest, Destroy) { + base::HistogramTester histograms; + CreateController(); + + EXPECT_CALL(*delegate(), OnBubbleHidden()); + controller()->OnBubbleClosing(); + ResetController(); + histograms.ExpectUniqueSample(kAcceptHistogram, false, 1); +} + TEST_F(RelaunchChromeBubbleControllerTest, Content) { CreateController(); EXPECT_NE(std::u16string(), controller()->GetTitle()); @@ -51,17 +80,46 @@ } TEST_F(RelaunchChromeBubbleControllerTest, Cancel) { - CreateController(); + base::HistogramTester histograms; + CreateCancelAndClose(); - controller()->OnCanceled(); EXPECT_EQ(test_pref_service()->GetInteger( password_manager::prefs::kRelaunchChromeBubbleDismissedCounter), 1); + histograms.ExpectUniqueSample(kAcceptHistogram, false, 1); } TEST_F(RelaunchChromeBubbleControllerTest, Restart) { + base::HistogramTester histograms; CreateController(); EXPECT_CALL(*delegate(), RelaunchChrome); controller()->OnAccepted(); + controller()->OnBubbleClosing(); + ResetController(); + + histograms.ExpectUniqueSample(kAcceptHistogram, true, 1); +} + +TEST_F(RelaunchChromeBubbleControllerTest, DontAskAgain) { + base::HistogramTester histograms; + + CreateController(); + std::u16string initial_cancel_button_text = + controller()->GetNoThanksButtonText(); + EXPECT_NE(std::u16string(), initial_cancel_button_text); + CancelAndClose(); + + // Simulate that the bubble was shown and cancelled 2 additional times, + // meaning than the next showup should be it's last. + test_pref_service()->SetInteger( + password_manager::prefs::kRelaunchChromeBubbleDismissedCounter, 3); + + CreateController(); + std::u16string never_button_text = controller()->GetNoThanksButtonText(); + EXPECT_NE(std::u16string(), never_button_text); + CancelAndClose(); + + EXPECT_NE(never_button_text, initial_cancel_button_text); + histograms.ExpectUniqueSample(kAcceptHistogram, false, 2); }
diff --git a/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc b/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc index eb20b42..b665f6d3 100644 --- a/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc +++ b/chrome/browser/ui/passwords/bubble_controllers/save_update_bubble_controller_unittest.cc
@@ -23,12 +23,12 @@ #include "chrome/browser/ui/passwords/passwords_model_delegate_mock.h" #include "chrome/test/base/testing_profile.h" #include "components/password_manager/core/browser/mock_password_feature_manager.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" -#include "components/password_manager/core/browser/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_form_metrics_recorder.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store/interactions_stats.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/common/credential_manager_types.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "components/sync/test/test_sync_service.h"
diff --git a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc index 849b288f..bf7ebbd20 100644 --- a/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc +++ b/chrome/browser/ui/passwords/manage_passwords_ui_controller_unittest.cc
@@ -30,13 +30,13 @@ #include "components/device_reauth/device_authenticator.h" #include "components/password_manager/core/browser/features/password_features.h" #include "components/password_manager/core/browser/mock_password_form_manager_for_ui.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_bubble_experiment.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_form_metrics_recorder.h" #include "components/password_manager/core/browser/password_manager_client.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_store/interactions_stats.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/password_manager/core/common/password_manager_pref_names.h"
diff --git a/chrome/browser/ui/startup/startup_tab_provider.cc b/chrome/browser/ui/startup/startup_tab_provider.cc index 2763e42..ccdb7a2 100644 --- a/chrome/browser/ui/startup/startup_tab_provider.cc +++ b/chrome/browser/ui/startup/startup_tab_provider.cc
@@ -9,7 +9,6 @@ #include "base/command_line.h" #include "base/feature_list.h" #include "base/files/file_path.h" -#include "base/metrics/histogram_macros.h" #include "base/ranges/algorithm.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" @@ -447,7 +446,6 @@ // static void StartupTabProviderImpl::AddIncompatibleApplicationsUrl(StartupTabs* tabs) { #if BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING) - UMA_HISTOGRAM_BOOLEAN("IncompatibleApplicationsPage.AddedPostCrash", true); GURL url(chrome::kChromeUISettingsURL); tabs->emplace_back(url.Resolve("incompatibleApplications")); #endif // BUILDFLAG(IS_WIN) && BUILDFLAG(GOOGLE_CHROME_BRANDING)
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_contents_view.cc b/chrome/browser/ui/views/download/bubble/download_bubble_contents_view.cc index 22e46d6..93844e28 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_contents_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_contents_view.cc
@@ -68,6 +68,9 @@ // Starts on the primary page. ShowPrimaryPage(); + + bubble_delegate->SetInitiallyFocusedView( + primary_view_->GetInitiallyFocusedView()); } DownloadBubbleContentsView::~DownloadBubbleContentsView() {
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_contents_view_unittest.cc b/chrome/browser/ui/views/download/bubble/download_bubble_contents_view_unittest.cc index 05f20a5..f9715a9 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_contents_view_unittest.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_contents_view_unittest.cc
@@ -151,8 +151,6 @@ bubble_delegate_ = bubble_delegate.get(); navigation_handler_ = std::make_unique<MockDownloadBubbleNavigationHandler>(); - views::BubbleDialogDelegate::CreateBubble(std::move(bubble_delegate)); - bubble_delegate_->GetWidget()->Show(); bubble_controller_ = std::make_unique<DownloadBubbleUIController>(browser_.get()); @@ -163,6 +161,11 @@ navigation_handler_->GetWeakPtr(), IsPrimaryPartialView(), std::make_unique<DownloadBubbleContentsViewInfo>(GetModels()), bubble_delegate_); + // The contents view has to be set up before the bubble is shown, because it + // sets initially focused view on the delegate (which cannot be set after + // the widget is shown). + views::BubbleDialogDelegate::CreateBubble(std::move(bubble_delegate)); + bubble_delegate_->GetWidget()->Show(); } void SetUpMockTrustSafetySentimentSurveys() {
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_interactive_uitest.cc b/chrome/browser/ui/views/download/bubble/download_bubble_interactive_uitest.cc index ed442d4..54d9ec5 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_interactive_uitest.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_interactive_uitest.cc
@@ -10,6 +10,7 @@ #include "chrome/browser/ui/accelerator_utils.h" #include "chrome/browser/ui/browser_element_identifiers.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_test.h" +#include "chrome/browser/ui/views/download/bubble/download_bubble_contents_view.h" #include "chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h" #include "chrome/browser/ui/views/exclusive_access_bubble_views.h" #include "chrome/browser/ui/views/frame/browser_view.h" @@ -102,39 +103,65 @@ } auto DownloadBubbleIsShowingDetails(bool showing) { - return base::BindLambdaForTesting([&, showing = showing]() { - return showing == download_toolbar_button()->IsShowingDetails(); - }); + return base::BindOnce( + [](DownloadToolbarButtonView* download_toolbar_button, bool showing) { + return showing == download_toolbar_button->IsShowingDetails(); + }, + download_toolbar_button(), showing); + } + + // Whether the download bubble's widget is showing and active. + auto DownloadBubbleIsActive(bool active) { + return base::BindOnce( + [](DownloadToolbarButtonView* download_toolbar_button, bool active) { + if (!download_toolbar_button->IsShowingDetails() || + !download_toolbar_button->bubble_contents_for_testing() + ->GetWidget()) { + return false; + } + return active == + download_toolbar_button->bubble_contents_for_testing() + ->GetWidget() + ->IsActive(); + }, + download_toolbar_button(), active); } auto DownloadBubblePromoIsActive(bool active) { - return base::BindLambdaForTesting([&, active = active]() { - return active == - BrowserView::GetBrowserViewForBrowser(browser()) - ->GetFeaturePromoController() - ->IsPromoActive( - feature_engagement::kIPHDownloadToolbarButtonFeature); - }); + return base::BindOnce( + [](DownloadToolbarButtonView* download_toolbar_button, Browser* browser, + bool active) { + return active == + BrowserView::GetBrowserViewForBrowser(browser) + ->GetFeaturePromoController() + ->IsPromoActive( + feature_engagement::kIPHDownloadToolbarButtonFeature); + }, + download_toolbar_button(), browser(), active); } auto ChangeButtonVisibility(bool visible) { - return base::BindLambdaForTesting([&, visible = visible]() { - if (visible) { - download_toolbar_button()->Show(); - } else { - download_toolbar_button()->Hide(); - } - }); + return base::BindOnce( + [](DownloadToolbarButtonView* download_toolbar_button, bool visible) { + if (visible) { + download_toolbar_button->Show(); + } else { + download_toolbar_button->Hide(); + } + }, + download_toolbar_button(), visible); } auto ChangeBubbleVisibility(bool visible) { - return base::BindLambdaForTesting([&, visible = visible]() { - if (visible) { - download_toolbar_button()->ShowDetails(); - } else { - download_toolbar_button()->HideDetails(); - } - }); + return base::BindOnce( + [](DownloadToolbarButtonView* download_toolbar_button, bool visible) { + if (visible) { + download_toolbar_button->ShowDetails(); + } else { + download_toolbar_button->HideDetails(); + } + }, + download_toolbar_button(), visible); } auto DownloadTestFile() { @@ -338,4 +365,39 @@ } #endif +// Tests that the partial view does not steal focus from the web contents, and +// that the partial view is still closable when clicking outside of it, and that +// the main view is focused when shown. +IN_PROC_BROWSER_TEST_F(DownloadBubbleInteractiveUiTest, + ClosePartialBubbleOnClick) { + RunTestSequence( + // Download a test file so that the partial view shows up. + Do(DownloadTestFile()), + InAnyContext(WaitForShow(kToolbarDownloadButtonElementId)), + Check(DownloadBubbleIsShowingDetails(IsPartialViewEnabled()), + "Partial view shows after download, if enabled."), + If([&] { return IsPartialViewEnabled(); }, + // The bubble, if enabled, should be shown as inactive to avoid + // stealing focus from the page. + Steps(Check(DownloadBubbleIsActive(false), + "Partial view, if enabled, is inactive."))), + // Click outside (at the center point of the browser) to close the bubble. + MoveMouseTo(kBrowserViewElementId), ClickMouse(), FlushEvents(), + EnsureNotPresent(kToolbarDownloadBubbleElementId), + Check(DownloadBubbleIsShowingDetails(false), + "Bubble is closed after clicking outside of it."), + // Click on the toolbar button to show the main view, which should always + // have focus. + PressButton(kToolbarDownloadButtonElementId), + WaitForShow(kToolbarDownloadBubbleElementId), + Check(DownloadBubbleIsShowingDetails(true), + "Main view is shown after clicking button."), + // The main view widget should be active. + Check(DownloadBubbleIsActive(true), "Main view is active."), + // Hide the bubble so it's not showing while tearing down the + // test browser (which causes a crash on Mac). + Do(ChangeBubbleVisibility(false)), Do(ChangeButtonVisibility(false)), + WaitForHide(kToolbarDownloadButtonElementId)); +} + } // namespace
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.cc b/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.cc index 8df510f..5fd69cb 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.cc
@@ -138,6 +138,14 @@ return row_list_view_->GetRow(id); } +views::View* DownloadBubblePrimaryView::GetInitiallyFocusedView() { + if (row_list_view_->children().empty()) { + return nullptr; + } + return static_cast<DownloadBubbleRowView*>(row_list_view_->children().front()) + ->transparent_button(); +} + DownloadBubbleRowView* DownloadBubblePrimaryView::GetRowForTesting( size_t index) { return static_cast<DownloadBubbleRowView*>(row_list_view_->children()[index]);
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.h b/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.h index c364242..ba6cadb 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.h +++ b/chrome/browser/ui/views/download/bubble/download_bubble_primary_view.h
@@ -24,6 +24,7 @@ namespace views { class ScrollView; +class View; } // namespace views // Base class for either type of primary view (partial or main). Consists of @@ -43,6 +44,10 @@ // Gets the row view with the given id. Returns nullptr if not found. DownloadBubbleRowView* GetRow(const offline_items_collection::ContentId& id); + // The view to focus first when the bubble is created. By default, returns + // the transparent button (main button) of the first row in the row list. + virtual views::View* GetInitiallyFocusedView(); + // Gets the row view at the given index. DownloadBubbleRowView* GetRowForTesting(size_t index);
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_row_view.cc b/chrome/browser/ui/views/download/bubble/download_bubble_row_view.cc index ac3ec04..a3d96be1 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_row_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_bubble_row_view.cc
@@ -106,6 +106,7 @@ : Button(callback), row_view_(row_view) { views::InkDrop::Get(this)->SetMode(views::InkDropHost::InkDropMode::OFF); SetInstallFocusRingOnFocus(false); + SetFocusBehavior(views::View::FocusBehavior::ALWAYS); } ~DownloadBubbleTransparentButton() override = default;
diff --git a/chrome/browser/ui/views/download/bubble/download_bubble_row_view.h b/chrome/browser/ui/views/download/bubble/download_bubble_row_view.h index 429b26c..6e6c34f 100644 --- a/chrome/browser/ui/views/download/bubble/download_bubble_row_view.h +++ b/chrome/browser/ui/views/download/bubble/download_bubble_row_view.h
@@ -89,6 +89,9 @@ bool AcceleratorPressed(const ui::Accelerator& accelerator) override; bool CanHandleAccelerators() const override; + // Returns the transparent button that is activated when the row is clicked. + views::Button* transparent_button() { return transparent_button_; } + const std::u16string& GetSecondaryLabelTextForTesting(); DownloadUIModel* model() { return info_->model(); }
diff --git a/chrome/browser/ui/views/download/bubble/download_dialog_view.cc b/chrome/browser/ui/views/download/bubble/download_dialog_view.cc index 2f7fe3c..5e732d29 100644 --- a/chrome/browser/ui/views/download/bubble/download_dialog_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_dialog_view.cc
@@ -129,6 +129,10 @@ } // namespace +views::View* DownloadDialogView::GetInitiallyFocusedView() { + return close_button_; +} + void DownloadDialogView::CloseBubble() { if (navigation_handler_) { navigation_handler_->CloseDialog( @@ -163,7 +167,7 @@ title->SetTextStyle(views::style::STYLE_HEADLINE_4); } - auto* close_button = + close_button_ = header->AddChildView(views::CreateVectorImageButtonWithNativeTheme( base::BindRepeating(&DownloadDialogView::CloseBubble, base::Unretained(this)), @@ -171,14 +175,14 @@ ? vector_icons::kCloseChromeRefreshIcon : vector_icons::kCloseRoundedIcon, GetLayoutConstant(DOWNLOAD_ICON_SIZE))); - InstallCircleHighlightPathGenerator(close_button); - close_button->SetTooltipText(l10n_util::GetStringUTF16(IDS_APP_CLOSE)); - close_button->SetProperty(views::kCrossAxisAlignmentKey, - views::LayoutAlignment::kStart); + InstallCircleHighlightPathGenerator(close_button_); + close_button_->SetTooltipText(l10n_util::GetStringUTF16(IDS_APP_CLOSE)); + close_button_->SetProperty(views::kCrossAxisAlignmentKey, + views::LayoutAlignment::kStart); if (features::IsChromeRefresh2023()) { // Remove the extra padding of ImageButton that causes the right padding of // the title row to appear larger than the left padding. - close_button->SetBorder(nullptr); + close_button_->SetBorder(nullptr); } }
diff --git a/chrome/browser/ui/views/download/bubble/download_dialog_view.h b/chrome/browser/ui/views/download/bubble/download_dialog_view.h index 2095f00..b3f8530 100644 --- a/chrome/browser/ui/views/download/bubble/download_dialog_view.h +++ b/chrome/browser/ui/views/download/bubble/download_dialog_view.h
@@ -16,6 +16,11 @@ class Browser; +namespace views { +class Button; +class View; +} // namespace views + // This view represents the 'main view' that is shown when the user clicks on // the download toolbar button. Unlike the partial view, it does not // automatically close. It also has a header and close button, as well as a @@ -33,6 +38,11 @@ const DownloadBubbleRowListViewInfo& info); ~DownloadDialogView() override; + // DownloadBubblePrimaryView: + // Returns the close button. The close button should be the initially focused + // view to make it easier for the user to close the dialog. + views::View* GetInitiallyFocusedView() override; + private: // DownloadBubblePrimaryView base::StringPiece GetVisibleTimeHistogramName() const override; @@ -44,6 +54,7 @@ base::WeakPtr<DownloadBubbleNavigationHandler> navigation_handler_; base::WeakPtr<Browser> browser_; + raw_ptr<views::Button> close_button_ = nullptr; }; #endif // CHROME_BROWSER_UI_VIEWS_DOWNLOAD_BUBBLE_DOWNLOAD_DIALOG_VIEW_H_
diff --git a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc index 02e01ec4..7cf9802 100644 --- a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc +++ b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.cc
@@ -64,6 +64,7 @@ #include "ui/views/controls/image_view.h" #include "ui/views/controls/progress_ring_utils.h" #include "ui/views/controls/scroll_view.h" +#include "ui/views/event_monitor.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/layout/layout_provider.h" @@ -574,6 +575,7 @@ immersive_revealed_lock_.reset(); bubble_delegate_ = nullptr; bubble_contents_ = nullptr; + bubble_closer_.reset(); } std::unique_ptr<DownloadBubbleNavigationHandler::CloseOnDeactivatePin> @@ -651,6 +653,12 @@ if (ShouldShowBubbleAsInactive()) { bubble_delegate_->GetWidget()->ShowInactive(); + bubble_closer_ = std::make_unique<BubbleCloser>(this); + bubble_delegate_->GetWidget() + ->GetRootView() + ->GetViewAccessibility() + .AnnounceText( + l10n_util::GetStringUTF16(IDS_SHOW_BUBBLE_INACTIVE_DESCRIPTION)); } else { bubble_delegate_->GetWidget()->Show(); } @@ -680,6 +688,32 @@ } } +DownloadToolbarButtonView::BubbleCloser::BubbleCloser( + DownloadToolbarButtonView* toolbar_button) + : toolbar_button_(toolbar_button) { + CHECK(toolbar_button_); + if (toolbar_button->GetWidget() && + toolbar_button->GetWidget()->GetNativeWindow()) { + event_monitor_ = views::EventMonitor::CreateWindowMonitor( + this, toolbar_button->GetWidget()->GetNativeWindow(), + {ui::ET_MOUSE_PRESSED, ui::ET_KEY_PRESSED, ui::ET_TOUCH_PRESSED}); + } +} + +DownloadToolbarButtonView::BubbleCloser::~BubbleCloser() = default; + +void DownloadToolbarButtonView::BubbleCloser::OnEvent(const ui::Event& event) { + CHECK(event_monitor_); + if (event.IsKeyEvent() && event.AsKeyEvent()->key_code() != ui::VKEY_ESCAPE) { + return; + } + + if (toolbar_button_->IsShowingDetails()) { + toolbar_button_->HideDetails(); + // `this` will be deleted. + } +} + void DownloadToolbarButtonView::OnPartialViewClosed() { if (download::ShouldSuppressDownloadBubbleIph( browser_->profile()->GetOriginalProfile())) { @@ -767,7 +801,9 @@ } } - return false; + // The partial view shows up without user interaction, so it should not + // steal focus from the web contents. + return is_primary_partial_view_; } SkColor DownloadToolbarButtonView::GetIconColor() const {
diff --git a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h index 8f7e479..df57c189 100644 --- a/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h +++ b/chrome/browser/ui/views/download/bubble/download_toolbar_button_view.h
@@ -17,6 +17,7 @@ #include "components/offline_items_collection/core/offline_item.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/metadata/metadata_header_macros.h" +#include "ui/events/event_observer.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" namespace gfx { @@ -27,6 +28,10 @@ struct ContentId; } +namespace views { +class EventMonitor; +} + class Browser; class BrowserView; class DownloadDisplayController; @@ -145,6 +150,32 @@ std::unique_ptr<DownloadBubbleUIController> bubble_controller); private: + // Closes the bubble when it detects an event such as a mouse click, escape + // key press, etc., which indicates the user's intent to close the bubble. + // This is needed when the bubble is inactive (shown with ShowInactive) + // because the normal close-on-deactivate mechanism doesn't work from an + // already-inactive state. This is created by the DownloadToolbarButtonView + // when the bubble is shown with ShowInactive, and is destroyed when the + // bubble is closed. + // TODO(crbug.com/1503082): Factor out common logic copied from translate + // bubble. + class BubbleCloser : public ui::EventObserver { + public: + explicit BubbleCloser(DownloadToolbarButtonView* toolbar_button); + + BubbleCloser(const BubbleCloser& other) = delete; + BubbleCloser& operator=(const BubbleCloser& other) = delete; + + ~BubbleCloser() override; + + // ui::EventObserver: + void OnEvent(const ui::Event& event) override; + + private: + raw_ptr<DownloadToolbarButtonView> toolbar_button_ = nullptr; // Owns this. + std::unique_ptr<views::EventMonitor> event_monitor_; + }; + // Max download count to show in the badge. Any higher number of downloads // results in a placeholder ("9+"). static constexpr int kMaxDownloadCountDisplayed = 9; @@ -256,6 +287,8 @@ // in immersive mode on ChromeOS and Mac. std::unique_ptr<ImmersiveRevealedLock> immersive_revealed_lock_; + std::unique_ptr<BubbleCloser> bubble_closer_; + base::WeakPtrFactory<DownloadToolbarButtonView> weak_factory_{this}; };
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index 8dce511..39b5264 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -2459,20 +2459,23 @@ // TODO: this fixes crbug.com/1042010 and crbug.com/1052676, but a more // general solution should be desirable to find any bubbles anchored in the // views hierarchy. - if (toolbar_ && toolbar_->app_menu_button()) { - views::DialogDelegate* bubble = - toolbar_->app_menu_button()->GetProperty(views::kAnchoredDialogKey); - if ((!bubble || user_education::HelpBubbleView::IsHelpBubble(bubble)) && - GetLocationBarView()) - bubble = GetLocationBarView()->GetProperty(views::kAnchoredDialogKey); - if ((!bubble || user_education::HelpBubbleView::IsHelpBubble(bubble)) && - toolbar_button_provider_ && - toolbar_button_provider_->GetAvatarToolbarButton()) { - bubble = toolbar_button_provider_->GetAvatarToolbarButton()->GetProperty( - views::kAnchoredDialogKey); + if (toolbar_) { + views::DialogDelegate* bubble = nullptr; + for (auto* view : std::initializer_list<views::View*>{ + toolbar_->app_menu_button(), GetLocationBarView(), + toolbar_button_provider_->GetAvatarToolbarButton(), + toolbar_button_provider_->GetDownloadButton()}) { + if (view) { + if (auto* dialog = view->GetProperty(views::kAnchoredDialogKey); + dialog && !user_education::HelpBubbleView::IsHelpBubble(dialog)) { + bubble = dialog; + break; + } + } } - if (bubble && !user_education::HelpBubbleView::IsHelpBubble(bubble)) { + if (bubble) { + CHECK(!user_education::HelpBubbleView::IsHelpBubble(bubble)); View* focusable = bubble->GetInitiallyFocusedView(); // A PermissionPromptBubbleView will explicitly return nullptr due to
diff --git a/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc b/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc index 3584376..c7fea10 100644 --- a/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_dialog_view.cc
@@ -31,6 +31,7 @@ #include "chrome/browser/ui/views/global_media_controls/media_item_ui_helper.h" #include "chrome/browser/ui/views/global_media_controls/media_item_ui_legacy_cast_footer_view.h" #include "chrome/grit/generated_resources.h" +#include "components/global_media_controls/public/constants.h" #include "components/global_media_controls/public/media_item_manager.h" #include "components/global_media_controls/public/views/media_item_ui_list_view.h" #include "components/global_media_controls/public/views/media_item_ui_view.h" @@ -67,6 +68,7 @@ #include "ui/views/view_class_properties.h" #include "ui/views/views_features.h" +using global_media_controls::GlobalMediaControlsEntryPoint; using media_session::mojom::MediaSessionAction; namespace { @@ -209,10 +211,11 @@ if (!observed_items_[id]) { return; } - + bool show_devices = + entry_point_ == GlobalMediaControlsEntryPoint::kPresentation; observed_items_[id]->UpdateFooterView(BuildFooter(id, item, profile_)); observed_items_[id]->UpdateDeviceSelector(BuildDeviceSelector( - id, item, service_, service_, profile_, entry_point_)); + id, item, service_, service_, profile_, entry_point_, show_devices)); UpdateBubbleSize(); } @@ -657,15 +660,16 @@ UpdateBubbleSize(); } - std::unique_ptr<global_media_controls::MediaItemUIView> MediaDialogView::BuildMediaItemUIView( const std::string& id, base::WeakPtr<media_message_center::MediaNotificationItem> item) { + bool show_devices = + entry_point_ == GlobalMediaControlsEntryPoint::kPresentation; return std::make_unique<global_media_controls::MediaItemUIView>( id, item, BuildFooter(id, item, profile_), - BuildDeviceSelector(id, item, service_, service_, profile_, - entry_point_)); + BuildDeviceSelector(id, item, service_, service_, profile_, entry_point_, + show_devices)); } BEGIN_METADATA(MediaDialogView)
diff --git a/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view.cc b/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view.cc index e5a11f5..deefa54c 100644 --- a/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view.cc +++ b/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view.cc
@@ -174,9 +174,7 @@ views::BoxLayout::Orientation::kVertical)); device_entry_views_container_->SetVisible(false); - if (entry_point_ == - global_media_controls::GlobalMediaControlsEntryPoint::kPresentation || - show_devices) { + if (show_devices) { ShowDevices(); } SetBackground(views::CreateSolidBackground(background_color_));
diff --git a/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view_unittest.cc b/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view_unittest.cc index 5f76bf01..6af77e3 100644 --- a/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view_unittest.cc +++ b/chrome/browser/ui/views/global_media_controls/media_item_ui_device_selector_view_unittest.cc
@@ -318,14 +318,6 @@ view_ = CreateDeviceSelectorView(&delegate); EXPECT_FALSE(view_->GetDeviceEntryViewVisibilityForTesting()); - // The device entry container should be expanded if the media dialog is opened - // for a presentation request. - view_ = CreateDeviceSelectorView( - &delegate, "1", - /*has_audio_output=*/true, - global_media_controls::GlobalMediaControlsEntryPoint::kPresentation); - EXPECT_TRUE(view_->GetDeviceEntryViewVisibilityForTesting()); - // The device entry container should be expanded if it is requested to show // devices. view_ = CreateDeviceSelectorView(
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_list_view.cc b/chrome/browser/ui/views/passwords/manage_passwords_list_view.cc index 8bc00d08..7b72019 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_list_view.cc +++ b/chrome/browser/ui/views/passwords/manage_passwords_list_view.cc
@@ -16,47 +16,13 @@ #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/base/models/image_model.h" #include "ui/gfx/favicon_size.h" #include "ui/gfx/vector_icon_utils.h" -#include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/separator.h" #include "ui/views/view_class_properties.h" using password_manager::metrics_util::PasswordManagementBubbleInteractions; -// static -std::unique_ptr<views::View> ManagePasswordsListView::CreateTitleView( - const std::u16string& title) { - const ChromeLayoutProvider* layout_provider = ChromeLayoutProvider::Get(); - auto header = std::make_unique<views::BoxLayoutView>(); - // Set the space between the icon and title similar to the default behavior in - // BubbleFrameView::Layout(). - header->SetBetweenChildSpacing( - layout_provider->GetInsetsMetric(views::INSETS_DIALOG_TITLE).left()); - header->AddChildView( - std::make_unique<views::ImageView>(ui::ImageModel::FromVectorIcon( - GooglePasswordManagerVectorIcon(), ui::kColorIcon, - layout_provider->GetDistanceMetric( - DISTANCE_BUBBLE_HEADER_VECTOR_ICON_SIZE)))); - views::Label* title_label = header->AddChildView( - views::BubbleFrameView::CreateDefaultTitleLabel(title)); - - const int close_button_width = - layout_provider->GetDistanceMetric( - views::DISTANCE_RELATED_BUTTON_HORIZONTAL) + - gfx::GetDefaultSizeOfVectorIcon(vector_icons::kCloseRoundedIcon) + - layout_provider->GetDistanceMetric(views::DISTANCE_CLOSE_BUTTON_MARGIN); - const int title_width = - layout_provider->GetDistanceMetric( - views::DISTANCE_BUBBLE_PREFERRED_WIDTH) - - layout_provider->GetInsetsMetric(views::INSETS_DIALOG).width() - - layout_provider->GetInsetsMetric(views::INSETS_DIALOG_TITLE).width() - - close_button_width; - title_label->SetMaximumWidth(title_width); - return header; -} - ManagePasswordsListView::ManagePasswordsListView( const std::vector<std::unique_ptr<password_manager::PasswordForm>>& credentials,
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_list_view.h b/chrome/browser/ui/views/passwords/manage_passwords_list_view.h index d0d7c79..1383200 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_list_view.h +++ b/chrome/browser/ui/views/passwords/manage_passwords_list_view.h
@@ -35,9 +35,6 @@ ManagePasswordsListView& operator=(const ManagePasswordsListView&) = delete; ~ManagePasswordsListView() override; - - static std::unique_ptr<views::View> CreateTitleView( - const std::u16string& title); }; #endif // CHROME_BROWSER_UI_VIEWS_PASSWORDS_MANAGE_PASSWORDS_LIST_VIEW_H_
diff --git a/chrome/browser/ui/views/passwords/manage_passwords_view.cc b/chrome/browser/ui/views/passwords/manage_passwords_view.cc index 7c2dec9..83878ca4 100644 --- a/chrome/browser/ui/views/passwords/manage_passwords_view.cc +++ b/chrome/browser/ui/views/passwords/manage_passwords_view.cc
@@ -91,8 +91,7 @@ // Since PasswordBubbleViewBase creates the bubble using // BubbleDialogDelegateView::CreateBubble() *after* the construction of the // ManagePasswordsView, the title view cannot be set in the constructor. - GetBubbleFrameView()->SetTitleView( - ManagePasswordsListView::CreateTitleView(controller_.GetTitle())); + GetBubbleFrameView()->SetTitleView(CreateTitleView(controller_.GetTitle())); } bool ManagePasswordsView::Accept() { @@ -243,8 +242,7 @@ .bottom())); } else { password_details_view_ = nullptr; - frame_view->SetTitleView( - ManagePasswordsListView::CreateTitleView(controller_.GetTitle())); + frame_view->SetTitleView(CreateTitleView(controller_.GetTitle())); page_container_->SwitchToPage(CreatePasswordListView()); page_container_->SetProperty( views::kMarginsKey,
diff --git a/chrome/browser/ui/views/passwords/password_bubble_view_base.cc b/chrome/browser/ui/views/passwords/password_bubble_view_base.cc index b8dc2fd..52b900b 100644 --- a/chrome/browser/ui/views/passwords/password_bubble_view_base.cc +++ b/chrome/browser/ui/views/passwords/password_bubble_view_base.cc
@@ -84,7 +84,7 @@ password_manager::ui::State model_state = PasswordsModelDelegateFromWebContents(web_contents)->GetState(); if (model_state == password_manager::ui::MANAGE_STATE) { - view = new ManagePasswordsView(web_contents, anchor_view); + view = new ManagePasswordsView(web_contents, anchor_view); } else if (model_state == password_manager::ui::AUTO_SIGNIN_STATE) { view = new PasswordAutoSignInView(web_contents, anchor_view); } else if (model_state == password_manager::ui::SAVE_CONFIRMATION_STATE ||
diff --git a/chrome/browser/ui/views/passwords/password_relaunch_chrome_view.cc b/chrome/browser/ui/views/passwords/password_relaunch_chrome_view.cc new file mode 100644 index 0000000..c156364 --- /dev/null +++ b/chrome/browser/ui/views/passwords/password_relaunch_chrome_view.cc
@@ -0,0 +1,63 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/passwords/password_relaunch_chrome_view.h" + +#include "base/functional/bind.h" +#include "chrome/browser/ui/passwords/passwords_model_delegate.h" +#include "chrome/browser/ui/passwords/ui_utils.h" +#include "chrome/browser/ui/views/chrome_layout_provider.h" +#include "chrome/browser/ui/views/chrome_typography.h" +#include "chrome/browser/ui/views/passwords/manage_passwords_list_view.h" +#include "chrome/browser/ui/views/passwords/views_utils.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/gfx/color_utils.h" +#include "ui/views/bubble/bubble_frame_view.h" +#include "ui/views/controls/styled_label.h" +#include "ui/views/layout/fill_layout.h" +#include "ui/views/layout/flex_layout.h" +#include "ui/views/layout/layout_provider.h" + +RelaunchChromeView::RelaunchChromeView(content::WebContents* web_contents, + views::View* anchor_view, + PrefService* prefs) + : PasswordBubbleViewBase(web_contents, + anchor_view, + /*easily_dismissable=*/false), + controller_(PasswordsModelDelegateFromWebContents(web_contents), prefs) { + SetLayoutManager(std::make_unique<views::FillLayout>()); + + SetButtons((ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL)); + SetButtonLabel(ui::DIALOG_BUTTON_OK, controller_.GetContinueButtonText()); + SetButtonLabel(ui::DIALOG_BUTTON_CANCEL, controller_.GetNoThanksButtonText()); + + auto label = std::make_unique<views::Label>(); + label->SetText(controller_.GetBody()); + label->SetMultiLine(/*multi_line=*/true); + AddChildView(std::move(label)); + + SetAcceptCallback(base::BindOnce(&RelaunchChromeBubbleController::OnAccepted, + base::Unretained(&controller_))); + + SetCancelCallback(base::BindOnce(&RelaunchChromeBubbleController::OnCanceled, + base::Unretained(&controller_))); +} + +RelaunchChromeView::~RelaunchChromeView() = default; + +RelaunchChromeBubbleController* RelaunchChromeView::GetController() { + return &controller_; +} + +const RelaunchChromeBubbleController* RelaunchChromeView::GetController() + const { + return &controller_; +} + +void RelaunchChromeView::AddedToWidget() { + // Since PasswordBubbleViewBase creates the bubble using + // BubbleDialogDelegateView::CreateBubble() *after* the construction of the + // RelaunchChromeView, the title view cannot be set in the constructor. + GetBubbleFrameView()->SetTitleView(CreateTitleView(controller_.GetTitle())); +}
diff --git a/chrome/browser/ui/views/passwords/password_relaunch_chrome_view.h b/chrome/browser/ui/views/passwords/password_relaunch_chrome_view.h new file mode 100644 index 0000000..f85f1c2e1 --- /dev/null +++ b/chrome/browser/ui/views/passwords/password_relaunch_chrome_view.h
@@ -0,0 +1,28 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_UI_VIEWS_PASSWORDS_PASSWORD_RELAUNCH_CHROME_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_PASSWORDS_PASSWORD_RELAUNCH_CHROME_VIEW_H_ + +#include "chrome/browser/ui/passwords/bubble_controllers/relaunch_chrome_bubble_controller.h" +#include "chrome/browser/ui/views/passwords/password_bubble_view_base.h" + +// Bubble prompting user to relaunch Chrome. +class RelaunchChromeView : public PasswordBubbleViewBase { + public: + RelaunchChromeView(content::WebContents* web_contents, + views::View* anchor_view, + PrefService* prefs); + ~RelaunchChromeView() override; + + private: + // PasswordBubbleViewBase: + RelaunchChromeBubbleController* GetController() override; + const RelaunchChromeBubbleController* GetController() const override; + void AddedToWidget() override; + + RelaunchChromeBubbleController controller_; +}; + +#endif // CHROME_BROWSER_UI_VIEWS_PASSWORDS_PASSWORD_RELAUNCH_CHROME_VIEW_H_
diff --git a/chrome/browser/ui/views/passwords/password_save_update_view_unittest.cc b/chrome/browser/ui/views/passwords/password_save_update_view_unittest.cc index 5ecbb2f2d..400c3b9 100644 --- a/chrome/browser/ui/views/passwords/password_save_update_view_unittest.cc +++ b/chrome/browser/ui/views/passwords/password_save_update_view_unittest.cc
@@ -16,9 +16,9 @@ #include "chrome/browser/ui/views/passwords/password_bubble_view_test_base.h" #include "chrome/grit/generated_resources.h" #include "components/password_manager/core/browser/mock_password_feature_manager.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/sync/test/test_sync_service.h" #include "content/public/test/navigation_simulator.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/chrome/browser/ui/views/passwords/views_utils.cc b/chrome/browser/ui/views/passwords/views_utils.cc index be880bfb..f15f283 100644 --- a/chrome/browser/ui/views/passwords/views_utils.cc +++ b/chrome/browser/ui/views/passwords/views_utils.cc
@@ -11,11 +11,15 @@ #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/grit/generated_resources.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/vector_icons/vector_icons.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/models/simple_combobox_model.h" +#include "ui/gfx/vector_icon_utils.h" +#include "ui/views/bubble/bubble_frame_view.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/editable_combobox/editable_combobox.h" #include "ui/views/controls/editable_combobox/editable_password_combobox.h" +#include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/flex_layout.h" @@ -299,3 +303,33 @@ kSavePasswordComboboxElementId); return combobox; } + +std::unique_ptr<views::View> CreateTitleView(const std::u16string& title) { + const ChromeLayoutProvider* layout_provider = ChromeLayoutProvider::Get(); + auto header = std::make_unique<views::BoxLayoutView>(); + // Set the space between the icon and title similar to the default behavior in + // BubbleFrameView::Layout(). + header->SetBetweenChildSpacing( + layout_provider->GetInsetsMetric(views::INSETS_DIALOG_TITLE).left()); + header->AddChildView( + std::make_unique<views::ImageView>(ui::ImageModel::FromVectorIcon( + GooglePasswordManagerVectorIcon(), ui::kColorIcon, + layout_provider->GetDistanceMetric( + DISTANCE_BUBBLE_HEADER_VECTOR_ICON_SIZE)))); + views::Label* title_label = header->AddChildView( + views::BubbleFrameView::CreateDefaultTitleLabel(title)); + + const int close_button_width = + layout_provider->GetDistanceMetric( + views::DISTANCE_RELATED_BUTTON_HORIZONTAL) + + gfx::GetDefaultSizeOfVectorIcon(vector_icons::kCloseRoundedIcon) + + layout_provider->GetDistanceMetric(views::DISTANCE_CLOSE_BUTTON_MARGIN); + const int title_width = + layout_provider->GetDistanceMetric( + views::DISTANCE_BUBBLE_PREFERRED_WIDTH) - + layout_provider->GetInsetsMetric(views::INSETS_DIALOG).width() - + layout_provider->GetInsetsMetric(views::INSETS_DIALOG_TITLE).width() - + close_button_width; + title_label->SetMaximumWidth(title_width); + return header; +}
diff --git a/chrome/browser/ui/views/passwords/views_utils.h b/chrome/browser/ui/views/passwords/views_utils.h index 3d2cbd74..2737909 100644 --- a/chrome/browser/ui/views/passwords/views_utils.h +++ b/chrome/browser/ui/views/passwords/views_utils.h
@@ -101,4 +101,7 @@ ui::ImageModel primary_account_avatar, bool is_using_account_store); +// Creates a view with PasswordManager icon and a `title` string. +std::unique_ptr<views::View> CreateTitleView(const std::u16string& title); + #endif // CHROME_BROWSER_UI_VIEWS_PASSWORDS_VIEWS_UTILS_H_
diff --git a/chrome/browser/ui/views/permissions/embedded_permission_prompt_content_scrim_view.cc b/chrome/browser/ui/views/permissions/embedded_permission_prompt_content_scrim_view.cc index 837734be..51da612 100644 --- a/chrome/browser/ui/views/permissions/embedded_permission_prompt_content_scrim_view.cc +++ b/chrome/browser/ui/views/permissions/embedded_permission_prompt_content_scrim_view.cc
@@ -48,7 +48,7 @@ std::make_unique<EmbeddedPermissionPromptContentScrimView>( delegate, top_level_widget); content_scrim_view->SetBackground(views::CreateSolidBackground( - SkColorSetA(gfx::kGoogleGrey700, SK_AlphaOPAQUE * 0.7f))); + SkColorSetA(gfx::kGoogleGrey700, SK_AlphaOPAQUE * 0.5f))); widget->SetContentsView(std::move(content_scrim_view)); widget->Show(); return widget;
diff --git a/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc b/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc index 1337713..a8d6217 100644 --- a/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc +++ b/chrome/browser/ui/views/web_apps/sub_apps_install_dialog.cc
@@ -48,13 +48,12 @@ } ui::DialogModelLabel DialogDescription(int num_sub_apps, - std::u16string parent_app_name, - std::u16string parent_app_scope) { + std::u16string parent_app_name) { std::u16string description = base::i18n::MessageFormatter::FormatWithNamedArgs( l10n_util::GetStringUTF16(IDS_SUB_APPS_INSTALL_DIALOG_DESCRIPTION), /*name0=*/"NUM_SUB_APP_INSTALLS", num_sub_apps, - /*name1=*/"APP_NAME", parent_app_name, "DOMAIN", parent_app_scope); + /*name1=*/"APP_NAME", parent_app_name); ui::DialogModelLabel label = ui::DialogModelLabel(description); label.set_is_secondary().set_allow_character_break(); return label; @@ -156,7 +155,6 @@ views::Widget* CreateSubAppsInstallDialogWidget( const std::u16string parent_app_name, - const std::u16string parent_app_scope, const std::vector<std::unique_ptr<web_app::WebAppInstallInfo>>& sub_apps, base::RepeatingClosure settings_page_callback, gfx::NativeWindow window) { @@ -166,8 +164,7 @@ .SetInternalName("SubAppsInstallDialogController") .SetIcon(GetInstallAppIcon()) .SetTitle(DialogTitle(num_sub_apps)) - .AddParagraph(DialogDescription(num_sub_apps, parent_app_name, - parent_app_scope)) + .AddParagraph(DialogDescription(num_sub_apps, parent_app_name)) .AddCustomField( std::make_unique<views::BubbleDialogModelHost::CustomView>( CreateSubAppsListView(sub_apps),
diff --git a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.cc b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.cc index 45d4cea..577b4fb 100644 --- a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.cc +++ b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.cc
@@ -40,7 +40,6 @@ base::OnceCallback<void(bool)> callback, const std::vector<std::unique_ptr<WebAppInstallInfo>>& sub_apps, const std::string& parent_app_name, - const std::string& parent_app_scope, const webapps::AppId& parent_app_id, Profile* profile, gfx::NativeWindow window) { @@ -59,8 +58,7 @@ callback_ = std::move(callback); widget_ = CreateSubAppsInstallDialogWidget( - base::UTF8ToUTF16(parent_app_name), base::UTF8ToUTF16(parent_app_scope), - sub_apps, + base::UTF8ToUTF16(parent_app_name), sub_apps, base::BindRepeating(OpenAppSettingsForParentApp, parent_app_id, profile), window); widget_observation_.Observe(widget_);
diff --git a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.h b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.h index c26e36d..7df126a 100644 --- a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.h +++ b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller.h
@@ -50,7 +50,6 @@ void Init(base::OnceCallback<void(bool)> callback, const std::vector<std::unique_ptr<WebAppInstallInfo>>& sub_apps, const std::string& parent_app_name, - const std::string& parent_app_scope, const webapps::AppId& parent_app_id, Profile* profile, gfx::NativeWindow window);
diff --git a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_browsertest.cc b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_browsertest.cc index 44b0ea6..508bc4e 100644 --- a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_browsertest.cc +++ b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_browsertest.cc
@@ -68,15 +68,13 @@ const webapps::AppId parent_app_id = parent_app.app_id(); auto controller = std::make_unique<SubAppsInstallDialogController>(); - controller->Init( - base::DoNothing(), {}, - provider().registrar_unsafe().GetAppShortName(parent_app_id), - provider().registrar_unsafe().GetAppScope(parent_app_id).spec(), - parent_app_id, profile(), - browser() - ->tab_strip_model() - ->GetActiveWebContents() - ->GetTopLevelNativeWindow()); + controller->Init(base::DoNothing(), {}, + provider().registrar_unsafe().GetAppShortName(parent_app_id), + parent_app_id, profile(), + browser() + ->tab_strip_model() + ->GetActiveWebContents() + ->GetTopLevelNativeWindow()); views::Widget* widget = controller->GetWidgetForTesting(); views::View* manage_permissions_link = widget->GetContentsView()->GetViewByID(base::to_underlying(
diff --git a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_unittest.cc b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_unittest.cc index e66f6344..0cf92266 100644 --- a/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_unittest.cc +++ b/chrome/browser/ui/web_applications/sub_apps_install_dialog_controller_unittest.cc
@@ -43,8 +43,7 @@ auto controller = std::make_unique<SubAppsInstallDialogController>(); controller->Init(std::move(callback), /*sub_apps=*/{}, kParentAppName, - kParentAppScope, parent_app_id, GetProfile(), - GetContext()); + parent_app_id, GetProfile(), GetContext()); return controller; } }; @@ -68,8 +67,7 @@ sub_apps.emplace_back(CreateInstallInfoWithIconForSubApp(kSubAppName3)); views::Widget* widget = CreateSubAppsInstallDialogWidget( - base::ASCIIToUTF16(std::string(kParentAppName)), - base::ASCIIToUTF16(std::string(kParentAppScope)), sub_apps, + base::ASCIIToUTF16(std::string(kParentAppName)), sub_apps, base::DoNothing(), GetContext()); views::DialogDelegate* dialog = widget->widget_delegate()->AsDialogDelegate(); @@ -107,8 +105,8 @@ webapps::AppId parent_app_id = web_app::GenerateAppIdFromManifestId(GURL(kParentAppScope)); auto controller = std::make_unique<SubAppsInstallDialogController>(); - controller->Init(base::DoNothing(), sub_apps, kParentAppName, kParentAppScope, - parent_app_id, GetProfile(), GetContext()); + controller->Init(base::DoNothing(), sub_apps, kParentAppName, parent_app_id, + GetProfile(), GetContext()); views::Widget* widget = controller->GetWidgetForTesting(); std::vector<views::View*> sub_app_labels;
diff --git a/chrome/browser/ui/web_applications/sub_apps_service_impl.cc b/chrome/browser/ui/web_applications/sub_apps_service_impl.cc index f9626ed..a6af3a5 100644 --- a/chrome/browser/ui/web_applications/sub_apps_service_impl.cc +++ b/chrome/browser/ui/web_applications/sub_apps_service_impl.cc
@@ -345,7 +345,6 @@ weak_ptr_factory_.GetWeakPtr(), add_call_id), add_call_info.install_infos, /*parent_app_name=*/registrar.GetAppShortName(*parent_app_id), - /*parent_app_scope=*/registrar.GetAppScope(*parent_app_id).spec(), *parent_app_id, GetProfile(render_frame_host()), /*window=*/ content::WebContents::FromRenderFrameHost(&render_frame_host())
diff --git a/chrome/browser/ui/web_applications/web_app_dialogs.h b/chrome/browser/ui/web_applications/web_app_dialogs.h index f9a99bb..de5960a 100644 --- a/chrome/browser/ui/web_applications/web_app_dialogs.h +++ b/chrome/browser/ui/web_applications/web_app_dialogs.h
@@ -70,7 +70,6 @@ // information to represent each app to the user. views::Widget* CreateSubAppsInstallDialogWidget( const std::u16string parent_app_name, - const std::u16string parent_app_scope, const std::vector<std::unique_ptr<WebAppInstallInfo>>& sub_apps, base::RepeatingClosure settings_page_callback, gfx::NativeWindow window);
diff --git a/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc b/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc index 42006dd..01a5b6f5 100644 --- a/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc +++ b/chrome/browser/web_applications/app_service/web_app_publisher_helper.cc
@@ -1602,17 +1602,12 @@ void WebAppPublisherHelper::OnWebAppSettingsPolicyChanged() { DCHECK(!IsShuttingDown()); - // TODO(crbug.com/1293961): when more fseatures are added to policy manager, - // we need to remove per-feature updates in favor of a full refresh, as each - // feature multiplicatively increases the complexity of this operation. + for (const WebApp& web_app : registrar().GetApps()) { if (IsAppServiceShortcut(web_app.app_id(), *provider_)) { continue; } - const auto login_mode = - registrar().GetAppRunOnOsLoginMode(web_app.app_id()); - - PublishRunOnOsLoginModeUpdate(web_app.app_id(), login_mode.value); + delegate_->PublishWebApp(CreateWebApp(&web_app)); } }
diff --git a/chrome/browser/web_applications/app_service/web_apps.cc b/chrome/browser/web_applications/app_service/web_apps.cc index aa3a62c..32f875ddb 100644 --- a/chrome/browser/web_applications/app_service/web_apps.cc +++ b/chrome/browser/web_applications/app_service/web_apps.cc
@@ -28,6 +28,8 @@ #include "ash/webui/projector_app/public/cpp/projector_app_constants.h" // nogncheck #include "base/functional/bind.h" #include "base/strings/utf_string_conversions.h" +#include "chrome/browser/apps/app_service/app_service_proxy.h" +#include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/apps/app_service/menu_item_constants.h" #include "chrome/browser/apps/app_service/menu_util.h" #include "chrome/browser/apps/app_service/promise_apps/promise_app_web_apps_utils.h" @@ -36,7 +38,6 @@ #include "chrome/browser/ash/system_web_apps/system_web_app_manager.h" #include "chrome/browser/web_applications/web_app_icon_manager.h" #include "chrome/grit/generated_resources.h" -#include "components/services/app_service/public/cpp/app_registry_cache.h" #include "components/services/app_service/public/cpp/instance_registry.h" #include "components/services/app_service/public/cpp/intent_filter_util.h" #endif @@ -180,6 +181,13 @@ return; } + bool can_close = true; + apps::AppServiceProxyFactory::GetForProfile(profile()) + ->AppRegistryCache() + .ForOneApp(app_id, [&can_close](const apps::AppUpdate& update) { + can_close = update.AllowClose().value_or(true); + }); + apps::MenuItems menu_items; auto* swa_manager = ash::SystemWebAppManager::Get(profile()); if (swa_manager && swa_manager->IsSystemWebApp(web_app->app_id())) { @@ -192,7 +200,10 @@ apps::AddCommandItem(ash::LAUNCH_NEW, IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW, menu_items); } - } else { + // If app cannot be closed there should be no more than 1 open window, so we + // should not allow open more windows because user won't be able to close + // them. + } else if (can_close) { if (chromeos::features::IsCrosShortstandEnabled()) { apps::AddCommandItem(ash::LAUNCH_NEW, IDS_APP_LIST_CONTEXT_MENU_NEW_WINDOW, menu_items); @@ -209,8 +220,7 @@ guest_os::AddTerminalMenuItems(profile_, menu_items); } - if (menu_type == apps::MenuType::kShelf && - instance_registry_->ContainsAppId(app_id)) { + if (ShouldAddCloseItem(app_id, menu_type, profile_)) { apps::AddCommandItem(ash::MENU_CLOSE, IDS_SHELF_CONTEXT_MENU_CLOSE, menu_items); }
diff --git a/chrome/browser/web_applications/app_service/web_apps_chromeos_browsertest.cc b/chrome/browser/web_applications/app_service/web_apps_chromeos_browsertest.cc index 066cf98..b5cf3c6 100644 --- a/chrome/browser/web_applications/app_service/web_apps_chromeos_browsertest.cc +++ b/chrome/browser/web_applications/app_service/web_apps_chromeos_browsertest.cc
@@ -11,21 +11,32 @@ #include "ash/public/cpp/shelf_model.h" #include "base/run_loop.h" #include "base/test/bind.h" +#include "base/test/test_future.h" +#include "chrome/browser/apps/app_service/app_registry_cache_waiter.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/ui/ash/shelf/chrome_shelf_controller_util.h" +#include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h" #include "chrome/browser/ui/web_applications/web_app_controller_browsertest.h" +#include "chrome/browser/web_applications/policy/web_app_policy_constants.h" +#include "chrome/browser/web_applications/test/web_app_install_test_utils.h" +#include "chrome/browser/web_applications/web_app_id_constants.h" +#include "chrome/common/pref_names.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/prefs/pref_service.h" #include "components/webapps/common/web_app_id.h" #include "content/public/browser/notification_service.h" #include "content/public/test/browser_test.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/models/image_model.h" +#include "ui/base/models/menu_model.h" #include "ui/base/models/simple_menu_model.h" #include "ui/display/display.h" +#include "ui/display/screen.h" #include "ui/events/event_constants.h" #include "ui/gfx/image/image.h" #include "url/gurl.h" @@ -116,3 +127,104 @@ ui::EF_LEFT_MOUSE_BUTTON); url_observer.Wait(); } + +namespace { + +constexpr char kCalculatorAppUrl[] = "https://calculator.apps.chrome/"; + +bool HasMenuModelCommandId(ui::MenuModel* model, ash::CommandId command_id) { + size_t index = 0; + return ui::MenuModel::GetModelAndIndexForCommandId(command_id, &model, + &index); +} + +} // namespace + +class WebAppsPreventCloseChromeOsBrowserTest + : public web_app::WebAppControllerBrowserTest, + public ::testing::WithParamInterface<bool> { + public: + WebAppsPreventCloseChromeOsBrowserTest() = default; + + WebAppsPreventCloseChromeOsBrowserTest( + const WebAppsPreventCloseChromeOsBrowserTest&) = delete; + WebAppsPreventCloseChromeOsBrowserTest& operator=( + const WebAppsPreventCloseChromeOsBrowserTest&) = delete; + + ~WebAppsPreventCloseChromeOsBrowserTest() override = default; + + bool IsPreventCloseEnabled() const { return GetParam(); } + + void InstallPWA(const GURL& app_url, const webapps::AppId& app_id) { + auto web_app_info = std::make_unique<web_app::WebAppInstallInfo>(); + web_app_info->start_url = app_url; + web_app_info->scope = app_url.GetWithoutFilename(); + const webapps::AppId installed_app_id = web_app::test::InstallWebApp( + browser()->profile(), std::move(web_app_info)); + EXPECT_EQ(app_id, installed_app_id); + } +}; + +IN_PROC_BROWSER_TEST_P(WebAppsPreventCloseChromeOsBrowserTest, CheckMenuModel) { + InstallPWA(GURL(kCalculatorAppUrl), web_app::kCalculatorAppId); + PinAppWithIDToShelf(web_app::kCalculatorAppId); + + Browser* const browser = LaunchWebAppBrowser(web_app::kCalculatorAppId); + ASSERT_TRUE(browser); + + // Set up policy values. + profile()->GetPrefs()->SetList( + prefs::kWebAppSettings, + base::Value::List().Append( + base::Value::Dict() + .Set(web_app::kManifestId, kCalculatorAppUrl) + .Set(web_app::kRunOnOsLogin, web_app::kRunWindowed) + .Set(web_app::kPreventClose, IsPreventCloseEnabled()))); + + // Wait until prefs are propagated and App `allow_close` field is updated to + // expected value. + apps::AppUpdateWaiter waiter( + profile(), web_app::kCalculatorAppId, + base::BindRepeating( + [](bool expected_allow_close, const apps::AppUpdate& update) { + return update.AllowClose().has_value() && + update.AllowClose().value() == expected_allow_close; + }, + !IsPreventCloseEnabled())); + waiter.Wait(); + + ash::ShelfModel* const shelf_model = ash::ShelfModel::Get(); + ASSERT_TRUE(shelf_model); + + ash::ShelfItemDelegate* const delegate = shelf_model->GetShelfItemDelegate( + ash::ShelfID(web_app::kCalculatorAppId)); + ASSERT_TRUE(delegate); + + base::test::TestFuture<std::unique_ptr<ui::SimpleMenuModel>> model_future; + delegate->GetContextMenu(display::Display::GetDefaultDisplay().id(), + model_future.GetCallback()); + std::unique_ptr<ui::SimpleMenuModel> menu_model(model_future.Take()); + ASSERT_TRUE(menu_model); + + // Check close button. + EXPECT_EQ(HasMenuModelCommandId(menu_model.get(), ash::MENU_CLOSE), + !IsPreventCloseEnabled()); + + // Check new window and new tab buttons. + EXPECT_EQ(HasMenuModelCommandId(menu_model.get(), ash::LAUNCH_NEW), + !IsPreventCloseEnabled()); + EXPECT_EQ( + HasMenuModelCommandId(menu_model.get(), ash::USE_LAUNCH_TYPE_REGULAR), + !IsPreventCloseEnabled()); + EXPECT_EQ( + HasMenuModelCommandId(menu_model.get(), ash::USE_LAUNCH_TYPE_WINDOW), + !IsPreventCloseEnabled()); + + // Clear policy values, otherwise we won't be able to gracefully close stop + // browser test. + profile()->GetPrefs()->SetList(prefs::kWebAppSettings, base::Value::List()); +} + +INSTANTIATE_TEST_SUITE_P(All, + WebAppsPreventCloseChromeOsBrowserTest, + ::testing::Bool());
diff --git a/chrome/build/android-arm32.pgo.txt b/chrome/build/android-arm32.pgo.txt index cea0d444..c8d2a3b 100644 --- a/chrome/build/android-arm32.pgo.txt +++ b/chrome/build/android-arm32.pgo.txt
@@ -1 +1 @@ -chrome-android32-main-1700438073-b700ac64e357f6edfde004f5fe7052dd22cfc71e.profdata +chrome-android32-main-1700481515-65aa7de54bfda6dd1c1c8ccaa010694885671eef.profdata
diff --git a/chrome/build/android-arm64.pgo.txt b/chrome/build/android-arm64.pgo.txt index 2aeee2a..92dd0b0 100644 --- a/chrome/build/android-arm64.pgo.txt +++ b/chrome/build/android-arm64.pgo.txt
@@ -1 +1 @@ -chrome-android64-main-1700438073-bfe0fbd10fedb26cd5c558cb8d1da1b51637c67a.profdata +chrome-android64-main-1700481515-61b7d809905c4fe7048161ca37935eb847d66447.profdata
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 0e5fd35..8c5d2642 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1700438073-8c2b1ed47a172b736e943ea2202594b436e05975.profdata +chrome-linux-main-1700459332-b9d9b3d8e973cad2e19ff1c1f7ea3e737a612e07.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index eb4c60c3..5d1939cb 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1700438073-932d511927ea9d2cc26366780ad0a740210963ef.profdata +chrome-mac-main-1700459332-fc1ad09421901981da9f2593ace2ff42a7243d3e.profdata
diff --git a/chrome/build/win-arm64.pgo.txt b/chrome/build/win-arm64.pgo.txt index e217c97..7d266ea4 100644 --- a/chrome/build/win-arm64.pgo.txt +++ b/chrome/build/win-arm64.pgo.txt
@@ -1 +1 @@ -chrome-win-arm64-main-1700265573-5ab7af3afcc15a295a22305a3c9652ab95648320.profdata +chrome-win-arm64-main-1700481515-8dba4686d96c01903a2c11a3f0940a00857b0c81.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 4160ebe..731aab2 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1700438073-af3bf248ea36afa4e8d90781d503d82ec2732aa8.profdata +chrome-win32-main-1700470769-74b9a98c3b707d47350cbba9df75acdda636e01f.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 39e9723..b688109 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1700438073-c5bde7e805c54c4720d2a6df06816d77c949c292.profdata +chrome-win64-main-1700470769-3528682c89cd6fc964424332d567ae34563b572b.profdata
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 73de8df..3d2925c 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -4719,6 +4719,7 @@ "../browser/ui/ash/desks/desks_client_browsertest.cc", "../browser/ui/ash/device_scheduled_reboot/reboot_notification_controller_browsertest.cc", "../browser/ui/ash/download_status/holding_space_display_client_browsertest.cc", + "../browser/ui/ash/download_status/notification_display_client_browsertest.cc", "../browser/ui/ash/event_latency_metrics_browsertest.cc", "../browser/ui/ash/feature_discovery_duration_reporter_browsertest.cc", "../browser/ui/ash/float_controller_browsertest.cc",
diff --git a/chromeos/ash/services/auth_factor_config/password_factor_editor.cc b/chromeos/ash/services/auth_factor_config/password_factor_editor.cc index 5308c5ce..3df14d5 100644 --- a/chromeos/ash/services/auth_factor_config/password_factor_editor.cc +++ b/chromeos/ash/services/auth_factor_config/password_factor_editor.cc
@@ -162,12 +162,13 @@ mojom::ConfigureResult::kFatalError)); return; } + bool new_password_local = label.value() == kCryptohomeLocalPasswordKeyLabel; - if (!IsLocalPassword(*password_factor)) { + if (IsLocalPassword(*password_factor) != new_password_local) { // TODO(b/290916811): *Atomically* replace the Gaia password factor with // a local password factor. - LOG(ERROR) << "Current password is not local, will not replace with local " - "password"; + LOG(ERROR) + << "Switching between online and local password is not supported"; auth_factor_config_->NotifyFactorObserversAfterFailure( auth_token, std::move(user_context), base::BindOnce(std::move(callback), @@ -175,9 +176,11 @@ return; } + // Note that old online factors might have label "legacy-0" instead of + // "gaia", so we use password_factor->ref().label() here. auth_factor_editor_.ReplacePasswordFactor( std::move(user_context), cryptohome::RawPassword(new_password), - std::move(label), + password_factor->ref().label(), base::BindOnce(&PasswordFactorEditor::OnPasswordConfigured, weak_factory_.GetWeakPtr(), std::move(callback), auth_token));
diff --git a/chromeos/crosapi/mojom/app_service_types.mojom b/chromeos/crosapi/mojom/app_service_types.mojom index d8628b2..898b8192 100644 --- a/chromeos/crosapi/mojom/app_service_types.mojom +++ b/chromeos/crosapi/mojom/app_service_types.mojom
@@ -112,6 +112,10 @@ // The amount of storage (in bytes) used by the app's data. [MinVersion=21] uint64? data_size_in_bytes@31; + + [MinVersion=22] + // Whether the app publisher allows the app to be closed. + OptionalBool allow_close@32; }; // The types of apps available in the registry.
diff --git a/chromeos/crosapi/mojom/app_service_types_mojom_traits.cc b/chromeos/crosapi/mojom/app_service_types_mojom_traits.cc index d0b83ab..cc2b204 100644 --- a/chromeos/crosapi/mojom/app_service_types_mojom_traits.cc +++ b/chromeos/crosapi/mojom/app_service_types_mojom_traits.cc
@@ -159,6 +159,13 @@ return r->data_size_in_bytes; } +// static +crosapi::mojom::OptionalBool +StructTraits<crosapi::mojom::AppDataView, apps::AppPtr>::allow_close( + const apps::AppPtr& r) { + return ConvertOptionalBoolToMojomOptionalBool(r->allow_close); +} + bool StructTraits<crosapi::mojom::AppDataView, apps::AppPtr>::Read( crosapi::mojom::AppDataView data, apps::AppPtr* out) { @@ -282,6 +289,11 @@ absl::optional<uint64_t> data_size_in_bytes = data.data_size_in_bytes(); + crosapi::mojom::OptionalBool allow_close; + if (!data.ReadAllowClose(&allow_close)) { + return false; + } + auto app = std::make_unique<apps::App>(app_type, app_id); app->readiness = readiness; app->name = name; @@ -323,6 +335,7 @@ ConvertMojomOptionalBoolToOptionalBool(is_platform_app); app->app_size_in_bytes = app_size_in_bytes; app->data_size_in_bytes = data_size_in_bytes; + app->allow_close = ConvertMojomOptionalBoolToOptionalBool(allow_close); *out = std::move(app); return true; }
diff --git a/chromeos/crosapi/mojom/app_service_types_mojom_traits.h b/chromeos/crosapi/mojom/app_service_types_mojom_traits.h index 7a5aeb96..8833b3f 100644 --- a/chromeos/crosapi/mojom/app_service_types_mojom_traits.h +++ b/chromeos/crosapi/mojom/app_service_types_mojom_traits.h
@@ -124,6 +124,8 @@ static absl::optional<uint64_t> data_size_in_bytes(const apps::AppPtr& r); + static crosapi::mojom::OptionalBool allow_close(const apps::AppPtr& r); + static bool Read(crosapi::mojom::AppDataView data, apps::AppPtr* out); };
diff --git a/chromeos/crosapi/mojom/app_service_types_mojom_traits_unittest.cc b/chromeos/crosapi/mojom/app_service_types_mojom_traits_unittest.cc index acae285..b356d60 100644 --- a/chromeos/crosapi/mojom/app_service_types_mojom_traits_unittest.cc +++ b/chromeos/crosapi/mojom/app_service_types_mojom_traits_unittest.cc
@@ -68,6 +68,7 @@ input->handles_intents = true; input->is_platform_app = true; + input->allow_close = true; apps::AppPtr output; ASSERT_TRUE( @@ -129,6 +130,7 @@ EXPECT_TRUE(output->handles_intents.value()); EXPECT_TRUE(output->is_platform_app.value()); + EXPECT_TRUE(output->allow_close.value()); } // Test that serialization and deserialization works with optional fields that @@ -158,6 +160,7 @@ input->is_platform_app = absl::nullopt; input->app_size_in_bytes = absl::nullopt; input->data_size_in_bytes = absl::nullopt; + input->allow_close = absl::nullopt; apps::AppPtr output; ASSERT_TRUE( @@ -195,6 +198,7 @@ EXPECT_TRUE(output->allow_uninstall); EXPECT_TRUE(output->handles_intents); EXPECT_FALSE(output->is_platform_app.has_value()); + EXPECT_FALSE(output->allow_close.has_value()); } // Test that serialization and deserialization works with updating app type.
diff --git a/clank b/clank index 545e490..68949fa 160000 --- a/clank +++ b/clank
@@ -1 +1 @@ -Subproject commit 545e490705f01ebb699f788c8eadb47a77a4fa6c +Subproject commit 68949fa36ab0fb6ad6d4f07bfed5139ecc426c3b
diff --git a/components/BUILD.gn b/components/BUILD.gn index 8192153..784535f 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -260,6 +260,7 @@ "//components/password_manager/core/browser/export:unit_tests", "//components/password_manager/core/browser/features:unit_tests", "//components/password_manager/core/browser/generation:unit_tests", + "//components/password_manager/core/browser/password_store:unit_tests", "//components/password_manager/core/browser/sharing:unit_tests", "//components/password_manager/core/browser/sync:unit_tests", "//components/password_manager/core/browser/ui:unit_tests",
diff --git a/components/android_autofill/browser/autofill_provider_android.cc b/components/android_autofill/browser/autofill_provider_android.cc index 7cbdfda..d31e49f 100644 --- a/components/android_autofill/browser/autofill_provider_android.cc +++ b/components/android_autofill/browser/autofill_provider_android.cc
@@ -144,9 +144,19 @@ const FormData& form, const FormFieldData& field, const gfx::RectF& bounding_box) { - // TODO(crbug.com/1502097): Check whether this form has been cached but not - // interacted with since the caching and, if so, use its session id. - form_ = std::make_unique<FormDataAndroid>(form, GetSessionId()); + // The form is assigned the same session id form sent to the Android framework + // in the prefill request iff all of the following conditions are met: + // - There is a cached form. + // - This is the first time we try to show the bottom sheet for the cached + // form (on their second interaction, the user should see the keyboard). + // - The cached form is similar to the current form - i.e. it consists of the + // same DOM elements as the cached form and their attributes have not + // changed substantially enough - see `FormDataAndroid::SimilarFormAs`. + const bool use_id_of_cached_form = cached_form_ && !has_used_cached_form_ && + cached_form_->SimilarFormAs(form); + form_ = std::make_unique<FormDataAndroid>( + form, + use_id_of_cached_form ? cached_form_->session_id() : CreateSessionId()); FieldInfo field_info; if (!form_->GetFieldIndex(field, &field_info.index)) { Reset(); @@ -165,6 +175,9 @@ form_->UpdateFieldTypes(*form_structure); } field_info.bounds = ToClientAreaBound(bounding_box); + // TODO(crbug.com/1502108): Only set to true once there is confirmation that + // the bottom sheet has been shown. + has_used_cached_form_ = true; bridge_->StartAutofillSession( *form_, field_info, manager->has_server_prediction(form.global_id())); } @@ -447,7 +460,7 @@ // Autofill session is truly terminated. } -SessionId AutofillProviderAndroid::GetSessionId() { +SessionId AutofillProviderAndroid::CreateSessionId() { last_session_id_ = last_session_id_ == kMaximumSessionId ? kMinimumSessionId : SessionId(last_session_id_.value() + 1); @@ -509,7 +522,8 @@ return; } - cached_form_ = std::make_unique<FormDataAndroid>(form_data, GetSessionId()); + cached_form_ = + std::make_unique<FormDataAndroid>(form_data, CreateSessionId()); cached_form_->UpdateFieldTypes(*form_structure); bridge_->SendPrefillRequest(*cached_form_); }
diff --git a/components/android_autofill/browser/autofill_provider_android.h b/components/android_autofill/browser/autofill_provider_android.h index 1948649..89fa76d 100644 --- a/components/android_autofill/browser/autofill_provider_android.h +++ b/components/android_autofill/browser/autofill_provider_android.h
@@ -129,7 +129,7 @@ // Returns a new session id. Session ids are required when creating a // `FormDataAndroid` object and used to generate virtual ids that identify // form fields uniquely to the Android Autofill framework. - SessionId GetSessionId(); + SessionId CreateSessionId(); // Returns whether prefill requests are supported. This depends on the // Android version. @@ -150,6 +150,12 @@ // The form for which a prefill request has been sent. std::unique_ptr<FormDataAndroid> cached_form_; + // Indicates whether we have used the cached form to show a bottom sheet. This + // state is kept because a bottom sheet should only be shown once per cached + // form to allow the user to access the keyboard after focusing on the + // (cached) form a second time. + bool has_used_cached_form_ = false; + // The form of the current session (queried input or changed select box). std::unique_ptr<FormDataAndroid> form_;
diff --git a/components/android_autofill/browser/autofill_provider_android_unittest.cc b/components/android_autofill/browser/autofill_provider_android_unittest.cc index ea08a56..073dad4 100644 --- a/components/android_autofill/browser/autofill_provider_android_unittest.cc +++ b/components/android_autofill/browser/autofill_provider_android_unittest.cc
@@ -38,14 +38,17 @@ namespace { using ::testing::_; +using ::testing::AllOf; using ::testing::AtLeast; using ::testing::Eq; using ::testing::Field; using ::testing::Mock; +using ::testing::NiceMock; using ::testing::Optional; +using ::testing::Property; using ::testing::ResultOf; -using ::testing::SaveArg; using ::testing::UnorderedElementsAre; +using ::testing::WithArg; using FieldInfo = AutofillProviderAndroidBridge::FieldInfo; using test::CreateFormDataForFrame; using test::CreateTestCreditCardFormData; @@ -66,6 +69,22 @@ true); } +// Creates a matcher that compares the results of a `FormDataAndroid`'s `form()` +// and `session_id()` methods to `form` and `session_id`. +auto EqualsFormDataWithSessionId(const FormData& form, SessionId session_id) { + return AllOf(EqualsFormData(form), + Property(&FormDataAndroid::session_id, session_id)); +} + +// Returns an action that writes the `SessionId` of a `FormDataAndroid` into the +// out parameter `session_id`. Note that `session_id` must be valid at least +// until the action is executed. +auto SaveSessionId(SessionId* session_id) { + return [session_id](const FormDataAndroid& form_android) { + *session_id = form_android.session_id(); + }; +} + FormData CreateTestLoginForm() { FormData form; form.unique_renderer_id = test::MakeFormRendererId(); @@ -182,15 +201,16 @@ AndroidAutofillBridgeFactory::GetInstance() .SetFormFieldDataAndroidTestingFactory(base::BindLambdaForTesting( []() -> std::unique_ptr<FormFieldDataAndroidBridge> { - return std::make_unique<MockFormFieldDataAndroidBridge>(); + return std::make_unique< + NiceMock<MockFormFieldDataAndroidBridge>>(); })); AndroidAutofillBridgeFactory::GetInstance() .SetAutofillProviderAndroidTestingFactory(base::BindLambdaForTesting( [&bridge_ptr = provider_bridge_]( AutofillProviderAndroidBridge::Delegate* delegate) -> std::unique_ptr<AutofillProviderAndroidBridge> { - auto bridge = - std::make_unique<MockAutofillProviderAndroidBridge>(); + auto bridge = std::make_unique< + NiceMock<MockAutofillProviderAndroidBridge>>(); bridge_ptr = bridge.get(); return bridge; })); @@ -630,6 +650,151 @@ login_form2.global_id()); } +// Tests that the session id used in a prefill request is also used for starting +// the Autofill session for that form. +TEST_F(AutofillProviderAndroidTest, SessionIdIsReusedForCachedForms) { + if (base::android::BuildInfo::GetInstance()->sdk_int() < + base::android::SdkVersion::SDK_VERSION_U) { + GTEST_SKIP(); + } + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature( + features::kAndroidAutofillPrefillRequestsForLoginForms); + + FormData form = + CreateFormDataForFrame(CreateTestLoginForm(), main_frame_token()); + android_autofill_manager().OnFormsSeen({form}, /*removed_forms=*/{}); + ASSERT_TRUE(android_autofill_manager().FindCachedFormById(form.global_id())); + + // Upon receiving server predictions a prefill request should be sent. + SessionId cache_session_id = SessionId(0); + EXPECT_CALL(provider_bridge(), SendPrefillRequest(EqualsFormData(form))) + .WillOnce(SaveSessionId(&cache_session_id)); + android_autofill_manager().SimulatePropagateAutofillPredictions( + form.global_id()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + + EXPECT_CALL( + provider_bridge(), + StartAutofillSession(EqualsFormDataWithSessionId(form, cache_session_id), + EqualsFieldInfo(/*index=*/0), + /*has_server_predictions=*/true)); + android_autofill_manager().SimulateOnAskForValuesToFill(form, + form.fields.front()); +} + +// Tests that the session id used in a prefill request is not reused when +// starting a session on a form with the same id, but changed field content. +TEST_F(AutofillProviderAndroidTest, + SessionIdIsNotReusedForCachedFormsIfContentHasChanged) { + if (base::android::BuildInfo::GetInstance()->sdk_int() < + base::android::SdkVersion::SDK_VERSION_U) { + GTEST_SKIP(); + } + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature( + features::kAndroidAutofillPrefillRequestsForLoginForms); + + FormData form = + CreateFormDataForFrame(CreateTestLoginForm(), main_frame_token()); + android_autofill_manager().OnFormsSeen({form}, /*removed_forms=*/{}); + + // Upon receiving server predictions a prefill request should be sent. + SessionId cache_session_id = SessionId(0); + EXPECT_CALL(provider_bridge(), SendPrefillRequest(EqualsFormData(form))) + .WillOnce(SaveSessionId(&cache_session_id)); + android_autofill_manager().SimulatePropagateAutofillPredictions( + form.global_id()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + + FormData changed_form = form; + changed_form.fields.pop_back(); + android_autofill_manager().OnFormsSeen({changed_form}, + /*removed_forms=*/{form.global_id()}); + SessionId autofill_session_id = SessionId(0); + EXPECT_CALL(provider_bridge(), + StartAutofillSession(EqualsFormData(changed_form), + EqualsFieldInfo(/*index=*/0), + /*has_server_predictions=*/true)) + .WillOnce(WithArg<0>(SaveSessionId(&autofill_session_id))); + android_autofill_manager().SimulateOnAskForValuesToFill( + changed_form, changed_form.fields.front()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + + // A new session id is used to start the Autofill session. + EXPECT_NE(cache_session_id, autofill_session_id); +} + +// Tests that the session id used in a prefill request is only used once to +// start an Autofill session. If the user then focuses on a different form +// before returning to the (formerly) cached form, a new session is started. +TEST_F(AutofillProviderAndroidTest, + SessionIdIsNotReusedMultipleAutofillSessions) { + if (base::android::BuildInfo::GetInstance()->sdk_int() < + base::android::SdkVersion::SDK_VERSION_U) { + GTEST_SKIP(); + } + + base::test::ScopedFeatureList scoped_feature_list; + scoped_feature_list.InitAndEnableFeature( + features::kAndroidAutofillPrefillRequestsForLoginForms); + + FormData pw_form = + CreateFormDataForFrame(CreateTestLoginForm(), main_frame_token()); + FormData pi_form = CreateFormDataForFrame( + CreateTestPersonalInformationFormData(), main_frame_token()); + android_autofill_manager().OnFormsSeen({pw_form, pi_form}, + /*removed_forms=*/{}); + + // Upon receiving server predictions a prefill request should be sent. + SessionId cache_session_id = SessionId(0); + EXPECT_CALL(provider_bridge(), SendPrefillRequest(EqualsFormData(pw_form))) + .WillOnce(SaveSessionId(&cache_session_id)); + android_autofill_manager().SimulatePropagateAutofillPredictions( + pw_form.global_id()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + + EXPECT_CALL(provider_bridge(), + StartAutofillSession( + EqualsFormDataWithSessionId(pw_form, cache_session_id), + EqualsFieldInfo(/*index=*/0), + /*has_server_predictions=*/true)); + android_autofill_manager().SimulateOnAskForValuesToFill( + pw_form, pw_form.fields.front()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + + // Now focus on a different form. + SessionId pi_form_session_id = SessionId(0); + EXPECT_CALL(provider_bridge(), + StartAutofillSession(EqualsFormData(pi_form), + EqualsFieldInfo(/*index=*/0), + /*has_server_predictions=*/false)) + .WillOnce(WithArg<0>(SaveSessionId(&pi_form_session_id))); + android_autofill_manager().SimulateOnAskForValuesToFill( + pi_form, pi_form.fields.front()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + + // Unrelated forms should have different session ids. + EXPECT_NE(cache_session_id, pi_form_session_id); + + // Focus back on the original password form. + SessionId pw_form_second_session_id = SessionId(0); + EXPECT_CALL(provider_bridge(), + StartAutofillSession(EqualsFormData(pw_form), + EqualsFieldInfo(/*index=*/0), + /*has_server_predictions=*/true)) + .WillOnce(WithArg<0>(SaveSessionId(&pw_form_second_session_id))); + android_autofill_manager().SimulateOnAskForValuesToFill( + pw_form, pw_form.fields.front()); + Mock::VerifyAndClearExpectations(&provider_bridge()); + // The session id used when focusing back should be different from both those + // before. + EXPECT_NE(cache_session_id, pw_form_second_session_id); + EXPECT_NE(pi_form_session_id, pw_form_second_session_id); +} + class AutofillProviderAndroidTestHidingLogic : public AutofillProviderAndroidTest { public:
diff --git a/components/android_autofill/browser/form_data_android.h b/components/android_autofill/browser/form_data_android.h index ad7d88cb..953354d1 100644 --- a/components/android_autofill/browser/form_data_android.h +++ b/components/android_autofill/browser/form_data_android.h
@@ -69,6 +69,8 @@ const FormData& form() const { return form_; } + const SessionId session_id() const { return session_id_; } + private: // The session id of this form. It is used to generate virtual view ids for // the `ViewStructure` shared with the Android AutofillManager framework.
diff --git a/components/autofill/core/browser/autofill_experiments.cc b/components/autofill/core/browser/autofill_experiments.cc index 73474e5..fdd2fe6 100644 --- a/components/autofill/core/browser/autofill_experiments.cc +++ b/components/autofill/core/browser/autofill_experiments.cc
@@ -34,6 +34,7 @@ #include "components/prefs/pref_service.h" #include "components/strings/grit/components_strings.h" #include "components/sync/base/features.h" +#include "components/sync/base/user_selectable_type.h" #include "components/sync/service/sync_service.h" #include "components/sync/service/sync_service_utils.h" #include "components/sync/service/sync_user_settings.h" @@ -120,23 +121,26 @@ // sync settings become independent. However, since address information is // uploaded during the server card saving flow, credit card upload is not // available when address sync is disabled. - // TODO(crbug.com/1462552): Simplify once IsSyncFeatureActive() is deleted - // from the codebase. - if (sync_service->IsSyncFeatureActive() || + // Before address sync is available in transport mode, server card save is + // offered in transport mode regardless of the setting. (The sync API exposes + // the kAutofill type as disabled in this case.) + bool syncing_or_addresses_in_transport_mode = + sync_service->IsSyncFeatureActive() || base::FeatureList::IsEnabled( - syncer::kSyncDecoupleAddressPaymentSettings)) { - if (!sync_service->GetActiveDataTypes().Has(syncer::AUTOFILL_PROFILE)) { - // In full sync mode, we only allow card upload when addresses are also - // active, because we upload potential billing addresses with the card. - autofill_metrics::LogCardUploadEnabledMetric( - autofill_metrics::CardUploadEnabled:: - kSyncServiceMissingAutofillProfileActiveType, - signin_state_for_metrics); - LogCardUploadDisabled( - log_manager, - "SYNC_SERVICE_MISSING_AUTOFILL_PROFILE_ACTIVE_DATA_TYPE"); - return false; - } + syncer::kSyncEnableContactInfoDataTypeInTransportMode); + bool has_autofill_sync_type = + base::FeatureList::IsEnabled(syncer::kSyncDecoupleAddressPaymentSettings) + ? sync_service->GetUserSettings()->GetSelectedTypes().Has( + syncer::UserSelectableType::kAutofill) + : sync_service->GetActiveDataTypes().Has(syncer::AUTOFILL_PROFILE); + if (syncing_or_addresses_in_transport_mode && !has_autofill_sync_type) { + autofill_metrics::LogCardUploadEnabledMetric( + autofill_metrics::CardUploadEnabled:: + kSyncServiceMissingAutofillProfileActiveType, + signin_state_for_metrics); + LogCardUploadDisabled( + log_manager, "SYNC_SERVICE_MISSING_AUTOFILL_PROFILE_ACTIVE_DATA_TYPE"); + return false; } // Also don't offer upload for users that have an explicit sync passphrase.
diff --git a/components/autofill/core/browser/autofill_experiments_unittest.cc b/components/autofill/core/browser/autofill_experiments_unittest.cc index adc5b81..8646e349 100644 --- a/components/autofill/core/browser/autofill_experiments_unittest.cc +++ b/components/autofill/core/browser/autofill_experiments_unittest.cc
@@ -16,6 +16,7 @@ #include "components/device_reauth/mock_device_authenticator.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" +#include "components/sync/base/features.h" #include "components/sync/test/test_sync_service.h" #include "google_apis/gaia/google_service_auth_error.h" #include "testing/gtest/include/gtest/gtest.h" @@ -147,8 +148,12 @@ 1); } +// Tests that when SyncDecoupleAddressPaymentSettings is disabled, but +// AUTOFILL_PROFILE failed to start, credit card upload is disabled. TEST_F(AutofillExperimentsTest, IsCardUploadEnabled_SyncDoesNotHaveAutofillProfileActiveType) { + base::test::ScopedFeatureList feature; + feature.InitAndDisableFeature(syncer::kSyncDecoupleAddressPaymentSettings); sync_service_.GetUserSettings()->SetSelectedTypes( /*sync_everything=*/false, /*types=*/{syncer::UserSelectableType::kAutofill, @@ -168,6 +173,25 @@ 1); } +// Tests that when SyncDecoupleAddressPaymentSettings is enabled, and the +// kPayments UserSelectableType is selected without kAutofill, credit card +// upload is disabled. +TEST_F(AutofillExperimentsTest, + IsCardUploadEnabled_AutofillSyncSettingNotSelected) { + base::test::ScopedFeatureList feature{ + syncer::kSyncDecoupleAddressPaymentSettings}; + sync_service_.GetUserSettings()->SetSelectedTypes( + /*sync_everything=*/false, + /*types=*/{syncer::UserSelectableType::kPayments}); + EXPECT_FALSE(IsCreditCardUploadEnabled( + AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled)); + histogram_tester.ExpectUniqueSample( + "Autofill.CardUploadEnabled", + autofill_metrics::CardUploadEnabled:: + kSyncServiceMissingAutofillProfileActiveType, + 1); +} + TEST_F(AutofillExperimentsTest, IsCardUploadEnabled_SyncServiceUsingExplicitPassphrase) { sync_service_.SetIsUsingExplicitPassphrase(true); @@ -229,6 +253,11 @@ TEST_F( AutofillExperimentsTest, IsCardUploadEnabled_TransportSyncDoesNotHaveAutofillProfileActiveDataType) { + base::test::ScopedFeatureList features; + features.InitWithFeatures( + /*enabled_features=*/{}, /*disabled_features=*/{ + syncer::kSyncEnableContactInfoDataTypeInTransportMode, + syncer::kSyncDecoupleAddressPaymentSettings}); // When we don't have Sync consent, Sync will start in Transport-only mode // (if allowed). sync_service_.SetHasSyncConsent(false); @@ -237,7 +266,6 @@ /*sync_everything=*/false, /*types=*/{syncer::UserSelectableType::kAutofill, syncer::UserSelectableType::kPayments}); - sync_service_.SetFailedDataTypes({syncer::AUTOFILL_PROFILE}); EXPECT_TRUE(IsCreditCardUploadEnabled( AutofillMetrics::PaymentsSigninState::kSignedInAndSyncFeatureEnabled));
diff --git a/components/autofill/core/browser/autofill_external_delegate.cc b/components/autofill/core/browser/autofill_external_delegate.cc index 62e5960..0294dac 100644 --- a/components/autofill/core/browser/autofill_external_delegate.cc +++ b/components/autofill/core/browser/autofill_external_delegate.cc
@@ -6,6 +6,7 @@ #include <stddef.h> +#include <optional> #include <utility> #include "base/check.h" @@ -26,7 +27,9 @@ #include "components/autofill/core/browser/autofill_driver.h" #include "components/autofill/core/browser/autofill_granular_filling_utils.h" #include "components/autofill/core/browser/autofill_trigger_details.h" +#include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/browser_autofill_manager.h" +#include "components/autofill/core/browser/field_filling_address_util.h" #include "components/autofill/core/browser/metrics/address_rewriter_in_profile_subset_metrics.h" #include "components/autofill/core/browser/metrics/autofill_metrics.h" #include "components/autofill/core/browser/metrics/granular_filling_metrics.h" @@ -368,13 +371,16 @@ case PopupItemId::kAutocompleteEntry: case PopupItemId::kIbanEntry: case PopupItemId::kMerchantPromoCodeEntry: - case PopupItemId::kFieldByFieldFilling: case PopupItemId::kFillExistingPlusAddress: manager_->FillOrPreviewField( mojom::ActionPersistence::kPreview, mojom::TextReplacement::kReplaceAll, query_form_, query_field_, suggestion.main_text.value, suggestion.popup_item_id); break; + case PopupItemId::kFieldByFieldFilling: + FillOrPreviewFieldByFieldFillingSuggestion(suggestion, /*is_preview=*/ + true); + break; case PopupItemId::kVirtualCreditCardEntry: FillAutofillFormData( suggestion.popup_item_id, backend_id, /*is_preview=*/true, @@ -466,10 +472,8 @@ last_field_types_to_fill_for_address_form_section_ [autofill_trigger_field->section] = { autofill_trigger_field->Type().GetStorableType()}; - manager_->FillOrPreviewField( - mojom::ActionPersistence::kFill, - mojom::TextReplacement::kReplaceAll, query_form_, query_field_, - suggestion.main_text.value, PopupItemId::kFieldByFieldFilling); + FillOrPreviewFieldByFieldFillingSuggestion(suggestion, /*is_preview=*/ + false); } break; case PopupItemId::kIbanEntry: @@ -808,6 +812,31 @@ {.trigger_source = trigger_source}); } +void AutofillExternalDelegate::FillOrPreviewFieldByFieldFillingSuggestion( + const Suggestion& suggestion, + bool is_preview) { + CHECK_EQ(suggestion.popup_item_id, PopupItemId::kFieldByFieldFilling); + CHECK(suggestion.field_by_field_filling_type_used); + const AutofillProfile* profile = + manager_->client().GetPersonalDataManager()->GetProfileByGUID( + suggestion.GetBackendId<Suggestion::Guid>().value()); + if (!profile) { + return; + } + const std::optional<std::u16string> value_to_fill = GetValueForProfile( + *profile, manager_->app_locale(), + AutofillType(*suggestion.field_by_field_filling_type_used), query_field_, + manager_->client().GetAddressNormalizer()); + if (!value_to_fill) { + return; + } + manager_->FillOrPreviewField(is_preview ? mojom::ActionPersistence::kPreview + : mojom::ActionPersistence::kFill, + mojom::TextReplacement::kReplaceAll, query_form_, + query_field_, *value_to_fill, + suggestion.popup_item_id); +} + void AutofillExternalDelegate::FillAutofillFormData( PopupItemId popup_item_id, Suggestion::BackendId backend_id,
diff --git a/components/autofill/core/browser/autofill_external_delegate.h b/components/autofill/core/browser/autofill_external_delegate.h index 56eb6b9..9d5ff6e5 100644 --- a/components/autofill/core/browser/autofill_external_delegate.h +++ b/components/autofill/core/browser/autofill_external_delegate.h
@@ -177,6 +177,13 @@ bool is_preview, const AutofillTriggerDetails& trigger_details); + // Used by `PopupItemId::kFieldByFieldFilling` suggestions. Fills the `field` + // with the info stored in the `AutofillProfile` for the field type + // `suggestion.field_by_field_filling_type_used`. `is_preview` has the same + // meaning as the one in `FillAutofillFormData()`. + void FillOrPreviewFieldByFieldFillingSuggestion(const Suggestion& suggestion, + bool is_preview); + // Will remove Autofill warnings from |suggestions| if there are also // autocomplete entries in the vector. Note: at this point, it is assumed that // if there are Autofill warnings, they will be at the head of the vector and
diff --git a/components/autofill/core/browser/autofill_external_delegate_unittest.cc b/components/autofill/core/browser/autofill_external_delegate_unittest.cc index 8e30c91..316591d 100644 --- a/components/autofill/core/browser/autofill_external_delegate_unittest.cc +++ b/components/autofill/core/browser/autofill_external_delegate_unittest.cc
@@ -3,6 +3,7 @@ // found in the LICENSE file. #include <memory> +#include <optional> #include <string> #include <string_view> #include <vector> @@ -79,6 +80,25 @@ constexpr std::string_view kPlusAddressSuggestionMetric = "Autofill.PlusAddresses.Suggestion.Events"; + +// Creates a `PopupItemdId::kFieldByFieldFilling` suggestion. +// `profile_guid` is used to set `Suggestion::payload` as +// `Suggestion::Guid(profile_guid)`. This method also sets the +// `Suggestion::field_by_field_filling_type_used` to a default value of +// `NAME_FIRST`, which means that selecting this suggestion will fill the field +// with `NAME_FIRST` information stored in the profile that has `guid`. +Suggestion CreateFieldByFieldFillingSuggestion( + const std::string& profile_guid) { + Suggestion suggestion = test::CreateAutofillSuggestion( + PopupItemId::kFieldByFieldFilling, u"field by field", + Suggestion::Guid(profile_guid)); + // This is an arbitrary type. The delegate asserts the existence of + // `field_by_field_filling_type_used` for + // `PopupItemId::kFieldByFieldFilling` suggestions. + suggestion.field_by_field_filling_type_used = std::optional(NAME_FIRST); + return suggestion; +} + // Matches a FillFieldLogEvent by equality of fields. Use FillEventId(-1) if // you want to ignore the fill_event_id. auto EqualsFillFieldLogEvent(const FillFieldLogEvent& expected) { @@ -1114,13 +1134,15 @@ // Tests that for a certain `PopupItemId` accepted, the expected // `AutofillFillingMethodMetric` is recorded. -TEST_P(FillingMethodMetricsUnitTest, recordedsFillingMethodForPopupType) { +TEST_P(FillingMethodMetricsUnitTest, RecordFillingMethodForPopupType) { IssueOnQuery(); const FillingMethodMetricsTestParams& params = GetParam(); const AutofillProfile profile = test::GetFullProfile(); personal_data().AddProfile(profile); - const Suggestion suggestion = test::CreateAutofillSuggestion( - params.popup_item_id, u"baz foo", Suggestion::Guid(profile.guid())); + const Suggestion suggestion = + params.popup_item_id == PopupItemId::kFieldByFieldFilling + ? CreateFieldByFieldFillingSuggestion(profile.guid()) + : test::CreateAutofillSuggestion(params.popup_item_id); // Wait until form is parsed. We only perform field by field filling if the // AutofillField exists. browser_autofill_manager_->OnFormsSeen({queried_form_}, {}); @@ -1173,8 +1195,11 @@ const GroupFillingTestParams& params = GetParam(); const AutofillProfile profile = test::GetFullProfile(); personal_data().AddProfile(profile); - const Suggestion suggestion = test::CreateAutofillSuggestion( - params.popup_item_id, u"baz foo", Suggestion::Guid(profile.guid())); + const Suggestion suggestion = + params.popup_item_id == PopupItemId::kFieldByFieldFilling + ? CreateFieldByFieldFillingSuggestion(profile.guid()) + : test::CreateAutofillSuggestion(params.popup_item_id, u"baz foo", + Suggestion::Guid(profile.guid())); auto expected_source = #if BUILDFLAG(IS_ANDROID) AutofillTriggerSource::kKeyboardAccessory; @@ -1389,13 +1414,18 @@ base::test::ScopedFeatureList features( features::kAutofillGranularFillingAvailable); + const AutofillProfile profile = test::GetFullProfile(); + personal_data().AddProfile(profile); IssueOnQuery(); browser_autofill_manager_->OnFormsSeen({queried_form_}, {}); // Wait until form is parsed. task_environment_.RunUntilIdle(); ON_CALL(personal_data(), IsAutofillProfileEnabled) .WillByDefault(Return(true)); - Suggestion suggestion = test::CreateAutofillSuggestion(params.popup_item_id); + const Suggestion suggestion = + params.popup_item_id == PopupItemId::kFieldByFieldFilling + ? CreateFieldByFieldFillingSuggestion(profile.guid()) + : test::CreateAutofillSuggestion(params.popup_item_id); if (!params.is_preview) { external_delegate_->DidAcceptSuggestion( @@ -1791,30 +1821,33 @@ TEST_F(AutofillExternalDelegateUnitTest, ExternalDelegateFillFieldWithValue_FieldByFieldFilling) { - EXPECT_CALL(autofill_client_, - HideAutofillPopup(PopupHidingReason::kAcceptSuggestion)); + const AutofillProfile profile = test::GetFullProfile(); + personal_data().AddProfile(profile); IssueOnQuery(); // Wait until form is parsed. We only perform field by field filling if the // AutofillField exists. browser_autofill_manager_->OnFormsSeen({queried_form_}, {}); task_environment_.RunUntilIdle(); - const std::u16string dummy_field_by_field_string = u"field by field"; - EXPECT_CALL(*autofill_driver_, - ApplyFieldAction(mojom::ActionPersistence::kFill, - mojom::TextReplacement::kReplaceAll, - queried_form_triggering_field_id_, - dummy_field_by_field_string)); + Suggestion suggestion = CreateFieldByFieldFillingSuggestion(profile.guid()); + EXPECT_CALL(autofill_client_, + HideAutofillPopup(PopupHidingReason::kAcceptSuggestion)); + EXPECT_CALL( + *autofill_driver_, + ApplyFieldAction( + mojom::ActionPersistence::kFill, mojom::TextReplacement::kReplaceAll, + queried_form_triggering_field_id_, + profile.GetRawInfo(*suggestion.field_by_field_filling_type_used))); external_delegate_->DidAcceptSuggestion( - test::CreateAutofillSuggestion(PopupItemId::kFieldByFieldFilling, - dummy_field_by_field_string), - SuggestionPosition{.row = 0}, kDefaultTriggerSource); + suggestion, SuggestionPosition{.row = 0}, kDefaultTriggerSource); } TEST_F(AutofillExternalDelegateUnitTest, ExternalDelegate_FieldByFieldFilling_LogFillFieldEvent) { base::test::ScopedFeatureList features( features::kAutofillGranularFillingAvailable); + const AutofillProfile profile = test::GetFullProfile(); + personal_data().AddProfile(profile); EXPECT_CALL(autofill_client_, HideAutofillPopup(PopupHidingReason::kAcceptSuggestion)); IssueOnQuery(); @@ -1823,8 +1856,7 @@ browser_autofill_manager_->OnFormsSeen({queried_form_}, {}); task_environment_.RunUntilIdle(); external_delegate_->DidAcceptSuggestion( - test::CreateAutofillSuggestion(PopupItemId::kFieldByFieldFilling, - u"field by field"), + CreateFieldByFieldFillingSuggestion(profile.guid()), SuggestionPosition{.row = 0}, kDefaultTriggerSource); const std::vector<AutofillField::FieldLogEventType>& log_events = get_triggering_autofill_field()->field_log_events();
diff --git a/components/autofill/core/browser/data_model/autofill_metadata.cc b/components/autofill/core/browser/data_model/autofill_metadata.cc index f6dde71..0333555 100644 --- a/components/autofill/core/browser/data_model/autofill_metadata.cc +++ b/components/autofill/core/browser/data_model/autofill_metadata.cc
@@ -11,16 +11,6 @@ namespace autofill { -bool AutofillMetadata::operator==(const AutofillMetadata& metadata) const { - return id == metadata.id && use_count == metadata.use_count && - use_date == metadata.use_date && - billing_address_id == metadata.billing_address_id; -} - -bool AutofillMetadata::operator!=(const AutofillMetadata& metadata) const { - return !(*this == metadata); -} - bool AutofillMetadata::IsDeletable() const { return IsAutofillEntryWithUseDateDeletable(use_date); }
diff --git a/components/autofill/core/browser/data_model/autofill_metadata.h b/components/autofill/core/browser/data_model/autofill_metadata.h index d7f9a7d..90f20420 100644 --- a/components/autofill/core/browser/data_model/autofill_metadata.h +++ b/components/autofill/core/browser/data_model/autofill_metadata.h
@@ -15,11 +15,10 @@ // abstract the data from the metadata. struct AutofillMetadata { public: - AutofillMetadata() {} - ~AutofillMetadata() {} + AutofillMetadata() = default; + ~AutofillMetadata() = default; - bool operator==(const AutofillMetadata&) const; - bool operator!=(const AutofillMetadata&) const; + bool operator==(const AutofillMetadata&) const = default; // Returns whether the metadata is deletable: if it has not been used for // longer than |kDisusedAddressDeletionTimeDelta|.
diff --git a/components/autofill/core/browser/data_model/autofill_profile_comparator.cc b/components/autofill/core/browser/data_model/autofill_profile_comparator.cc index 97f2253..5c74f69d 100644 --- a/components/autofill/core/browser/data_model/autofill_profile_comparator.cc +++ b/components/autofill/core/browser/data_model/autofill_profile_comparator.cc
@@ -201,12 +201,6 @@ return user_visible_type; } -bool ProfileValueDifference::operator==( - const ProfileValueDifference& right) const { - return (type == right.type) && (first_value == right.first_value) && - (second_value == right.second_value); -} - AutofillProfileComparator::AutofillProfileComparator( const base::StringPiece& app_locale) : app_locale_(app_locale.data(), app_locale.size()) {}
diff --git a/components/autofill/core/browser/data_model/autofill_profile_comparator.h b/components/autofill/core/browser/data_model/autofill_profile_comparator.h index 6034f01..8b06b83 100644 --- a/components/autofill/core/browser/data_model/autofill_profile_comparator.h +++ b/components/autofill/core/browser/data_model/autofill_profile_comparator.h
@@ -25,7 +25,7 @@ std::u16string first_value; // The new value. std::u16string second_value; - bool operator==(const ProfileValueDifference& right) const; + bool operator==(const ProfileValueDifference& right) const = default; }; ServerFieldTypeSet GetUserVisibleTypes();
diff --git a/components/autofill/core/browser/form_autofill_history.h b/components/autofill/core/browser/form_autofill_history.h index f940c693..aaf634b0 100644 --- a/components/autofill/core/browser/form_autofill_history.h +++ b/components/autofill/core/browser/form_autofill_history.h
@@ -62,12 +62,8 @@ // `field_id`. const FieldFillingEntry& GetFieldFillingEntry(FieldGlobalId field_id) const; - friend bool operator==(const FillOperation& lhs, const FillOperation& rhs) { - return lhs.iterator_ == rhs.iterator_; - } - friend bool operator!=(const FillOperation& lhs, const FillOperation& rhs) { - return !(lhs == rhs); - } + friend bool operator==(const FillOperation& lhs, + const FillOperation& rhs) = default; private: friend class FormAutofillHistory;
diff --git a/components/autofill/core/browser/profile_token_quality.cc b/components/autofill/core/browser/profile_token_quality.cc index 0b486d7..0debf37 100644 --- a/components/autofill/core/browser/profile_token_quality.cc +++ b/components/autofill/core/browser/profile_token_quality.cc
@@ -335,16 +335,6 @@ } } -bool ProfileTokenQuality::Observation::operator==( - const ProfileTokenQuality::Observation& other) const { - return type == other.type && form_hash == other.form_hash; -} - -bool ProfileTokenQuality::Observation::operator!=( - const ProfileTokenQuality::Observation& other) const { - return !operator==(other); -} - ProfileTokenQuality::FormSignatureHash ProfileTokenQuality::GetFormSignatureHash(FormSignature form_signature) const { // Just take the lowest 8 bits of the `form_signature`.
diff --git a/components/autofill/core/browser/profile_token_quality.h b/components/autofill/core/browser/profile_token_quality.h index 426b701..e21a1ca 100644 --- a/components/autofill/core/browser/profile_token_quality.h +++ b/components/autofill/core/browser/profile_token_quality.h
@@ -211,8 +211,7 @@ std::underlying_type_t<ObservationType> type; FormSignatureHash form_hash = FormSignatureHash(0); - bool operator==(const Observation& other) const; - bool operator!=(const Observation& other) const; + bool operator==(const Observation& other) const = default; }; // Returns a low-entry hash of the `form_signature`.
diff --git a/components/autofill/core/browser/ui/suggestion.cc b/components/autofill/core/browser/ui/suggestion.cc index 35e6e113..dcfb3a1 100644 --- a/components/autofill/core/browser/ui/suggestion.cc +++ b/components/autofill/core/browser/ui/suggestion.cc
@@ -29,15 +29,6 @@ Suggestion::Text::~Text() = default; -bool Suggestion::Text::operator==(const Suggestion::Text& text) const { - return value == text.value && is_primary == text.is_primary && - should_truncate == text.should_truncate; -} - -bool Suggestion::Text::operator!=(const Suggestion::Text& text) const { - return !operator==(text); -} - Suggestion::Suggestion() = default; Suggestion::Suggestion(std::u16string main_text)
diff --git a/components/autofill/core/browser/ui/suggestion.h b/components/autofill/core/browser/ui/suggestion.h index df230bad..cabc4fb 100644 --- a/components/autofill/core/browser/ui/suggestion.h +++ b/components/autofill/core/browser/ui/suggestion.h
@@ -45,8 +45,7 @@ Text& operator=(const Text& other); Text& operator=(Text&& other); ~Text(); - bool operator==(const Suggestion::Text& text) const; - bool operator!=(const Suggestion::Text& text) const; + bool operator==(const Suggestion::Text& text) const = default; // The text value to be shown. std::u16string value;
diff --git a/components/autofill/core/browser/webdata/autocomplete_entry.cc b/components/autofill/core/browser/webdata/autocomplete_entry.cc index 134e418..4033118 100644 --- a/components/autofill/core/browser/webdata/autocomplete_entry.cc +++ b/components/autofill/core/browser/webdata/autocomplete_entry.cc
@@ -30,10 +30,6 @@ AutocompleteKey::~AutocompleteKey() = default; -bool AutocompleteKey::operator==(const AutocompleteKey& key) const { - return name_ == key.name() && value_ == key.value(); -} - bool AutocompleteKey::operator<(const AutocompleteKey& key) const { return std::tie(name_, value_) < std::tie(key.name(), key.value()); } @@ -49,16 +45,6 @@ AutocompleteEntry::~AutocompleteEntry() = default; -bool AutocompleteEntry::operator==(const AutocompleteEntry& entry) const { - return key() == entry.key() && - date_created() == entry.date_created() && - date_last_used() == entry.date_last_used(); -} - -bool AutocompleteEntry::operator!=(const AutocompleteEntry& entry) const { - return !(*this == entry); -} - bool AutocompleteEntry::operator<(const AutocompleteEntry& entry) const { return key_ < entry.key(); }
diff --git a/components/autofill/core/browser/webdata/autocomplete_entry.h b/components/autofill/core/browser/webdata/autocomplete_entry.h index 0230c197..0cd7854 100644 --- a/components/autofill/core/browser/webdata/autocomplete_entry.h +++ b/components/autofill/core/browser/webdata/autocomplete_entry.h
@@ -22,7 +22,7 @@ const std::u16string& name() const { return name_; } const std::u16string& value() const { return value_; } - bool operator==(const AutocompleteKey& key) const; + bool operator==(const AutocompleteKey& key) const = default; bool operator<(const AutocompleteKey& key) const; private: @@ -42,8 +42,7 @@ const base::Time& date_created() const { return date_created_; } const base::Time& date_last_used() const { return date_last_used_; } - bool operator==(const AutocompleteEntry& entry) const; - bool operator!=(const AutocompleteEntry& entry) const; + bool operator==(const AutocompleteEntry& entry) const = default; bool operator<(const AutocompleteEntry& entry) const; private:
diff --git a/components/autofill/core/browser/webdata/autofill_change.h b/components/autofill/core/browser/webdata/autofill_change.h index 2bea2e6..10b056db 100644 --- a/components/autofill/core/browser/webdata/autofill_change.h +++ b/components/autofill/core/browser/webdata/autofill_change.h
@@ -5,8 +5,8 @@ #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_AUTOFILL_CHANGE_H__ #define COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_AUTOFILL_CHANGE_H__ +#include <concepts> #include <string> -#include <type_traits> #include <vector> #include "base/check.h" @@ -16,6 +16,7 @@ #include "components/autofill/core/browser/data_model/iban.h" #include "components/autofill/core/browser/webdata/autocomplete_entry.h" #include "components/autofill/core/browser/webdata/autofill_table.h" +#include "third_party/abseil-cpp/absl/types/variant.h" namespace autofill { @@ -43,34 +44,35 @@ // Change notification details for Autofill related changes. // TODO(crbug/1476099): Update the name for `AutofillDataModelChange` as it now // captures non data model changes. -template <typename DataType> +template <typename DataType, typename KeyType> + requires std::derived_from<DataType, AutofillDataModel> || + std::same_as<DataType, ServerCvc> class AutofillDataModelChange { public: - static_assert(std::disjunction_v<std::is_base_of<AutofillDataModel, DataType>, - std::is_same<DataType, ServerCvc>>); - enum Type { ADD, UPDATE, REMOVE }; // The `type` input specifies the change type. The `key` input is the key // that identifies the `data_model`; it is the GUID of the entry for local // data and server_id of the entry for server data from GPay. - AutofillDataModelChange(Type type, - const std::string& key, - DataType data_model) - : type_(type), key_(key), data_model_(std::move(data_model)) { + AutofillDataModelChange(Type type, KeyType key, DataType data_model) + : type_(type), key_(std::move(key)), data_model_(std::move(data_model)) { // Verify that the `key_` corresponds to the `data_model_`. For REMOVE // changes, the `data_model` is optional and hence the check skipped. if (type_ == REMOVE) { return; } - if constexpr (std::is_same_v<DataType, Iban>) { - CHECK((data_model_.record_type() == Iban::RecordType::kLocalIban && - data_model_.guid() == key_) || - (data_model_.record_type() == Iban::RecordType::kServerIban && - base::NumberToString(data_model_.instrument_id()) == key_)); - } else if constexpr (std::is_same_v<DataType, ServerCvc>) { - CHECK(base::NumberToString(data_model_.instrument_id) == key_); - } else if constexpr (std::is_same_v<DataType, CreditCard>) { + if constexpr (std::same_as<DataType, Iban>) { + if (data_model_.record_type() == Iban::RecordType::kLocalIban) { + CHECK(absl::holds_alternative<std::string>(key_) && + absl::get<std::string>(key_) == data_model_.guid()); + } else { + CHECK(data_model_.record_type() == Iban::RecordType::kServerIban); + CHECK(absl::holds_alternative<int64_t>(key_) && + absl::get<int64_t>(key_) == data_model_.instrument_id()); + } + } else if constexpr (std::same_as<DataType, ServerCvc>) { + CHECK(data_model_.instrument_id == key_); + } else if constexpr (std::same_as<DataType, CreditCard>) { // TODO(crbug.com/1475085): Use `instrument_id()` for credit cards and // merge the `Iban` and `CreditCard` cases. CHECK(data_model_.guid() == key_ || data_model_.server_id() == key_); @@ -82,24 +84,37 @@ ~AutofillDataModelChange() = default; Type type() const { return type_; } - const std::string& key() const { return key_; } + const KeyType& key() const { return key_; } const DataType& data_model() const { return data_model_; } - bool operator==(const AutofillDataModelChange<DataType>& change) const { + bool operator==( + const AutofillDataModelChange<DataType, KeyType>& change) const { return type() == change.type() && key() == change.key() && (type() == REMOVE || data_model() == change.data_model()); } private: Type type_; - std::string key_; + KeyType key_; DataType data_model_; }; -using AutofillProfileChange = AutofillDataModelChange<AutofillProfile>; -using CreditCardChange = AutofillDataModelChange<CreditCard>; -using IbanChange = AutofillDataModelChange<Iban>; -using ServerCvcChange = AutofillDataModelChange<ServerCvc>; +// Identified by `AutofillProfile::guid()`. +using AutofillProfileChange = + AutofillDataModelChange<AutofillProfile, std::string>; + +// Identified by `CreditCard::guid()` for local cards and +// `CreditCard::server_id()` for server cards. +// TODO(crbug.com/1475085): For server cards, an instrument id should be used. +using CreditCardChange = AutofillDataModelChange<CreditCard, std::string>; + +// Identified by `Iban::guid()` for local IBANs and `Iban::instrument_id()` for +// server IBANs. +using IbanChange = + AutofillDataModelChange<Iban, absl::variant<std::string, int64_t>>; + +// Identified by `ServerCvc::instrument_id`. +using ServerCvcChange = AutofillDataModelChange<ServerCvc, int64_t>; } // namespace autofill
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge.cc b/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge.cc index 7470906..b21f9a1 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge.cc
@@ -257,17 +257,19 @@ CreateMetadataChangeList(); auto data = std::make_unique<syncer::EntityData>(); + std::string key_str = base::NumberToString(change.key()); switch (change.type()) { case ServerCvcChange::ADD: case ServerCvcChange::UPDATE: data->name = base::NumberToString(change.data_model().instrument_id); *data->specifics.mutable_autofill_wallet_credential() = AutofillWalletCredentialSpecificsFromStructData(change.data_model()); - change_processor()->Put(change.key(), std::move(data), + change_processor()->Put(std::move(key_str), std::move(data), metadata_change_list.get()); break; case ServerCvcChange::REMOVE: - change_processor()->Delete(change.key(), metadata_change_list.get()); + change_processor()->Delete(std::move(key_str), + metadata_change_list.get()); break; } }
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge_unittest.cc b/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge_unittest.cc index 7b241d58..9c45eb5 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_credential_sync_bridge_unittest.cc
@@ -350,8 +350,7 @@ const ServerCvc server_cvc = ServerCvc(1, u"123", base::Time::UnixEpoch() + base::Milliseconds(25000)); const ServerCvcChange change = ServerCvcChange( - ServerCvcChange::ADD, base::NumberToString(server_cvc.instrument_id), - server_cvc); + ServerCvcChange::ADD, server_cvc.instrument_id, server_cvc); bridge()->ServerCvcChanged(change); } @@ -370,8 +369,7 @@ const ServerCvc server_cvc = ServerCvc(1, u"123", base::Time::UnixEpoch() + base::Milliseconds(25000)); const ServerCvcChange change = ServerCvcChange( - ServerCvcChange::UPDATE, base::NumberToString(server_cvc.instrument_id), - server_cvc); + ServerCvcChange::UPDATE, server_cvc.instrument_id, server_cvc); bridge()->ServerCvcChanged(change); } @@ -390,8 +388,7 @@ const ServerCvc server_cvc = ServerCvc(1, u"123", base::Time::UnixEpoch() + base::Milliseconds(25000)); const ServerCvcChange change = ServerCvcChange( - ServerCvcChange::REMOVE, base::NumberToString(server_cvc.instrument_id), - server_cvc); + ServerCvcChange::REMOVE, server_cvc.instrument_id, server_cvc); bridge()->ServerCvcChanged(change); }
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.cc b/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.cc index 6b93916..ea7ac9c4 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.cc
@@ -646,10 +646,10 @@ return change_processor()->GetError(); } -template <class DataType> +template <typename DataType, typename KeyType> void AutofillWalletMetadataSyncBridge::LocalMetadataChanged( WalletMetadataSpecifics::Type type, - AutofillDataModelChange<DataType> change) { + AutofillDataModelChange<DataType, KeyType> change) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); const std::string& metadata_id = change.key(); @@ -659,7 +659,7 @@ CreateMetadataChangeList(); switch (change.type()) { - case AutofillDataModelChange<DataType>::REMOVE: + case AutofillDataModelChange<DataType, KeyType>::REMOVE: if (RemoveServerMetadata(GetAutofillTable(), type, metadata_id)) { cache_.erase(storage_key); // Send up deletion only if we had this entry in the DB. It is not there @@ -667,8 +667,8 @@ change_processor()->Delete(storage_key, metadata_change_list.get()); } return; - case AutofillDataModelChange<DataType>::ADD: - case AutofillDataModelChange<DataType>::UPDATE: + case AutofillDataModelChange<DataType, KeyType>::ADD: + case AutofillDataModelChange<DataType, KeyType>::UPDATE: AutofillMetadata new_entry = change.data_model().GetMetadata(); auto it = cache_.find(storage_key); absl::optional<AutofillMetadata> existing_entry = absl::nullopt;
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.h b/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.h index ff23a51..b30945f 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.h +++ b/components/autofill/core/browser/webdata/autofill_wallet_metadata_sync_bridge.h
@@ -121,9 +121,9 @@ syncer::EntityChangeList entity_data); // Reacts to a local |change| of an entry of type |type|. - template <class DataType> + template <typename DataType, typename KeyType> void LocalMetadataChanged(sync_pb::WalletMetadataSpecifics::Type type, - AutofillDataModelChange<DataType> change); + AutofillDataModelChange<DataType, KeyType> change); // AutofillWalletMetadataSyncBridge is owned by |web_data_backend_| through // SupportsUserData, so it's guaranteed to outlive |this|.
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge.cc b/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge.cc index 97b0356..fe08b086 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge.cc
@@ -393,8 +393,7 @@ found_diff = true; if (notify_webdata_backend) { web_data_backend_->NotifyOfIbanChanged( - IbanChange(IbanChange::REMOVE, - base::NumberToString(existing_iban->instrument_id()), + IbanChange(IbanChange::REMOVE, existing_iban->instrument_id(), *existing_iban)); } } @@ -408,8 +407,7 @@ found_diff = true; if (notify_webdata_backend) { web_data_backend_->NotifyOfIbanChanged(IbanChange( - IbanChange::ADD, - base::NumberToString(wallet_iban.instrument_id()), wallet_iban)); + IbanChange::ADD, wallet_iban.instrument_id(), wallet_iban)); } } }
diff --git a/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge_unittest.cc b/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge_unittest.cc index 28d94c1..de8a5ff 100644 --- a/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge_unittest.cc +++ b/components/autofill/core/browser/webdata/autofill_wallet_sync_bridge_unittest.cc
@@ -57,6 +57,7 @@ using autofill::AutofillProfileChange; using autofill::CreditCardChange; using base::ScopedTempDir; +using IbanChangeKey = absl::variant<std::string, int64_t>; using sync_pb::AutofillWalletSpecifics; using sync_pb::EntityMetadata; using sync_pb::ModelTypeState; @@ -220,8 +221,7 @@ return false; } if (arg.key() != key) { - *result_listener << "key " << arg.key() << " does not match expected " - << key; + *result_listener << "keys don't match"; } return true; } @@ -231,8 +231,7 @@ return false; } if (arg.key() != key) { - *result_listener << "key " << arg.key() << " does not match expected " - << key; + *result_listener << "keys don't match"; } if (arg.data_model() != data) { *result_listener << "data " << arg.data_model() @@ -897,9 +896,9 @@ EXPECT_CALL(*backend(), NotifyOnAutofillChangedBySync(syncer::AUTOFILL_WALLET_DATA)); - EXPECT_CALL(*backend(), NotifyOfIbanChanged(AddChange( - base::NumberToString(server_iban.instrument_id()), - server_iban))); + EXPECT_CALL(*backend(), + NotifyOfIbanChanged(AddChange( + IbanChangeKey(server_iban.instrument_id()), server_iban))); StartSyncing({masked_iban_specifics}); EXPECT_THAT(GetAllLocalData(), @@ -926,12 +925,11 @@ EXPECT_CALL(*backend(), NotifyOnAutofillChangedBySync(syncer::AUTOFILL_WALLET_DATA)); - EXPECT_CALL(*backend(), NotifyOfIbanChanged(RemoveChange(base::NumberToString( - server_iban1.instrument_id())))); - EXPECT_CALL( - *backend(), - NotifyOfIbanChanged(AddChange( - base::NumberToString(server_iban2.instrument_id()), server_iban2))); + EXPECT_CALL(*backend(), NotifyOfIbanChanged(RemoveChange( + IbanChangeKey(server_iban1.instrument_id())))); + EXPECT_CALL(*backend(), + NotifyOfIbanChanged(AddChange( + IbanChangeKey(server_iban2.instrument_id()), server_iban2))); StartSyncing({masked_iban2_specifics}); std::vector<std::unique_ptr<Iban>> iban_vector;
diff --git a/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc b/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc index 0c0aa571f..7cdffebe 100644 --- a/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc +++ b/components/autofill/core/browser/webdata/autofill_webdata_backend_impl.cc
@@ -713,8 +713,8 @@ const ServerCvc server_cvc{instrument_id, cvc, /*last_updated_timestamp=*/AutofillClock::Now()}; if (AutofillTable::FromWebDatabase(db)->AddServerCvc(server_cvc)) { - const ServerCvcChange change{ - ServerCvcChange::ADD, base::NumberToString(instrument_id), server_cvc}; + const ServerCvcChange change{ServerCvcChange::ADD, instrument_id, + server_cvc}; for (auto& db_observer : db_observer_list_) { // TODO(crbug/1477924): Add integration tests for Add, Remove and Update // for Wallet Credential data. @@ -735,8 +735,7 @@ const ServerCvc server_cvc{instrument_id, cvc, /*last_updated_timestamp=*/AutofillClock::Now()}; if (AutofillTable::FromWebDatabase(db)->UpdateServerCvc(server_cvc)) { - const ServerCvcChange change{ServerCvcChange::UPDATE, - base::NumberToString(instrument_id), + const ServerCvcChange change{ServerCvcChange::UPDATE, instrument_id, server_cvc}; for (auto& db_observer : db_observer_list_) { db_observer.ServerCvcChanged(change); @@ -755,8 +754,7 @@ if (AutofillTable::FromWebDatabase(db)->RemoveServerCvc(instrument_id)) { // Remove doesn't require `ServerCvc` struct data, so an empty data is // passed to the ServerCvcChange - const ServerCvcChange change{ServerCvcChange::REMOVE, - base::NumberToString(instrument_id), + const ServerCvcChange change{ServerCvcChange::REMOVE, instrument_id, ServerCvc{}}; for (auto& db_observer : db_observer_list_) { db_observer.ServerCvcChanged(change); @@ -778,10 +776,9 @@ server_cvc_list) { // Remove doesn't require `ServerCvc` struct data, so an empty data is // passed to the ServerCvcChange - const ServerCvcChange change{ - ServerCvcChange::REMOVE, - base::NumberToString(server_cvc_from_list->instrument_id), - ServerCvc{}}; + const ServerCvcChange change{ServerCvcChange::REMOVE, + server_cvc_from_list->instrument_id, + ServerCvc{}}; for (auto& db_observer : db_observer_list_) { db_observer.ServerCvcChanged(change); }
diff --git a/components/autofill/core/common/dense_set.h b/components/autofill/core/common/dense_set.h index 3ae857b5..a26284e 100644 --- a/components/autofill/core/common/dense_set.h +++ b/components/autofill/core/common/dense_set.h
@@ -87,9 +87,8 @@ return x; } - friend constexpr bool operator==(const Bitset& lhs, const Bitset& rhs) { - return lhs.words_ == rhs.words_; - } + friend constexpr bool operator==(const Bitset& lhs, + const Bitset& rhs) = default; constexpr base::span<const Word, kNumWords> data() const { return words_; } @@ -137,9 +136,7 @@ return x; } - friend constexpr bool operator==(Bitset lhs, Bitset rhs) { - return lhs.word_ == rhs.word_; - } + friend constexpr bool operator==(Bitset lhs, Bitset rhs) = default; constexpr base::span<const Word, 1> data() const { return base::span<const Word, 1>(&word_, 1u); @@ -355,13 +352,7 @@ return bitset_.data(); } - friend bool operator==(const DenseSet& a, const DenseSet& b) { - return a.bitset_ == b.bitset_; - } - - friend bool operator!=(const DenseSet& a, const DenseSet& b) { - return !(a == b); - } + friend bool operator==(const DenseSet& a, const DenseSet& b) = default; // Iterators.
diff --git a/components/autofill/core/common/form_data.cc b/components/autofill/core/common/form_data.cc index 82be5ce..7a5b0653 100644 --- a/components/autofill/core/common/form_data.cc +++ b/components/autofill/core/common/form_data.cc
@@ -82,16 +82,6 @@ FrameTokenWithPredecessor&&) = default; FrameTokenWithPredecessor::~FrameTokenWithPredecessor() = default; -bool operator==(const FrameTokenWithPredecessor& a, - const FrameTokenWithPredecessor& b) { - return a.token == b.token && a.predecessor == b.predecessor; -} - -bool operator!=(const FrameTokenWithPredecessor& a, - const FrameTokenWithPredecessor& b) { - return !(a == b); -} - FormData::FormData() = default; FormData::FormData(const FormData&) = default;
diff --git a/components/autofill/core/common/form_data.h b/components/autofill/core/common/form_data.h index a8717f5..01a8bcc 100644 --- a/components/autofill/core/common/form_data.h +++ b/components/autofill/core/common/form_data.h
@@ -47,9 +47,7 @@ int predecessor = -1; friend bool operator==(const FrameTokenWithPredecessor& a, - const FrameTokenWithPredecessor& b); - friend bool operator!=(const FrameTokenWithPredecessor& a, - const FrameTokenWithPredecessor& b); + const FrameTokenWithPredecessor& b) = default; }; // Autofill represents forms and fields as FormData and FormFieldData objects.
diff --git a/components/certificate_transparency/data/log_list.json b/components/certificate_transparency/data/log_list.json index d3e46997..30d4b82 100644 --- a/components/certificate_transparency/data/log_list.json +++ b/components/certificate_transparency/data/log_list.json
@@ -1,6 +1,6 @@ { - "version": "26.49", - "log_list_timestamp": "2023-11-19T12:54:56Z", + "version": "26.50", + "log_list_timestamp": "2023-11-20T12:53:57Z", "operators": [ { "name": "Google",
diff --git a/components/cronet/android/test/javatests/src/org/chromium/net/PkpTest.java b/components/cronet/android/test/javatests/src/org/chromium/net/PkpTest.java index a9307bcb..bb0e772 100644 --- a/components/cronet/android/test/javatests/src/org/chromium/net/PkpTest.java +++ b/components/cronet/android/test/javatests/src/org/chromium/net/PkpTest.java
@@ -13,6 +13,8 @@ import static org.chromium.net.Http2TestServer.SERVER_CERT_PEM; import static org.chromium.net.truth.UrlResponseInfoSubject.assertThat; +import android.os.Build; + import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.SmallTest; @@ -42,16 +44,12 @@ @DoNotBatch(reason = "crbug/1459563") @RunWith(AndroidJUnit4.class) @IgnoreFor( - implementations = {CronetImplementation.FALLBACK, CronetImplementation.AOSP_PLATFORM}, - reason = - "The fallback implementation does not support public key pinning. " - + "crbug.com/1494845") + implementations = {CronetImplementation.FALLBACK}, + reason = "The fallback implementation does not support public key pinning") public class PkpTest { private static final int DISTANT_FUTURE = Integer.MAX_VALUE; private static final boolean INCLUDE_SUBDOMAINS = true; private static final boolean EXCLUDE_SUBDOMAINS = false; - private static final boolean KNOWN_ROOT = true; - private static final boolean UNKNOWN_ROOT = false; private static final boolean ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS = true; private static final boolean DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS = false; @@ -76,7 +74,7 @@ @SmallTest public void testErrorCodeIfPinDoesNotMatch() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -103,7 +101,7 @@ @SmallTest public void testSuccessIfPinMatches() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); // Get PKP hash of the real certificate X509Certificate cert = readCertFromFileInPemFormat(SERVER_CERT_PEM); byte[] matchingHash = CertTestUtil.getPublicKeySha256(cert); @@ -132,11 +130,19 @@ */ @Test @SmallTest + @IgnoreFor( + implementations = {CronetImplementation.AOSP_PLATFORM}, + reason = + "Requires the use of subdomains. This can currently only be done through" + + " HostResolverRules, which fakes hostname resultion." + + " TODO(crbug/1501033): Enable for HttpEngine once we have" + + " hostname resolution") public void testIncludeSubdomainsFlagEqualTrue() throws Exception { String fakeUrl = "https://test.example.com:8443"; String fakeDomain = "example.com"; - applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + + applyCronetEngineBuilderConfigurationPatchWithMockCertVerifier( + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -163,11 +169,19 @@ */ @Test @SmallTest + @IgnoreFor( + implementations = {CronetImplementation.AOSP_PLATFORM}, + reason = + "Requires the use of subdomains. This can currently only be done through" + + " HostResolverRules, which fakes hostname resultion." + + " TODO(crbug/1501033): Enable for HttpEngine once we have" + + " hostname resolution") public void testIncludeSubdomainsFlagEqualFalse() throws Exception { String fakeUrl = "https://test.example.com:8443"; String fakeDomain = "example.com"; - applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + + applyCronetEngineBuilderConfigurationPatchWithMockCertVerifier( + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -196,7 +210,7 @@ @SmallTest public void testSuccessIfNoPinSpecified() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -223,7 +237,7 @@ @SmallTest public void testSoonExpiringPin() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); final int tenSecondsAhead = 10; byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( @@ -251,7 +265,7 @@ @SmallTest public void testRecentlyExpiredPin() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); final int oneSecondAgo = -1; byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( @@ -279,9 +293,7 @@ @SmallTest public void testLocalTrustAnchorPinningEnforced() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), - DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, - UNKNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -308,9 +320,7 @@ @SmallTest public void testLocalTrustAnchorPinningNotEnforced() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), - ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, - UNKNOWN_ROOT); + mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -336,7 +346,7 @@ @SmallTest public void testPinsAreNotPersisted() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] nonMatchingHash = generateSomeSha256(); applyPkpSha256Patch( mTestRule.getTestFramework(), @@ -361,7 +371,7 @@ .getTestFramework() .createNewSecondaryBuilder(mTestRule.getTestFramework().getContext()); - configureCronetEngineBuilder(builder, ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + configureCronetEngineBuilder(builder, DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); engine = builder.build(); callback = new TestUrlRequestCallback(); requestBuilder = @@ -380,7 +390,7 @@ @SmallTest public void testHostNameArgumentValidation() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); final String label63 = "123456789-123456789-123456789-123456789-123456789-123456789-123"; final String host255 = label63 + "." + label63 + "." + label63 + "." + label63; // Valid host names. @@ -442,7 +452,7 @@ @SmallTest public void testNullArguments() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); verifyExceptionWhenAddPkpArgumentIsNull(mTestRule.getTestFramework(), true, false, false); verifyExceptionWhenAddPkpArgumentIsNull(mTestRule.getTestFramework(), false, true, false); verifyExceptionWhenAddPkpArgumentIsNull(mTestRule.getTestFramework(), false, false, true); @@ -456,7 +466,7 @@ @SmallTest public void testIllegalArgumentExceptionWhenPinValueIsSHA1() throws Exception { applyCronetEngineBuilderConfigurationPatch( - mTestRule.getTestFramework(), ENABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS, KNOWN_ROOT); + mTestRule.getTestFramework(), DISABLE_PINNING_BYPASS_FOR_LOCAL_ANCHORS); byte[] sha1 = new byte[20]; assertThrows( "Pin value was: " + Arrays.toString(sha1), @@ -473,6 +483,11 @@ /** Asserts that the response from the server contains an PKP error. */ private void assertErrorResponse(TestUrlRequestCallback callback) { assertThat(callback.mError).isNotNull(); + // NetworkException#getCronetInternalErrorCode is exposed only by the native implementation. + if (mTestRule.implementationUnderTest() != CronetImplementation.STATICALLY_LINKED) { + return; + } + int errorCode = ((NetworkException) callback.mError).getCronetInternalErrorCode(); Set<Integer> expectedErrors = new HashSet<>(); expectedErrors.add(NetError.ERR_CONNECTION_REFUSED); @@ -499,31 +514,67 @@ } private static void applyCronetEngineBuilderConfigurationPatch( - CronetTestFramework testFramework, - boolean bypassPinningForLocalAnchors, - boolean knownRoot) + CronetTestFramework testFramework, boolean bypassPinningForLocalAnchors) + throws Exception { + testFramework.applyEngineBuilderPatch( + (builder) -> configureCronetEngineBuilder(builder, bypassPinningForLocalAnchors)); + } + + private static void applyCronetEngineBuilderConfigurationPatchWithMockCertVerifier( + CronetTestFramework testFramework, boolean bypassPinningForLocalAnchors) throws Exception { testFramework.applyEngineBuilderPatch( (builder) -> - configureCronetEngineBuilder( - builder, bypassPinningForLocalAnchors, knownRoot)); + configureCronetEngineBuilderWithMockCertVerifier( + builder, bypassPinningForLocalAnchors)); } - private static void configureCronetEngineBuilder( - ExperimentalCronetEngine.Builder builder, - boolean bypassPinningForLocalAnchors, - boolean knownRoot) + private static void enableMockCertVerifier(ExperimentalCronetEngine.Builder builder) throws Exception { - builder.enablePublicKeyPinningBypassForLocalTrustAnchors(bypassPinningForLocalAnchors); final String[] server_certs = {SERVER_CERT_PEM}; + // knownRoot maps to net::CertVerifyResult.is_issued_by_known_root. There is no test which + // depends on that value as the only thing it affects is certificate verification for QUIC + // (where we never trust non web PKI certs, regardless of app/user config). Hence, always + // set this to false to maintain consistency with the non-MockCertVerifier case, where we + // use a non-trusted self signed certificate. CronetTestUtil.setMockCertVerifierForTesting( - builder, MockCertVerifier.createMockCertVerifier(server_certs, knownRoot)); + builder, + MockCertVerifier.createMockCertVerifier(server_certs, /* knownRoot= */ false)); + // MockCertVerifier uses certificates with hostname != localhost. So, setup fake + // hostname resolution. JSONObject hostResolverParams = CronetTestUtil.generateHostResolverRules(); JSONObject experimentalOptions = new JSONObject().put("HostResolverRules", hostResolverParams); builder.setExperimentalOptions(experimentalOptions.toString()); } + private static void internalConfigureCronetEngineBuilder( + ExperimentalCronetEngine.Builder builder, + boolean bypassPinningForLocalAnchors, + boolean useMockCertVerifier) + throws Exception { + builder.enablePublicKeyPinningBypassForLocalTrustAnchors(bypassPinningForLocalAnchors); + // TODO(crbug/1490552): When not explicitly enabled, fall back to MockCertVerifier if + // custom CAs are not supported. + if (useMockCertVerifier || Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) { + enableMockCertVerifier(builder); + } + } + + private static void configureCronetEngineBuilder( + ExperimentalCronetEngine.Builder builder, boolean bypassPinningForLocalAnchors) + throws Exception { + internalConfigureCronetEngineBuilder( + builder, bypassPinningForLocalAnchors, /* useMockCertVerifier= */ false); + } + + private static void configureCronetEngineBuilderWithMockCertVerifier( + ExperimentalCronetEngine.Builder builder, boolean bypassPinningForLocalAnchors) + throws Exception { + internalConfigureCronetEngineBuilder( + builder, bypassPinningForLocalAnchors, /* useMockCertVerifier= */ true); + } + private static byte[] generateSomeSha256() { byte[] sha256 = new byte[32]; Arrays.fill(sha256, (byte) 58);
diff --git a/components/embedder_support/BUILD.gn b/components/embedder_support/BUILD.gn index 5030f302..f8940e1 100644 --- a/components/embedder_support/BUILD.gn +++ b/components/embedder_support/BUILD.gn
@@ -4,14 +4,10 @@ static_library("embedder_support") { sources = [ - "features.cc", - "features.h", "pref_names.h", "switches.cc", "switches.h", ] - - public_deps = [ "//base" ] } # Target for general utilities that are only used in the browser process.
diff --git a/components/embedder_support/features.cc b/components/embedder_support/features.cc deleted file mode 100644 index 9e3e1cb..0000000 --- a/components/embedder_support/features.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "components/embedder_support/features.h" - -#include "base/feature_list.h" - -namespace embedder_support { - -BASE_FEATURE(kClientHintsXRFormFactor, - "ClientHintsXRFormFactor", - base::FEATURE_DISABLED_BY_DEFAULT); - -} // namespace embedder_support
diff --git a/components/embedder_support/features.h b/components/embedder_support/features.h deleted file mode 100644 index be02efd..0000000 --- a/components/embedder_support/features.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef COMPONENTS_EMBEDDER_SUPPORT_FEATURES_H_ -#define COMPONENTS_EMBEDDER_SUPPORT_FEATURES_H_ - -#include "base/feature_list.h" - -namespace embedder_support { - -// Sets "XR" in the form factor filed of client hints. -BASE_DECLARE_FEATURE(kClientHintsXRFormFactor); - -} // namespace embedder_support - -#endif // COMPONENTS_EMBEDDER_SUPPORT_FEATURES_H_
diff --git a/components/embedder_support/user_agent_utils.cc b/components/embedder_support/user_agent_utils.cc index 41fc8c4..556dcce 100644 --- a/components/embedder_support/user_agent_utils.cc +++ b/components/embedder_support/user_agent_utils.cc
@@ -18,7 +18,6 @@ #include "base/version.h" #include "build/branding_buildflags.h" #include "build/build_config.h" -#include "components/embedder_support/features.h" #include "components/embedder_support/pref_names.h" #include "components/embedder_support/switches.h" #include "components/policy/core/common/policy_pref_names.h" @@ -237,19 +236,6 @@ blink::UserAgentBrandVersionType::kFullVersion); } -std::vector<std::string> GetFormFactorClientHints( - const blink::UserAgentMetadata& metadata, - bool is_mobile) { - // By default, use "Mobile" or "Desktop" depending on the `mobile` bit. - std::vector<std::string> form_factor = { - is_mobile ? blink::kMobileFormFactor : blink::kDesktopFormFactor}; - - if (base::FeatureList::IsEnabled(kClientHintsXRFormFactor)) { - form_factor.push_back(blink::kXRFormFactor); - } - return form_factor; -} - } // namespace std::string GetProductAndVersion( @@ -500,7 +486,10 @@ metadata.full_version = std::string(version_info::GetVersionNumber()); metadata.architecture = content::GetCpuArchitecture(); metadata.model = content::BuildModelInfo(); - metadata.form_factor = GetFormFactorClientHints(metadata, metadata.mobile); + + // By default, use "Mobile" or "Desktop" depending on the `mobile` bit. + metadata.form_factor = {metadata.mobile ? blink::kMobileFormFactor + : blink::kDesktopFormFactor}; #if BUILDFLAG(IS_WIN) metadata.platform_version = GetWindowsPlatformVersion(); @@ -532,8 +521,7 @@ std::string(); // match content::GetOSVersion(false) on Linux spoofed_ua.ua_metadata_override->model = std::string(); spoofed_ua.ua_metadata_override->mobile = false; - spoofed_ua.ua_metadata_override->form_factor = - GetFormFactorClientHints(metadata, /*is_mobile=*/false); + spoofed_ua.ua_metadata_override->form_factor = {blink::kDesktopFormFactor}; // Match the above "CpuInfo" string, which is also the most common Linux // CPU architecture and bitness.` spoofed_ua.ua_metadata_override->architecture = "x86";
diff --git a/components/embedder_support/user_agent_utils_unittest.cc b/components/embedder_support/user_agent_utils_unittest.cc index b4994ec..2f36322 100644 --- a/components/embedder_support/user_agent_utils_unittest.cc +++ b/components/embedder_support/user_agent_utils_unittest.cc
@@ -20,7 +20,6 @@ #include "base/version.h" #include "build/branding_buildflags.h" #include "build/build_config.h" -#include "components/embedder_support/features.h" #include "components/embedder_support/pref_names.h" #include "components/embedder_support/switches.h" #include "components/prefs/pref_registry_simple.h" @@ -783,15 +782,6 @@ EXPECT_TRUE(metadata.full_version.empty()); } -TEST_F(UserAgentUtilsTest, UserAgentMetadataXR) { - base::test::ScopedFeatureList scoped_feature_list; - scoped_feature_list.InitAndEnableFeature(kClientHintsXRFormFactor); - auto metadata = GetUserAgentMetadata(); - std::vector<std::string> expected_form_factor = { - (metadata.mobile ? "Mobile" : "Desktop"), "XR"}; - EXPECT_EQ(metadata.form_factor, expected_form_factor); -} - TEST_F(UserAgentUtilsTest, GenerateBrandVersionListUnbranded) { blink::UserAgentMetadata metadata; metadata.brand_version_list = GenerateBrandVersionList(
diff --git a/components/global_media_controls/public/constants.h b/components/global_media_controls/public/constants.h index 9b7f0fa9..12facc9 100644 --- a/components/global_media_controls/public/constants.h +++ b/components/global_media_controls/public/constants.h
@@ -16,28 +16,20 @@ // The entry point through which the dialog was opened. // These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. +// numeric values should never be reused. Keep this in sync with its counterpart +// in tools/metrics/histograms/metadata/media/enums.xml. enum class GlobalMediaControlsEntryPoint { // Through the Global Media Controls toolbar icon. kToolbarIcon = 0, // Through the use of the Presentation API (Cast) by a web page. kPresentation = 1, - // Through the ChromeOS System Tray + // Through the ChromeOS System Tray. kSystemTray = 2, - kMaxValue = kSystemTray, -}; - -// These values are persisted to logs. Entries should not be renumbered and -// numeric values should never be reused. Keep this in sync with its counterpart -// in tools/metrics/histograms/enums.xml. -enum class GlobalMediaControlsCastActionAndEntryPoint { - kStartViaToolbarIcon = 0, - kStopViaToolbarIcon = 1, - kStartViaPresentation = 2, - kStopViaPresentation = 3, - kStartViaSystemTray = 4, - kStopViaSystemTray = 5, - kMaxValue = kStopViaSystemTray, + // Through the mini player in the ChromeOS quick settings. + kQuickSettingsMiniPlayer = 3, + // Through the Cast button in the mini player in the ChromeOS quick settings. + kQuickSettingsMiniPlayerCastButton = 4, + kMaxValue = kQuickSettingsMiniPlayerCastButton, }; // The minimum size in px that the media artwork can be to be displayed in the
diff --git a/components/password_manager/core/browser/BUILD.gn b/components/password_manager/core/browser/BUILD.gn index fd8b3e1..173fead 100644 --- a/components/password_manager/core/browser/BUILD.gn +++ b/components/password_manager/core/browser/BUILD.gn
@@ -161,11 +161,11 @@ public_deps = [ ":metrics_util", ":passkey_credential", - ":password_store_impl", "//base", "//components/password_manager/core/browser/affiliation", "//components/password_manager/core/browser/features:utils", "//components/password_manager/core/browser/leak_detection:leak_detection_interface_headers", + "//components/password_manager/core/browser/password_store:password_store_impl", "//components/password_manager/core/browser/sync", # TODO(crbug.com/1479425): Remove and update all tagerts to include browser/ui directly. @@ -177,59 +177,27 @@ deps = [ ":hash_password_manager", ":password_hash_data", - "//base", - "//base:i18n", "//build:blink_buildflags", "//build:branding_buildflags", - "//build:chromeos_buildflags", "//components/autofill/core/browser", - "//components/autofill/core/browser/proto", "//components/autofill/core/common", - "//components/autofill/core/common:features", - "//components/autofill/core/common/mojom:mojo_types", "//components/device_reauth", "//components/favicon/core", - "//components/keyed_service/core", - "//components/os_crypt/sync", - "//components/password_manager/core/browser/affiliation:affiliation_proto", "//components/password_manager/core/browser/features:password_features", "//components/password_manager/core/browser/form_parsing", "//components/password_manager/core/browser/generation", - "//components/password_manager/core/browser/import:csv", "//components/password_manager/core/browser/leak_detection:leak_detection", "//components/password_manager/core/common", - "//components/password_manager/core/common:features", "//components/pref_registry", "//components/prefs", "//components/profile_metrics", "//components/safe_browsing/core/common", "//components/safe_browsing/core/common:safe_browsing_prefs", - "//components/security_state/core", - "//components/signin/public/base", - "//components/signin/public/identity_manager", "//components/strings", - "//components/strings:components_strings", - "//components/sync", - "//components/sync_preferences", - "//components/undo", "//components/url_formatter", - "//components/variations/net", - "//components/version_info:channel", - "//components/webdata/common", - "//google_apis", - "//net", "//services/metrics/public/cpp:metrics_cpp", "//services/metrics/public/cpp:ukm_builders", - "//services/network/public/cpp", - "//sql", - "//third_party/abseil-cpp:absl", - "//third_party/protobuf:protobuf_lite", - "//third_party/re2", "//ui/accessibility:accessibility", - "//ui/base", - "//ui/gfx", - "//ui/gfx/range", - "//url", ] if (is_android) { @@ -280,29 +248,6 @@ configs += [ "//build/config/compiler:wexit_time_destructors" ] } -source_set("password_store_interface") { - sources = [ - "password_store/interactions_stats.cc", - "password_store/interactions_stats.h", - "password_store/password_store_backend_error.cc", - "password_store/password_store_backend_error.h", - "password_store/password_store_change.cc", - "password_store/password_store_change.h", - "password_store/password_store_consumer.cc", - "password_store/password_store_consumer.h", - "password_store/password_store_interface.h", - "password_store/password_store_util.cc", - "password_store/password_store_util.h", - ] - deps = [ - ":password_form", - "//base", - "//components/keyed_service/core", - "//url", - ] - configs += [ "//build/config/compiler:wexit_time_destructors" ] -} - source_set("passkey_credential") { sources = [ "passkey_credential.cc", @@ -337,83 +282,6 @@ ] } -# TODO(crbug.com/1479425): Move to a subfolder. -source_set("password_store_impl") { - sources = [ - "password_store/get_logins_with_affiliations_request_handler.cc", - "password_store/get_logins_with_affiliations_request_handler.h", - "password_store/insecure_credentials_table.cc", - "password_store/insecure_credentials_table.h", - "password_store/login_database.cc", - "password_store/login_database.h", - "password_store/login_database_async_helper.cc", - "password_store/login_database_async_helper.h", - "password_store/password_notes_table.cc", - "password_store/password_notes_table.h", - "password_store/password_store.cc", - "password_store/password_store.h", - "password_store/password_store_backend.h", - "password_store/password_store_backend_metrics_recorder.cc", - "password_store/password_store_backend_metrics_recorder.h", - "password_store/password_store_built_in_backend.cc", - "password_store/password_store_built_in_backend.h", - "password_store/psl_matching_helper.cc", - "password_store/psl_matching_helper.h", - "password_store/smart_bubble_stats_store.h", - "password_store/statistics_table.cc", - "password_store/statistics_table.h", - ] - public_deps = [ - ":password_form", - ":password_store_interface", - ] - deps = [ - ":metrics_util", - ":sql_builder", - "//base", - "//build:blink_buildflags", - "//components/autofill/core/common", - "//components/os_crypt/sync:os_crypt", - "//components/password_manager/core/browser/affiliation", - "//components/password_manager/core/browser/features:password_features", - "//components/password_manager/core/browser/sync", - "//components/password_manager/core/common", - "//components/password_manager/core/common:features", - "//components/prefs", - "//components/safe_browsing/core/common:safe_browsing_prefs", - "//components/sync/base", - "//components/sync/base:features", - "//components/sync/model", - "//components/sync/protocol", - "//sql", - "//third_party/abseil-cpp:absl", - "//third_party/re2", - "//url", - ] - if (is_android) { - sources += [ - "password_store/android_backend_error.cc", - "password_store/android_backend_error.h", - ] - } - - if ((is_posix && !is_apple) || is_fuchsia) { - sources += [ "password_store/login_database_posix.cc" ] - } - - if (is_mac) { - sources += [ "password_store/login_database_mac.cc" ] - } - - if (is_ios) { - sources += [ "password_store/login_database_ios.cc" ] - } - - if (is_win) { - sources += [ "password_store/login_database_win.cc" ] - } -} - if (is_android) { # Wrap the java_cpp_enum in android_library so it can be used by both # chrome_java and modules. @@ -467,8 +335,6 @@ sources = [ "fake_form_fetcher.cc", "fake_form_fetcher.h", - "fake_password_store_backend.cc", - "fake_password_store_backend.h", "mock_password_feature_manager.cc", "mock_password_feature_manager.h", "mock_password_form_manager_for_ui.cc", @@ -477,20 +343,10 @@ "mock_password_manager_settings_service.h", "mock_password_reuse_manager.cc", "mock_password_reuse_manager.h", - "mock_password_store_consumer.cc", - "mock_password_store_consumer.h", - "mock_password_store_interface.cc", - "mock_password_store_interface.h", - "mock_smart_bubble_stats_store.cc", - "mock_smart_bubble_stats_store.h", "mock_webauthn_credentials_delegate.cc", "mock_webauthn_credentials_delegate.h", "password_manager_test_utils.cc", "password_manager_test_utils.h", - "password_store/mock_password_store_backend.cc", - "password_store/mock_password_store_backend.h", - "password_store/test_password_store.cc", - "password_store/test_password_store.h", "stub_credentials_filter.cc", "stub_credentials_filter.h", "stub_form_saver.cc", @@ -513,6 +369,7 @@ "//components/keyed_service/core", "//components/password_manager/core/browser/affiliation:test_support", "//components/password_manager/core/browser/leak_detection", + "//components/password_manager/core/browser/password_store:test_support", "//components/safe_browsing:buildflags", "//components/signin/public/identity_manager:test_support", "//components/sync:test_support", @@ -576,32 +433,17 @@ "password_reuse_detector_unittest.cc", "password_reuse_manager_impl_unittest.cc", "password_save_manager_impl_unittest.cc", - "password_store/get_logins_with_affiliations_request_handler_unittest.cc", - "password_store/insecure_credentials_table_unittest.cc", - "password_store/login_database_unittest.cc", - "password_store/password_notes_table_unittest.cc", - "password_store/password_store_built_in_backend_unittest.cc", - "password_store/password_store_unittest.cc", - "password_store/psl_matching_helper_unittest.cc", - "password_store_consumer_unittest.cc", "password_sync_util_unittest.cc", "password_ui_utils_unittest.cc", "possible_username_data_unittest.cc", "sql_table_builder_unittest.cc", - "statistics_table_unittest.cc", "store_metrics_reporter_unittest.cc", "sync_credentials_filter_unittest.cc", "vote_uploads_test_matchers.h", "votes_uploader_unittest.cc", ] if (is_android) { - sources += [ - "password_credential_filler_impl_unittest.cc", - "password_store/password_store_backend_metrics_recorder_unittest.cc", - ] - } - if (is_ios) { - sources += [ "login_database_ios_unittest.cc" ] + sources += [ "password_credential_filler_impl_unittest.cc" ] } if (use_blink) { sources += [ "http_credentials_cleaner_unittest.cc" ] @@ -616,64 +458,41 @@ } deps = [ - ":hash_password_manager", - ":password_hash_data", ":sql_builder", ":test_support", - "//base/test:test_support", "//build:branding_buildflags", - "//build:chromeos_buildflags", "//components/autofill/core/browser", "//components/autofill/core/browser:test_support", - "//components/autofill/core/browser/proto", "//components/autofill/core/common", + "//components/autofill/core/common:test_support", "//components/device_reauth", "//components/device_reauth:test_support", "//components/favicon/core/test:test_support", - "//components/os_crypt/sync", "//components/os_crypt/sync:test_support", - "//components/password_manager/core/browser/affiliation:affiliation_proto", - "//components/password_manager/core/browser/affiliation:test_support", "//components/password_manager/core/browser/features:password_features", - "//components/password_manager/core/browser/features:utils", - "//components/password_manager/core/browser/form_parsing:form_parsing", - "//components/password_manager/core/browser/form_parsing:unit_tests", + "//components/password_manager/core/browser/form_parsing", "//components/password_manager/core/browser/generation", - "//components/password_manager/core/browser/import:csv", - "//components/password_manager/core/browser/import:csv_unit_tests", - "//components/password_manager/core/browser/leak_detection", - "//components/password_manager/core/browser/leak_detection:leak_detection_interface_headers", + "//components/password_manager/core/browser/leak_detection:leak_detection", "//components/password_manager/core/browser/leak_detection:test_support", - "//components/password_manager/core/browser/leak_detection:unit_tests", "//components/password_manager/core/common", - "//components/password_manager/core/common:features", "//components/prefs:test_support", - "//components/safe_browsing/core/browser/password_protection:test_support", "//components/safe_browsing/core/common", "//components/safe_browsing/core/common:safe_browsing_prefs", "//components/security_state/core", "//components/signin/public/base", - "//components/signin/public/identity_manager:test_support", "//components/strings", - "//components/sync:test_support", "//components/sync_preferences:test_support", "//components/ukm:test_support", "//components/url_formatter", - "//components/variations:test_support", - "//components/version_info:channel", - "//google_apis:google_apis", "//net:test_support", "//services/metrics/public/cpp:ukm_builders", "//services/network:network_service", "//services/network:test_support", - "//services/network/public/cpp", "//sql:test_support", "//testing/gmock", "//testing/gtest", - "//third_party/sqlite", "//ui/base", "//ui/gfx:test_support", - "//url", ] if (!is_android && !is_ios) {
diff --git a/components/password_manager/core/browser/affiliation/BUILD.gn b/components/password_manager/core/browser/affiliation/BUILD.gn index 921eadf..06f88df 100644 --- a/components/password_manager/core/browser/affiliation/BUILD.gn +++ b/components/password_manager/core/browser/affiliation/BUILD.gn
@@ -44,9 +44,9 @@ "//base", "//components/keyed_service/core", "//components/password_manager/core/browser:password_form", - "//components/password_manager/core/browser:password_store_interface", "//components/password_manager/core/browser:sql_builder", "//components/password_manager/core/browser/features:password_features", + "//components/password_manager/core/browser/password_store:password_store_interface", "//components/prefs", "//components/url_formatter", "//components/variations/net", @@ -135,7 +135,7 @@ "//base", "//base/test:test_support", "//components/password_manager/core/browser:password_form", - "//components/password_manager/core/browser:password_store_interface", + "//components/password_manager/core/browser/password_store:password_store_interface", "//components/password_manager/core/common", "//components/password_manager/core/common:features", "//components/variations:test_support",
diff --git a/components/password_manager/core/browser/form_fetcher_impl_unittest.cc b/components/password_manager/core/browser/form_fetcher_impl_unittest.cc index b3686cc..eed4041f 100644 --- a/components/password_manager/core/browser/form_fetcher_impl_unittest.cc +++ b/components/password_manager/core/browser/form_fetcher_impl_unittest.cc
@@ -20,11 +20,11 @@ #include "components/password_manager/core/browser/affiliation/affiliated_match_helper.h" #include "components/password_manager/core/browser/affiliation/mock_affiliated_match_helper.h" #include "components/password_manager/core/browser/features/password_features.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" -#include "components/password_manager/core/browser/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store/interactions_stats.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "components/password_manager/core/browser/password_store/password_store_util.h" #include "components/password_manager/core/browser/stub_credentials_filter.h"
diff --git a/components/password_manager/core/browser/form_saver_impl_unittest.cc b/components/password_manager/core/browser/form_saver_impl_unittest.cc index 4d748db..795b07c 100644 --- a/components/password_manager/core/browser/form_saver_impl_unittest.cc +++ b/components/password_manager/core/browser/form_saver_impl_unittest.cc
@@ -15,9 +15,9 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/task_environment.h" #include "components/autofill/core/common/unique_ids.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_util.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h"
diff --git a/components/password_manager/core/browser/http_auth_manager_unittest.cc b/components/password_manager/core/browser/http_auth_manager_unittest.cc index 57254be..a4d72c57 100644 --- a/components/password_manager/core/browser/http_auth_manager_unittest.cc +++ b/components/password_manager/core/browser/http_auth_manager_unittest.cc
@@ -19,12 +19,12 @@ #include "components/password_manager/core/browser/features/password_features.h" #include "components/password_manager/core/browser/form_fetcher_impl.h" #include "components/password_manager/core/browser/http_auth_manager_impl.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" -#include "components/password_manager/core/browser/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_form_manager.h" #include "components/password_manager/core/browser/password_form_manager_for_ui.h" #include "components/password_manager/core/browser/password_manager_driver.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_store/password_store_consumer.h" #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "components/password_manager/core/browser/stub_password_manager_client.h"
diff --git a/components/password_manager/core/browser/http_password_store_migrator_unittest.cc b/components/password_manager/core/browser/http_password_store_migrator_unittest.cc index e42dfea..166b16b 100644 --- a/components/password_manager/core/browser/http_password_store_migrator_unittest.cc +++ b/components/password_manager/core/browser/http_password_store_migrator_unittest.cc
@@ -9,9 +9,9 @@ #include "base/ranges/algorithm.h" #include "base/strings/utf_string_conversions.h" #include "base/test/task_environment.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" -#include "components/password_manager/core/browser/mock_smart_bubble_stats_store.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h" #include "services/network/test/test_network_context.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/insecure_credentials_helper_unittest.cc b/components/password_manager/core/browser/insecure_credentials_helper_unittest.cc index 0772564..7a507ee 100644 --- a/components/password_manager/core/browser/insecure_credentials_helper_unittest.cc +++ b/components/password_manager/core/browser/insecure_credentials_helper_unittest.cc
@@ -7,9 +7,9 @@ #include "base/functional/callback.h" #include "base/test/task_environment.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/password_store_consumer.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/leak_detection_delegate_helper_unittest.cc b/components/password_manager/core/browser/leak_detection_delegate_helper_unittest.cc index c69099f2..8889a21 100644 --- a/components/password_manager/core/browser/leak_detection_delegate_helper_unittest.cc +++ b/components/password_manager/core/browser/leak_detection_delegate_helper_unittest.cc
@@ -14,8 +14,8 @@ #include "base/test/task_environment.h" #include "components/password_manager/core/browser/form_parsing/form_data_parser.h" #include "components/password_manager/core/browser/leak_detection_dialog_utils.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/test_password_store.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/leak_detection_delegate_unittest.cc b/components/password_manager/core/browser/leak_detection_delegate_unittest.cc index dc7dd5e8..a19e30e 100644 --- a/components/password_manager/core/browser/leak_detection_delegate_unittest.cc +++ b/components/password_manager/core/browser/leak_detection_delegate_unittest.cc
@@ -18,8 +18,8 @@ #include "components/password_manager/core/browser/leak_detection/mock_leak_detection_check_factory.h" #include "components/password_manager/core/browser/leak_detection_delegate.h" #include "components/password_manager/core/browser/leak_detection_dialog_utils.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/password_store_consumer.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/common/password_manager_features.h"
diff --git a/components/password_manager/core/browser/old_google_credentials_cleaner_unittest.cc b/components/password_manager/core/browser/old_google_credentials_cleaner_unittest.cc index cc1d0e63..f409bca 100644 --- a/components/password_manager/core/browser/old_google_credentials_cleaner_unittest.cc +++ b/components/password_manager/core/browser/old_google_credentials_cleaner_unittest.cc
@@ -6,7 +6,7 @@ #include "base/test/task_environment.h" #include "base/time/time.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h"
diff --git a/components/password_manager/core/browser/password_generation_manager_unittest.cc b/components/password_manager/core/browser/password_generation_manager_unittest.cc index bc9a10b5..bcec1405 100644 --- a/components/password_manager/core/browser/password_generation_manager_unittest.cc +++ b/components/password_manager/core/browser/password_generation_manager_unittest.cc
@@ -11,9 +11,9 @@ #include "base/test/task_environment.h" #include "components/password_manager/core/browser/fake_form_fetcher.h" #include "components/password_manager/core/browser/form_saver_impl.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_form_manager_for_ui.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h" #include "components/password_manager/core/common/password_manager_features.h"
diff --git a/components/password_manager/core/browser/password_manager.cc b/components/password_manager/core/browser/password_manager.cc index 902dc8d..978079e98 100644 --- a/components/password_manager/core/browser/password_manager.cc +++ b/components/password_manager/core/browser/password_manager.cc
@@ -59,10 +59,6 @@ #include "components/prefs/pref_registry_simple.h" #endif // BUILDFLAG(IS_WIN) -#if BUILDFLAG(IS_MAC) -#include "components/os_crypt/sync/os_crypt.h" -#endif - using autofill::ACCOUNT_CREATION_PASSWORD; using autofill::CalculateFormSignature; using autofill::FieldDataManager;
diff --git a/components/password_manager/core/browser/password_manager_test_utils.h b/components/password_manager/core/browser/password_manager_test_utils.h index 0b334d9..cb72d57 100644 --- a/components/password_manager/core/browser/password_manager_test_utils.h +++ b/components/password_manager/core/browser/password_manager_test_utils.h
@@ -9,13 +9,13 @@ #include <vector> #include "base/memory/ref_counted.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" #include "components/password_manager/core/browser/origin_credential_store.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_hash_data.h" #include "components/password_manager/core/browser/password_reuse_detector.h" #include "components/password_manager/core/browser/password_reuse_detector_consumer.h" #include "components/password_manager/core/browser/password_reuse_manager.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "testing/gmock/include/gmock/gmock.h" #include "url/gurl.h"
diff --git a/components/password_manager/core/browser/password_store/BUILD.gn b/components/password_manager/core/browser/password_store/BUILD.gn new file mode 100644 index 0000000..536d463d --- /dev/null +++ b/components/password_manager/core/browser/password_store/BUILD.gn
@@ -0,0 +1,176 @@ +# Copyright 2023 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/chromeos/ui_mode.gni") +import("//build/config/features.gni") + +source_set("password_store_interface") { + sources = [ + "interactions_stats.cc", + "interactions_stats.h", + "password_store_backend_error.cc", + "password_store_backend_error.h", + "password_store_change.cc", + "password_store_change.h", + "password_store_consumer.cc", + "password_store_consumer.h", + "password_store_interface.h", + "password_store_util.cc", + "password_store_util.h", + ] + public_deps = [ "//components/password_manager/core/browser:password_form" ] + deps = [ + "//base", + "//components/keyed_service/core", + "//url", + ] + configs += [ "//build/config/compiler:wexit_time_destructors" ] +} + +source_set("password_store_impl") { + sources = [ + "get_logins_with_affiliations_request_handler.cc", + "get_logins_with_affiliations_request_handler.h", + "insecure_credentials_table.cc", + "insecure_credentials_table.h", + "login_database.cc", + "login_database.h", + "login_database_async_helper.cc", + "login_database_async_helper.h", + "password_notes_table.cc", + "password_notes_table.h", + "password_store.cc", + "password_store.h", + "password_store_backend.h", + "password_store_backend_metrics_recorder.cc", + "password_store_backend_metrics_recorder.h", + "password_store_built_in_backend.cc", + "password_store_built_in_backend.h", + "psl_matching_helper.cc", + "psl_matching_helper.h", + "smart_bubble_stats_store.h", + "statistics_table.cc", + "statistics_table.h", + ] + public_deps = [ ":password_store_interface" ] + deps = [ + "//base", + "//build:blink_buildflags", + "//components/autofill/core/common", + "//components/os_crypt/sync:os_crypt", + "//components/password_manager/core/browser:metrics_util", + "//components/password_manager/core/browser:sql_builder", + "//components/password_manager/core/browser/affiliation", + "//components/password_manager/core/browser/features:password_features", + "//components/password_manager/core/browser/sync", + "//components/password_manager/core/common", + "//components/password_manager/core/common:features", + "//components/prefs", + "//components/safe_browsing/core/common:safe_browsing_prefs", + "//components/sync/base", + "//components/sync/base:features", + "//components/sync/model", + "//components/sync/protocol", + "//sql", + "//third_party/abseil-cpp:absl", + "//third_party/re2", + "//url", + ] + if (is_android) { + sources += [ + "android_backend_error.cc", + "android_backend_error.h", + ] + } + + if ((is_posix && !is_apple) || is_fuchsia) { + sources += [ "login_database_posix.cc" ] + } + + if (is_mac) { + sources += [ "login_database_mac.cc" ] + } + + if (is_ios) { + sources += [ "login_database_ios.cc" ] + } + + if (is_win) { + sources += [ "login_database_win.cc" ] + } + configs += [ "//build/config/compiler:wexit_time_destructors" ] +} + +static_library("test_support") { + testonly = true + sources = [ + "fake_password_store_backend.cc", + "fake_password_store_backend.h", + "mock_password_store_backend.cc", + "mock_password_store_backend.h", + "mock_password_store_consumer.cc", + "mock_password_store_consumer.h", + "mock_password_store_interface.cc", + "mock_password_store_interface.h", + "mock_smart_bubble_stats_store.cc", + "mock_smart_bubble_stats_store.h", + "test_password_store.cc", + "test_password_store.h", + ] + deps = [ + ":password_store_impl", + "//base", + "//components/password_manager/core/browser/affiliation", + "//components/sync/model", + "//testing/gmock", + ] + configs += [ "//build/config/compiler:wexit_time_destructors" ] +} + +source_set("unit_tests") { + testonly = true + sources = [ + "get_logins_with_affiliations_request_handler_unittest.cc", + "insecure_credentials_table_unittest.cc", + "login_database_unittest.cc", + "password_notes_table_unittest.cc", + "password_store_built_in_backend_unittest.cc", + "password_store_consumer_unittest.cc", + "password_store_unittest.cc", + "psl_matching_helper_unittest.cc", + "statistics_table_unittest.cc", + ] + + if (is_android) { + sources += [ "password_store_backend_metrics_recorder_unittest.cc" ] + } + if (is_ios) { + sources += [ "login_database_ios_unittest.cc" ] + } + deps = [ + ":password_store_impl", + ":test_support", + "//base", + "//base/test:test_support", + "//components/autofill/core/common", + "//components/os_crypt/sync:os_crypt", + "//components/os_crypt/sync:test_support", + "//components/password_manager/core/browser:test_support", + "//components/password_manager/core/browser/affiliation", + "//components/password_manager/core/browser/affiliation:test_support", + "//components/password_manager/core/browser/features:password_features", + "//components/password_manager/core/browser/form_parsing", + "//components/password_manager/core/browser/sync", + "//components/password_manager/core/common", + "//components/prefs", + "//components/prefs:test_support", + "//components/sync/model", + "//sql", + "//sql:test_support", + "//testing/gmock", + "//testing/gtest", + "//url", + ] + configs += [ "//build/config/compiler:wexit_time_destructors" ] +}
diff --git a/components/password_manager/core/browser/fake_password_store_backend.cc b/components/password_manager/core/browser/password_store/fake_password_store_backend.cc similarity index 98% rename from components/password_manager/core/browser/fake_password_store_backend.cc rename to components/password_manager/core/browser/password_store/fake_password_store_backend.cc index c8d30e1..ed42382 100644 --- a/components/password_manager/core/browser/fake_password_store_backend.cc +++ b/components/password_manager/core/browser/password_store/fake_password_store_backend.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/password_manager/core/browser/fake_password_store_backend.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include <utility> @@ -17,7 +17,6 @@ #include "components/password_manager/core/browser/password_store/get_logins_with_affiliations_request_handler.h" #include "components/password_manager/core/browser/password_store/psl_matching_helper.h" #include "components/sync/model/proxy_model_type_controller_delegate.h" -#include "password_form.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/fake_password_store_backend.h b/components/password_manager/core/browser/password_store/fake_password_store_backend.h similarity index 94% rename from components/password_manager/core/browser/fake_password_store_backend.h rename to components/password_manager/core/browser/password_store/fake_password_store_backend.h index 3c0f04a1..b7ec92b7 100644 --- a/components/password_manager/core/browser/fake_password_store_backend.h +++ b/components/password_manager/core/browser/password_store/fake_password_store_backend.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_PASSWORD_STORE_BACKEND_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_PASSWORD_STORE_BACKEND_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_FAKE_PASSWORD_STORE_BACKEND_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_FAKE_PASSWORD_STORE_BACKEND_H_ #include <map> #include <memory> @@ -127,4 +127,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FAKE_PASSWORD_STORE_BACKEND_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_FAKE_PASSWORD_STORE_BACKEND_H_
diff --git a/components/password_manager/core/browser/password_store/get_logins_with_affiliations_request_handler_unittest.cc b/components/password_manager/core/browser/password_store/get_logins_with_affiliations_request_handler_unittest.cc index e9a38d1f..a481b2e1 100644 --- a/components/password_manager/core/browser/password_store/get_logins_with_affiliations_request_handler_unittest.cc +++ b/components/password_manager/core/browser/password_store/get_logins_with_affiliations_request_handler_unittest.cc
@@ -14,11 +14,10 @@ #include "base/test/task_environment.h" #include "components/password_manager/core/browser/affiliation/affiliated_match_helper.h" #include "components/password_manager/core/browser/affiliation/mock_affiliation_service.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" #include "components/password_manager/core/browser/features/password_features.h" -#include "components/password_manager/core/browser/mock_password_store_consumer.h" #include "components/password_manager/core/browser/password_form.h" -#include "components/password_manager/core/browser/password_manager_test_utils.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_consumer.h" #include "components/password_manager/core/browser/password_store/password_store_backend_error.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/password_store/insecure_credentials_table_unittest.cc b/components/password_manager/core/browser/password_store/insecure_credentials_table_unittest.cc index 110e4fbe..82269dc3 100644 --- a/components/password_manager/core/browser/password_store/insecure_credentials_table_unittest.cc +++ b/components/password_manager/core/browser/password_store/insecure_credentials_table_unittest.cc
@@ -18,7 +18,6 @@ #include "components/password_manager/core/browser/password_store/login_database.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/common/password_manager_features.h" -#include "components/safe_browsing/core/common/features.h" #include "sql/database.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h"
diff --git a/components/password_manager/core/browser/login_database_ios_unittest.cc b/components/password_manager/core/browser/password_store/login_database_ios_unittest.cc similarity index 100% rename from components/password_manager/core/browser/login_database_ios_unittest.cc rename to components/password_manager/core/browser/password_store/login_database_ios_unittest.cc
diff --git a/components/password_manager/core/browser/password_store/login_database_unittest.cc b/components/password_manager/core/browser/password_store/login_database_unittest.cc index de2a585..286b3f49c 100644 --- a/components/password_manager/core/browser/password_store/login_database_unittest.cc +++ b/components/password_manager/core/browser/password_store/login_database_unittest.cc
@@ -29,7 +29,6 @@ #include "components/os_crypt/sync/os_crypt_mocker.h" #include "components/password_manager/core/browser/features/password_features.h" #include "components/password_manager/core/browser/password_form.h" -#include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store/password_store_change.h" #include "components/password_manager/core/browser/password_store/psl_matching_helper.h" #include "components/password_manager/core/browser/sync/password_store_sync.h"
diff --git a/components/password_manager/core/browser/mock_password_store_consumer.cc b/components/password_manager/core/browser/password_store/mock_password_store_consumer.cc similarity index 87% rename from components/password_manager/core/browser/mock_password_store_consumer.cc rename to components/password_manager/core/browser/password_store/mock_password_store_consumer.cc index c195aae..891526a 100644 --- a/components/password_manager/core/browser/mock_password_store_consumer.cc +++ b/components/password_manager/core/browser/password_store/mock_password_store_consumer.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/password_manager/core/browser/mock_password_store_consumer.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_consumer.h" #include "components/password_manager/core/browser/password_form.h"
diff --git a/components/password_manager/core/browser/mock_password_store_consumer.h b/components/password_manager/core/browser/password_store/mock_password_store_consumer.h similarity index 80% rename from components/password_manager/core/browser/mock_password_store_consumer.h rename to components/password_manager/core/browser/password_store/mock_password_store_consumer.h index f09d407f..77a73fc5f 100644 --- a/components/password_manager/core/browser/mock_password_store_consumer.h +++ b/components/password_manager/core/browser/password_store/mock_password_store_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 COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_STORE_CONSUMER_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_STORE_CONSUMER_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_PASSWORD_STORE_CONSUMER_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_PASSWORD_STORE_CONSUMER_H_ #include <memory> @@ -44,4 +44,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_STORE_CONSUMER_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_PASSWORD_STORE_CONSUMER_H_
diff --git a/components/password_manager/core/browser/mock_password_store_interface.cc b/components/password_manager/core/browser/password_store/mock_password_store_interface.cc similarity index 80% rename from components/password_manager/core/browser/mock_password_store_interface.cc rename to components/password_manager/core/browser/password_store/mock_password_store_interface.cc index 66ee370c..11d82c72 100644 --- a/components/password_manager/core/browser/mock_password_store_interface.cc +++ b/components/password_manager/core/browser/password_store/mock_password_store_interface.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/password_manager/core/browser/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/mock_password_store_interface.h b/components/password_manager/core/browser/password_store/mock_password_store_interface.h similarity index 92% rename from components/password_manager/core/browser/mock_password_store_interface.h rename to components/password_manager/core/browser/password_store/mock_password_store_interface.h index a458df9..71cdd703a 100644 --- a/components/password_manager/core/browser/mock_password_store_interface.h +++ b/components/password_manager/core/browser/password_store/mock_password_store_interface.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_STORE_INTERFACE_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_STORE_INTERFACE_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_PASSWORD_STORE_INTERFACE_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_PASSWORD_STORE_INTERFACE_H_ #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "components/sync/model/proxy_model_type_controller_delegate.h" @@ -100,4 +100,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_PASSWORD_STORE_INTERFACE_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_PASSWORD_STORE_INTERFACE_H_
diff --git a/components/password_manager/core/browser/mock_smart_bubble_stats_store.cc b/components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.cc similarity index 77% rename from components/password_manager/core/browser/mock_smart_bubble_stats_store.cc rename to components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.cc index efdd842..f80cf47 100644 --- a/components/password_manager/core/browser/mock_smart_bubble_stats_store.cc +++ b/components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.cc
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include "components/password_manager/core/browser/mock_smart_bubble_stats_store.h" +#include "components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h" namespace password_manager {
diff --git a/components/password_manager/core/browser/mock_smart_bubble_stats_store.h b/components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h similarity index 78% rename from components/password_manager/core/browser/mock_smart_bubble_stats_store.h rename to components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h index d82acfefc..a6db4b8d 100644 --- a/components/password_manager/core/browser/mock_smart_bubble_stats_store.h +++ b/components/password_manager/core/browser/password_store/mock_smart_bubble_stats_store.h
@@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_SMART_BUBBLE_STATS_STORE_H_ -#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_SMART_BUBBLE_STATS_STORE_H_ +#ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_SMART_BUBBLE_STATS_STORE_H_ +#define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_SMART_BUBBLE_STATS_STORE_H_ #include "base/functional/callback.h" #include "components/password_manager/core/browser/password_store/smart_bubble_stats_store.h" @@ -33,4 +33,4 @@ } // namespace password_manager -#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_MOCK_SMART_BUBBLE_STATS_STORE_H_ +#endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_STORE_MOCK_SMART_BUBBLE_STATS_STORE_H_
diff --git a/components/password_manager/core/browser/password_store/password_notes_table_unittest.cc b/components/password_manager/core/browser/password_store/password_notes_table_unittest.cc index adc114b..7eb70c2 100644 --- a/components/password_manager/core/browser/password_store/password_notes_table_unittest.cc +++ b/components/password_manager/core/browser/password_store/password_notes_table_unittest.cc
@@ -29,10 +29,6 @@ return form; } -const PasswordNote kFirstNote(u"note 1", base::Time::Now()); -const PasswordNote kSecondNote(u"note 2", base::Time::Now() + base::Hours(1)); -const PasswordNote kThirdNote(u"note 3", base::Time::Now() + base::Hours(1)); - using testing::ElementsAre; using testing::IsEmpty; using testing::SizeIs; @@ -74,47 +70,57 @@ WithSameParentIdThereCanBeOnlyOneAndItsReplaced) { EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm()), SizeIs(1)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kFirstNote)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kSecondNote)); + const PasswordNote first_note(u"note 1", base::Time::Now()), + second_note(u"note 2", base::Time::Now() + base::Hours(1)), + third_note(u"note 3", base::Time::Now() + base::Hours(1)); + + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), first_note)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), second_note)); EXPECT_THAT(table()->GetPasswordNotes(FormPrimaryKey(1)), - ElementsAre(kSecondNote)); + ElementsAre(second_note)); EXPECT_THAT(table()->GetAllPasswordNotesForTest(), SizeIs(1)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kThirdNote)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), third_note)); EXPECT_THAT(table()->GetPasswordNotes(FormPrimaryKey(1)), - ElementsAre(kThirdNote)); + ElementsAre(third_note)); EXPECT_THAT(table()->GetAllPasswordNotesForTest(), SizeIs(1)); } TEST_F(PasswordNotesTableTest, ReloadingDatabasePersistsEntries) { + const PasswordNote first_note(u"note 1", base::Time::Now()), + second_note(u"note 2", base::Time::Now() + base::Hours(1)); + EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user1")), SizeIs(1)); EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user2")), SizeIs(1)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kFirstNote)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(2), kSecondNote)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), first_note)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(2), second_note)); ReloadDatabase(); EXPECT_THAT(table()->GetAllPasswordNotesForTest(), UnorderedElementsAre( std::make_pair(FormPrimaryKey(1), - std::vector<PasswordNote>({kFirstNote})), + std::vector<PasswordNote>({first_note})), std::make_pair(FormPrimaryKey(2), - std::vector<PasswordNote>({kSecondNote})))); + std::vector<PasswordNote>({second_note})))); } TEST_F(PasswordNotesTableTest, GetPasswordNotes) { + const PasswordNote first_note(u"note 1", base::Time::Now()), + second_note(u"note 2", base::Time::Now() + base::Hours(1)); + EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user1")), SizeIs(1)); EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user2")), SizeIs(1)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kFirstNote)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(2), kSecondNote)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), first_note)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(2), second_note)); EXPECT_THAT(table()->GetPasswordNotes(FormPrimaryKey(1)), - ElementsAre(kFirstNote)); + ElementsAre(first_note)); EXPECT_THAT(table()->GetPasswordNotes(FormPrimaryKey(2)), - ElementsAre(kSecondNote)); + ElementsAre(second_note)); } TEST_F(PasswordNotesTableTest, GetPasswordNotesWhenParentIdDoesntExist) { @@ -122,31 +128,37 @@ } TEST_F(PasswordNotesTableTest, RemovePasswordNotes) { + const PasswordNote first_note(u"note 1", base::Time::Now()), + second_note(u"note 2", base::Time::Now() + base::Hours(1)), + third_note(u"note 3", base::Time::Now() + base::Hours(1)); + EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user1")), SizeIs(1)); EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user2")), SizeIs(1)); EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user3")), SizeIs(1)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kFirstNote)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(2), kSecondNote)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(3), kThirdNote)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), first_note)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(2), second_note)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(3), third_note)); EXPECT_TRUE(table()->RemovePasswordNotes(FormPrimaryKey(2))); EXPECT_THAT( table()->GetAllPasswordNotesForTest(), ElementsAre(std::make_pair(FormPrimaryKey(1), - std::vector<PasswordNote>({kFirstNote})), + std::vector<PasswordNote>({first_note})), std::make_pair(FormPrimaryKey(3), - std::vector<PasswordNote>({kThirdNote})))); + std::vector<PasswordNote>({third_note})))); } TEST_F(PasswordNotesTableTest, RemovePasswordNotesWithNonExistingKey) { + const PasswordNote first_note(u"note 1", base::Time::Now()); + EXPECT_THAT(login_db()->AddLogin(CreatePasswordForm(u"user1")), SizeIs(1)); - EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), kFirstNote)); + EXPECT_TRUE(table()->InsertOrReplace(FormPrimaryKey(1), first_note)); EXPECT_FALSE(table()->RemovePasswordNotes(FormPrimaryKey(1000))); EXPECT_THAT(table()->GetAllPasswordNotesForTest(), ElementsAre(std::make_pair( - FormPrimaryKey(1), std::vector<PasswordNote>({kFirstNote})))); + FormPrimaryKey(1), std::vector<PasswordNote>({first_note})))); } } // namespace
diff --git a/components/password_manager/core/browser/password_store_consumer_unittest.cc b/components/password_manager/core/browser/password_store/password_store_consumer_unittest.cc similarity index 95% rename from components/password_manager/core/browser/password_store_consumer_unittest.cc rename to components/password_manager/core/browser/password_store/password_store_consumer_unittest.cc index 604c78b..391ba4c4 100644 --- a/components/password_manager/core/browser/password_store_consumer_unittest.cc +++ b/components/password_manager/core/browser/password_store/password_store_consumer_unittest.cc
@@ -3,8 +3,8 @@ // found in the LICENSE file. #include "components/password_manager/core/browser/password_store/password_store_consumer.h" -#include "components/password_manager/core/browser/mock_password_store_consumer.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_consumer.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/components/password_manager/core/browser/password_store/password_store_unittest.cc b/components/password_manager/core/browser/password_store/password_store_unittest.cc index 1d17963..2f67adf5 100644 --- a/components/password_manager/core/browser/password_store/password_store_unittest.cc +++ b/components/password_manager/core/browser/password_store/password_store_unittest.cc
@@ -25,21 +25,18 @@ #include "components/os_crypt/sync/os_crypt_mocker.h" #include "components/password_manager/core/browser/affiliation/fake_affiliation_service.h" #include "components/password_manager/core/browser/affiliation/mock_affiliated_match_helper.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" #include "components/password_manager/core/browser/features/password_features.h" #include "components/password_manager/core/browser/form_parsing/form_data_parser.h" -#include "components/password_manager/core/browser/mock_password_store_consumer.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" -#include "components/password_manager/core/browser/password_reuse_detector.h" -#include "components/password_manager/core/browser/password_reuse_manager.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include "components/password_manager/core/browser/password_store/login_database.h" #include "components/password_manager/core/browser/password_store/mock_password_store_backend.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_consumer.h" #include "components/password_manager/core/browser/password_store/password_store.h" #include "components/password_manager/core/browser/password_store/password_store_backend.h" #include "components/password_manager/core/browser/password_store/password_store_built_in_backend.h" #include "components/password_manager/core/browser/password_store/password_store_consumer.h" -#include "components/password_manager/core/browser/password_store_signin_notifier.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_registry_simple.h"
diff --git a/components/password_manager/core/browser/password_store/psl_matching_helper.h b/components/password_manager/core/browser/password_store/psl_matching_helper.h index 2ce80ec0..97d276ba 100644 --- a/components/password_manager/core/browser/password_store/psl_matching_helper.h +++ b/components/password_manager/core/browser/password_store/psl_matching_helper.h
@@ -27,11 +27,6 @@ // These functions are used in production internally but exposed for testing. -// Returns true iff |form_signon_realm| designates a federated credential for -// |origin|. It doesn't check the port because |form_signon_realm| doesn't have -// it. -bool IsFederatedRealm(const std::string& form_signon_realm, const GURL& origin); - // Returns true iff |form_signon_realm| and |form_origin| designate a federated // PSL matching credential for the |origin|. bool IsFederatedPSLMatch(const std::string& form_signon_realm, @@ -39,6 +34,11 @@ const GURL& origin); #endif +// Returns true iff |form_signon_realm| designates a federated credential for +// |origin|. It doesn't check the port because |form_signon_realm| doesn't have +// it. +bool IsFederatedRealm(const std::string& form_signon_realm, const GURL& origin); + // Returns what type of match applies to |form| and |form_digest|. MatchResult GetMatchResult(const PasswordForm& form, const PasswordFormDigest& form_digest);
diff --git a/components/password_manager/core/browser/statistics_table_unittest.cc b/components/password_manager/core/browser/password_store/statistics_table_unittest.cc similarity index 100% rename from components/password_manager/core/browser/statistics_table_unittest.cc rename to components/password_manager/core/browser/password_store/statistics_table_unittest.cc
diff --git a/components/password_manager/core/browser/password_store/test_password_store.h b/components/password_manager/core/browser/password_store/test_password_store.h index 1afcf73..ba969bee 100644 --- a/components/password_manager/core/browser/password_store/test_password_store.h +++ b/components/password_manager/core/browser/password_store/test_password_store.h
@@ -8,7 +8,7 @@ #include <functional> #include "base/callback_list.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" #include "components/password_manager/core/browser/password_store/password_store.h" #include "testing/gmock/include/gmock/gmock.h"
diff --git a/components/password_manager/core/browser/sharing/BUILD.gn b/components/password_manager/core/browser/sharing/BUILD.gn index 326d034..4fd311b3 100644 --- a/components/password_manager/core/browser/sharing/BUILD.gn +++ b/components/password_manager/core/browser/sharing/BUILD.gn
@@ -33,9 +33,9 @@ "//base", "//components/password_manager/core/browser:metrics_util", "//components/password_manager/core/browser:password_form", - "//components/password_manager/core/browser:password_store_interface", "//components/password_manager/core/browser/features:password_features", "//components/password_manager/core/browser/features:utils", + "//components/password_manager/core/browser/password_store:password_store_interface", "//components/password_manager/core/common", "//components/prefs", "//components/signin/public/identity_manager",
diff --git a/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.cc b/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.cc index 55cf43c..46301ba 100644 --- a/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.cc +++ b/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.cc
@@ -33,30 +33,57 @@ sync_pb::OutgoingPasswordSharingInvitationSpecifics CreateOutgoingPasswordSharingInvitationSpecifics( - const PasswordForm& password_form, + const std::vector<PasswordForm>& passwords, const PasswordRecipient& recipient) { + CHECK(!passwords.empty()); sync_pb::OutgoingPasswordSharingInvitationSpecifics specifics; specifics.set_guid(base::Uuid::GenerateRandomV4().AsLowercaseString()); specifics.set_recipient_user_id(recipient.user_id); + sync_pb::PasswordSharingInvitationData::PasswordGroupData* + password_group_data = specifics.mutable_client_only_unencrypted_data() + ->mutable_password_group_data(); + password_group_data->set_username_value( + base::UTF16ToUTF8(passwords[0].username_value)); + password_group_data->set_password_value( + base::UTF16ToUTF8(passwords[0].password_value)); + + for (const PasswordForm& password : passwords) { + sync_pb::PasswordSharingInvitationData::PasswordGroupElementData* + element_data = password_group_data->add_element_data(); + element_data->set_scheme(static_cast<int>(password.scheme)); + element_data->set_signon_realm(password.signon_realm); + element_data->set_origin(password.url.is_valid() ? password.url.spec() + : ""); + element_data->set_username_element( + base::UTF16ToUTF8(password.username_element)); + element_data->set_password_element( + base::UTF16ToUTF8(password.password_element)); + element_data->set_display_name(base::UTF16ToUTF8(password.display_name)); + element_data->set_avatar_url( + password.icon_url.is_valid() ? password.icon_url.spec() : ""); + } + + // TODO(http://crbug.com/1448235) Stop populating the legacy proto format. + // Pick the first paassword and place it in the old proto format to achieve + // backwards compatibility. sync_pb::PasswordSharingInvitationData::PasswordData* password_data = specifics.mutable_client_only_unencrypted_data()->mutable_password_data(); password_data->set_password_value( - base::UTF16ToUTF8(password_form.password_value)); - password_data->set_scheme(static_cast<int>(password_form.scheme)); - password_data->set_signon_realm(password_form.signon_realm); + base::UTF16ToUTF8(passwords[0].password_value)); + password_data->set_scheme(static_cast<int>(passwords[0].scheme)); + password_data->set_signon_realm(passwords[0].signon_realm); password_data->set_origin( - password_form.url.is_valid() ? password_form.url.spec() : ""); + passwords[0].url.is_valid() ? passwords[0].url.spec() : ""); password_data->set_username_element( - base::UTF16ToUTF8(password_form.username_element)); + base::UTF16ToUTF8(passwords[0].username_element)); password_data->set_password_element( - base::UTF16ToUTF8(password_form.password_element)); + base::UTF16ToUTF8(passwords[0].password_element)); password_data->set_username_value( - base::UTF16ToUTF8(password_form.username_value)); - password_data->set_display_name( - base::UTF16ToUTF8(password_form.display_name)); + base::UTF16ToUTF8(passwords[0].username_value)); + password_data->set_display_name(base::UTF16ToUTF8(passwords[0].display_name)); password_data->set_avatar_url( - password_form.icon_url.is_valid() ? password_form.icon_url.spec() : ""); + passwords[0].icon_url.is_valid() ? passwords[0].icon_url.spec() : ""); return specifics; } @@ -86,16 +113,27 @@ return std::make_unique<syncer::DummyMetadataChangeList>(); } -void OutgoingPasswordSharingInvitationSyncBridge::SendPassword( - const PasswordForm& password, +void OutgoingPasswordSharingInvitationSyncBridge::SendPasswordGroup( + const std::vector<PasswordForm>& passwords, const PasswordRecipient& recipient) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + CHECK(!passwords.empty()); + // All `passwords` are expected to belong to the same group and hence have the + // same `username_value` and `password_value`. + CHECK_EQ(base::ranges::count(passwords, passwords[0].username_value, + &PasswordForm::username_value), + static_cast<int>(passwords.size())); + CHECK_EQ(base::ranges::count(passwords, passwords[0].password_value, + &PasswordForm::password_value), + static_cast<int>(passwords.size())); + if (!change_processor()->IsTrackingMetadata()) { return; } sync_pb::OutgoingPasswordSharingInvitationSpecifics specifics = - CreateOutgoingPasswordSharingInvitationSpecifics(password, recipient); + CreateOutgoingPasswordSharingInvitationSpecifics(passwords, recipient); const std::string storage_key = GetStorageKeyFromSpecifics(specifics); outgoing_invitations_in_flight_.emplace(
diff --git a/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.h b/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.h index a67c275b..f1d1451 100644 --- a/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.h +++ b/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.h
@@ -39,9 +39,12 @@ const OutgoingPasswordSharingInvitationSyncBridge&) = delete; ~OutgoingPasswordSharingInvitationSyncBridge() override; - // Sends `password` to the corresponding `recipient`. - void SendPassword(const PasswordForm& password, - const PasswordRecipient& recipient); + // Sends `passwords` to the corresponding `recipient`. All entries in + // `passwords` are expected to belong to the same credentials group. i.e. they + // all share the same username and password, and all origins are affiliated. + // `passwords` must not be empty. + void SendPasswordGroup(const std::vector<PasswordForm>& passwords, + const PasswordRecipient& recipient); // ModelTypeSyncBridge implementation. std::unique_ptr<syncer::MetadataChangeList> CreateMetadataChangeList()
diff --git a/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge_unittest.cc b/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge_unittest.cc index f8089c5..7b66da87 100644 --- a/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge_unittest.cc +++ b/components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge_unittest.cc
@@ -34,8 +34,10 @@ using testing::IsNull; using testing::Not; using testing::NotNull; +using testing::Property; using testing::Return; using testing::SaveArg; +using testing::UnorderedElementsAre; namespace password_manager { namespace { @@ -50,7 +52,8 @@ constexpr char kRecipientUserId[] = "recipient_user_id"; constexpr char kPasswordValue[] = "password"; -constexpr char kSignonRealm[] = "signon_realm"; +constexpr char kSignonRealm[] = "http://abc.com/"; +constexpr char kPslMatchSignonRealm[] = "http://n.abc.com/"; constexpr char kOrigin[] = "http://abc.com/"; constexpr char kUsernameElement[] = "username_element"; constexpr char kUsernameValue[] = "username"; @@ -175,25 +178,30 @@ DoAll(SaveArg<0>(&storage_key), SaveArgPointeeMove<1>(&entity_data))); CreateBridge(); - bridge()->SendPassword(MakePasswordForm(), /*recipient=*/{kRecipientUserId}); + bridge()->SendPasswordGroup({MakePasswordForm()}, + /*recipient=*/{kRecipientUserId}); const OutgoingPasswordSharingInvitationSpecifics& invitation_specifics = entity_data.specifics.outgoing_password_sharing_invitation(); EXPECT_EQ(invitation_specifics.guid(), storage_key); EXPECT_EQ(invitation_specifics.recipient_user_id(), kRecipientUserId); - const sync_pb::PasswordSharingInvitationData::PasswordData& password_data = - invitation_specifics.client_only_unencrypted_data().password_data(); - EXPECT_EQ(password_data.password_value(), kPasswordValue); - EXPECT_EQ(password_data.scheme(), + const sync_pb::PasswordSharingInvitationData::PasswordGroupData& + password_group_data = invitation_specifics.client_only_unencrypted_data() + .password_group_data(); + EXPECT_EQ(password_group_data.username_value(), kUsernameValue); + EXPECT_EQ(password_group_data.password_value(), kPasswordValue); + + const sync_pb::PasswordSharingInvitationData::PasswordGroupElementData& + password_group_element_data = password_group_data.element_data()[0]; + EXPECT_EQ(password_group_element_data.scheme(), static_cast<int>(PasswordForm::Scheme::kHtml)); - EXPECT_EQ(password_data.signon_realm(), kSignonRealm); - EXPECT_EQ(password_data.origin(), kOrigin); - EXPECT_EQ(password_data.username_element(), kUsernameElement); - EXPECT_EQ(password_data.username_value(), kUsernameValue); - EXPECT_EQ(password_data.password_element(), kPasswordElement); - EXPECT_EQ(password_data.display_name(), kPasswordDisplayName); - EXPECT_EQ(password_data.avatar_url(), kPasswordAvatarUrl); + EXPECT_EQ(password_group_element_data.signon_realm(), kSignonRealm); + EXPECT_EQ(password_group_element_data.origin(), kOrigin); + EXPECT_EQ(password_group_element_data.username_element(), kUsernameElement); + EXPECT_EQ(password_group_element_data.password_element(), kPasswordElement); + EXPECT_EQ(password_group_element_data.display_name(), kPasswordDisplayName); + EXPECT_EQ(password_group_element_data.avatar_url(), kPasswordAvatarUrl); } TEST_F(OutgoingPasswordSharingInvitationSyncBridgeTest, @@ -201,7 +209,8 @@ std::string storage_key; EXPECT_CALL(*mock_processor(), Put).WillOnce(SaveArg<0>(&storage_key)); CreateBridge(); - bridge()->SendPassword(MakePasswordForm(), /*recipient=*/{kRecipientUserId}); + bridge()->SendPasswordGroup({MakePasswordForm()}, + /*recipient=*/{kRecipientUserId}); ASSERT_THAT(storage_key, Not(IsEmpty())); std::unique_ptr<EntityData> get_data_result = GetDataFromBridge(storage_key); @@ -214,6 +223,62 @@ EXPECT_EQ(invitation_specifics.guid(), storage_key); EXPECT_EQ(invitation_specifics.recipient_user_id(), kRecipientUserId); + const sync_pb::PasswordSharingInvitationData::PasswordGroupData& + password_group_data = invitation_specifics.client_only_unencrypted_data() + .password_group_data(); + EXPECT_EQ(password_group_data.username_value(), kUsernameValue); + EXPECT_EQ(password_group_data.password_value(), kPasswordValue); + + const sync_pb::PasswordSharingInvitationData::PasswordGroupElementData& + password_group_element_data = password_group_data.element_data()[0]; + EXPECT_EQ(password_group_element_data.scheme(), + static_cast<int>(PasswordForm::Scheme::kHtml)); + EXPECT_EQ(password_group_element_data.signon_realm(), kSignonRealm); + EXPECT_EQ(password_group_element_data.origin(), kOrigin); + EXPECT_EQ(password_group_element_data.username_element(), kUsernameElement); + EXPECT_EQ(password_group_element_data.password_element(), kPasswordElement); + EXPECT_EQ(password_group_element_data.display_name(), kPasswordDisplayName); + EXPECT_EQ(password_group_element_data.avatar_url(), kPasswordAvatarUrl); +} + +TEST_F(OutgoingPasswordSharingInvitationSyncBridgeTest, + ShouldSendEntityForCommitForPasswordGroup) { + std::string storage_key; + EntityData entity_data; + EXPECT_CALL(*mock_processor(), Put) + .WillOnce( + DoAll(SaveArg<0>(&storage_key), SaveArgPointeeMove<1>(&entity_data))); + CreateBridge(); + + PasswordForm form = MakePasswordForm(); + PasswordForm psl_match_form = form; + psl_match_form.signon_realm = kPslMatchSignonRealm; + + bridge()->SendPasswordGroup({form, psl_match_form}, + /*recipient=*/{kRecipientUserId}); + + const OutgoingPasswordSharingInvitationSpecifics& invitation_specifics = + entity_data.specifics.outgoing_password_sharing_invitation(); + EXPECT_EQ(invitation_specifics.guid(), storage_key); + EXPECT_EQ(invitation_specifics.recipient_user_id(), kRecipientUserId); + + const sync_pb::PasswordSharingInvitationData::PasswordGroupData& + password_group_data = invitation_specifics.client_only_unencrypted_data() + .password_group_data(); + EXPECT_EQ(password_group_data.username_value(), kUsernameValue); + EXPECT_EQ(password_group_data.password_value(), kPasswordValue); + + EXPECT_THAT( + password_group_data.element_data(), + UnorderedElementsAre(Property(&sync_pb::PasswordSharingInvitationData:: + PasswordGroupElementData::signon_realm, + kSignonRealm), + Property(&sync_pb::PasswordSharingInvitationData:: + PasswordGroupElementData::signon_realm, + kPslMatchSignonRealm))); + + // The legacy proto format should also be populated with the first password in + // the group. const sync_pb::PasswordSharingInvitationData::PasswordData& password_data = invitation_specifics.client_only_unencrypted_data().password_data(); EXPECT_EQ(password_data.password_value(), kPasswordValue); @@ -233,7 +298,8 @@ std::string storage_key; EXPECT_CALL(*mock_processor(), Put).WillOnce(SaveArg<0>(&storage_key)); CreateBridge(); - bridge()->SendPassword(MakePasswordForm(), /*recipient=*/{kRecipientUserId}); + bridge()->SendPasswordGroup({MakePasswordForm()}, + /*recipient=*/{kRecipientUserId}); // Verify that the invitation is still in flight. ASSERT_THAT(storage_key, Not(IsEmpty())); @@ -255,7 +321,8 @@ std::string storage_key; EXPECT_CALL(*mock_processor(), Put).WillOnce(SaveArg<0>(&storage_key)); CreateBridge(); - bridge()->SendPassword(MakePasswordForm(), /*recipient=*/{kRecipientUserId}); + bridge()->SendPasswordGroup({MakePasswordForm()}, + /*recipient=*/{kRecipientUserId}); // Verify that the invitation is still in flight. ASSERT_THAT(storage_key, Not(IsEmpty())); @@ -274,7 +341,8 @@ std::string storage_key; EXPECT_CALL(*mock_processor(), Put).WillOnce(SaveArg<0>(&storage_key)); CreateBridge(); - bridge()->SendPassword(MakePasswordForm(), /*recipient=*/{kRecipientUserId}); + bridge()->SendPasswordGroup({MakePasswordForm()}, + /*recipient=*/{kRecipientUserId}); // Verify that the invitation is still in flight. ASSERT_THAT(storage_key, Not(IsEmpty()));
diff --git a/components/password_manager/core/browser/sharing/password_sender_service.h b/components/password_manager/core/browser/sharing/password_sender_service.h index da3e429..626389f 100644 --- a/components/password_manager/core/browser/sharing/password_sender_service.h +++ b/components/password_manager/core/browser/sharing/password_sender_service.h
@@ -35,7 +35,9 @@ PasswordSenderService& operator=(const PasswordSenderService&) = delete; ~PasswordSenderService() override = default; - // Sends `passwords` to the specified `recipient`. + // Sends `passwords` to the specified `recipient`. All entries in `passwords` + // are expected to belong to the same credentials group. i.e. they all share + // the same username and password, and all origins are affiliated. virtual void SendPasswords(const std::vector<PasswordForm>& passwords, const PasswordRecipient& recipient) = 0;
diff --git a/components/password_manager/core/browser/sharing/password_sender_service_impl.cc b/components/password_manager/core/browser/sharing/password_sender_service_impl.cc index d389040..c85cf884 100644 --- a/components/password_manager/core/browser/sharing/password_sender_service_impl.cc +++ b/components/password_manager/core/browser/sharing/password_sender_service_impl.cc
@@ -4,6 +4,7 @@ #include "components/password_manager/core/browser/sharing/password_sender_service_impl.h" +#include "base/ranges/algorithm.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/sharing/outgoing_password_sharing_invitation_sync_bridge.h" #include "components/sync/model/model_type_controller_delegate.h" @@ -21,9 +22,10 @@ void PasswordSenderServiceImpl::SendPasswords( const std::vector<PasswordForm>& passwords, const PasswordRecipient& recipient) { - for (const PasswordForm& password : passwords) { - sync_bridge_->SendPassword(password, recipient); + if (passwords.empty()) { + return; } + sync_bridge_->SendPasswordGroup(passwords, recipient); } base::WeakPtr<syncer::ModelTypeControllerDelegate>
diff --git a/components/password_manager/core/browser/store_metrics_reporter_unittest.cc b/components/password_manager/core/browser/store_metrics_reporter_unittest.cc index 53fdd03..77ace69a 100644 --- a/components/password_manager/core/browser/store_metrics_reporter_unittest.cc +++ b/components/password_manager/core/browser/store_metrics_reporter_unittest.cc
@@ -17,10 +17,10 @@ #include "components/password_manager/core/browser/features/password_features.h" #include "components/password_manager/core/browser/features/password_manager_features_util.h" #include "components/password_manager/core/browser/mock_password_reuse_manager.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" #include "components/password_manager/core/browser/password_manager_util.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/test_password_store.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/sync_username_test_base.h"
diff --git a/components/password_manager/core/browser/sync/BUILD.gn b/components/password_manager/core/browser/sync/BUILD.gn index 4905343..4d32c7f 100644 --- a/components/password_manager/core/browser/sync/BUILD.gn +++ b/components/password_manager/core/browser/sync/BUILD.gn
@@ -21,9 +21,9 @@ deps = [ "//components/password_manager/core/browser:metrics_util", "//components/password_manager/core/browser:password_form", - "//components/password_manager/core/browser:password_store_interface", "//components/password_manager/core/browser/features:password_features", "//components/password_manager/core/browser/features:utils", + "//components/password_manager/core/browser/password_store:password_store_interface", "//components/password_manager/core/common", "//components/password_manager/core/common:features", "//components/prefs",
diff --git a/components/password_manager/core/browser/sync_credentials_filter_unittest.cc b/components/password_manager/core/browser/sync_credentials_filter_unittest.cc index 1667cd4..68aa668 100644 --- a/components/password_manager/core/browser/sync_credentials_filter_unittest.cc +++ b/components/password_manager/core/browser/sync_credentials_filter_unittest.cc
@@ -18,13 +18,13 @@ #include "components/autofill/core/browser/ui/suggestion.h" #include "components/password_manager/core/browser/fake_form_fetcher.h" #include "components/password_manager/core/browser/features/password_features.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/mock_webauthn_credentials_delegate.h" #include "components/password_manager/core/browser/passkey_credential.h" #include "components/password_manager/core/browser/password_form.h" #include "components/password_manager/core/browser/password_form_manager.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_save_manager_impl.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/stub_form_saver.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/stub_password_manager_driver.h"
diff --git a/components/password_manager/core/browser/ui/BUILD.gn b/components/password_manager/core/browser/ui/BUILD.gn index 0aed63c..3ddcfec 100644 --- a/components/password_manager/core/browser/ui/BUILD.gn +++ b/components/password_manager/core/browser/ui/BUILD.gn
@@ -51,10 +51,10 @@ "//components/password_manager/core/browser:metrics_util", "//components/password_manager/core/browser:passkey_credential", "//components/password_manager/core/browser:password_form", - "//components/password_manager/core/browser:password_store_interface", "//components/password_manager/core/browser/affiliation", "//components/password_manager/core/browser/features:password_features", "//components/password_manager/core/browser/leak_detection", + "//components/password_manager/core/browser/password_store:password_store_interface", "//components/password_manager/core/common", "//components/prefs", "//components/safe_browsing/core/common:safe_browsing_prefs",
diff --git a/components/password_manager/core/browser/ui/post_save_compromised_helper_unittest.cc b/components/password_manager/core/browser/ui/post_save_compromised_helper_unittest.cc index ab321a2..7e7978de 100644 --- a/components/password_manager/core/browser/ui/post_save_compromised_helper_unittest.cc +++ b/components/password_manager/core/browser/ui/post_save_compromised_helper_unittest.cc
@@ -9,8 +9,8 @@ #include "base/test/mock_callback.h" #include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/common/password_manager_features.h" #include "components/password_manager/core/common/password_manager_pref_names.h" #include "components/prefs/pref_registry_simple.h"
diff --git a/components/password_manager/core/browser/ui/saved_passwords_presenter_unittest.cc b/components/password_manager/core/browser/ui/saved_passwords_presenter_unittest.cc index 80de4ad..37eeb2ca 100644 --- a/components/password_manager/core/browser/ui/saved_passwords_presenter_unittest.cc +++ b/components/password_manager/core/browser/ui/saved_passwords_presenter_unittest.cc
@@ -24,10 +24,10 @@ #include "base/time/time.h" #include "components/password_manager/core/browser/affiliation/fake_affiliation_service.h" #include "components/password_manager/core/browser/affiliation/mock_affiliation_service.h" -#include "components/password_manager/core/browser/fake_password_store_backend.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/passkey_credential.h" #include "components/password_manager/core/browser/password_form.h" +#include "components/password_manager/core/browser/password_store/fake_password_store_backend.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_store/password_store_interface.h" #include "components/password_manager/core/browser/password_store/test_password_store.h" #include "components/password_manager/core/browser/ui/credential_ui_entry.h"
diff --git a/components/password_manager/core/browser/votes_uploader_unittest.cc b/components/password_manager/core/browser/votes_uploader_unittest.cc index 32fda1ac..d31e725 100644 --- a/components/password_manager/core/browser/votes_uploader_unittest.cc +++ b/components/password_manager/core/browser/votes_uploader_unittest.cc
@@ -23,7 +23,7 @@ #include "components/autofill/core/common/signatures.h" #include "components/autofill/core/common/unique_ids.h" #include "components/password_manager/core/browser/features/password_features.h" -#include "components/password_manager/core/browser/mock_password_store_interface.h" +#include "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/browser/vote_uploads_test_matchers.h" #include "components/prefs/pref_registry_simple.h"
diff --git a/components/policy/ENTERPRISE_POLICY_OWNERS b/components/policy/ENTERPRISE_POLICY_OWNERS index 6511c4f..72f14c9 100644 --- a/components/policy/ENTERPRISE_POLICY_OWNERS +++ b/components/policy/ENTERPRISE_POLICY_OWNERS
@@ -12,6 +12,7 @@ pastarmovj@chromium.org #{LAST_RESORT_SUGGESTION} pmarko@chromium.org #{LAST_RESORT_SUGGESTION} poromov@chromium.org #{LAST_RESORT_SUGGESTION} +rbock@google.com #{LAST_RESORT_SUGGESTION} vsavu@google.com #{LAST_RESORT_SUGGESTION} ydago@chromium.org #{LAST_RESORT_SUGGESTION} zmin@chromium.org #{LAST_RESORT_SUGGESTION}
diff --git a/components/reporting/proto/synced/metric_data.proto b/components/reporting/proto/synced/metric_data.proto index 422f9cb..7554eeaa 100644 --- a/components/reporting/proto/synced/metric_data.proto +++ b/components/reporting/proto/synced/metric_data.proto
@@ -407,6 +407,12 @@ optional bool is_internal = 5; } +// deliberately left empty as there is no payload for Heartbeat messages. +// It just implicitly indicates that the sender is still alive. +message KioskHeartbeatTelemetry { + // No payload +} + // Data that can change over time, collected and reported every specific period // of time or when an event occur. // IMPORTANT: Do not add additional non-message fields (bool, int, string, @@ -438,6 +444,8 @@ optional RuntimeCountersTelemetry runtime_counters_telemetry = 10; // Website telemetry data. optional WebsiteTelemetry website_telemetry = 11; + // Kiosk Heartbeats as telemetry data + optional KioskHeartbeatTelemetry heartbeat_telemetry = 12; } enum MetricEventType { @@ -456,6 +464,7 @@ CRASH_FATALLY = 17; URL_OPENED = 18; URL_CLOSED = 19; + KIOSK_HEARTBEAT = 20; reserved 2, 3, 10, 11, 12; }
diff --git a/components/reporting/proto/synced/record_constants.proto b/components/reporting/proto/synced/record_constants.proto index 60da0b9..73c111d 100644 --- a/components/reporting/proto/synced/record_constants.proto +++ b/components/reporting/proto/synced/record_constants.proto
@@ -103,6 +103,10 @@ // |CROS_SECURITY_USER| is for events that are occurring from user actions. CROS_SECURITY_USER = 28; + // |KIOSK_HEARTBEAT_EVENTS| is for events from Kiosk/MGS devices that write + // heartbeats to dds based on the telemetry pipeline using ERP + KIOSK_HEARTBEAT_EVENTS = 29; + reserved 8; }
diff --git a/components/supervised_user/core/browser/BUILD.gn b/components/supervised_user/core/browser/BUILD.gn index 81950956..8c1076e5 100644 --- a/components/supervised_user/core/browser/BUILD.gn +++ b/components/supervised_user/core/browser/BUILD.gn
@@ -10,11 +10,13 @@ deps = [ "//base", + "//components/google/core/common:common", "//components/keyed_service/core", "//components/pref_registry:pref_registry", "//components/prefs", "//components/supervised_user/core/browser/proto", "//components/supervised_user/core/common", + "//url", ] if (is_android) {
diff --git a/components/supervised_user/core/browser/supervised_user_preferences.cc b/components/supervised_user/core/browser/supervised_user_preferences.cc index 07589e8..bcc4a269 100644 --- a/components/supervised_user/core/browser/supervised_user_preferences.cc +++ b/components/supervised_user/core/browser/supervised_user_preferences.cc
@@ -8,6 +8,7 @@ #include "base/logging.h" #include "base/notreached.h" +#include "components/google/core/common/google_util.h" #include "components/prefs/pref_service.h" #include "components/supervised_user/core/browser/proto/kidschromemanagement_messages.pb.h" #include "components/supervised_user/core/common/features.h" @@ -198,6 +199,20 @@ #endif // BUILDFLAG(ENABLE_EXTENSIONS) } +bool IsCookieDeletionDisabled(const GURL& origin, + const PrefService& pref_service) { + if (!base::FeatureList::IsEnabled( + supervised_user::kClearingCookiesKeepsSupervisedUsersSignedIn)) { + return false; + } + + if (!IsChildAccount(pref_service)) { + return false; + } + return google_util::IsYoutubeDomainUrl(origin, google_util::ALLOW_SUBDOMAIN, + google_util::ALLOW_NON_STANDARD_PORTS); +} + } // namespace supervised_user #if BUILDFLAG(IS_ANDROID)
diff --git a/components/supervised_user/core/browser/supervised_user_preferences.h b/components/supervised_user/core/browser/supervised_user_preferences.h index dcb6c19..8d85c43 100644 --- a/components/supervised_user/core/browser/supervised_user_preferences.h +++ b/components/supervised_user/core/browser/supervised_user_preferences.h
@@ -8,6 +8,7 @@ #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/supervised_user/core/browser/proto/kidschromemanagement_messages.pb.h" +#include "url/gurl.h" // Functions in this module should take a preferences service as an argument and // perform operations on it that manipulate the preferences related to the @@ -41,6 +42,11 @@ // Returns true if the extensions permissions parental control is enabled. bool AreExtensionsPermissionsEnabled(const PrefService& pref_service); +// Returns true if the user is supervised and the origin is a Google +// affiliated domain that is not allowed to delete cookies for supervised users. +bool IsCookieDeletionDisabled(const GURL& origin, + const PrefService& pref_service); + } // namespace supervised_user #endif // COMPONENTS_SUPERVISED_USER_CORE_BROWSER_SUPERVISED_USER_PREFERENCES_H_
diff --git a/components/supervised_user/core/browser/supervised_user_preferences_unittest.cc b/components/supervised_user/core/browser/supervised_user_preferences_unittest.cc index 19d0d137..5f813f6 100644 --- a/components/supervised_user/core/browser/supervised_user_preferences_unittest.cc +++ b/components/supervised_user/core/browser/supervised_user_preferences_unittest.cc
@@ -143,6 +143,86 @@ EXPECT_FALSE(supervised_user::IsSafeSitesEnabled(pref_service_)); } +enum class ClearingCookiesSingInImpact { kKeepUserSignedIn, kSignoutUser }; + +// Tests for the method IsCookieDeletionDisabled which +// depends on enabling a feature flag. +class SupervisedUserPreferencesTestWithClearingCookies + : public ::testing::Test, + public testing::WithParamInterface<ClearingCookiesSingInImpact> { + public: + void SetUp() override { + auto* registry = pref_service_.registry(); + supervised_user::RegisterProfilePrefs(registry); + if (ClearingCookiesKeepsUserSignedIn()) { + feature_list_.InitAndEnableFeature( + supervised_user::kClearingCookiesKeepsSupervisedUsersSignedIn); + } else { + feature_list_.InitAndDisableFeature( + supervised_user::kClearingCookiesKeepsSupervisedUsersSignedIn); + } + } + + bool ClearingCookiesKeepsUserSignedIn() { + return GetParam() == ClearingCookiesSingInImpact::kKeepUserSignedIn; + } + + protected: + TestingPrefServiceSimple pref_service_; + + private: + base::test::ScopedFeatureList feature_list_; +}; + +TEST_P(SupervisedUserPreferencesTestWithClearingCookies, + IsCookieDeletionDisabledForSupervisedUser) { + // Set supervised user preference. + pref_service_.SetString(prefs::kSupervisedUserId, + supervised_user::kChildAccountSUID); + + EXPECT_FALSE(supervised_user::IsCookieDeletionDisabled( + GURL("https://google.com"), pref_service_)); + EXPECT_FALSE(supervised_user::IsCookieDeletionDisabled( + GURL("https://example.com"), pref_service_)); + + EXPECT_EQ(supervised_user::IsCookieDeletionDisabled( + GURL("http://youtube.com"), pref_service_), + ClearingCookiesKeepsUserSignedIn()); + EXPECT_EQ(supervised_user::IsCookieDeletionDisabled( + GURL("https://youtube.com"), pref_service_), + ClearingCookiesKeepsUserSignedIn()); +} + +TEST_P(SupervisedUserPreferencesTestWithClearingCookies, + IsCookieDeletionDisabledForNonSupervisedUser) { + // Set non-supervised user preference. + pref_service_.SetString(prefs::kSupervisedUserId, std::string()); + + EXPECT_FALSE(supervised_user::IsCookieDeletionDisabled( + GURL("https://google.com"), pref_service_)); + EXPECT_FALSE(supervised_user::IsCookieDeletionDisabled( + GURL("https://example.com"), pref_service_)); + EXPECT_FALSE(supervised_user::IsCookieDeletionDisabled( + GURL("http://youtube.com"), pref_service_)); + EXPECT_FALSE(supervised_user::IsCookieDeletionDisabled( + GURL("https://youtube.com"), pref_service_)); +} + +INSTANTIATE_TEST_SUITE_P( + All, + SupervisedUserPreferencesTestWithClearingCookies, + testing::Values(ClearingCookiesSingInImpact::kKeepUserSignedIn, + ClearingCookiesSingInImpact::kSignoutUser), + [](const testing::TestParamInfo<ClearingCookiesSingInImpact> info) { + // Generate the test suffix from boolean param. + switch (info.param) { + case ClearingCookiesSingInImpact::kKeepUserSignedIn: + return "with_keep_signed_in_user"; + case ClearingCookiesSingInImpact::kSignoutUser: + return "with_signout_user"; + } + }); + enum class UrlFilteringStatus { kEnabled, kDisabled }; // Tests for the method IsSubjectToParentalControlsForSupervisedUser which
diff --git a/components/supervised_user/core/browser/supervised_user_service.cc b/components/supervised_user/core/browser/supervised_user_service.cc index 5649291..e9491f38 100644 --- a/components/supervised_user/core/browser/supervised_user_service.cc +++ b/components/supervised_user/core/browser/supervised_user_service.cc
@@ -18,7 +18,6 @@ #include "base/values.h" #include "base/version.h" #include "build/build_config.h" -#include "components/google/core/common/google_util.h" #include "components/prefs/pref_service.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "components/supervised_user/core/browser/kids_chrome_management_client.h" @@ -396,19 +395,4 @@ user_prefs_->GetInteger(prefs::kFirstTimeInterstitialBannerState)); return banner_state == FirstTimeInterstitialBannerState::kNeedToShow; } - -// Some Google-affiliated domains are not allowed to delete cookies for -// supervised accounts. -bool SupervisedUserService::IsCookieDeletionDisabled(const GURL& origin) const { - if (!base::FeatureList::IsEnabled( - supervised_user::kClearingCookiesKeepsSupervisedUsersSignedIn)) { - return false; - } - - if (!supervised_user::IsChildAccount(user_prefs_.get())) { - return false; - } - return google_util::IsYoutubeDomainUrl(origin, google_util::ALLOW_SUBDOMAIN, - google_util::ALLOW_NON_STANDARD_PORTS); -} } // namespace supervised_user
diff --git a/components/supervised_user/core/browser/supervised_user_service.h b/components/supervised_user/core/browser/supervised_user_service.h index 0b9ede72..a4bf55b 100644 --- a/components/supervised_user/core/browser/supervised_user_service.h +++ b/components/supervised_user/core/browser/supervised_user_service.h
@@ -132,10 +132,6 @@ // Returns true if the interstitial banner needs to be shown to user. bool ShouldShowFirstTimeInterstitialBanner() const; - // Some Google-affiliated domains are not allowed to delete cookies for - // supervised users. - bool IsCookieDeletionDisabled(const GURL& origin) const; - // Use |SupervisedUserServiceFactory::GetForProfile(..)| to get // an instance of this service. // Public to allow visibility to iOS factory.
diff --git a/components/supervised_user/core/browser/supervised_user_service_unittest.cc b/components/supervised_user/core/browser/supervised_user_service_unittest.cc index 3612bb79..6db86e6 100644 --- a/components/supervised_user/core/browser/supervised_user_service_unittest.cc +++ b/components/supervised_user/core/browser/supervised_user_service_unittest.cc
@@ -199,29 +199,6 @@ SupervisedUserURLFilter::GetBlockedSitesCountHistogramNameForTest(), /*expected_count=*/3); } -TEST_F(SupervisedUserServiceTest, - CookieDeletionDisabledForYoutubeDomainsWhenClearingCookiesEnabled) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - kClearingCookiesKeepsSupervisedUsersSignedIn); - - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://google.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://example.com"))); - EXPECT_TRUE(service_->IsCookieDeletionDisabled(GURL("http://youtube.com"))); - EXPECT_TRUE(service_->IsCookieDeletionDisabled(GURL("https://youtube.com"))); -} - -TEST_F(SupervisedUserServiceTest, - CookieDeletionAllowedForYoutubeDomainsWhenClearingCookiesDisabled) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndDisableFeature( - kClearingCookiesKeepsSupervisedUsersSignedIn); - - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://google.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://example.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("http://youtube.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://youtube.com"))); -} TEST_F(SupervisedUserServiceTest, InterstitialBannerState) { #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || \ @@ -307,28 +284,4 @@ /* SupervisedUserURLFilter::WARN */ 1)); } -TEST_F(SupervisedUserServiceTestUnsupervised, - CookieDeletionAllowedForYoutubeDomainsWhenClearingCookiesEnabled) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndEnableFeature( - kClearingCookiesKeepsSupervisedUsersSignedIn); - - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://google.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://example.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("http://youtube.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://youtube.com"))); -} - -TEST_F(SupervisedUserServiceTestUnsupervised, - CookieDeletionAllowedForYoutubeDomainsWhenClearingCookiesDisabled) { - base::test::ScopedFeatureList feature_list; - feature_list.InitAndDisableFeature( - kClearingCookiesKeepsSupervisedUsersSignedIn); - - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://google.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://example.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("http://youtube.com"))); - EXPECT_FALSE(service_->IsCookieDeletionDisabled(GURL("https://youtube.com"))); -} - } // namespace supervised_user
diff --git a/components/web_resource/resource_request_allowed_notifier.h b/components/web_resource/resource_request_allowed_notifier.h index d544e21..0379ce2 100644 --- a/components/web_resource/resource_request_allowed_notifier.h +++ b/components/web_resource/resource_request_allowed_notifier.h
@@ -126,7 +126,7 @@ const char* disable_network_switch_; // The local state this class is observing. - raw_ptr<PrefService, LeakedDanglingUntriaged> local_state_; + raw_ptr<PrefService> local_state_; // Tracks whether or not the observer/service depending on this class actually // requested permission to make a request or not. If it did not, then this @@ -143,8 +143,8 @@ raw_ptr<Observer> observer_; NetworkConnectionTrackerGetter network_connection_tracker_getter_; - raw_ptr<network::NetworkConnectionTracker, LeakedDanglingUntriaged> - network_connection_tracker_ = nullptr; + raw_ptr<network::NetworkConnectionTracker> network_connection_tracker_ = + nullptr; network::mojom::ConnectionType connection_type_ = network::mojom::ConnectionType::CONNECTION_UNKNOWN; bool connection_initialized_ = false;
diff --git a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc index 5542a7a..dff0ff8 100644 --- a/content/browser/accessibility/dump_accessibility_tree_browsertest.cc +++ b/content/browser/accessibility/dump_accessibility_tree_browsertest.cc
@@ -3677,7 +3677,13 @@ RunRegressionTest(FILE_PATH_LITERAL("reused-map.html")); } -IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, ReusedMapMoveImage) { +// TODO(crbug.com/1503567): Re-enable this test +#if BUILDFLAG(IS_LINUX) && defined(MEMORY_SANITIZER) +#define MAYBE_ReusedMapMoveImage DISABLED_ReusedMapMoveImage +#else +#define MAYBE_ReusedMapMoveImage ReusedMapMoveImage +#endif +IN_PROC_BROWSER_TEST_P(DumpAccessibilityTreeTest, MAYBE_ReusedMapMoveImage) { RunRegressionTest(FILE_PATH_LITERAL("reused-map-move-image.html")); }
diff --git a/content/browser/media/media_devices_util.cc b/content/browser/media/media_devices_util.cc index 6cf8bb98..142e95a 100644 --- a/content/browser/media/media_devices_util.cc +++ b/content/browser/media/media_devices_util.cc
@@ -27,6 +27,7 @@ #include "content/public/common/content_client.h" #include "crypto/hmac.h" #include "media/base/media_switches.h" +#include "media/capture/video/video_capture_device_descriptor.h" #include "net/cookies/site_for_cookies.h" #include "url/origin.h" @@ -258,7 +259,8 @@ ? std::string() : GetHMACForRawMediaDeviceID(salt_and_origin, device_info.group_id, /*use_group_salt=*/true), - device_info.video_control_support, device_info.video_facing); + device_info.video_control_support, device_info.video_facing, + device_info.availability); } return blink::WebMediaDeviceInfo(std::string(), std::string(), std::string(), media::VideoCaptureControlSupport(),
diff --git a/content/browser/media/media_devices_util_unittest.cc b/content/browser/media/media_devices_util_unittest.cc index f5dbe6cb..72c00c0 100644 --- a/content/browser/media/media_devices_util_unittest.cc +++ b/content/browser/media/media_devices_util_unittest.cc
@@ -5,6 +5,7 @@ #include "content/browser/media/media_devices_util.h" #include "media/audio/audio_device_description.h" +#include "media/capture/video/video_capture_device_descriptor.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/mediastream/media_devices.h" @@ -25,9 +26,13 @@ } blink::WebMediaDeviceInfo ExampleWebMediaDeviceInfo() { - return blink::WebMediaDeviceInfo(/*device_id=*/"example device id", - /*label=*/"example label", - /*group_id=*/"example_group_id"); + return blink::WebMediaDeviceInfo( + /*device_id=*/"example device id", + /*label=*/"example label", + /*group_id=*/"example_group_id", + /*video_control_support=*/{.pan = true, .tilt = true, .zoom = true}, + blink::mojom::FacingMode::kEnvironment, + media::CameraAvailability::kAvailable); } } // namespace @@ -55,6 +60,14 @@ EXPECT_EQ(translated_info.group_id, GetHMACForRawMediaDeviceID(salt_and_origin, original_info.group_id, /*use_group_salt=*/true)); + EXPECT_EQ(translated_info.video_facing, original_info.video_facing); + EXPECT_EQ(translated_info.video_control_support.pan, + original_info.video_control_support.pan); + EXPECT_EQ(translated_info.video_control_support.tilt, + original_info.video_control_support.tilt); + EXPECT_EQ(translated_info.video_control_support.zoom, + original_info.video_control_support.zoom); + EXPECT_EQ(translated_info.availability, original_info.availability); } TEST(MediaDevicesUtilBrowserTest, TranslateMediaDeviceInfoWithoutPermission) { @@ -65,6 +78,11 @@ EXPECT_TRUE(translated_info.device_id.empty()); EXPECT_TRUE(translated_info.label.empty()); EXPECT_TRUE(translated_info.group_id.empty()); + EXPECT_EQ(translated_info.video_facing, blink::mojom::FacingMode::kNone); + EXPECT_FALSE(translated_info.video_control_support.pan); + EXPECT_FALSE(translated_info.video_control_support.tilt); + EXPECT_FALSE(translated_info.video_control_support.zoom); + EXPECT_FALSE(translated_info.availability.has_value()); } TEST(MediaDevicesUtilTest, TranslateSpecialDeviceIDs) {
diff --git a/content/browser/preloading/prerender/prerender_features.cc b/content/browser/preloading/prerender/prerender_features.cc index 0b97ca73..88bc638 100644 --- a/content/browser/preloading/prerender/prerender_features.cc +++ b/content/browser/preloading/prerender/prerender_features.cc
@@ -21,4 +21,14 @@ "Prerender2NewLimitAndScheduler", base::FEATURE_ENABLED_BY_DEFAULT); +// Allows activation in background tab. For now, this is used only on web +// platform tests on macOS to run activation with target hint tests that have +// race conditions between visibility change and activation start on a prerender +// WebContents. Note that this issue does not happen on browser_tests, so this +// could be specific to WPT setup. +// TODO(crbug.com/1399709): Allow activation in background by default. +BASE_FEATURE(kPrerender2AllowActivationInBackground, + "Prerender2AllowActivationInBackground", + base::FEATURE_DISABLED_BY_DEFAULT); + } // namespace content::features
diff --git a/content/browser/preloading/prerender/prerender_features.h b/content/browser/preloading/prerender/prerender_features.h index 795ef5d..3e07841 100644 --- a/content/browser/preloading/prerender/prerender_features.h +++ b/content/browser/preloading/prerender/prerender_features.h
@@ -12,6 +12,7 @@ CONTENT_EXPORT BASE_DECLARE_FEATURE(kPrerender2BypassMemoryLimitCheck); CONTENT_EXPORT BASE_DECLARE_FEATURE(kPrerender2NewLimitAndScheduler); +CONTENT_EXPORT BASE_DECLARE_FEATURE(kPrerender2AllowActivationInBackground); } // namespace content::features
diff --git a/content/browser/preloading/prerender/prerender_host_registry.cc b/content/browser/preloading/prerender/prerender_host_registry.cc index 1c9009c6..0a0b39a 100644 --- a/content/browser/preloading/prerender/prerender_host_registry.cc +++ b/content/browser/preloading/prerender/prerender_host_registry.cc
@@ -60,6 +60,21 @@ } } +// Returns true when it is allowed to activate a prerendered page in a +// background tab. +bool IsAllowedToActivateInBackgroundForTesting() { + // Now it is allowed to activate a prerendered page in a background only on + // macOS for running web platform tests. See comments on the flag definition + // for more details. +#if BUILDFLAG(IS_MAC) + if (base::FeatureList::IsEnabled( + features::kPrerender2AllowActivationInBackground)) { + return true; + } +#endif + return false; +} + bool DeviceHasEnoughMemoryForPrerender() { // This method disallows prerendering on low-end devices if the // kPrerender2MemoryControls feature is enabled. @@ -1511,7 +1526,8 @@ // TODO(crbug.com/1399709): Remove the restriction after further investigation // and discussion. // Disallow activation when the navigation happens in the hidden tab. - if (web_contents()->GetVisibility() == Visibility::HIDDEN) { + if (web_contents()->GetVisibility() == Visibility::HIDDEN && + !IsAllowedToActivateInBackgroundForTesting()) { CancelHost(host->frame_tree_node_id(), PrerenderFinalStatus::kActivatedInBackground); return RenderFrameHost::kNoFrameTreeNodeId;
diff --git a/content/browser/renderer_host/media/media_devices_manager.cc b/content/browser/renderer_host/media/media_devices_manager.cc index d2953f3..18b5f18 100644 --- a/content/browser/renderer_host/media/media_devices_manager.cc +++ b/content/browser/renderer_host/media/media_devices_manager.cc
@@ -38,6 +38,7 @@ #include "media/audio/audio_device_description.h" #include "media/audio/audio_system.h" #include "media/base/media_switches.h" +#include "media/capture/mojom/video_capture_types.mojom-shared.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/audio/public/mojom/device_notifications.mojom.h" @@ -957,6 +958,11 @@ capabilities->formats = GetVideoInputFormats(raw_device_infos[i].device_id, false /* try_in_use_first */); capabilities->facing_mode = translated_device_infos[i].video_facing; + if (translated_device_infos[i].availability) { + capabilities->availability = + static_cast<media::mojom::CameraAvailability>( + *translated_device_infos[i].availability); + } video_input_capabilities.push_back(std::move(capabilities)); } return video_input_capabilities;
diff --git a/content/browser/renderer_host/media/media_devices_manager_unittest.cc b/content/browser/renderer_host/media/media_devices_manager_unittest.cc index 3f18975..aed93ab4 100644 --- a/content/browser/renderer_host/media/media_devices_manager_unittest.cc +++ b/content/browser/renderer_host/media/media_devices_manager_unittest.cc
@@ -30,8 +30,10 @@ #include "media/audio/fake_audio_log_factory.h" #include "media/audio/fake_audio_manager.h" #include "media/audio/test_audio_thread.h" +#include "media/base/video_facing.h" #include "media/capture/mojom/video_capture_types.mojom.h" #include "media/capture/video/fake_video_capture_device_factory.h" +#include "media/capture/video/video_capture_device_descriptor.h" #include "media/capture/video/video_capture_system_impl.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver_set.h" @@ -377,6 +379,14 @@ video_capabilities[i]->formats[j], expected_video_capture_device_settings[i].supported_formats[j]); } + EXPECT_EQ( + video_capabilities[i]->availability.has_value(), + expected_video_capture_device_settings[i].availability.has_value()); + if (video_capabilities[i]->availability.has_value()) { + EXPECT_EQ(static_cast<media::CameraAvailability>( + *video_capabilities[i]->availability), + *expected_video_capture_device_settings[i].availability); + } } EXPECT_EQ(audio_capabilities.size(), kNumAudioInputDevices); for (size_t i = 0; i < audio_capabilities.size(); ++i) { @@ -1163,6 +1173,7 @@ fake_device1.supported_formats = { {{1000, 1000}, 60.0, media::PIXEL_FORMAT_I420}, {{2000, 2000}, 120.0, media::PIXEL_FORMAT_I420}}; + fake_device1.availability = media::CameraAvailability::kAvailable; media::FakeVideoCaptureDeviceSettings fake_device2; fake_device2.device_id = "fake_id_2";
diff --git a/content/browser/service_worker/service_worker_registration_object_host.cc b/content/browser/service_worker/service_worker_registration_object_host.cc index c3d58e31..8d56c9d 100644 --- a/content/browser/service_worker/service_worker_registration_object_host.cc +++ b/content/browser/service_worker/service_worker_registration_object_host.cc
@@ -4,6 +4,7 @@ #include "content/browser/service_worker/service_worker_registration_object_host.h" +#include "base/debug/crash_logging.h" #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" #include "base/strings/stringprintf.h" @@ -478,7 +479,10 @@ std::vector<GURL> urls = {container_host_->url(), registration_->scope()}; if (!service_worker_security_utils::AllOriginsMatchAndCanAccessServiceWorkers( urls)) { - base::debug::Alias(&urls); + SCOPED_CRASH_KEY_STRING256("SWROH_CSROHM", "host_url", + container_host_->url().spec()); + SCOPED_CRASH_KEY_STRING256("SWROH_CSROHM", "reg_scope", + registration_->scope().spec()); receivers_.ReportBadMessage( ServiceWorkerConsts::kBadMessageImproperOrigins); return false;
diff --git a/content/public/test/render_view_test.cc b/content/public/test/render_view_test.cc index 9a6ad3b..2bf1c155 100644 --- a/content/public/test/render_view_test.cc +++ b/content/public/test/render_view_test.cc
@@ -616,13 +616,15 @@ return gfx::Rect(); v8::Local<v8::Array> array = value.As<v8::Array>(); + v8::Local<v8::Context> v8_context = + array->GetCreationContext().ToLocalChecked(); + v8::Context::Scope v8_context_scope(v8_context); if (array->Length() != 4) return gfx::Rect(); std::vector<int> coords; for (int i = 0; i < 4; ++i) { v8::Local<v8::Number> index = v8::Number::New(isolate, i); - if (!array->Get(isolate->GetCurrentContext(), index).ToLocal(&value) || - !value->IsInt32()) { + if (!array->Get(v8_context, index).ToLocal(&value) || !value->IsInt32()) { return gfx::Rect(); } coords.push_back(value.As<v8::Int32>()->Value());
diff --git a/infra/config/generated/testing/variants.pyl b/infra/config/generated/testing/variants.pyl index cef03f5..ea191b9 100644 --- a/infra/config/generated/testing/variants.pyl +++ b/infra/config/generated/testing/variants.pyl
@@ -70,16 +70,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'identifier': 'Lacros version skew testing ash canary', - 'description': 'Run with ash-chrome version 121.0.6136.0', + 'description': 'Run with ash-chrome version 121.0.6137.0', 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome', ], 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v121.0.6136.0', - 'revision': 'version:121.0.6136.0', + 'location': 'lacros_version_skew_tests_v121.0.6137.0', + 'revision': 'version:121.0.6137.0', }, ], },
diff --git a/infra/config/targets/lacros-version-skew-variants.json b/infra/config/targets/lacros-version-skew-variants.json index 70ed284..0b1d1dd1 100644 --- a/infra/config/targets/lacros-version-skew-variants.json +++ b/infra/config/targets/lacros-version-skew-variants.json
@@ -1,16 +1,16 @@ { "LACROS_VERSION_SKEW_CANARY": { "args": [ - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "identifier": "Lacros version skew testing ash canary", "swarming": { "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ] }
diff --git a/internal b/internal index 2263269..a745a52 160000 --- a/internal +++ b/internal
@@ -1 +1 @@ -Subproject commit 226326934fb1466c7a57898dbd24c922e173702c +Subproject commit a745a52bdcff739fdbd370e7fb7da57c8111786e
diff --git a/ios/chrome/app/application_delegate/BUILD.gn b/ios/chrome/app/application_delegate/BUILD.gn index 446cedc..40443b2 100644 --- a/ios/chrome/app/application_delegate/BUILD.gn +++ b/ios/chrome/app/application_delegate/BUILD.gn
@@ -58,7 +58,6 @@ "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/url:constants", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/shared/public/features", "//ios/chrome/browser/shared/public/features:system_flags",
diff --git a/ios/chrome/app/application_delegate/metrics_mediator_unittest.mm b/ios/chrome/app/application_delegate/metrics_mediator_unittest.mm index 5ddae36..c7348534 100644 --- a/ios/chrome/app/application_delegate/metrics_mediator_unittest.mm +++ b/ios/chrome/app/application_delegate/metrics_mediator_unittest.mm
@@ -22,7 +22,6 @@ #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" #import "ios/chrome/browser/shared/model/url/chrome_url_constants.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/common/app_group/app_group_metrics.h"
diff --git a/ios/chrome/browser/autofill/autofill_controller_unittest.mm b/ios/chrome/browser/autofill/autofill_controller_unittest.mm index 8551f3f..b9a7916 100644 --- a/ios/chrome/browser/autofill/autofill_controller_unittest.mm +++ b/ios/chrome/browser/autofill/autofill_controller_unittest.mm
@@ -34,8 +34,8 @@ #import "components/infobars/core/infobar.h" #import "components/infobars/core/infobar_manager.h" #import "components/keyed_service/core/service_access_type.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_manager_test_utils.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "ios/chrome/browser/autofill/form_suggestion_controller.h" #import "ios/chrome/browser/autofill/personal_data_manager_factory.h" #import "ios/chrome/browser/infobars/infobar_manager_impl.h"
diff --git a/ios/chrome/browser/autofill/form_structure_browsertest.mm b/ios/chrome/browser/autofill/form_structure_browsertest.mm index a3c41fb8..1d506b4 100644 --- a/ios/chrome/browser/autofill/form_structure_browsertest.mm +++ b/ios/chrome/browser/autofill/form_structure_browsertest.mm
@@ -30,8 +30,8 @@ #import "components/autofill/ios/browser/test_autofill_manager_injector.h" #import "components/autofill/ios/form_util/form_util_java_script_feature.h" #import "components/autofill/ios/form_util/unique_id_data_tab_helper.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_manager_test_utils.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "components/sync_user_events/fake_user_event_service.h" #import "ios/chrome/browser/autofill/address_normalizer_factory.h" #import "ios/chrome/browser/autofill/form_suggestion_controller.h"
diff --git a/ios/chrome/browser/crash_report/model/breadcrumbs/BUILD.gn b/ios/chrome/browser/crash_report/model/breadcrumbs/BUILD.gn index b6451ff..179e4c7 100644 --- a/ios/chrome/browser/crash_report/model/breadcrumbs/BUILD.gn +++ b/ios/chrome/browser/crash_report/model/breadcrumbs/BUILD.gn
@@ -67,7 +67,6 @@ "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/url:constants", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/ui/infobars/test", "//ios/chrome/test:test_support",
diff --git a/ios/chrome/browser/credential_provider/model/credential_provider_migrator_unittest.mm b/ios/chrome/browser/credential_provider/model/credential_provider_migrator_unittest.mm index 1071296..75215567 100644 --- a/ios/chrome/browser/credential_provider/model/credential_provider_migrator_unittest.mm +++ b/ios/chrome/browser/credential_provider/model/credential_provider_migrator_unittest.mm
@@ -8,8 +8,8 @@ #import "base/strings/utf_string_conversions.h" #import "base/test/ios/wait_util.h" #import "base/test/task_environment.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_form.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "ios/chrome/browser/credential_provider/model/archivable_credential+password_form.h" #import "ios/chrome/common/credential_provider/archivable_credential.h" #import "ios/chrome/common/credential_provider/user_defaults_credential_store.h"
diff --git a/ios/chrome/browser/download/model/BUILD.gn b/ios/chrome/browser/download/model/BUILD.gn index 25f971a4..713b4476 100644 --- a/ios/chrome/browser/download/model/BUILD.gn +++ b/ios/chrome/browser/download/model/BUILD.gn
@@ -96,7 +96,6 @@ "//base/test:test_support", "//ios/chrome/browser/download/model", "//ios/chrome/browser/shared/model/browser_state:test_support", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/ui/download:features", "//ios/chrome/test/fakes", "//ios/web/public",
diff --git a/ios/chrome/browser/infobars/BUILD.gn b/ios/chrome/browser/infobars/BUILD.gn index b13e377..5b6bd97a 100644 --- a/ios/chrome/browser/infobars/BUILD.gn +++ b/ios/chrome/browser/infobars/BUILD.gn
@@ -78,7 +78,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/ui/badges:public", "//ios/chrome/browser/ui/badges:util", "//ios/chrome/browser/ui/infobars:test_support",
diff --git a/ios/chrome/browser/infobars/overlays/browser_agent/BUILD.gn b/ios/chrome/browser/infobars/overlays/browser_agent/BUILD.gn index de0c1026..5b542f04 100644 --- a/ios/chrome/browser/infobars/overlays/browser_agent/BUILD.gn +++ b/ios/chrome/browser/infobars/overlays/browser_agent/BUILD.gn
@@ -56,7 +56,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/test:test_support", "//ios/web/public/test", "//ios/web/public/test/fakes",
diff --git a/ios/chrome/browser/infobars/overlays/browser_agent/interaction_handlers/common/BUILD.gn b/ios/chrome/browser/infobars/overlays/browser_agent/interaction_handlers/common/BUILD.gn index 53c16b2..629f689 100644 --- a/ios/chrome/browser/infobars/overlays/browser_agent/interaction_handlers/common/BUILD.gn +++ b/ios/chrome/browser/infobars/overlays/browser_agent/interaction_handlers/common/BUILD.gn
@@ -55,7 +55,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/test:test_support", "//ios/web/public/test", "//ios/web/public/test/fakes",
diff --git a/ios/chrome/browser/overlays/model/BUILD.gn b/ios/chrome/browser/overlays/model/BUILD.gn index 7dbc849..3f2dade 100644 --- a/ios/chrome/browser/overlays/model/BUILD.gn +++ b/ios/chrome/browser/overlays/model/BUILD.gn
@@ -92,7 +92,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/web/public", "//ios/web/public/test", "//ios/web/public/test/fakes",
diff --git a/ios/chrome/browser/passwords/model/ios_chrome_password_manager_client_unittest.mm b/ios/chrome/browser/passwords/model/ios_chrome_password_manager_client_unittest.mm index 5176dbf..f8d3bb7 100644 --- a/ios/chrome/browser/passwords/model/ios_chrome_password_manager_client_unittest.mm +++ b/ios/chrome/browser/passwords/model/ios_chrome_password_manager_client_unittest.mm
@@ -13,9 +13,9 @@ #import "components/autofill/ios/form_util/unique_id_data_tab_helper.h" #import "components/password_manager/core/browser/mock_password_form_manager_for_ui.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_form_manager.h" #import "components/password_manager/core/browser/password_form_manager_for_ui.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "components/password_manager/core/common/password_manager_pref_names.h" #import "components/prefs/testing_pref_service.h" #import "ios/chrome/browser/credential_provider_promo/model/features.h"
diff --git a/ios/chrome/browser/passwords/model/password_controller_unittest.mm b/ios/chrome/browser/passwords/model/password_controller_unittest.mm index 46011e0..4b0176d7 100644 --- a/ios/chrome/browser/passwords/model/password_controller_unittest.mm +++ b/ios/chrome/browser/passwords/model/password_controller_unittest.mm
@@ -29,10 +29,10 @@ #import "components/autofill/ios/form_util/form_util_java_script_feature.h" #import "components/autofill/ios/form_util/unique_id_data_tab_helper.h" #import "components/password_manager/core/browser/leak_detection/mock_leak_detection_check_factory.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_form_manager.h" #import "components/password_manager/core/browser/password_form_metrics_recorder.h" #import "components/password_manager/core/browser/password_manager.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_store/password_store_consumer.h" #import "components/password_manager/core/browser/stub_password_manager_client.h" #import "components/password_manager/core/common/password_manager_features.h"
diff --git a/ios/chrome/browser/safe_browsing/model/chrome_password_protection_service_unittest.mm b/ios/chrome/browser/safe_browsing/model/chrome_password_protection_service_unittest.mm index 18fda17..e8fd7024 100644 --- a/ios/chrome/browser/safe_browsing/model/chrome_password_protection_service_unittest.mm +++ b/ios/chrome/browser/safe_browsing/model/chrome_password_protection_service_unittest.mm
@@ -13,10 +13,10 @@ #import "base/test/mock_callback.h" #import "base/values.h" #import "components/keyed_service/core/service_access_type.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_manager_metrics_util.h" #import "components/password_manager/core/browser/password_manager_test_utils.h" #import "components/password_manager/core/browser/password_reuse_detector.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "components/prefs/pref_service.h" #import "components/safe_browsing/core/browser/password_protection/metrics_util.h" #import "components/safe_browsing/core/common/safe_browsing_prefs.h"
diff --git a/ios/chrome/browser/screenshot/model/BUILD.gn b/ios/chrome/browser/screenshot/model/BUILD.gn index 1cdd0731..18df317 100644 --- a/ios/chrome/browser/screenshot/model/BUILD.gn +++ b/ios/chrome/browser/screenshot/model/BUILD.gn
@@ -32,7 +32,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/ui/main", "//ios/chrome/test:test_support", "//ios/web/public/test",
diff --git a/ios/chrome/browser/translate/model/translate_service_ios.mm b/ios/chrome/browser/translate/model/translate_service_ios.mm index 70bf72b..4265a40 100644 --- a/ios/chrome/browser/translate/model/translate_service_ios.mm +++ b/ios/chrome/browser/translate/model/translate_service_ios.mm
@@ -54,6 +54,8 @@ translate::TranslateDownloadManager* download_manager = translate::TranslateDownloadManager::GetInstance(); download_manager->Shutdown(); + delete g_translate_service; + g_translate_service = nullptr; } void TranslateServiceIOS::OnResourceRequestsAllowed() {
diff --git a/ios/chrome/browser/ui/badges/BUILD.gn b/ios/chrome/browser/ui/badges/BUILD.gn index e10037c..2c148e46 100644 --- a/ios/chrome/browser/ui/badges/BUILD.gn +++ b/ios/chrome/browser/ui/badges/BUILD.gn
@@ -104,7 +104,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/ui/infobars:test_support", "//ios/web/public/test/fakes", "//testing/gtest",
diff --git a/ios/chrome/browser/ui/browser_view/BUILD.gn b/ios/chrome/browser/ui/browser_view/BUILD.gn index 0a1761b..3d40645 100644 --- a/ios/chrome/browser/ui/browser_view/BUILD.gn +++ b/ios/chrome/browser/ui/browser_view/BUILD.gn
@@ -315,7 +315,6 @@ "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/url:constants", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/shared/public/features", "//ios/chrome/browser/shared/ui/util:url_with_title",
diff --git a/ios/chrome/browser/ui/browser_view/browser_view_controller_unittest.mm b/ios/chrome/browser/ui/browser_view/browser_view_controller_unittest.mm index 7badcbca..5a01d76 100644 --- a/ios/chrome/browser/ui/browser_view/browser_view_controller_unittest.mm +++ b/ios/chrome/browser/ui/browser_view/browser_view_controller_unittest.mm
@@ -32,7 +32,6 @@ #import "ios/chrome/browser/shared/coordinator/scene/scene_state.h" #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/browser/shared/public/commands/activity_service_commands.h"
diff --git a/ios/chrome/browser/ui/default_promo/BUILD.gn b/ios/chrome/browser/ui/default_promo/BUILD.gn index d2ece39f..58bd689 100644 --- a/ios/chrome/browser/ui/default_promo/BUILD.gn +++ b/ios/chrome/browser/ui/default_promo/BUILD.gn
@@ -118,7 +118,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands:commands", "//ios/chrome/common/ui/confirmation_alert:constants", "//ios/chrome/test:test_support",
diff --git a/ios/chrome/browser/ui/download/BUILD.gn b/ios/chrome/browser/ui/download/BUILD.gn index b6da137..95530aab 100644 --- a/ios/chrome/browser/ui/download/BUILD.gn +++ b/ios/chrome/browser/ui/download/BUILD.gn
@@ -102,7 +102,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list:web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/test:test_support", "//ios/chrome/test/app:test_support",
diff --git a/ios/chrome/browser/ui/download/ar_quick_look_coordinator_unittest.mm b/ios/chrome/browser/ui/download/ar_quick_look_coordinator_unittest.mm index 5767f83..38dd53b 100644 --- a/ios/chrome/browser/ui/download/ar_quick_look_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/download/ar_quick_look_coordinator_unittest.mm
@@ -20,7 +20,6 @@ #import "ios/chrome/browser/download/model/download_test_util.h" #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/test/scoped_key_window.h"
diff --git a/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm b/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm index 142dff9e..79ed0e7 100644 --- a/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/download/download_manager_coordinator_unittest.mm
@@ -27,7 +27,6 @@ #import "ios/chrome/browser/overlays/model/public/web_content_area/alert_overlay.h" #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/browser/shared/public/commands/browser_coordinator_commands.h"
diff --git a/ios/chrome/browser/ui/download/safari_download_coordinator_unittest.mm b/ios/chrome/browser/ui/download/safari_download_coordinator_unittest.mm index 2bb8b27..1c34a020 100644 --- a/ios/chrome/browser/ui/download/safari_download_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/download/safari_download_coordinator_unittest.mm
@@ -17,7 +17,6 @@ #import "ios/chrome/browser/download/model/safari_download_tab_helper_delegate.h" #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/test/scoped_key_window.h"
diff --git a/ios/chrome/browser/ui/download/vcard_coordinator_unittest.mm b/ios/chrome/browser/ui/download/vcard_coordinator_unittest.mm index 22ac5c6..d0eb857 100644 --- a/ios/chrome/browser/ui/download/vcard_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/download/vcard_coordinator_unittest.mm
@@ -9,7 +9,6 @@ #import "ios/chrome/browser/download/model/vcard_tab_helper_delegate.h" #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/test/scoped_key_window.h"
diff --git a/ios/chrome/browser/ui/incognito_reauth/BUILD.gn b/ios/chrome/browser/ui/incognito_reauth/BUILD.gn index ef3b7deb..86feccc 100644 --- a/ios/chrome/browser/ui/incognito_reauth/BUILD.gn +++ b/ios/chrome/browser/ui/incognito_reauth/BUILD.gn
@@ -85,7 +85,6 @@ "//ios/chrome/browser/shared/model/prefs:pref_names", "//ios/chrome/browser/shared/model/web_state_list", "//ios/chrome/browser/shared/model/web_state_list:web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/features", "//ios/chrome/browser/ui/browser_view", "//ios/chrome/common/ui/reauthentication",
diff --git a/ios/chrome/browser/ui/location_bar/BUILD.gn b/ios/chrome/browser/ui/location_bar/BUILD.gn index 05a3f46b..8088196e 100644 --- a/ios/chrome/browser/ui/location_bar/BUILD.gn +++ b/ios/chrome/browser/ui/location_bar/BUILD.gn
@@ -165,7 +165,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/ui/location_bar/test", "//ios/chrome/browser/ui/omnibox",
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/BUILD.gn b/ios/chrome/browser/ui/omnibox/popup/debugger/BUILD.gn index 175c68d..36d2465 100644 --- a/ios/chrome/browser/ui/omnibox/popup/debugger/BUILD.gn +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/BUILD.gn
@@ -4,6 +4,10 @@ source_set("debugger") { sources = [ + "autocomplete_match_cell.h", + "autocomplete_match_cell.mm", + "autocomplete_match_group.h", + "autocomplete_match_group.mm", "omnibox_autocomplete_event.h", "omnibox_autocomplete_event.mm", "omnibox_autocomplete_event_view_controller.h", @@ -13,6 +17,10 @@ deps = [ "//base", "//components/omnibox/browser", + "//ios/chrome/browser/shared/ui/elements", + "//ios/chrome/browser/shared/ui/symbols", "//ios/chrome/browser/ui/omnibox/popup:popup_internal", + "//ios/chrome/browser/ui/omnibox/popup:popup_internal", + "//ios/chrome/common/ui/util", ] }
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.h b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.h new file mode 100644 index 0000000..bd041d1 --- /dev/null +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.h
@@ -0,0 +1,23 @@ +// Copyright 2023 The Chromium Authors +// 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_OMNIBOX_POPUP_DEBUGGER_AUTOCOMPLETE_MATCH_CELL_H_ +#define IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_DEBUGGER_AUTOCOMPLETE_MATCH_CELL_H_ + +#import <UIKit/UIKit.h> + +#import "ios/chrome/browser/ui/omnibox/popup/autocomplete_match_formatter.h" + +extern NSString* const kAutocompleteMatchCellReuseIdentifier; + +/// UITableViewCell to display an autocomplete match in the omnibox debugger. +@interface AutocompleteMatchCell : UITableViewCell + +- (void)setupWithAutocompleteMatchFormatter: + (AutocompleteMatchFormatter*)matchFormatter + showProviderType:(BOOL)shouldShowProviderType; + +@end + +#endif // IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_DEBUGGER_AUTOCOMPLETE_MATCH_CELL_H_
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.mm b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.mm new file mode 100644 index 0000000..aebb4e2 --- /dev/null +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.mm
@@ -0,0 +1,188 @@ +// Copyright 2023 The Chromium Authors +// 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/omnibox/popup/debugger/autocomplete_match_cell.h" + +#import "base/strings/sys_string_conversions.h" +#import "components/omnibox/browser/autocomplete_match.h" +#import "components/omnibox/browser/autocomplete_match_type.h" +#import "components/omnibox/browser/autocomplete_provider.h" +#import "ios/chrome/browser/shared/ui/elements/fade_truncating_label.h" +#import "ios/chrome/browser/shared/ui/symbols/symbols.h" +#import "ios/chrome/browser/ui/omnibox/popup/autocomplete_match_formatter.h" +#import "ios/chrome/common/ui/util/constraints_ui_util.h" + +NSString* const kAutocompleteMatchCellReuseIdentifier = + @"AutocompleteMatchCell"; + +namespace { + +/// Size of the default match icon. +const CGFloat kDefaultMatchIconSize = 17.0; +/// Leading and trailing padding for the content view. +const CGFloat kContentViewHorizontalPadding = 10.0; +/// Top and bottom padding for the content view. +const CGFloat kContentViewVerticalPadding = 00.0; + +} // namespace + +@implementation AutocompleteMatchCell { + /// Label for AutocompleteMatch.provider.type. + UILabel* _providerTypeLabel; + /// Label for AutocompleteMatch.type. + UILabel* _matchTypeLabel; + + /// Label for AutocompleteMatchFormatter.text. + UILabel* _textLabel; + /// Label for AutocompleteMatch.relevance. + UILabel* _relevanceLabel; + /// Icon for AutocompleteMatch.allowed_to_be_default_match. + UIImageView* _defaultMatchImageView; + + /// Label for AutocompleteMatch.description. + UILabel* _descriptionLabel; + /// Label for AutocompleteMatch.destination_url. + UILabel* _URLLabel; + /// Label for AutocompleteMatch.additional_info. + UILabel* _additionalInfoLabel; +} + +- (instancetype)initWithStyle:(UITableViewCellStyle)style + reuseIdentifier:(NSString*)reuseIdentifier { + self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; + if (self) { + // First row for types. + _matchTypeLabel = [[UILabel alloc] init]; + _matchTypeLabel.translatesAutoresizingMaskIntoConstraints = NO; + _matchTypeLabel.textColor = UIColor.systemGrayColor; + + _providerTypeLabel = [[UILabel alloc] init]; + _providerTypeLabel.translatesAutoresizingMaskIntoConstraints = NO; + _providerTypeLabel.textAlignment = NSTextAlignmentRight; + _providerTypeLabel.textColor = UIColor.systemGreenColor; + + UIStackView* firstRowStackView = [[UIStackView alloc] + initWithArrangedSubviews:@[ _matchTypeLabel, _providerTypeLabel ]]; + firstRowStackView.translatesAutoresizingMaskIntoConstraints = NO; + + // Second row for text, relevance and canBeDefaultMatch. + _textLabel = [[UILabel alloc] init]; + _textLabel.translatesAutoresizingMaskIntoConstraints = NO; + _textLabel.numberOfLines = 0; + + _relevanceLabel = [[UILabel alloc] init]; + _relevanceLabel.translatesAutoresizingMaskIntoConstraints = NO; + _relevanceLabel.textAlignment = NSTextAlignmentRight; + + _defaultMatchImageView = [[UIImageView alloc] init]; + _defaultMatchImageView.translatesAutoresizingMaskIntoConstraints = NO; + [NSLayoutConstraint activateConstraints:@[ + [_defaultMatchImageView.widthAnchor + constraintEqualToConstant:kDefaultMatchIconSize], + [_defaultMatchImageView.heightAnchor + constraintEqualToConstant:kDefaultMatchIconSize] + ]]; + + UIStackView* secondRowStackView = + [[UIStackView alloc] initWithArrangedSubviews:@[ + _textLabel, _relevanceLabel, _defaultMatchImageView + ]]; + secondRowStackView.translatesAutoresizingMaskIntoConstraints = NO; + + // Additional rows + _descriptionLabel = [[UILabel alloc] init]; + _descriptionLabel.translatesAutoresizingMaskIntoConstraints = NO; + + _URLLabel = [[UILabel alloc] init]; + _URLLabel.translatesAutoresizingMaskIntoConstraints = NO; + _URLLabel.textColor = UIColor.darkGrayColor; + + _additionalInfoLabel = [[UILabel alloc] init]; + _additionalInfoLabel.translatesAutoresizingMaskIntoConstraints = NO; + _additionalInfoLabel.numberOfLines = 0; + + // Content view. + UIStackView* contentStackView = + [[UIStackView alloc] initWithArrangedSubviews:@[ + firstRowStackView, secondRowStackView, _descriptionLabel, _URLLabel, + _additionalInfoLabel + ]]; + contentStackView.translatesAutoresizingMaskIntoConstraints = NO; + contentStackView.axis = UILayoutConstraintAxisVertical; + + [self.contentView addSubview:contentStackView]; + AddSameConstraintsWithInsets( + contentStackView, self.contentView, + NSDirectionalEdgeInsetsMake( + kContentViewVerticalPadding, kContentViewHorizontalPadding, + kContentViewVerticalPadding, kContentViewHorizontalPadding)); + } + return self; +} + +- (void)prepareForReuse { + [super prepareForReuse]; + _providerTypeLabel.text = nil; + _matchTypeLabel.text = nil; + _textLabel.text = nil; + _relevanceLabel.text = nil; + _defaultMatchImageView.image = nil; + _descriptionLabel.text = nil; + _URLLabel.text = nil; + _additionalInfoLabel.text = nil; +} + +- (void)setupWithAutocompleteMatchFormatter: + (AutocompleteMatchFormatter*)matchFormatter + showProviderType:(BOOL)shouldShowProviderType { + const AutocompleteMatch& match = matchFormatter.autocompleteMatch; + + _providerTypeLabel.text = base::SysUTF8ToNSString( + AutocompleteProvider::TypeToString(match.provider->type())); + _providerTypeLabel.hidden = !shouldShowProviderType; + + _matchTypeLabel.text = + base::SysUTF8ToNSString(AutocompleteMatchType::ToString(match.type)); + _textLabel.attributedText = matchFormatter.text; + _relevanceLabel.text = [NSString stringWithFormat:@"%d", match.relevance]; + _descriptionLabel.text = base::SysUTF16ToNSString(match.description); + _URLLabel.text = base::SysUTF8ToNSString(match.destination_url.spec()); + + if (match.allowed_to_be_default_match) { + UIImage* checkmarkSymbol = + SymbolWithPalette(DefaultSymbolWithPointSize(kCheckmarkCircleFillSymbol, + kDefaultMatchIconSize), + @[ UIColor.systemGreenColor ]); + _defaultMatchImageView.image = checkmarkSymbol; + } else { + UIImage* xmarkSymbol = + SymbolWithPalette(DefaultSymbolWithPointSize(kXMarkCircleFillSymbol, + kDefaultMatchIconSize), + @[ UIColor.redColor ]); + _defaultMatchImageView.image = xmarkSymbol; + } + + NSMutableAttributedString* additionalInfoString = + [[NSMutableAttributedString alloc] init]; + for (const auto& info : match.additional_info) { + NSString* infoName = base::SysUTF8ToNSString(info.first + ": "); + NSString* infoValue = base::SysUTF8ToNSString(info.second + "\n"); + NSAttributedString* attributedName = [[NSAttributedString alloc] + initWithString:infoName + attributes:@{ + NSForegroundColorAttributeName : UIColor.systemRedColor, + }]; + NSAttributedString* attributedValue = [[NSAttributedString alloc] + initWithString:infoValue + attributes:@{ + NSForegroundColorAttributeName : UIColor.systemIndigoColor, + }]; + + [additionalInfoString appendAttributedString:attributedName]; + [additionalInfoString appendAttributedString:attributedValue]; + } + _additionalInfoLabel.attributedText = additionalInfoString; +} + +@end
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.h b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.h new file mode 100644 index 0000000..70e910c0 --- /dev/null +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.h
@@ -0,0 +1,24 @@ +// Copyright 2023 The Chromium Authors +// 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_OMNIBOX_POPUP_DEBUGGER_AUTOCOMPLETE_MATCH_GROUP_H_ +#define IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_DEBUGGER_AUTOCOMPLETE_MATCH_GROUP_H_ + +#import <UIKit/UIKit.h> + +#import "ios/chrome/browser/ui/omnibox/popup/autocomplete_match_formatter.h" + +/// A class that store a list of autocomplete matches with a title. +@interface AutocompleteMatchGroup : NSObject + +@property(nonatomic, strong) NSString* title; +@property(nonatomic, strong) NSArray<AutocompleteMatchFormatter*>* matches; + ++ (AutocompleteMatchGroup*) + groupWithTitle:(NSString*)title + matches:(NSArray<AutocompleteMatchFormatter*>*)matches; + +@end + +#endif // IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_DEBUGGER_AUTOCOMPLETE_MATCH_GROUP_H_
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.mm b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.mm new file mode 100644 index 0000000..22ff378 --- /dev/null +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.mm
@@ -0,0 +1,18 @@ +// Copyright 2023 The Chromium Authors +// 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/omnibox/popup/debugger/autocomplete_match_group.h" + +@implementation AutocompleteMatchGroup + ++ (AutocompleteMatchGroup*) + groupWithTitle:(NSString*)title + matches:(NSArray<AutocompleteMatchFormatter*>*)matches { + AutocompleteMatchGroup* group = [[self alloc] init]; + group.title = title; + group.matches = matches; + return group; +} + +@end
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.h b/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.h index cfd70f9..7ac6a78 100644 --- a/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.h +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.h
@@ -5,21 +5,22 @@ #ifndef IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_DEBUGGER_OMNIBOX_AUTOCOMPLETE_EVENT_H_ #define IOS_CHROME_BROWSER_UI_OMNIBOX_POPUP_DEBUGGER_OMNIBOX_AUTOCOMPLETE_EVENT_H_ +#import "ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_group.h" #import "ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_event.h" class AutocompleteController; @class AutocompleteMatchFormatter; -// A class that captures the state of the AutocompleteController at an update -// observation. +/// A class that captures the state of the AutocompleteController at an update +/// observation. @interface OmniboxAutocompleteEvent : NSObject <OmniboxEvent> - (OmniboxAutocompleteEvent*)initWithAutocompleteController: (AutocompleteController*)controller; -// A list of the autocomplete matches. -@property(nonatomic, strong) - NSMutableArray<AutocompleteMatchFormatter*>* matches; +/// Autocomplete match groups. The first group contains the result matches, +/// following groups contains provider matches. +@property(nonatomic, strong) NSArray<AutocompleteMatchGroup*>* matchGroups; @end
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.mm b/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.mm index c18949f..abd85d8 100644 --- a/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.mm +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.mm
@@ -5,15 +5,39 @@ #import "ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.h" #import "components/omnibox/browser/autocomplete_controller.h" +#import "components/omnibox/browser/autocomplete_match.h" +#import "components/omnibox/browser/autocomplete_provider.h" #import "ios/chrome/browser/ui/omnibox/popup/autocomplete_match_formatter.h" #import "ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_event.h" +namespace { + +/// Copy autocomplete matches into a NSArray. +template <class Iterable> +NSArray<AutocompleteMatchFormatter*>* ExtractAutocompleteMatches( + const Iterable& matches) { + NSMutableArray<AutocompleteMatchFormatter*>* mutableArray = + [[NSMutableArray alloc] init]; + for (const auto& match : matches) { + AutocompleteMatchFormatter* matchFormatter = + [[AutocompleteMatchFormatter alloc] initWithMatch:match]; + [mutableArray addObject:matchFormatter]; + } + return mutableArray; +} + +} // namespace + @implementation OmniboxAutocompleteEvent { /// Whether all sync and async providers from the autocomplete controller are /// done. BOOL _autocompleteControllerAsyncPassDone; /// Whether all sync providers from the autocomplete controller are done. BOOL _autocompleteControllerSyncPassDone; + /// List of the autocomplete matches from the AutocompleteResult. + NSArray<AutocompleteMatchFormatter*>* _matches; + /// List of autocomplete matches from the ShortcutsProvider. + NSArray<AutocompleteMatchFormatter*>* _shortcutsMatches; } - (OmniboxAutocompleteEvent*)initWithAutocompleteController: @@ -24,12 +48,32 @@ _autocompleteControllerAsyncPassDone = controller->done(); _autocompleteControllerSyncPassDone = controller->sync_pass_done(); - self.matches = [[NSMutableArray alloc] init]; - for (auto acm : controller->result()) { - AutocompleteMatchFormatter* matcher = - [[AutocompleteMatchFormatter alloc] initWithMatch:acm]; - [self.matches addObject:matcher]; + // Extract matches. + _matches = ExtractAutocompleteMatches(controller->result()); + + // Adding shortcuts suggestions for debugging purposes. Future provider may + // be added with a way to filter the list of providers to avoid scrolling. + for (const auto& provider : controller->providers()) { + switch (provider->type()) { + case AutocompleteProvider::TYPE_SHORTCUTS: + _shortcutsMatches = ExtractAutocompleteMatches(provider->matches()); + break; + default: + break; + } } + + // Create groups. + NSMutableArray<AutocompleteMatchGroup*>* groups = + [[NSMutableArray alloc] init]; + [groups addObject:[AutocompleteMatchGroup groupWithTitle:nil + matches:_matches]]; + if (_shortcutsMatches.count) { + [groups + addObject:[AutocompleteMatchGroup groupWithTitle:@"Shortcuts" + matches:_shortcutsMatches]]; + } + _matchGroups = groups; } return self; }
diff --git a/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event_view_controller.mm b/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event_view_controller.mm index 2e7612a..d634dd2 100644 --- a/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event_view_controller.mm +++ b/ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event_view_controller.mm
@@ -5,6 +5,7 @@ #import "ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event_view_controller.h" #import "ios/chrome/browser/ui/omnibox/popup/autocomplete_match_formatter.h" +#import "ios/chrome/browser/ui/omnibox/popup/debugger/autocomplete_match_cell.h" #import "ios/chrome/browser/ui/omnibox/popup/debugger/omnibox_autocomplete_event.h" @implementation OmniboxAutocompleteEventViewController @@ -12,26 +13,34 @@ - (void)viewDidLoad { [super viewDidLoad]; self.title = self.event.title; - [self.tableView registerClass:[UITableViewCell class] - forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])]; + [self.tableView registerClass:[AutocompleteMatchCell class] + forCellReuseIdentifier:kAutocompleteMatchCellReuseIdentifier]; +} + +- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView { + return self.event.matchGroups.count; } - (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section { - return self.event.matches.count; + return self.event.matchGroups[section].matches.count; +} + +- (NSString*)tableView:(UITableView*)tableView + titleForHeaderInSection:(NSInteger)section { + return self.event.matchGroups[section].title; } - (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { - UITableViewCell* cell = [tableView - dequeueReusableCellWithIdentifier:NSStringFromClass( - [UITableViewCell class])]; - UIListContentConfiguration* config = cell.defaultContentConfiguration; + AutocompleteMatchCell* cell = [tableView + dequeueReusableCellWithIdentifier:kAutocompleteMatchCellReuseIdentifier]; - AutocompleteMatchFormatter* matcher = self.event.matches[indexPath.row]; + AutocompleteMatchGroup* group = self.event.matchGroups[indexPath.section]; - config.attributedText = matcher.text; - cell.contentConfiguration = config; + AutocompleteMatchFormatter* matchFormatter = group.matches[indexPath.row]; + [cell setupWithAutocompleteMatchFormatter:matchFormatter + showProviderType:!group.title.length]; return cell; }
diff --git a/ios/chrome/browser/ui/overlays/infobar_modal/BUILD.gn b/ios/chrome/browser/ui/overlays/infobar_modal/BUILD.gn index aeb9afd..0db607ce 100644 --- a/ios/chrome/browser/ui/overlays/infobar_modal/BUILD.gn +++ b/ios/chrome/browser/ui/overlays/infobar_modal/BUILD.gn
@@ -57,7 +57,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/ui/overlays:coordinators", "//ios/chrome/browser/ui/overlays/test", "//ios/chrome/test:test_support",
diff --git a/ios/chrome/browser/ui/popup_menu/BUILD.gn b/ios/chrome/browser/ui/popup_menu/BUILD.gn index 4ec74d3c..091b955 100644 --- a/ios/chrome/browser/ui/popup_menu/BUILD.gn +++ b/ios/chrome/browser/ui/popup_menu/BUILD.gn
@@ -176,7 +176,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/shared/public/features", "//ios/chrome/browser/shared/ui/symbols",
diff --git a/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator_unittest.mm b/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator_unittest.mm index 349eff5a..7d584a1 100644 --- a/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator_unittest.mm +++ b/ios/chrome/browser/ui/popup_menu/overflow_menu/overflow_menu_mediator_unittest.mm
@@ -18,8 +18,8 @@ #import "components/feature_engagement/test/mock_tracker.h" #import "components/language/ios/browser/ios_language_detection_tab_helper.h" #import "components/language/ios/browser/language_detection_java_script_feature.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_manager_test_utils.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "components/policy/core/common/mock_configuration_policy_provider.h" #import "components/pref_registry/pref_registry_syncable.h" #import "components/prefs/pref_registry_simple.h"
diff --git a/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm b/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm index 85c5df5..f2ad8c36 100644 --- a/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm +++ b/ios/chrome/browser/ui/popup_menu/popup_menu_mediator_unittest.mm
@@ -17,8 +17,8 @@ #import "components/feature_engagement/test/mock_tracker.h" #import "components/language/ios/browser/ios_language_detection_tab_helper.h" #import "components/language/ios/browser/language_detection_java_script_feature.h" -#import "components/password_manager/core/browser/mock_password_store_interface.h" #import "components/password_manager/core/browser/password_manager_test_utils.h" +#import "components/password_manager/core/browser/password_store/mock_password_store_interface.h" #import "components/policy/core/common/mock_configuration_policy_provider.h" #import "components/prefs/pref_registry_simple.h" #import "components/prefs/testing_pref_service.h"
diff --git a/ios/chrome/browser/ui/recent_tabs/BUILD.gn b/ios/chrome/browser/ui/recent_tabs/BUILD.gn index cdf70d22..2b53692e 100644 --- a/ios/chrome/browser/ui/recent_tabs/BUILD.gn +++ b/ios/chrome/browser/ui/recent_tabs/BUILD.gn
@@ -150,7 +150,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/shared/public/features", "//ios/chrome/browser/signin/model",
diff --git a/ios/chrome/browser/ui/search_engine_choice/search_engine_choice_view_controller.mm b/ios/chrome/browser/ui/search_engine_choice/search_engine_choice_view_controller.mm index 8071de9d..9d3a3a5 100644 --- a/ios/chrome/browser/ui/search_engine_choice/search_engine_choice_view_controller.mm +++ b/ios/chrome/browser/ui/search_engine_choice/search_engine_choice_view_controller.mm
@@ -13,6 +13,7 @@ #import "ios/chrome/common/ui/colors/semantic_color_names.h" #import "ios/chrome/common/ui/util/button_util.h" #import "ios/chrome/common/ui/util/device_util.h" +#import "ios/chrome/common/ui/util/sdk_forward_declares.h" #import "net/base/mac/url_conversions.h" #import "ui/base/l10n/l10n_util_mac.h" #import "url/gurl.h" @@ -37,12 +38,10 @@ constexpr CGFloat kHorizontalInsets = -48.; // Space between the Chrome logo and the top of the screen. constexpr CGFloat kTopSpacing = 40.; -// Space between the bottom of the primary button and the bottom of the screen. -constexpr CGFloat kBottomSpacing = 12.; // Spacing between the elements of the top stack view. constexpr CGFloat kTopStackViewSpacing = 16.; -// Space between the table and the primary button. -constexpr CGFloat kPrimaryButtonTopPadding = 16.; +// Space above and below the primary button. +constexpr CGFloat kPrimaryButtonPadding = 14.; // Primary button height. constexpr CGFloat kPrimaryButtonHeight = 50.; // Logo dimensions. @@ -267,9 +266,12 @@ } - (void)enablePrimaryButton { - _primaryButton.backgroundColor = [UIColor colorNamed:kBlue600Color]; - [_primaryButton setTitleColor:[UIColor colorNamed:kSolidButtonTextColor] - forState:UIControlStateNormal]; + UIButtonConfiguration* buttonConfiguration = _primaryButton.configuration; + buttonConfiguration.background.backgroundColor = + [UIColor colorNamed:kBlue600Color]; + buttonConfiguration.baseForegroundColor = + [UIColor colorNamed:kSolidButtonTextColor]; + _primaryButton.configuration = buttonConfiguration; _primaryButton.enabled = YES; } @@ -379,21 +381,21 @@ _primaryButton = PrimaryActionButton(/*pointer_interaction_enabled=*/YES); [self.view addSubview:_primaryButton]; - [_primaryButton - setTitle:l10n_util::GetNSString(IDS_SEARCH_ENGINE_CHOICE_BUTTON_TITLE) - forState:UIControlStateNormal]; + SetConfigurationTitle( + _primaryButton, + l10n_util::GetNSString(IDS_SEARCH_ENGINE_CHOICE_BUTTON_TITLE)); _primaryButton.translatesAutoresizingMaskIntoConstraints = NO; [_primaryButton addTarget:self action:@selector(primaryButtonAction) forControlEvents:UIControlEventTouchUpInside]; - _primaryButton.backgroundColor = + + UIButtonConfiguration* buttonConfiguration = _primaryButton.configuration; + buttonConfiguration.background.backgroundColor = [UIColor colorNamed:kTertiaryBackgroundColor]; - [_primaryButton setTitleColor:[UIColor colorNamed:kDisabledTintColor] - forState:UIControlStateNormal]; - _primaryButton.titleLabel.adjustsFontSizeToFitWidth = YES; - _primaryButton.titleLabel.minimumScaleFactor = 0.7; - _primaryButton.titleLabel.adjustsFontForContentSizeCategory = YES; - _primaryButton.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail; + buttonConfiguration.baseForegroundColor = + [UIColor colorNamed:kDisabledTintColor]; + buttonConfiguration.titleLineBreakMode = NSLineBreakByTruncatingTail; + _primaryButton.configuration = buttonConfiguration; _primaryButton.enabled = NO; [NSLayoutConstraint activateConstraints:@[ @@ -432,7 +434,7 @@ [_primaryButton.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor - constant:-kBottomSpacing], + constant:-kPrimaryButtonPadding], [_primaryButton.widthAnchor constraintEqualToAnchor:self.view.widthAnchor constant:kHorizontalInsets], [_primaryButton.heightAnchor @@ -442,7 +444,7 @@ [_separatorView.heightAnchor constraintEqualToConstant:kLineWidth], [_separatorView.bottomAnchor constraintEqualToAnchor:_primaryButton.topAnchor - constant:-kPrimaryButtonTopPadding], + constant:-kPrimaryButtonPadding], [searchEngineTableView.widthAnchor constraintEqualToAnchor:_scrollContentView.widthAnchor],
diff --git a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/base_grid_view_controller.mm b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/base_grid_view_controller.mm index 10be2eb..7732582 100644 --- a/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/base_grid_view_controller.mm +++ b/ios/chrome/browser/ui/tab_switcher/tab_grid/grid/base_grid_view_controller.mm
@@ -1225,6 +1225,7 @@ - (void)didCloseAll { self.isClosingAllOrUndoRunning = NO; + [self.collectionView.collectionViewLayout invalidateLayout]; } - (void)willUndoCloseAll { @@ -1233,6 +1234,7 @@ - (void)didUndoCloseAll { self.isClosingAllOrUndoRunning = NO; + [self.collectionView.collectionViewLayout invalidateLayout]; } #pragma mark - GridItemProvider
diff --git a/ios/chrome/browser/ui/tabs/BUILD.gn b/ios/chrome/browser/ui/tabs/BUILD.gn index 948e7f6..d5748f0 100644 --- a/ios/chrome/browser/ui/tabs/BUILD.gn +++ b/ios/chrome/browser/ui/tabs/BUILD.gn
@@ -112,7 +112,6 @@ "//ios/chrome/browser/shared/model/browser/test:test_support", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/public/commands", "//ios/chrome/browser/tabs/model", "//ios/web/public",
diff --git a/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn b/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn index cf72d808..f17527db 100644 --- a/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn +++ b/ios/chrome/browser/ui/toolbar/fullscreen/BUILD.gn
@@ -40,7 +40,6 @@ "//ios/chrome/browser/bookmarks/model", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/shared/ui/util", "//ios/chrome/browser/tabs/model", "//ios/chrome/browser/ui/broadcaster",
diff --git a/ios/chrome/browser/url_loading/model/BUILD.gn b/ios/chrome/browser/url_loading/model/BUILD.gn index 56f9fa3..c826ca9 100644 --- a/ios/chrome/browser/url_loading/model/BUILD.gn +++ b/ios/chrome/browser/url_loading/model/BUILD.gn
@@ -98,7 +98,6 @@ "//ios/chrome/browser/shared/model/browser_state", "//ios/chrome/browser/shared/model/browser_state:test_support", "//ios/chrome/browser/shared/model/web_state_list", - "//ios/chrome/browser/shared/model/web_state_list/test:test_support", "//ios/chrome/browser/tab_insertion/model", "//ios/chrome/browser/web", "//ios/chrome/browser/web:web_internal",
diff --git a/ios/chrome/browser/url_loading/model/url_loading_browser_agent_unittest.mm b/ios/chrome/browser/url_loading/model/url_loading_browser_agent_unittest.mm index 3a54857..f9c8842 100644 --- a/ios/chrome/browser/url_loading/model/url_loading_browser_agent_unittest.mm +++ b/ios/chrome/browser/url_loading/model/url_loading_browser_agent_unittest.mm
@@ -14,7 +14,6 @@ #import "ios/chrome/browser/ntp/new_tab_page_tab_helper_delegate.h" #import "ios/chrome/browser/shared/model/browser/test/test_browser.h" #import "ios/chrome/browser/shared/model/browser_state/test_chrome_browser_state.h" -#import "ios/chrome/browser/shared/model/web_state_list/test/fake_web_state_list_delegate.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_list.h" #import "ios/chrome/browser/shared/model/web_state_list/web_state_opener.h" #import "ios/chrome/browser/tab_insertion/model/tab_insertion_browser_agent.h"
diff --git a/ios/web_view/internal/translate/web_view_translate_service.h b/ios/web_view/internal/translate/web_view_translate_service.h index 46373ac..d2fe9b6 100644 --- a/ios/web_view/internal/translate/web_view_translate_service.h +++ b/ios/web_view/internal/translate/web_view_translate_service.h
@@ -59,7 +59,8 @@ friend class base::NoDestructor<WebViewTranslateService>; // Listener which manages when translate requests can occur. - TranslateRequestsAllowedListener translate_requests_allowed_listener_; + std::unique_ptr<TranslateRequestsAllowedListener> + translate_requests_allowed_listener_; }; } // namespace ios_web_view
diff --git a/ios/web_view/internal/translate/web_view_translate_service.mm b/ios/web_view/internal/translate/web_view_translate_service.mm index ce5c479..41302654 100644 --- a/ios/web_view/internal/translate/web_view_translate_service.mm +++ b/ios/web_view/internal/translate/web_view_translate_service.mm
@@ -45,8 +45,10 @@ WebViewTranslateService::~WebViewTranslateService() = default; void WebViewTranslateService::Initialize() { + translate_requests_allowed_listener_ = + std::make_unique<TranslateRequestsAllowedListener>(); // Initialize the allowed state for resource requests. - translate_requests_allowed_listener_.OnResourceRequestsAllowed(); + translate_requests_allowed_listener_->OnResourceRequestsAllowed(); // Initialize translate. translate::TranslateDownloadManager* download_manager = @@ -63,6 +65,7 @@ translate::TranslateDownloadManager* download_manager = translate::TranslateDownloadManager::GetInstance(); download_manager->Shutdown(); + translate_requests_allowed_listener_.reset(); } } // namespace ios_web_view
diff --git a/ios_internal b/ios_internal index eb61322..12205ca 160000 --- a/ios_internal +++ b/ios_internal
@@ -1 +1 @@ -Subproject commit eb61322a92140850bf94cb6e7a2511743c80ade5 +Subproject commit 12205cac93d6adfbfad832d5c9401fbd1c19fa35
diff --git a/media/audio/ios/audio_manager_ios.cc b/media/audio/ios/audio_manager_ios.cc index 78dcc24..8a0b55c 100644 --- a/media/audio/ios/audio_manager_ios.cc +++ b/media/audio/ios/audio_manager_ios.cc
@@ -25,34 +25,38 @@ AudioManagerIOS::AudioManagerIOS(std::unique_ptr<AudioThread> audio_thread, AudioLogFactory* audio_log_factory) : AudioManagerBase(std::move(audio_thread), audio_log_factory) { - audio_session_manager_ = std::make_unique<AudioSessionManagerIOS>(); + AudioSessionManagerIOS::GetInstance().SetActive(true); } -AudioManagerIOS::~AudioManagerIOS() = default; +AudioManagerIOS::~AudioManagerIOS() { + AudioSessionManagerIOS::GetInstance().SetActive(false); +} bool AudioManagerIOS::HasAudioOutputDevices() { - return audio_session_manager_->HasAudioHardware(/*is_input=*/false); + return AudioSessionManagerIOS::GetInstance().HasAudioHardware( + /*is_input=*/false); } bool AudioManagerIOS::HasAudioInputDevices() { - return audio_session_manager_->HasAudioHardware(/*is_input=*/true); + return AudioSessionManagerIOS::GetInstance().HasAudioHardware( + /*is_input=*/true); } void AudioManagerIOS::GetAudioInputDeviceNames(AudioDeviceNames* device_names) { DCHECK(device_names->empty()); - audio_session_manager_->GetAudioDeviceInfo(true, device_names); + AudioSessionManagerIOS::GetInstance().GetAudioDeviceInfo(true, device_names); } void AudioManagerIOS::GetAudioOutputDeviceNames( AudioDeviceNames* device_names) { DCHECK(device_names->empty()); - audio_session_manager_->GetAudioDeviceInfo(false, device_names); + AudioSessionManagerIOS::GetInstance().GetAudioDeviceInfo(false, device_names); } AudioParameters AudioManagerIOS::GetInputStreamParameters( const std::string& input_device_id) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); - int sample_rate = audio_session_manager_->HardwareSampleRate(); + int sample_rate = AudioSessionManagerIOS::GetInstance().HardwareSampleRate(); return AudioParameters(AudioParameters::AUDIO_PCM_LINEAR, ChannelLayoutConfig::Stereo(), sample_rate, kDefaultInputBufferSize); @@ -128,12 +132,12 @@ std::string AudioManagerIOS::GetDefaultInputDeviceID() { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); - return audio_session_manager_->GetDefaultInputDeviceID(); + return AudioSessionManagerIOS::GetInstance().GetDefaultInputDeviceID(); } std::string AudioManagerIOS::GetDefaultOutputDeviceID() { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); - return audio_session_manager_->GetDefaultOutputDeviceID(); + return AudioSessionManagerIOS::GetInstance().GetDefaultOutputDeviceID(); } bool AudioManagerIOS::MaybeChangeBufferSize(AudioDeviceID device_id, @@ -145,24 +149,44 @@ return true; } +double AudioManagerIOS::HardwareSampleRate() { + return AudioSessionManagerIOS::GetInstance().HardwareSampleRate(); +} + +double AudioManagerIOS::HardwareIOBufferDuration() { + return AudioSessionManagerIOS::GetInstance().HardwareIOBufferDuration(); +} + +double AudioManagerIOS::HardwareLatency(bool is_input) { + return AudioSessionManagerIOS::GetInstance().HardwareLatency(is_input); +} + +long AudioManagerIOS::GetDeviceChannels(bool is_input) { + return AudioSessionManagerIOS::GetInstance().GetDeviceChannels(is_input); +} + float AudioManagerIOS::GetInputGain() { - return audio_session_manager_->GetInputGain(); + return AudioSessionManagerIOS::GetInstance().GetInputGain(); } bool AudioManagerIOS::SetInputGain(float volume) { - return audio_session_manager_->SetInputGain(volume); + return AudioSessionManagerIOS::GetInstance().SetInputGain(volume); } bool AudioManagerIOS::IsInputMuted() { - return audio_session_manager_->IsInputMuted(); + return AudioSessionManagerIOS::GetInstance().IsInputMuted(); } -// private +bool AudioManagerIOS::IsInputGainSettable() { + return AudioSessionManagerIOS::GetInstance().IsInputGainSettable(); +} + +// protected AudioParameters AudioManagerIOS::GetPreferredOutputStreamParameters( const std::string& output_device_id, const AudioParameters& input_params) { DCHECK(GetTaskRunner()->BelongsToCurrentThread()); - int sample_rate = audio_session_manager_->HardwareSampleRate(); + int sample_rate = AudioSessionManagerIOS::GetInstance().HardwareSampleRate(); return AudioParameters(AudioParameters::AUDIO_PCM_LOW_LATENCY, ChannelLayoutConfig::Stereo(), sample_rate, kDefaultInputBufferSize);
diff --git a/media/audio/ios/audio_manager_ios.h b/media/audio/ios/audio_manager_ios.h index c51021a0..5604a18 100644 --- a/media/audio/ios/audio_manager_ios.h +++ b/media/audio/ios/audio_manager_ios.h
@@ -21,7 +21,6 @@ namespace media { class AUHALStream; -class AudioSessionManagerIOS; // iOS implementation of the AudioManager singleton. This class is internal // to the audio output and only internal users can call methods not exposed by @@ -78,10 +77,17 @@ AudioUnitElement element, size_t desired_buffer_size) override; + // Hardware information + double HardwareSampleRate(); + double HardwareIOBufferDuration(); + double HardwareLatency(bool is_input); + long GetDeviceChannels(bool is_input); + // Gain float GetInputGain(); bool SetInputGain(float volume); bool IsInputMuted(); + bool IsInputGainSettable(); protected: AudioParameters GetPreferredOutputStreamParameters( @@ -89,8 +95,6 @@ const AudioParameters& input_params) override; private: - std::unique_ptr<AudioSessionManagerIOS> audio_session_manager_; - // Tracks all constructed input and output streams. std::list<AUHALStream*> output_streams_; std::list<AudioInputStream*> basic_input_streams_;
diff --git a/media/audio/ios/audio_session_manager_ios.h b/media/audio/ios/audio_session_manager_ios.h index 1ed00e0..40309e2 100644 --- a/media/audio/ios/audio_session_manager_ios.h +++ b/media/audio/ios/audio_session_manager_ios.h
@@ -5,31 +5,48 @@ #ifndef MEDIA_AUDIO_IOS_AUDIO_SESSION_MANAGER_IOS_H_ #define MEDIA_AUDIO_IOS_AUDIO_SESSION_MANAGER_IOS_H_ +#include "base/no_destructor.h" #include "media/audio/audio_device_name.h" namespace media { +// This utility class serves as a bridge to convey iOS platform-specific details +// to the AudioManagerIOS. Internally, it relies on iOS platform-specific +// singleton classes such as AVAudioSession and AVAudioApplication. class AudioSessionManagerIOS { public: + static AudioSessionManagerIOS& GetInstance(); + AudioSessionManagerIOS(const AudioSessionManagerIOS&) = delete; AudioSessionManagerIOS& operator=(const AudioSessionManagerIOS&) = delete; - ~AudioSessionManagerIOS() = default; - AudioSessionManagerIOS(); + // Activate and Deactivate AVAudioSession. + void SetActive(bool active); // Methods to support AudioManagerIOS bool HasAudioHardware(bool is_input); void GetAudioDeviceInfo(bool is_input, media::AudioDeviceNames* device_names); std::string GetDefaultOutputDeviceID(); std::string GetDefaultInputDeviceID(); - int HardwareSampleRate(); + + // Hardware information + double HardwareSampleRate(); + double HardwareIOBufferDuration(); + double HardwareLatency(bool is_input); + long GetDeviceChannels(bool is_input); // Gain float GetInputGain(); bool SetInputGain(float volume); bool IsInputMuted(); + bool IsInputGainSettable(); private: + friend base::NoDestructor<AudioSessionManagerIOS>; + + AudioSessionManagerIOS(); + ~AudioSessionManagerIOS() = default; + void GetAudioInputDeviceInfo(media::AudioDeviceNames* device_names); void GetAudioOutputDeviceInfo(media::AudioDeviceNames* device_names); };
diff --git a/media/audio/ios/audio_session_manager_ios.mm b/media/audio/ios/audio_session_manager_ios.mm index aad9a29..30405b4 100644 --- a/media/audio/ios/audio_session_manager_ios.mm +++ b/media/audio/ios/audio_session_manager_ios.mm
@@ -12,6 +12,18 @@ namespace media { +// Below constant values are taken from : +// https://source.chromium.org/chromium/chromium/src/+/main:third_party/webrtc/sdk/objc/components/audio/RTCAudioSessionConfiguration.m +const int kRTCAudioSessionPreferredNumberOfChannels = 1; +const double kRTCAudioSessionHighPerformanceSampleRate = 48000.0; +const double kRTCAudioSessionHighPerformanceIOBufferDuration = 0.02; + +// static +AudioSessionManagerIOS& AudioSessionManagerIOS::GetInstance() { + static base::NoDestructor<AudioSessionManagerIOS> instance; + return *instance; +} + AudioSessionManagerIOS::AudioSessionManagerIOS() { AVAudioSession* audio_session = [AVAudioSession sharedInstance]; @@ -29,6 +41,12 @@ error.localizedDescription); } + [audio_session + setPreferredSampleRate:kRTCAudioSessionHighPerformanceSampleRate + error:nil]; + [audio_session setPreferredIOBufferDuration: + kRTCAudioSessionHighPerformanceIOBufferDuration + error:nil]; // Find the desired input port NSArray* inputs = [audio_session availableInputs]; AVAudioSessionPortDescription* builtInMic = nil; @@ -97,6 +115,21 @@ } [audio_session setActive:YES error:nil]; + [audio_session setPreferredInputNumberOfChannels: + kRTCAudioSessionPreferredNumberOfChannels + error:nil]; + [audio_session setPreferredOutputNumberOfChannels: + kRTCAudioSessionPreferredNumberOfChannels + error:nil]; +} + +void AudioSessionManagerIOS::SetActive(bool active) { + AVAudioSession* audio_session = [AVAudioSession sharedInstance]; + if (active) { + [audio_session setActive:YES error:nil]; + } else { + [audio_session setActive:NO error:nil]; + } } bool AudioSessionManagerIOS::HasAudioHardware(bool is_input) { @@ -137,9 +170,25 @@ return base::SysNSStringToUTF8([currentInput portName]); } -int AudioSessionManagerIOS::HardwareSampleRate() { +double AudioSessionManagerIOS::HardwareSampleRate() { AVAudioSession* audio_session = [AVAudioSession sharedInstance]; - return static_cast<int>(audio_session.sampleRate); + return audio_session.sampleRate; +} + +double AudioSessionManagerIOS::HardwareIOBufferDuration() { + AVAudioSession* audio_session = [AVAudioSession sharedInstance]; + return audio_session.IOBufferDuration; +} + +double AudioSessionManagerIOS::HardwareLatency(bool is_input) { + AVAudioSession* audio_session = [AVAudioSession sharedInstance]; + return is_input ? audio_session.inputLatency : audio_session.outputLatency; +} + +long AudioSessionManagerIOS::GetDeviceChannels(bool is_input) { + AVAudioSession* audio_session = [AVAudioSession sharedInstance]; + return is_input ? audio_session.inputNumberOfChannels + : audio_session.outputNumberOfChannels; } float AudioSessionManagerIOS::GetInputGain() { @@ -166,6 +215,11 @@ return false; } +bool AudioSessionManagerIOS::IsInputGainSettable() { + AVAudioSession* audio_session = [AVAudioSession sharedInstance]; + return [audio_session isInputGainSettable] == YES; +} + // private void AudioSessionManagerIOS::GetAudioInputDeviceInfo( media::AudioDeviceNames* device_names) {
diff --git a/media/audio/mac/audio_low_latency_input_mac.cc b/media/audio/mac/audio_low_latency_input_mac.cc index 34935789..55e89012 100644 --- a/media/audio/mac/audio_low_latency_input_mac.cc +++ b/media/audio/mac/audio_low_latency_input_mac.cc
@@ -1019,14 +1019,15 @@ return (error == noErr && is_running); } -void AUAudioInputStream::HandleError(OSStatus err) { +void AUAudioInputStream::HandleError(OSStatus err, + const base::Location& location) { // Log the latest OSStatus error message and also change the sign of the // error if no callbacks are active. I.e., the sign of the error message // carries one extra level of information. base::UmaHistogramSparse("Media.InputErrorMac", GetInputCallbackIsActive() ? err : (err * -1)); - LOG(ERROR) << "Input error " << logging::DescriptionFromOSStatus(err) << - " (" << err << ")"; + LOG(ERROR) << "Input error " << logging::DescriptionFromOSStatus(err) << " (" + << err << ") at line " << location.line_number(); if (sink_) sink_->OnError(); }
diff --git a/media/audio/mac/audio_low_latency_input_mac.h b/media/audio/mac/audio_low_latency_input_mac.h index 5a1cc125..db00f039 100644 --- a/media/audio/mac/audio_low_latency_input_mac.h +++ b/media/audio/mac/audio_low_latency_input_mac.h
@@ -133,7 +133,7 @@ base::TimeTicks GetCaptureTime(const AudioTimeStamp* input_time_stamp); // Issues the OnError() callback to the |sink_|. - void HandleError(OSStatus err); + void HandleError(OSStatus err, const base::Location& location = FROM_HERE); // Helper methods to set and get atomic |input_callback_is_active_|. void SetInputCallbackIsActive(bool active);
diff --git a/media/capture/mojom/video_capture_types.mojom b/media/capture/mojom/video_capture_types.mojom index 38bdf95..b02eb86 100644 --- a/media/capture/mojom/video_capture_types.mojom +++ b/media/capture/mojom/video_capture_types.mojom
@@ -69,6 +69,12 @@ }; [Stable, Extensible] +enum CameraAvailability { + [Default] kAvailable, + kUnavailableExclusivelyUsedByOtherApplication, +}; + +[Stable, Extensible] enum VideoCaptureApi { LINUX_V4L2_SINGLE_PLANE, WIN_MEDIA_FOUNDATION, @@ -379,6 +385,7 @@ VideoCaptureApi capture_api; VideoCaptureControlSupport control_support; VideoCaptureTransportType transport_type; + [MinVersion=1] CameraAvailability? availability; }; // Bundles a VideoCaptureDeviceDescriptor with corresponding supported
diff --git a/media/capture/mojom/video_capture_types_mojom_traits.cc b/media/capture/mojom/video_capture_types_mojom_traits.cc index 281d2eb..a976434 100644 --- a/media/capture/mojom/video_capture_types_mojom_traits.cc +++ b/media/capture/mojom/video_capture_types_mojom_traits.cc
@@ -1788,6 +1788,21 @@ } // static +media::mojom::CameraAvailability EnumTraits< + media::mojom::CameraAvailability, + media::CameraAvailability>::ToMojom(media::CameraAvailability input) { + switch (input) { + case media::CameraAvailability::kAvailable: + return media::mojom::CameraAvailability::kAvailable; + case media::CameraAvailability:: + kUnavailableExclusivelyUsedByOtherApplication: + return media::mojom::CameraAvailability:: + kUnavailableExclusivelyUsedByOtherApplication; + } + NOTREACHED_NORETURN(); +} + +// static bool EnumTraits<media::mojom::VideoCaptureApi, media::VideoCaptureApi>:: FromMojom(media::mojom::VideoCaptureApi input, media::VideoCaptureApi* output) { @@ -1836,6 +1851,23 @@ } // static +bool EnumTraits<media::mojom::CameraAvailability, media::CameraAvailability>:: + FromMojom(media::mojom::CameraAvailability input, + media::CameraAvailability* output) { + switch (input) { + case media::mojom::CameraAvailability::kAvailable: + *output = media::CameraAvailability::kAvailable; + return true; + case media::mojom::CameraAvailability:: + kUnavailableExclusivelyUsedByOtherApplication: + *output = media::CameraAvailability:: + kUnavailableExclusivelyUsedByOtherApplication; + return true; + } + NOTREACHED_NORETURN(); +} + +// static media::mojom::VideoCaptureTransportType EnumTraits< media::mojom::VideoCaptureTransportType, media::VideoCaptureTransportType>::ToMojom(media::VideoCaptureTransportType @@ -1922,6 +1954,9 @@ return false; if (!data.ReadFacingMode(&(output->facing))) return false; + if (!data.ReadAvailability(&(output->availability))) { + return false; + } if (!data.ReadCaptureApi(&(output->capture_api))) return false; media::VideoCaptureControlSupport control_support;
diff --git a/media/capture/mojom/video_capture_types_mojom_traits.h b/media/capture/mojom/video_capture_types_mojom_traits.h index db1f047..ae9af758 100644 --- a/media/capture/mojom/video_capture_types_mojom_traits.h +++ b/media/capture/mojom/video_capture_types_mojom_traits.h
@@ -94,6 +94,15 @@ template <> struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS) + EnumTraits<media::mojom::CameraAvailability, media::CameraAvailability> { + static media::mojom::CameraAvailability ToMojom( + media::CameraAvailability input); + static bool FromMojom(media::mojom::CameraAvailability input, + media::CameraAvailability* output); +}; + +template <> +struct COMPONENT_EXPORT(MEDIA_CAPTURE_MOJOM_TRAITS) EnumTraits<media::mojom::VideoCaptureTransportType, media::VideoCaptureTransportType> { static media::mojom::VideoCaptureTransportType ToMojom( @@ -204,6 +213,11 @@ return input.facing; } + static absl::optional<media::CameraAvailability> availability( + const media::VideoCaptureDeviceDescriptor& input) { + return input.availability; + } + static media::VideoCaptureApi capture_api( const media::VideoCaptureDeviceDescriptor& input) { return input.capture_api;
diff --git a/media/capture/video/fake_video_capture_device_factory.cc b/media/capture/video/fake_video_capture_device_factory.cc index 0a60ccd..9c9b383c 100644 --- a/media/capture/video/fake_video_capture_device_factory.cc +++ b/media/capture/video/fake_video_capture_device_factory.cc
@@ -14,6 +14,7 @@ #include "build/build_config.h" #include "gpu/ipc/common/gpu_memory_buffer_support.h" #include "media/base/media_switches.h" +#include "media/base/video_facing.h" #include "media/capture/capture_switches.h" namespace { @@ -246,9 +247,11 @@ #endif devices_info.emplace_back(VideoCaptureDeviceDescriptor( - base::StringPrintf("fake_device_%d", entry_index), entry.device_id, api, + base::StringPrintf("fake_device_%d", entry_index), entry.device_id, + /*model_id=*/std::string(), api, entry.photo_device_config.control_support, - VideoCaptureTransportType::OTHER_TRANSPORT)); + VideoCaptureTransportType::OTHER_TRANSPORT, + media::MEDIA_VIDEO_FACING_NONE, entry.availability)); devices_info.back().supported_formats = GetSupportedFormats(entry.device_id);
diff --git a/media/capture/video/fake_video_capture_device_factory.h b/media/capture/video/fake_video_capture_device_factory.h index 143bdd1..060089b 100644 --- a/media/capture/video/fake_video_capture_device_factory.h +++ b/media/capture/video/fake_video_capture_device_factory.h
@@ -12,7 +12,9 @@ #include <vector> #include "build/build_config.h" +#include "media/base/video_facing.h" #include "media/capture/video/fake_video_capture_device.h" +#include "media/capture/video/video_capture_device_descriptor.h" #include "media/capture/video/video_capture_device_factory.h" #if BUILDFLAG(IS_WIN) @@ -36,6 +38,7 @@ VideoCaptureFormats supported_formats; FakePhotoDeviceConfig photo_device_config; FakeVideoCaptureDevice::DisplayMediaType display_media_type; + absl::optional<media::CameraAvailability> availability; }; // Implementation of VideoCaptureDeviceFactory that creates fake devices
diff --git a/media/capture/video/video_capture_device_descriptor.cc b/media/capture/video/video_capture_device_descriptor.cc index 78ec4f7..87b966c5 100644 --- a/media/capture/video/video_capture_device_descriptor.cc +++ b/media/capture/video/video_capture_device_descriptor.cc
@@ -41,10 +41,12 @@ VideoCaptureApi capture_api, const VideoCaptureControlSupport& control_support, VideoCaptureTransportType transport_type, - VideoFacingMode facing) + VideoFacingMode facing, + absl::optional<CameraAvailability> availability) : device_id(device_id), model_id(model_id), facing(facing), + availability(std::move(availability)), capture_api(capture_api), transport_type(transport_type), display_name_(TrimDisplayName(display_name)),
diff --git a/media/capture/video/video_capture_device_descriptor.h b/media/capture/video/video_capture_device_descriptor.h index 8f4cd30..682fa7c8 100644 --- a/media/capture/video/video_capture_device_descriptor.h +++ b/media/capture/video/video_capture_device_descriptor.h
@@ -10,6 +10,7 @@ #include "media/base/video_facing.h" #include "media/capture/capture_export.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace media { @@ -47,6 +48,13 @@ OTHER_TRANSPORT }; +// LINT.IfChange +enum class CameraAvailability { + kAvailable, + kUnavailableExclusivelyUsedByOtherApplication, +}; +// LINT.ThenChange(//media/capture/mojom/video_capture_types.mojom) + // Represents information about a capture device as returned by // VideoCaptureDeviceFactory::GetDeviceDescriptors(). // |device_id| represents a unique id of a physical device. Since the same @@ -76,7 +84,8 @@ const VideoCaptureControlSupport& control_support, VideoCaptureTransportType transport_type = VideoCaptureTransportType::OTHER_TRANSPORT, - VideoFacingMode facing = VideoFacingMode::MEDIA_VIDEO_FACING_NONE); + VideoFacingMode facing = VideoFacingMode::MEDIA_VIDEO_FACING_NONE, + absl::optional<CameraAvailability> availability = absl::nullopt); VideoCaptureDeviceDescriptor(const VideoCaptureDeviceDescriptor& other); ~VideoCaptureDeviceDescriptor(); @@ -110,6 +119,7 @@ std::string model_id; VideoFacingMode facing; + absl::optional<CameraAvailability> availability; VideoCaptureApi capture_api; VideoCaptureTransportType transport_type;
diff --git a/net/http/transport_security_state_static.pins b/net/http/transport_security_state_static.pins index 314377dc..c544325 100644 --- a/net/http/transport_security_state_static.pins +++ b/net/http/transport_security_state_static.pins
@@ -43,9 +43,9 @@ # hash function for preloaded entries again (we have already done so once). # -# Last updated: 2023-11-19 12:54 UTC +# Last updated: 2023-11-20 12:53 UTC PinsListTimestamp -1700398496 +1700484837 TestSPKI sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
diff --git a/net/http/transport_security_state_static_pins.json b/net/http/transport_security_state_static_pins.json index 6c3c4cc2..57962f82 100644 --- a/net/http/transport_security_state_static_pins.json +++ b/net/http/transport_security_state_static_pins.json
@@ -31,7 +31,7 @@ // the 'static_spki_hashes' and 'bad_static_spki_hashes' fields in 'pinsets' // refer to, and the timestamp at which the pins list was last updated. // -// Last updated: 2023-11-19 12:54 UTC +// Last updated: 2023-11-20 12:53 UTC // { "pinsets": [
diff --git a/styleguide/c++/c++-features.md b/styleguide/c++/c++-features.md index 2a6e5e2..ec99196 100644 --- a/styleguide/c++/c++-features.md +++ b/styleguide/c++/c++-features.md
@@ -43,6 +43,7 @@ * CRC32C library: Initially added to third_party Dec 5, 2022 * Nullability annotation: Initially added to third_party Jun 21, 2023 * Overload: Initially added to third_party Sep 27, 2023 + * NoDestructor: Initially added to third_party Nov 15, 2023 [TOC] @@ -2801,6 +2802,30 @@ Overlaps and uses same macros names as `base/logging.h`. *** +### NoDestructor <sup>[tbd]</sup> + +```c++ +// Global or namespace scope. +ABSL_CONST_INIT absl::NoDestructor<MyRegistry> reg{"foo", "bar", 8008}; + +// Function scope. +const std::string& MyString() { + static const absl::NoDestructor<std::string> x("foo"); + return *x; +} +``` + +**Description:** `absl::NoDestructor<T>` is a wrapper around an object of +type T that behaves as an object of type T but never calls T's destructor. + +**Documentation:** +[no_destructor.h](https://source.chromium.org/chromium/chromium/src/+/main:third_party/abseil-cpp/absl/base/no_desctructor.h) + +**Notes:** +*** promo +Overlaps with `base::NoDestructor`. +*** + ### Nullability annotations <sup>[tbd]</sup> ```c++
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 696c444..b8fe59a0 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -6093,9 +6093,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -6105,8 +6105,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -6243,9 +6243,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter;../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -6255,8 +6255,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": {
diff --git a/testing/buildbot/chromium.coverage.json b/testing/buildbot/chromium.coverage.json index 08ca59a..57e689b 100644 --- a/testing/buildbot/chromium.coverage.json +++ b/testing/buildbot/chromium.coverage.json
@@ -20442,9 +20442,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -20454,8 +20454,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -20592,9 +20592,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter;../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -20604,8 +20604,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": {
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 43104c8..a001920 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -43585,9 +43585,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43596,8 +43596,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -43735,9 +43735,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter;../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43746,8 +43746,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -45044,9 +45044,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -45055,8 +45055,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -45194,9 +45194,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter;../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -45205,8 +45205,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -45889,9 +45889,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -45900,8 +45900,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": {
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 89c6722..c574efe 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -16151,12 +16151,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.filter;../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -16166,8 +16166,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": { @@ -16321,12 +16321,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.filter;../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 121.0.6136.0", + "description": "Run with ash-chrome version 121.0.6137.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -16336,8 +16336,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v121.0.6136.0", - "revision": "version:121.0.6136.0" + "location": "lacros_version_skew_tests_v121.0.6137.0", + "revision": "version:121.0.6137.0" } ], "dimensions": {
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index cef03f5..ea191b9 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -70,16 +70,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'identifier': 'Lacros version skew testing ash canary', - 'description': 'Run with ash-chrome version 121.0.6136.0', + 'description': 'Run with ash-chrome version 121.0.6137.0', 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6136.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v121.0.6137.0/test_ash_chrome', ], 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v121.0.6136.0', - 'revision': 'version:121.0.6136.0', + 'location': 'lacros_version_skew_tests_v121.0.6137.0', + 'revision': 'version:121.0.6137.0', }, ], },
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 7ab875e..868bf34 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -8838,21 +8838,6 @@ ] } ], - "IOSPhoneNumberExperience": [ - { - "platforms": [ - "ios" - ], - "experiments": [ - { - "name": "Enabled", - "enable_features": [ - "EnablePhoneNumbersExperience" - ] - } - ] - } - ], "IOSPromosManagerMigration": [ { "platforms": [
diff --git a/third_party/abseil-cpp/absl.gni b/third_party/abseil-cpp/absl.gni index 3a0d97b..7cefc24 100644 --- a/third_party/abseil-cpp/absl.gni +++ b/third_party/abseil-cpp/absl.gni
@@ -32,7 +32,7 @@ if (is_component_build) { defines = [ "ABSL_BUILD_DLL" ] - if (!is_win) { + if (!is_win && (current_os != "aix")) { configs -= [ "//build/config/gcc:symbol_visibility_hidden" ] configs += [ "//build/config/gcc:symbol_visibility_default" ] }
diff --git a/third_party/angle b/third_party/angle index 98d7926..c8a544d 160000 --- a/third_party/angle +++ b/third_party/angle
@@ -1 +1 @@ -Subproject commit 98d79260fa0ebfcd5a4d959c9c21bf44071a00e6 +Subproject commit c8a544dddbae3d1f495e05a36d5c2f4427b4994b
diff --git a/third_party/bidimapper/README.chromium b/third_party/bidimapper/README.chromium index f45919b..891f2c5 100644 --- a/third_party/bidimapper/README.chromium +++ b/third_party/bidimapper/README.chromium
@@ -1,10 +1,10 @@ Name: Implementation of WebDriver BiDi standard Short Name: chromium-bidi -URL: https://github.com/GoogleChromeLabs/chromium-bidi/archive/55d1622f065dad36248977f1fed5ac143f526497.zip +URL: https://github.com/GoogleChromeLabs/chromium-bidi/archive/cefbee70bc39c9c2e49ff76d780471f72f458340.zip Version: 0 -Date: 2023-10-31 -Revision: 55d1622f065dad36248977f1fed5ac143f526497 -SHA-512: c5104404378f646522e39cc9bc8bf28acf4ba5a73624730f117d732b0dd511f528a9642422e0b9421870f45a4be3be973952f78e29163d891f1c2afb70a679ac +Date: 2023-11-20 +Revision: cefbee70bc39c9c2e49ff76d780471f72f458340 +SHA-512: 9eb05dff27a2728453ca36833812f449b4f39f7f674b392d9a93e996ab94b1b8896e02d7f56d708d4e2331abef1be9c0349a47ae83feb88568b8b2ffcb3d9b3e License: Apache 2.0 License File: LICENSE Shipped: yes
diff --git a/third_party/bidimapper/mapper.js b/third_party/bidimapper/mapper.js index f1445341..a45c23a 100644 --- a/third_party/bidimapper/mapper.js +++ b/third_party/bidimapper/mapper.js
@@ -1,4 +1,4 @@ -var mapperTab=function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var a=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};a.prototype=t.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),a}var a={},r={},n={},s={};var o=Object.freeze({__proto__:null,default:function(e){return{all:e=e||new Map,on:function(t,a){var r=e.get(t);r?r.push(a):e.set(t,[a])},off:function(t,a){var r=e.get(t);r&&(a?r.splice(r.indexOf(a)>>>0,1):e.set(t,[]))},emit:function(t,a){var r=e.get(t);r&&r.slice().map((function(e){e(a)})),(r=e.get("*"))&&r.slice().map((function(e){e(t,a)}))}}}}),i=t(o),c=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(s,"__esModule",{value:!0}),s.EventEmitter=void 0;const d=c(i);s.EventEmitter=class{#e=(0,d.default)();on(e,t){return this.#e.on(e,t),this}once(e,t){const a=r=>{t(r),this.off(e,a)};return this.on(e,a)}off(e,t){return this.#e.off(e,t),this}emit(e,t){this.#e.emit(e,t)}removeAllListeners(e){return e?this.#e.all.delete(e):this.#e.all.clear(),this}};var u,l={};Object.defineProperty(l,"__esModule",{value:!0}),l.LogType=void 0,function(e){e.bidi="bidi",e.cdp="cdp",e.debug="debug",e.debugError="debug:error",e.debugInfo="debug:info"}(u||(l.LogType=u={}));var h={};Object.defineProperty(h,"__esModule",{value:!0}),h.ProcessingQueue=void 0;const p=l;class m{static LOGGER_PREFIX=`${p.LogType.debug}:queue`;#t;#a;#r=[];#n=!1;constructor(e,t){this.#a=e,this.#t=t}add(e,t){this.#r.push([e,t]),this.#s()}async#s(){if(!this.#n){for(this.#n=!0;this.#r.length>0;){const e=this.#r.shift();if(!e)continue;const[t,a]=e;this.#t?.(m.LOGGER_PREFIX,"Processing event:",a),await t.then((e=>{if("error"!==e.kind)return this.#a(e.value);this.#t?.(p.LogType.debugError,"Event threw before sending:",e.error.message,e.error.stack)})).catch((e=>{this.#t?.(p.LogType.debugError,"Event was not processed:",e?.message)}))}this.#n=!1}}}h.ProcessingQueue=m;var f={},g={},y={};Object.defineProperty(y,"__esModule",{value:!0});var S,v,w,b,C,x={};Object.defineProperty(x,"__esModule",{value:!0}),x.EVENT_NAMES=x.Network=x.BrowsingContext=x.Log=x.Script=x.BiDiModule=void 0,function(e){e.Browser="browser",e.BrowsingContext="browsingContext",e.Cdp="cdp",e.Input="input",e.Log="log",e.Network="network",e.Script="script",e.Session="session"}(S||(x.BiDiModule=S={})),function(e){var t;(t=e.EventNames||(e.EventNames={})).Message="script.message",t.RealmCreated="script.realmCreated",t.RealmDestroyed="script.realmDestroyed"}(v||(x.Script=v={})),function(e){(e.EventNames||(e.EventNames={})).LogEntryAdded="log.entryAdded"}(w||(x.Log=w={})),function(e){var t;(t=e.EventNames||(e.EventNames={})).ContextCreated="browsingContext.contextCreated",t.ContextDestroyed="browsingContext.contextDestroyed",t.DomContentLoaded="browsingContext.domContentLoaded",t.DownloadWillBegin="browsingContext.downloadWillBegin",t.FragmentNavigated="browsingContext.fragmentNavigated",t.Load="browsingContext.load",t.NavigationAborted="browsingContext.navigationAborted",t.NavigationFailed="browsingContext.navigationFailed",t.NavigationStarted="browsingContext.navigationStarted",t.UserPromptClosed="browsingContext.userPromptClosed",t.UserPromptOpened="browsingContext.userPromptOpened"}(b||(x.BrowsingContext=b={})),function(e){var t;(t=e.EventNames||(e.EventNames={})).AuthRequired="network.authRequired",t.BeforeRequestSent="network.beforeRequestSent",t.FetchError="network.fetchError",t.ResponseCompleted="network.responseCompleted",t.ResponseStarted="network.responseStarted"}(C||(x.Network=C={})),x.EVENT_NAMES=new Set([...Object.values(S),...Object.values(b.EventNames),...Object.values(w.EventNames),...Object.values(C.EventNames),...Object.values(v.EventNames)]);var I={};Object.defineProperty(I,"__esModule",{value:!0});var P={};Object.defineProperty(P,"__esModule",{value:!0}),P.UnsupportedOperationException=P.UnableToCloseBrowserException=P.UnableToCaptureScreenException=P.UnknownErrorException=P.UnknownCommandException=P.SessionNotCreatedException=P.NoSuchScriptException=P.NoSuchRequestException=P.NoSuchNodeException=P.NoSuchInterceptException=P.NoSuchHandleException=P.NoSuchFrameException=P.NoSuchElementException=P.NoSuchAlertException=P.MoveTargetOutOfBoundsException=P.InvalidSessionIdException=P.InvalidArgumentException=P.Exception=void 0;class k{error;message;stacktrace;constructor(e,t,a){this.error=e,this.message=t,this.stacktrace=a}toErrorResponse(e){return{type:"error",id:e,error:this.error,message:this.message,stacktrace:this.stacktrace}}}P.Exception=k;P.InvalidArgumentException=class extends k{constructor(e,t){super("invalid argument",e,t)}};P.InvalidSessionIdException=class extends k{constructor(e,t){super("invalid session id",e,t)}};P.MoveTargetOutOfBoundsException=class extends k{constructor(e,t){super("move target out of bounds",e,t)}};P.NoSuchAlertException=class extends k{constructor(e,t){super("no such alert",e,t)}};P.NoSuchElementException=class extends k{constructor(e,t){super("no such element",e,t)}};P.NoSuchFrameException=class extends k{constructor(e,t){super("no such frame",e,t)}};P.NoSuchHandleException=class extends k{constructor(e,t){super("no such handle",e,t)}};P.NoSuchInterceptException=class extends k{constructor(e,t){super("no such intercept",e,t)}};P.NoSuchNodeException=class extends k{constructor(e,t){super("no such node",e,t)}};P.NoSuchRequestException=class extends k{constructor(e,t){super("no such request",e,t)}};P.NoSuchScriptException=class extends k{constructor(e,t){super("no such script",e,t)}};P.SessionNotCreatedException=class extends k{constructor(e,t){super("session not created",e,t)}};P.UnknownCommandException=class extends k{constructor(e,t){super("unknown command",e,t)}};P.UnknownErrorException=class extends k{constructor(e,t=(new Error).stack){super("unknown error",e,t)}};P.UnableToCaptureScreenException=class extends k{constructor(e,t){super("unable to capture screen",e,t)}};P.UnableToCloseBrowserException=class extends k{constructor(e,t){super("unable to close browser",e,t)}};P.UnsupportedOperationException=class extends k{constructor(e,t){super("unsupported operation",e,t)}},function(t){var a=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,r,n)}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&a(t,e,n);return r(t,e),t},s=e&&e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.ChromiumBidi=t.Cdp=void 0,t.Cdp=n(y),t.ChromiumBidi=n(x),s(I,t),s(P,t)}(g);var R={};Object.defineProperty(R,"__esModule",{value:!0}),R.BidiNoOpParser=void 0;R.BidiNoOpParser=class{parseActivateParams(e){return e}parseCaptureScreenshotParams(e){return e}parseCloseParams(e){return e}parseCreateParams(e){return e}parseGetTreeParams(e){return e}parseHandleUserPromptParams(e){return e}parseNavigateParams(e){return e}parsePrintParams(e){return e}parseReloadParams(e){return e}parseSetViewportParams(e){return e}parseGetSessionParams(e){return e}parseSendCommandParams(e){return e}parseAddPreloadScriptParams(e){return e}parseCallFunctionParams(e){return e}parseDisownParams(e){return e}parseEvaluateParams(e){return e}parseGetRealmsParams(e){return e}parseRemovePreloadScriptParams(e){return e}parsePerformActionsParams(e){return e}parseReleaseActionsParams(e){return e}parseAddInterceptParams(e){return e}parseContinueRequestParams(e){return e}parseContinueResponseParams(e){return e}parseContinueWithAuthParams(e){return e}parseFailRequestParams(e){return e}parseProvideResponseParams(e){return e}parseRemoveInterceptParams(e){return e}parseSubscribeParams(e){return e}};var _={};Object.defineProperty(_,"__esModule",{value:!0}),_.BrowserProcessor=void 0;_.BrowserProcessor=class{#o;constructor(e){this.#o=e}close(){return setTimeout((()=>this.#o.sendCommand("Browser.close")),0),{}}};var E={};Object.defineProperty(E,"__esModule",{value:!0}),E.CdpProcessor=void 0;E.CdpProcessor=class{#i;#c;#o;constructor(e,t,a){this.#i=e,this.#c=t,this.#o=a}getSession(e){const t=e.context,a=this.#i.getContext(t).cdpTarget.cdpSessionId;return void 0===a?{}:{session:a}}async sendCommand(e){const t=e.session?this.#c.getCdpClient(e.session):this.#o;return{result:await t.sendCommand(e.method,e.params),session:e.session}}};var T={},N={},j={};Object.defineProperty(j,"__esModule",{value:!0}),j.assert=void 0,j.assert=function(e,t){if(!e)throw new Error(t??"Internal assertion failed.")};var O={};Object.defineProperty(O,"__esModule",{value:!0}),O.Deferred=void 0;class M{#d=!1;#u;#l;#h;get isFinished(){return this.#d}constructor(){this.#u=new Promise(((e,t)=>{this.#l=e,this.#h=t})),this.#u.catch((e=>{}))}then(e,t){return this.#u.then(e,t)}catch(e){return this.#u.catch(e)}resolve(e){this.#d||(this.#d=!0,this.#l(e))}reject(e){this.#d||(this.#d=!0,this.#h(e))}finally(e){return this.#u.finally(e)}[Symbol.toStringTag]="Promise"}O.Deferred=M;var A={};Object.defineProperty(A,"__esModule",{value:!0}),A.inchesFromCm=void 0,A.inchesFromCm=function(e){return e/2.54};var D={},B={},z={};Object.defineProperty(z,"__esModule",{value:!0}),z.uuidv4=void 0,z.uuidv4=function(){if("crypto"in globalThis&&"randomUUID"in globalThis.crypto)return globalThis.crypto.randomUUID();const e=new Uint8Array(16);"crypto"in globalThis&&"getRandomValues"in globalThis.crypto?globalThis.crypto.getRandomValues(e):require("crypto").webcrypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=e=>e.reduce(((e,t)=>e+t.toString(16).padStart(2,"0")),"");return[t(e.subarray(0,4)),t(e.subarray(4,6)),t(e.subarray(6,8)),t(e.subarray(8,10)),t(e.subarray(10,16))].join("-")},Object.defineProperty(B,"__esModule",{value:!0}),B.ChannelProxy=void 0;const L=g,Z=l,U=z;class q{#p;#m=(0,U.uuidv4)();#t;constructor(e,t){this.#p=e,this.#t=t}async init(e,t){const a=await q.#f(e),r=await q.#g(e,a);return this.#y(e,a,t),r}async startListenerFromWindow(e,t){try{const a=await this.#S(e);this.#y(e,a,t)}catch(e){this.#t?.(Z.LogType.debugError,e)}}static#v(){return`(${String((()=>{const e=[];let t=null;return{async getMessage(){const a=e.length>0?Promise.resolve():new Promise((e=>{t=e}));return await a,e.shift()},sendMessage(a){e.push(a),null!==t&&(t(),t=null)}}}))})()`}static async#f(e){const t=await e.cdpClient.sendCommand("Runtime.evaluate",{expression:this.#v(),contextId:e.executionContextId,serializationOptions:{serialization:"idOnly"}});if(t.exceptionDetails||void 0===t.result.objectId)throw new Error("Cannot create channel");return t.result.objectId}static async#g(e,t){return(await e.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>e.sendMessage)),arguments:[{objectId:t}],executionContextId:e.executionContextId,serializationOptions:{serialization:"idOnly"}})).result.objectId}async#y(e,t,a){for(;;)try{const r=await e.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((async e=>await e.getMessage())),arguments:[{objectId:t}],awaitPromise:!0,executionContextId:e.executionContextId,serializationOptions:{serialization:"deep",maxDepth:this.#p.serializationOptions?.maxObjectDepth??void 0}});if(r.exceptionDetails)throw r.exceptionDetails;a.registerEvent({type:"event",method:L.ChromiumBidi.Script.EventNames.Message,params:{channel:this.#p.channel,data:e.cdpToBidiValue(r,this.#p.ownership??"none"),source:{realm:e.realmId,context:e.browsingContextId}}},e.browsingContextId)}catch(e){this.#t?.(Z.LogType.debugError,e);break}}async#S(e){const t=await e.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>{const t=window;if(void 0===t[e])return new Promise((a=>t[e]=a));const a=t[e];return delete t[e],a})),arguments:[{value:this.#m}],executionContextId:e.executionContextId,awaitPromise:!0,serializationOptions:{serialization:"idOnly"}});if(void 0!==t.exceptionDetails||void 0===t.result.objectId)throw new Error(`ChannelHandle not found in window["${this.#m}"]`);return t.result.objectId}getEvalInWindowStr(){const e=String(((e,t)=>{const a=window;return void 0===a[e]?a[e]=t:(a[e](t),delete a[e]),t.sendMessage})),t=q.#v();return`(${e})('${this.#m}',${t})`}}B.ChannelProxy=q,Object.defineProperty(D,"__esModule",{value:!0}),D.Realm=void 0;const V=g,F=l,$=B,K="_element_";class W{#w;#i;#b;#C;#x;#I;#P;#k;#R;sandbox;#t;constructor(e,t,a,r,n,s,o,i,c,d,u){this.#b=a,this.#C=r,this.#x=n,this.sandbox=i,this.#I=s,this.#P=o,this.#k=c,this.#w=e,this.#i=t,this.#R=d,this.#t=u,this.#w.addRealm(this),this.#R.registerEvent({type:"event",method:V.ChromiumBidi.Script.EventNames.RealmCreated,params:this.realmInfo},this.browsingContextId)}cdpToBidiValue(e,t){const a=this.#_(e.result.deepSerializedValue);if(e.result.objectId){const r=e.result.objectId;"root"===t?(a.handle=r,this.#w.knownHandlesToRealmMap.set(r,this.realmId)):this.#E(r).catch((e=>this.#t?.(F.LogType.debugError,e)))}if("object"===e.result.type)switch(e.result.subtype){case"generator":case"iterator":a.type=e.result.subtype,delete a.value}return a}#_(e){if(Object.hasOwn(e,"weakLocalObjectReference")&&(e.internalId=`${e.weakLocalObjectReference}`,delete e.weakLocalObjectReference),"platformobject"===e.type)return{type:"object"};const t=e.value;if(void 0===t)return e;if("node"===e.type){if(Object.hasOwn(t,"backendNodeId")&&(e.sharedId=`${this.navigableId}${K}${t.backendNodeId}`,delete t.backendNodeId),Object.hasOwn(t,"children"))for(const e in t.children)t.children[e]=this.#_(t.children[e]);Object.hasOwn(t,"shadowRoot")&&null!==t.shadowRoot&&(t.shadowRoot=this.#_(t.shadowRoot)),""===t.namespaceURI&&(t.namespaceURI=null)}if(["array","set","htmlcollection","nodelist"].includes(e.type))for(const e in t)t[e]=this.#_(t[e]);if(["object","map"].includes(e.type))for(const e in t)t[e]=[this.#_(t[e][0]),this.#_(t[e][1])];return e}get realmId(){return this.#b}get navigableId(){return this.#i.findContext(this.#C)?.navigableId??"UNKNOWN"}get browsingContextId(){return this.#C}get executionContextId(){return this.#x}get origin(){return this.#I}get type(){return this.#P}get cdpClient(){return this.#k}get realmInfo(){return{realm:this.realmId,origin:this.origin,type:this.type,context:this.browsingContextId,...void 0===this.sandbox?{}:{sandbox:this.sandbox}}}async evaluate(e,t,a,r,n=!1){await this.#i.getContext(this.browsingContextId).targetUnblockedOrThrow();const s=await this.cdpClient.sendCommand("Runtime.evaluate",{contextId:this.executionContextId,expression:e,awaitPromise:t,serializationOptions:W.#T("deep",r),userGesture:n});return s.exceptionDetails?await this.#N(s.exceptionDetails,0,a):{realm:this.realmId,result:this.cdpToBidiValue(s,a),type:"success"}}async serializeCdpObject(e,t){const a=W.#j(e),r=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>e)),awaitPromise:!1,arguments:[a],serializationOptions:{serialization:"deep"},executionContextId:this.executionContextId});return this.cdpToBidiValue(r,t)}static#j(e){return void 0!==e.objectId?{objectId:e.objectId}:void 0!==e.unserializableValue?{unserializableValue:e.unserializableValue}:{value:e.value}}async stringifyObject(e){const{result:t}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>String(e))),awaitPromise:!1,arguments:[e],returnByValue:!0,executionContextId:this.executionContextId});return t.value}async#O(e){const t=[];for(const[a,r]of e){let e;e="string"==typeof a?{value:a}:await this.#M(a);const n=await this.#M(r);t.push(e),t.push(n)}return t}async#A(e){return await Promise.all(e.map((e=>this.#M(e))))}async#D(e,t,a){const r=e.stackTrace?.callFrames.map((e=>({url:e.url,functionName:e.functionName,lineNumber:e.lineNumber-t,columnNumber:e.columnNumber})))??[],n=e.exception;return{exception:await this.serializeCdpObject(n,a),columnNumber:e.columnNumber,lineNumber:e.lineNumber-t,stackTrace:{callFrames:r},text:await this.stringifyObject(n)||e.text}}async callFunction(e,t,a,r,n,s,o=!1){await this.#i.getContext(this.browsingContextId).targetUnblockedOrThrow();const i=`(...args) => {\n function callFunction(f, args) {\n const deserializedThis = args.shift();\n const deserializedArgs = args;\n return f.apply(deserializedThis, deserializedArgs);\n }\n return callFunction((\n ${e}\n ), args);\n }`,c=[await this.#M(t),...await Promise.all(a.map((async e=>await this.#M(e))))];let d;try{d=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:i,awaitPromise:r,arguments:c,serializationOptions:W.#T("deep",s),executionContextId:this.executionContextId,userGesture:o})}catch(e){if(-32e3===e.code&&["Could not find object with given id","Argument should belong to the same JavaScript world as target object","Invalid remote object id"].includes(e.message))throw new V.NoSuchHandleException("Handle was not found.");throw e}return d.exceptionDetails?await this.#N(d.exceptionDetails,1,n):{type:"success",result:this.cdpToBidiValue(d,n),realm:this.realmId}}async#M(e){if("sharedId"in e&&e.sharedId){const[t,a]=e.sharedId.split(K),r=parseInt(a??"");if(isNaN(r)||void 0===r||void 0===t)throw new V.NoSuchNodeException(`SharedId "${e.sharedId}" was not found.`);if(this.navigableId!==t)throw new V.NoSuchNodeException(`SharedId "${e.sharedId}" belongs to different document. Current document is ${this.navigableId}.`);try{const{object:e}=await this.cdpClient.sendCommand("DOM.resolveNode",{backendNodeId:r,executionContextId:this.executionContextId});return{objectId:e.objectId}}catch(t){if(-32e3===t.code&&"No node with given id found"===t.message)throw new V.NoSuchNodeException(`SharedId "${e.sharedId}" was not found.`);throw new V.UnknownErrorException(t.message,t.stack)}}else{if("handle"in e&&e.handle)return{objectId:e.handle};if("handle"in e||"sharedId"in e)throw new V.NoSuchHandleException("Handle was not found.")}switch(e.type){case"undefined":return{unserializableValue:"undefined"};case"null":return{unserializableValue:"null"};case"string":return{value:e.value};case"number":return"NaN"===e.value?{unserializableValue:"NaN"}:"-0"===e.value?{unserializableValue:"-0"}:"Infinity"===e.value?{unserializableValue:"Infinity"}:"-Infinity"===e.value?{unserializableValue:"-Infinity"}:{value:e.value};case"boolean":return{value:Boolean(e.value)};case"bigint":return{unserializableValue:`BigInt(${JSON.stringify(e.value)})`};case"date":return{unserializableValue:`new Date(Date.parse(${JSON.stringify(e.value)}))`};case"regexp":return{unserializableValue:`new RegExp(${JSON.stringify(e.value.pattern)}, ${JSON.stringify(e.value.flags)})`};case"map":{const t=await this.#O(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>{const t=new Map;for(let a=0;a<e.length;a+=2)t.set(e[a],e[a+1]);return t})),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"object":{const t=await this.#O(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>{const t={};for(let a=0;a<e.length;a+=2){t[e[a]]=e[a+1]}return t})),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"array":{const t=await this.#A(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>e)),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"set":{const t=await this.#A(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>new Set(e))),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"channel":{const t=new $.ChannelProxy(e.value,this.#t);return{objectId:await t.init(this,this.#R)}}}throw new Error(`Value ${JSON.stringify(e)} is not deserializable.`)}async#N(e,t,a){return{exceptionDetails:await this.#D(e,t,a),realm:this.realmId,type:"exception"}}static#T(e,t){return{serialization:e,additionalParameters:W.#B(t),...W.#z(t)}}static#B(e){const t={};return void 0!==e.maxDomDepth&&(t.maxNodeDepth=null===e.maxDomDepth?1e3:e.maxDomDepth),void 0!==e.includeShadowTree&&(t.includeShadowTree=e.includeShadowTree),t}static#z(e){return void 0===e.maxObjectDepth||null===e.maxObjectDepth?{}:{maxDepth:e.maxObjectDepth}}async#E(e){try{await this.cdpClient.sendCommand("Runtime.releaseObject",{objectId:e})}catch(e){if(-32e3!==e.code||"Invalid remote object id"!==e.message)throw e}}async disown(e){this.#w.knownHandlesToRealmMap.get(e)===this.realmId&&(await this.#E(e),this.#w.knownHandlesToRealmMap.delete(e))}dispose(){this.#R.registerEvent({type:"event",method:V.ChromiumBidi.Script.EventNames.RealmDestroyed,params:{realm:this.realmId}},this.browsingContextId)}}D.Realm=W,Object.defineProperty(N,"__esModule",{value:!0}),N.BrowsingContextImpl=void 0;const H=g,J=j,G=O,X=l,Y=A,Q=D;class ee{static LOGGER_PREFIX=`${X.LogType.debug}:browsingContext`;#m;#L;#Z=new Set;#i;#U={Page:{navigatedWithinDocument:new G.Deferred,lifecycleEvent:{DOMContentLoaded:new G.Deferred,load:new G.Deferred},frameStartedLoading:new G.Deferred}};#q="about:blank";#R;#w;#V;#F;#$;#t;constructor(e,t,a,r,n,s,o){this.#F=e,this.#w=t,this.#m=a,this.#L=r,this.#R=n,this.#i=s,this.#t=o}static create(e,t,a,r,n,s,o){const i=new ee(e,t,a,r,n,s,o);return i.#K(),s.addContext(i),i.isTopLevelContext()||i.parent.addChild(i.id),n.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.ContextCreated,params:i.serializeToBidiValue()},i.id),i}static getTimestamp(){return(new Date).getTime()}get navigableId(){return this.#V}dispose(){this.#W(),this.#w.deleteRealms({browsingContextId:this.id}),this.isTopLevelContext()||this.parent.#Z.delete(this.id),this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.ContextDestroyed,params:this.serializeToBidiValue()},this.id),this.#i.deleteContextById(this.id)}get id(){return this.#m}get parentId(){return this.#L}get parent(){return null===this.parentId?null:this.#i.getContext(this.parentId)}get directChildren(){return[...this.#Z].map((e=>this.#i.getContext(e)))}get allChildren(){const e=this.directChildren;return e.concat(...e.map((e=>e.allChildren)))}isTopLevelContext(){return null===this.#L}get top(){let e=this,t=e.parent;for(;t;)e=t,t=e.parent;return e}addChild(e){this.#Z.add(e)}#W(){this.directChildren.map((e=>e.dispose()))}get#H(){return(0,J.assert)(this.#$,`No default realm for browsing context ${this.#m}`),this.#$}get cdpTarget(){return this.#F}updateCdpTarget(e){this.#F=e,this.#K()}get url(){return this.#q}async lifecycleLoaded(){await this.#U.Page.lifecycleEvent.load}async targetUnblockedOrThrow(){const e=await this.#F.targetUnblocked;if("error"===e.kind)throw e.error}async getOrCreateSandbox(e){if(void 0===e||""===e)return this.#H;let t=this.#w.findRealms({browsingContextId:this.id,sandbox:e});return 0===t.length&&(await this.#F.cdpClient.sendCommand("Page.createIsolatedWorld",{frameId:this.id,worldName:e}),t=this.#w.findRealms({browsingContextId:this.id,sandbox:e}),(0,J.assert)(0!==t.length)),t[0]}serializeToBidiValue(e=0,t=!0){return{context:this.#m,url:this.url,children:e>0?this.directChildren.map((t=>t.serializeToBidiValue(e-1,!1))):null,...t?{parent:this.#L}:{}}}onTargetInfoChanged(e){this.#q=e.targetInfo.url}#K(){this.#F.cdpClient.on("Page.frameNavigated",(e=>{this.id===e.frame.id&&(this.#q=e.frame.url+(e.frame.urlFragment??""),this.#W())})),this.#F.cdpClient.on("Page.navigatedWithinDocument",(e=>{if(this.id!==e.frameId)return;const t=ee.getTimestamp();this.#q=e.url,this.#U.Page.navigatedWithinDocument.resolve(e),this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.FragmentNavigated,params:{context:this.id,navigation:null,timestamp:t,url:this.#q}},this.id)})),this.#F.cdpClient.on("Page.frameStartedLoading",(e=>{this.id===e.frameId&&this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.NavigationStarted,params:{context:this.id,navigation:null,timestamp:ee.getTimestamp(),url:""}},this.id)})),this.#F.cdpClient.on("Page.lifecycleEvent",(e=>{if(this.id!==e.frameId)return;if("init"===e.name)return void this.#J(e.loaderId);if("commit"===e.name)return void(this.#V=e.loaderId);if(e.loaderId!==this.#V)return;const t=ee.getTimestamp();switch(e.name){case"DOMContentLoaded":this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.DomContentLoaded,params:{context:this.id,navigation:this.#V??null,timestamp:t,url:this.#q}},this.id),this.#U.Page.lifecycleEvent.DOMContentLoaded.resolve(e);break;case"load":this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.Load,params:{context:this.id,navigation:this.#V??null,timestamp:t,url:this.#q}},this.id),this.#U.Page.lifecycleEvent.load.resolve(e)}})),this.#F.cdpClient.on("Runtime.executionContextCreated",(e=>{if(e.context.auxData.frameId!==this.id)return;if(!["default","isolated"].includes(e.context.auxData.type))return;const t=new Q.Realm(this.#w,this.#i,e.context.uniqueId,this.id,e.context.id,this.#G(e),"window","isolated"===e.context.auxData.type?e.context.name:void 0,this.#F.cdpClient,this.#R,this.#t);e.context.auxData.isDefault&&(this.#$=t,Promise.all(this.#F.getChannels().map((e=>e.startListenerFromWindow(t,this.#R)))))})),this.#F.cdpClient.on("Runtime.executionContextDestroyed",(e=>{this.#w.deleteRealms({cdpSessionId:this.#F.cdpSessionId,executionContextId:e.executionContextId})})),this.#F.cdpClient.on("Runtime.executionContextsCleared",(()=>{this.#w.deleteRealms({cdpSessionId:this.#F.cdpSessionId})})),this.#F.cdpClient.on("Page.javascriptDialogClosed",(e=>{const t=e.result;this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.UserPromptClosed,params:{context:this.id,accepted:t,userText:t&&e.userInput?e.userInput:void 0}},this.id)})),this.#F.cdpClient.on("Page.javascriptDialogOpening",(e=>{this.#R.registerEvent({type:"event",method:H.ChromiumBidi.BrowsingContext.EventNames.UserPromptOpened,params:{context:this.id,type:e.type,message:e.message,defaultValue:e.defaultPrompt||void 0}},this.id)}))}#G(e){return"isolated"===e.context.auxData.type?this.#H.origin:["://",""].includes(e.context.origin)?"null":e.context.origin}#J(e){void 0!==e&&this.#V!==e?(this.#X(),this.#V=e):this.#U.Page.navigatedWithinDocument.isFinished?this.#U.Page.navigatedWithinDocument=new G.Deferred:this.#t?.(ee.LOGGER_PREFIX,"Document changed (navigatedWithinDocument)")}#X(){this.#U.Page.lifecycleEvent.DOMContentLoaded.isFinished?this.#U.Page.lifecycleEvent.DOMContentLoaded=new G.Deferred:this.#t?.(ee.LOGGER_PREFIX,"Document changed (DOMContentLoaded)"),this.#U.Page.lifecycleEvent.load.isFinished?this.#U.Page.lifecycleEvent.load=new G.Deferred:this.#t?.(ee.LOGGER_PREFIX,"Document changed (load)")}async navigate(e,t){try{new URL(e)}catch{throw new H.InvalidArgumentException(`Invalid URL: ${e}`)}await this.targetUnblockedOrThrow();const a=await this.#F.cdpClient.sendCommand("Page.navigate",{url:e,frameId:this.id});if(a.errorText)throw new H.UnknownErrorException(a.errorText);switch(this.#J(a.loaderId),t){case"none":break;case"interactive":void 0===a.loaderId?await this.#U.Page.navigatedWithinDocument:await this.#U.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":void 0===a.loaderId?await this.#U.Page.navigatedWithinDocument:await this.lifecycleLoaded()}return{navigation:a.loaderId??null,url:"none"===t?e:this.#q}}async reload(e,t){switch(await this.targetUnblockedOrThrow(),await this.#F.cdpClient.sendCommand("Page.reload",{ignoreCache:e}),this.#X(),t){case"none":break;case"interactive":await this.#U.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":await this.lifecycleLoaded()}return{navigation:"none"===t?null:this.navigableId??null,url:this.url}}async setViewport(e,t){if(null===e&&null===t)await this.#F.cdpClient.sendCommand("Emulation.clearDeviceMetricsOverride");else try{await this.#F.cdpClient.sendCommand("Emulation.setDeviceMetricsOverride",{width:e?e.width:0,height:e?e.height:0,deviceScaleFactor:t||0,mobile:!1,dontSetVisibleSize:!0})}catch(e){if(e.message.startsWith("Width and height values must be positive"))throw new H.UnsupportedOperationException("Provided viewport dimensions are not supported");throw e}}async handleUserPrompt(e){await this.#F.cdpClient.sendCommand("Page.handleJavaScriptDialog",{accept:e.accept??!0,promptText:e.userText})}async activate(){await this.#F.cdpClient.sendCommand("Page.bringToFront")}async captureScreenshot(e){if(!this.isTopLevelContext())throw new H.UnsupportedOperationException(`Non-top-level 'context' (${e.context}) is currently not supported`);const t=function(e){const{quality:t,type:a}=e.format??{type:"image/png"};switch(a){case"image/png":return{format:"png"};case"image/jpeg":return{format:"jpeg",...void 0===t?{}:{quality:Math.round(100*t)}};case"image/webp":return{format:"webp",...void 0===t?{}:{quality:Math.round(100*t)}}}throw new H.UnsupportedOperationException(`Image format '${a}' is not a supported format`)}(e);await this.#F.cdpClient.sendCommand("Page.bringToFront");let a,r=!1;switch(e.origin??="viewport",e.origin){case"document":a=String((()=>{const e=document.documentElement;return{x:0,y:0,width:e.scrollWidth,height:e.scrollHeight}})),r=!0;break;case"viewport":a=String((()=>{const e=window.visualViewport;return{x:e.pageLeft,y:e.pageTop,width:e.width,height:e.height}}))}const n=await this.getOrCreateSandbox(void 0),s=await n.callFunction(a,{type:"undefined"},[],!1,"none",{},!1);(0,J.assert)("success"===s.type);const o=te(s.result);(0,J.assert)(o);const i=e.clip?function(e,t){e=ae(e),t=ae(t);const a=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return{x:a,y:r,width:Math.max(Math.min(e.x+e.width,t.x+t.width)-a,0),height:Math.max(Math.min(e.y+e.height,t.y+t.height)-r,0)}}(await this.#Y(e.clip),o):o;if(0===i.width||0===i.height)throw new H.UnableToCaptureScreenException(`Unable to capture screenshot with zero dimensions: width=${i.width}, height=${i.height}`);return await this.#F.cdpClient.sendCommand("Page.captureScreenshot",{clip:{...i,scale:1},...t,captureBeyondViewport:r})}async print(e){const t={};if(void 0!==e.background&&(t.printBackground=e.background),void 0!==e.margin?.bottom&&(t.marginBottom=(0,Y.inchesFromCm)(e.margin.bottom)),void 0!==e.margin?.left&&(t.marginLeft=(0,Y.inchesFromCm)(e.margin.left)),void 0!==e.margin?.right&&(t.marginRight=(0,Y.inchesFromCm)(e.margin.right)),void 0!==e.margin?.top&&(t.marginTop=(0,Y.inchesFromCm)(e.margin.top)),void 0!==e.orientation&&(t.landscape="landscape"===e.orientation),void 0!==e.page?.height&&(t.paperHeight=(0,Y.inchesFromCm)(e.page.height)),void 0!==e.page?.width&&(t.paperWidth=(0,Y.inchesFromCm)(e.page.width)),void 0!==e.pageRanges){for(const t of e.pageRanges){if("number"==typeof t)continue;const e=t.split("-");if(e.length<1||e.length>2)throw new H.InvalidArgumentException(`Invalid page range: ${t} is not a valid integer range.`);if(1===e.length){re(e[0]??"");continue}let a,r;const[n="",s=""]=e;if(a=""===n?1:re(n),r=""===s?Number.MAX_SAFE_INTEGER:re(s),a>r)throw new H.InvalidArgumentException(`Invalid page range: ${n} > ${s}`)}t.pageRanges=e.pageRanges.join(",")}void 0!==e.scale&&(t.scale=e.scale),void 0!==e.shrinkToFit&&(t.preferCSSPageSize=!e.shrinkToFit);try{return{data:(await this.#F.cdpClient.sendCommand("Page.printToPDF",t)).data}}catch(e){if("invalid print parameters: content area is empty"===e.message)throw new H.UnsupportedOperationException(e.message);throw e}}async#Y(e){switch(e.type){case"box":return{x:e.x,y:e.y,width:e.width,height:e.height};case"element":{if(e.scrollIntoView)throw new H.UnsupportedOperationException("'scrollIntoView' is currently not supported");const t=await this.getOrCreateSandbox(void 0),a=await t.callFunction(String((e=>e instanceof Element)),{type:"undefined"},[e.element],!1,"none",{});if("exception"===a.type)throw new H.NoSuchElementException(`Element '${e.element.sharedId}' was not found`);if((0,J.assert)("boolean"===a.result.type),!a.result.value)throw new H.NoSuchElementException(`Node '${e.element.sharedId}' is not an Element`);{const a=await t.callFunction(String((e=>{const t=e.getBoundingClientRect();return{x:t.x,y:t.y,height:t.height,width:t.width}})),{type:"undefined"},[e.element],!1,"none",{});(0,J.assert)("success"===a.type);const r=te(a.result);if(!r)throw new H.UnableToCaptureScreenException(`Could not get bounding box for Element '${e.element.sharedId}'`);return r}}}}async close(){await this.#F.cdpClient.sendCommand("Page.close")}}function te(e){if("object"!==e.type||void 0===e.value)return;const t=e.value.find((([e])=>"x"===e))?.[1],a=e.value.find((([e])=>"y"===e))?.[1],r=e.value.find((([e])=>"height"===e))?.[1],n=e.value.find((([e])=>"width"===e))?.[1];return"number"===t?.type&&"number"===a?.type&&"number"===r?.type&&"number"===n?.type?{x:t.value,y:a.value,width:n.value,height:r.value}:void 0}function ae(e){return{...e.width<0?{x:e.x+e.width,width:-e.width}:{x:e.x,width:e.width},...e.height<0?{y:e.y+e.height,height:-e.height}:{y:e.y,height:e.height}}}function re(e){if(e=e.trim(),!/^[0-9]+$/.test(e))throw new H.InvalidArgumentException(`Invalid integer: ${e}`);return parseInt(e)}N.BrowsingContextImpl=ee;var ne={},se={},oe={};Object.defineProperty(oe,"__esModule",{value:!0}),oe.getRemoteValuesText=oe.logMessageFormatter=void 0;const ie=j,ce=["%s","%d","%i","%f","%o","%O","%c"];function de(e){return ce.some((t=>e.includes(t)))}function ue(e){let t="";const a=e[0].value.toString(),r=e.slice(1,void 0),n=a.split(new RegExp(ce.map((e=>`(${e})`)).join("|"),"g"));for(const a of n)if(void 0!==a&&""!==a)if(de(a)){const n=r.shift();(0,ie.assert)(n,`Less value is provided: "${pe(e,!1)}"`),"%s"===a?t+=he(n):"%d"===a||"%i"===a?"bigint"===n.type||"number"===n.type||"string"===n.type?t+=parseInt(n.value.toString(),10):t+="NaN":"%f"===a?"bigint"===n.type||"number"===n.type||"string"===n.type?t+=parseFloat(n.value.toString()):t+="NaN":t+=le(n)}else t+=a;if(r.length>0)throw new Error(`More value is provided: "${pe(e,!1)}"`);return t}function le(e){if("array"!==e.type&&"bigint"!==e.type&&"date"!==e.type&&"number"!==e.type&&"object"!==e.type&&"string"!==e.type)return he(e);if("bigint"===e.type)return`${e.value.toString()}n`;if("number"===e.type)return e.value.toString();if(["date","string"].includes(e.type))return JSON.stringify(e.value);if("object"===e.type)return`{${e.value.map((e=>`${JSON.stringify(e[0])}:${le(e[1])}`)).join(",")}}`;if("array"===e.type)return`[${e.value?.map((e=>le(e))).join(",")??""}]`;throw Error(`Invalid value type: ${e}`)}function he(e){if(!Object.hasOwn(e,"value"))return e.type;switch(e.type){case"string":case"number":case"boolean":case"bigint":return String(e.value);case"regexp":return`/${e.value.pattern}/${e.value.flags??""}`;case"date":return new Date(e.value).toString();case"object":return`Object(${e.value?.length??""})`;case"array":return`Array(${e.value?.length??""})`;case"map":return`Map(${e.value?.length})`;case"set":return`Set(${e.value?.length})`;default:return e.type}}function pe(e,t){const a=e[0];return a?"string"===a.type&&de(a.value.toString())&&t?ue(e):e.map((e=>he(e))).join(" "):""}oe.logMessageFormatter=ue,oe.getRemoteValuesText=pe,Object.defineProperty(se,"__esModule",{value:!0}),se.LogManager=void 0;const me=g,fe=oe;function ge(e){const t=e?.callFrames.map((e=>({columnNumber:e.columnNumber,functionName:e.functionName,lineNumber:e.lineNumber,url:e.url})));return t?{callFrames:t}:void 0}class ye{#R;#w;#F;constructor(e,t,a){this.#F=e,this.#w=t,this.#R=a}static create(e,t,a){const r=new ye(e,t,a);return r.#Q(),r}#Q(){this.#F.cdpClient.on("Runtime.consoleAPICalled",(e=>{const t=this.#w.findRealm({cdpSessionId:this.#F.cdpSessionId,executionContextId:e.executionContextId}),a=void 0===t?Promise.resolve(e.args):Promise.all(e.args.map((e=>t.serializeCdpObject(e,"none"))));this.#R.registerPromiseEvent(a.then((a=>{return{kind:"success",value:{type:"event",method:me.ChromiumBidi.Log.EventNames.LogEntryAdded,params:{level:(r=e.type,["error","assert"].includes(r)?"error":["debug","trace"].includes(r)?"debug":["warn","warning"].includes(r)?"warn":"info"),source:{realm:t?.realmId??"UNKNOWN",context:t?.browsingContextId??"UNKNOWN"},text:(0,fe.getRemoteValuesText)(a,!0),timestamp:Math.round(e.timestamp),stackTrace:ge(e.stackTrace),type:"console",method:"warning"===e.type?"warn":e.type,args:a}}};var r})),t?.browsingContextId??"UNKNOWN",me.ChromiumBidi.Log.EventNames.LogEntryAdded)})),this.#F.cdpClient.on("Runtime.exceptionThrown",(e=>{const t=this.#w.findRealm({cdpSessionId:this.#F.cdpSessionId,executionContextId:e.exceptionDetails.executionContextId});this.#R.registerPromiseEvent(ye.#ee(e,t).then((a=>({kind:"success",value:{type:"event",method:me.ChromiumBidi.Log.EventNames.LogEntryAdded,params:{level:"error",source:{realm:t?.realmId??"UNKNOWN",context:t?.browsingContextId??"UNKNOWN"},text:a,timestamp:Math.round(e.timestamp),stackTrace:ge(e.exceptionDetails.stackTrace),type:"javascript"}}}))),t?.browsingContextId??"UNKNOWN",me.ChromiumBidi.Log.EventNames.LogEntryAdded)}))}static async#ee(e,t){return e.exceptionDetails.exception?void 0===t?JSON.stringify(e.exceptionDetails.exception):await t.stringifyObject(e.exceptionDetails.exception):e.exceptionDetails.text}}se.LogManager=ye;var Se={},ve={},we={};Object.defineProperty(we,"__esModule",{value:!0}),we.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction=we.cdpFetchHeadersFromBidiNetworkHeaders=we.bidiNetworkHeadersFromCdpFetchHeaders=we.cdpNetworkHeadersFromBidiNetworkHeaders=we.bidiNetworkHeadersFromCdpNetworkHeaders=we.computeHeadersSize=void 0,we.computeHeadersSize=function(e){const t=e.reduce(((e,t)=>`${e}${t.name}: ${t.value.value}\r\n`),"");return(new TextEncoder).encode(t).length},we.bidiNetworkHeadersFromCdpNetworkHeaders=function(e){return e?Object.entries(e).map((([e,t])=>({name:e,value:{type:"string",value:t}}))):[]},we.cdpNetworkHeadersFromBidiNetworkHeaders=function(e){if(void 0!==e)return e.reduce(((e,t)=>(e[t.name]=t.value.value,e)),{})},we.bidiNetworkHeadersFromCdpFetchHeaders=function(e){return e?e.map((({name:e,value:t})=>({name:e,value:{type:"string",value:t}}))):[]},we.cdpFetchHeadersFromBidiNetworkHeaders=function(e){if(void 0!==e)return e.map((({name:e,value:t})=>({name:e,value:t.value})))},we.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction=function(e){switch(e){case"default":return"Default";case"cancel":return"CancelAuth";case"provideCredentials":return"ProvideCredentials"}},Object.defineProperty(ve,"__esModule",{value:!0}),ve.NetworkRequest=void 0;const be=g,Ce=j,xe=O,Ie=we;class Pe{static#te="UNKNOWN";#ae;#re=void 0;#ne=!1;#se;#R;#oe;#ie={};#ce={};#de=new xe.Deferred;#ue=new xe.Deferred;#le=new xe.Deferred;#F;constructor(e,t,a,r,n=0){this.#ae=e,this.#R=t,this.#oe=a,this.#F=r,this.#se=n}get requestId(){return this.#ae}get url(){return this.#ce.info?.url??this.#ie.info?.request.url}get redirectCount(){return this.#se}get cdpTarget(){return this.#F}isRedirecting(){return Boolean(this.#ie.info)}handleRedirect(e){this.#he(),this.#pe(),this.#ce.hasExtraInfo=e.redirectHasExtraInfo,this.#ce.info=e.redirectResponse,this.#me(!0)}#me(e=!1){const t=e||Boolean(this.#ie.extraInfo)||this.#ne||Boolean(this.#ce.info&&!this.#ce.hasExtraInfo)||"beforeRequestSent"===this.#re;this.#ie.info&&t&&this.#de.resolve({kind:"success",value:void 0});const a=Boolean(this.#ce.extraInfo)||this.#ne||Boolean(this.#ce.info&&!this.#ce.hasExtraInfo)||"responseStarted"===this.#re;this.#ce.info&&a&&(this.#ue.resolve({kind:"success",value:void 0}),this.#le.resolve({kind:"success",value:void 0}))}onRequestWillBeSentEvent(e){this.#ie.info=e,this.#fe(),this.#me()}onRequestWillBeSentExtraInfoEvent(e){this.#ie.extraInfo=e,this.#me()}onResponseReceivedExtraInfoEvent(e){this.#ce.extraInfo=e,this.#me()}onResponseReceivedEvent(e){this.#ce.hasExtraInfo=e.hasExtraInfo,this.#ce.info=e.response,this.#he(),this.#pe(),this.#me()}onServedFromCache(){this.#ne=!0,this.#me()}onLoadingFailedEvent(e){this.#de.resolve({kind:"success",value:void 0}),this.#ue.resolve({kind:"error",error:new Error("Network event loading failed")}),this.#le.resolve({kind:"error",error:new Error("Network event loading failed")}),this.#R.registerEvent({type:"event",method:be.ChromiumBidi.Network.EventNames.FetchError,params:{...this.#ge(),errorText:e.errorText}},this.#ye)}onRequestPaused(e,t){let a;a=void 0===e.responseErrorReason&&void 0===e.responseStatusCode?"beforeRequestSent":401===e.responseStatusCode&&"Unauthorized"===e.responseStatusText?"authRequired":"responseStarted";const r=(0,Ie.bidiNetworkHeadersFromCdpFetchHeaders)(e.responseHeaders);(0,Ce.assert)(this.requestId===e.networkId),t.addBlockedRequest(this.requestId,{request:e.requestId,phase:a,response:{url:e.request.url,protocol:"",status:e.responseStatusCode??0,statusText:e.responseStatusText??"",fromCache:!1,headers:r,mimeType:"",bytesReceived:0,headersSize:(0,Ie.computeHeadersSize)(r),bodySize:0,content:{size:0},authChallenge:void 0}}),this.#re=a,this.#me()}async failRequest(e,t){await this.#F.cdpClient.sendCommand("Fetch.failRequest",{requestId:e,errorReason:t}),this.#re=void 0}async continueRequest(e,t,a,r){await this.#F.cdpClient.sendCommand("Fetch.continueRequest",{requestId:e,url:t,method:a,headers:r}),this.#re=void 0}async continueResponse(e,t,a,r){await this.#F.cdpClient.sendCommand("Fetch.continueResponse",{requestId:e,responseCode:t,responsePhrase:a,responseHeaders:r}),this.#re=void 0}async continueWithAuth(e,t,a,r){await this.#F.cdpClient.sendCommand("Fetch.continueWithAuth",{requestId:e,authChallengeResponse:{response:t,username:a,password:r}}),this.#re=void 0}async provideResponse(e,t,a,r,n){await this.#F.cdpClient.sendCommand("Fetch.fulfillRequest",{requestId:e,responseCode:t,responsePhrase:a,responseHeaders:r,...n?{body:btoa(n)}:{}}),this.#re=void 0}dispose(){const e={kind:"error",error:new Error("Network processor detached")};this.#de.resolve(e),this.#ue.resolve(e),this.#le.resolve(e)}get#ye(){return this.#ie.info?.frameId??null}get statusCode(){return this.#ce.info?.status??this.#ce.extraInfo?.statusCode??-1}#ge(e){const t=void 0!==e&&e===this.#re,a=this.#oe.getNetworkIntercepts(this.#ae,e);return{isBlocked:t,context:this.#ye,navigation:this.#Se(),redirectCount:this.#se,request:this.#ve(),timestamp:Math.round(1e3*(this.#ie.info?.wallTime??0)),intercepts:t?a:void 0}}#Se(){return this.#ie.info&&this.#ie.info.loaderId&&this.#ie.info.loaderId===this.#ie.info.requestId?this.#ie.info.loaderId:null}#ve(){const e=this.#ie.extraInfo?Pe.#we(this.#ie.extraInfo.associatedCookies):[],t=(0,Ie.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#ie.info?.request.headers);return{request:this.#ie.info?.requestId??Pe.#te,url:this.#ie.info?.request.url??Pe.#te,method:this.#ie.info?.request.method??Pe.#te,headers:t,cookies:e,headersSize:(0,Ie.computeHeadersSize)(t),bodySize:0,timings:this.#be()}}#be(){return{timeOrigin:0,requestTime:0,redirectStart:0,redirectEnd:0,fetchStart:0,dnsStart:0,dnsEnd:0,connectStart:0,connectEnd:0,tlsStart:0,requestStart:0,responseStart:0,responseEnd:0}}#fe(){this.#Ce()||this.#R.registerPromiseEvent(this.#de.then((e=>{if("success"===e.kind)try{return{kind:"success",value:Object.assign(this.#xe(),{type:"event"})}}catch(e){return{kind:"error",error:e instanceof Error?e:new Error("Unknown")}}return e})),this.#ye,be.ChromiumBidi.Network.EventNames.BeforeRequestSent)}#xe(){return(0,Ce.assert)(this.#ie.info,"RequestWillBeSentEvent is not set"),{method:be.ChromiumBidi.Network.EventNames.BeforeRequestSent,params:{...this.#ge("beforeRequestSent"),initiator:{type:Pe.#Ie(this.#ie.info.initiator.type)}}}}#he(){this.#Ce()||this.#R.registerPromiseEvent(this.#ue.then((e=>{if("success"===e.kind)try{return{kind:"success",value:Object.assign(this.#Pe(),{type:"event"})}}catch(e){return{kind:"error",error:e instanceof Error?e:new Error("Unknown")}}return e})),this.#ye,be.ChromiumBidi.Network.EventNames.ResponseStarted)}#Pe(){(0,Ce.assert)(this.#ie.info,"RequestWillBeSentEvent is not set"),(0,Ce.assert)(this.#ce.info,"ResponseReceivedEvent is not set"),this.#ce.info.fromDiskCache&&(this.#ce.extraInfo=void 0);const e=(0,Ie.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#ce.info.headers);return{method:be.ChromiumBidi.Network.EventNames.ResponseStarted,params:{...this.#ge(),response:{url:this.#ce.info.url??Pe.#te,protocol:this.#ce.info.protocol??"",status:this.statusCode,statusText:this.#ce.info.statusText,fromCache:this.#ce.info.fromDiskCache||this.#ce.info.fromPrefetchCache||this.#ne,headers:e,mimeType:this.#ce.info.mimeType,bytesReceived:this.#ce.info.encodedDataLength,headersSize:(0,Ie.computeHeadersSize)(e),bodySize:0,content:{size:0}}}}}#pe(){this.#Ce()||this.#R.registerPromiseEvent(this.#le.then((e=>{if("success"===e.kind)try{return{kind:"success",value:Object.assign(this.#ke(),{type:"event"})}}catch(e){return{kind:"error",error:e instanceof Error?e:new Error("Unknown")}}return e})),this.#ye,be.ChromiumBidi.Network.EventNames.ResponseCompleted)}#ke(){(0,Ce.assert)(this.#ie.info,"RequestWillBeSentEvent is not set"),(0,Ce.assert)(this.#ce.info,"ResponseReceivedEvent is not set"),this.#ce.info.fromDiskCache&&(this.#ce.extraInfo=void 0);const e=(0,Ie.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#ce.info.headers);return{method:be.ChromiumBidi.Network.EventNames.ResponseCompleted,params:{...this.#ge(),response:{url:this.#ce.info.url??Pe.#te,protocol:this.#ce.info.protocol??"",status:this.statusCode,statusText:this.#ce.info.statusText,fromCache:this.#ce.info.fromDiskCache||this.#ce.info.fromPrefetchCache||this.#ne,headers:e,mimeType:this.#ce.info.mimeType,bytesReceived:this.#ce.info.encodedDataLength,headersSize:(0,Ie.computeHeadersSize)(e),bodySize:0,content:{size:0}}}}}#Ce(){return this.#ie.info?.request.url.endsWith("/favicon.ico")??!1}static#Ie(e){switch(e){case"parser":case"script":case"preflight":return e;default:return"other"}}static#we(e){return e.filter((({blockedReasons:e})=>!Array.isArray(e)||0===e.length)).map((({cookie:e})=>({name:e.name,value:{type:"string",value:e.value},domain:e.domain,path:e.path,expires:e.expires,size:e.size,httpOnly:e.httpOnly,secure:e.secure,sameSite:Pe.#Re(e.sameSite)})))}static#Re(e){switch(e){case"Strict":return"strict";case"Lax":return"lax";default:return"none"}}}ve.NetworkRequest=Pe,Object.defineProperty(Se,"__esModule",{value:!0}),Se.NetworkManager=void 0;const ke=ve;class Re{#F;#R;#oe;constructor(e,t,a){this.#F=e,this.#R=t,this.#oe=a}get cdpTarget(){return this.#F}#_e(e,t){let a=this.#oe.getRequest(e);return a||(a=new ke.NetworkRequest(e,this.#R,this.#oe,this.#F,t),this.#oe.addRequest(a),a)}static create(e,t,a){const r=new Re(e,t,a);return e.browserCdpClient.on("Target.detachedFromTarget",(t=>{e.cdpClient.sessionId===t.sessionId&&r.#oe.disposeRequestMap()})),e.cdpClient.on("Network.requestWillBeSent",(e=>{const t=r.#oe.getRequest(e.requestId);t&&t.isRedirecting()?(t.handleRedirect(e),r.#oe.deleteRequest(e.requestId),r.#_e(e.requestId,t.redirectCount+1).onRequestWillBeSentEvent(e)):t?t.onRequestWillBeSentEvent(e):r.#_e(e.requestId).onRequestWillBeSentEvent(e)})),e.cdpClient.on("Network.requestWillBeSentExtraInfo",(e=>{r.#_e(e.requestId).onRequestWillBeSentExtraInfoEvent(e)})),e.cdpClient.on("Network.responseReceived",(e=>{r.#_e(e.requestId).onResponseReceivedEvent(e)})),e.cdpClient.on("Network.responseReceivedExtraInfo",(e=>{r.#_e(e.requestId).onResponseReceivedExtraInfoEvent(e)})),e.cdpClient.on("Network.requestServedFromCache",(e=>{r.#_e(e.requestId).onServedFromCache()})),e.cdpClient.on("Network.loadingFailed",(e=>{r.#_e(e.requestId).onLoadingFailedEvent(e)})),e.cdpClient.on("Fetch.requestPaused",(e=>{e.networkId&&r.#_e(e.networkId).onRequestPaused(e,r.#oe)})),r}}Se.NetworkManager=Re,Object.defineProperty(ne,"__esModule",{value:!0}),ne.CdpTarget=void 0;const _e=O,Ee=se,Te=Se;class Ne{#Ee;#k;#o;#Te;#R;#Ne;#oe;#je=new _e.Deferred;static create(e,t,a,r,n,s,o,i){const c=new Ne(e,t,a,r,s,o,i);return Ee.LogManager.create(c,n,s),Te.NetworkManager.create(c,s,i),c.#Oe(),c.#Me(),c}constructor(e,t,a,r,n,s,o){this.#Ee=e,this.#k=t,this.#Te=r,this.#R=n,this.#Ne=s,this.#oe=o,this.#o=a}get targetUnblocked(){return this.#je}get targetId(){return this.#Ee}get cdpClient(){return this.#k}get browserCdpClient(){return this.#o}get cdpSessionId(){return this.#Te}async fetchEnable(){await this.#k.sendCommand("Fetch.enable",this.#oe.getFetchEnableParams())}async fetchDisable(){await this.#k.sendCommand("Fetch.disable")}async#Me(){try{await Promise.all([this.#k.sendCommand("Runtime.enable"),this.#k.sendCommand("Page.enable"),this.#k.sendCommand("Page.setLifecycleEventsEnabled",{enabled:!0}),this.#k.sendCommand("Network.enable"),this.fetchEnable(),this.#k.sendCommand("Target.setAutoAttach",{autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),this.#Ae(),this.#k.sendCommand("Runtime.runIfWaitingForDebugger")])}catch(e){if(!this.#k.isCloseError(e))return void this.#je.resolve({kind:"error",error:e})}this.#je.resolve({kind:"success",value:void 0})}#Oe(){this.#k.on("*",((e,t)=>{"string"==typeof e&&this.#R.registerEvent({type:"event",method:`cdp.${e}`,params:{event:e,params:t,session:this.#Te}},null)}))}getChannels(){return this.#Ne.find().flatMap((e=>e.channels))}async#Ae(){for(const e of this.#Ne.find({global:!0}))await e.initInTarget(this,!0)}}ne.CdpTarget=Ne,Object.defineProperty(T,"__esModule",{value:!0}),T.BrowsingContextProcessor=void 0;const je=g,Oe=l,Me=N,Ae=ne;T.BrowsingContextProcessor=class{#o;#c;#De;#R;#i;#oe;#Ne;#w;#t;constructor(e,t,a,r,n,s,o,i,c){this.#c=e,this.#o=t,this.#De=a,this.#R=r,this.#i=n,this.#Ne=i,this.#oe=o,this.#w=s,this.#t=c,this.#Oe(t)}getTree(e){return{contexts:(void 0===e.root?this.#i.getTopLevelContexts():[this.#i.getContext(e.root)]).map((t=>t.serializeToBidiValue(e.maxDepth??Number.MAX_VALUE)))}}async create(e){let t,a;if(void 0!==e.referenceContext&&(t=this.#i.getContext(e.referenceContext),!t.isTopLevelContext()))throw new je.InvalidArgumentException("referenceContext should be a top-level context");switch(e.type){case"tab":a=await this.#o.sendCommand("Target.createTarget",{url:"about:blank",newWindow:!1});break;case"window":a=await this.#o.sendCommand("Target.createTarget",{url:"about:blank",newWindow:!0})}const r=a.targetId,n=this.#i.getContext(r);return await n.lifecycleLoaded(),{context:n.id}}navigate(e){return this.#i.getContext(e.context).navigate(e.url,e.wait??"none")}reload(e){return this.#i.getContext(e.context).reload(e.ignoreCache??!1,e.wait??"none")}async activate(e){const t=this.#i.getContext(e.context);if(!t.isTopLevelContext())throw new je.InvalidArgumentException("Activation is only supported on the top-level context");return await t.activate(),{}}async captureScreenshot(e){const t=this.#i.getContext(e.context);return await t.captureScreenshot(e)}async print(e){const t=this.#i.getContext(e.context);return await t.print(e)}async setViewport(e){const t=this.#i.getContext(e.context);if(!t.isTopLevelContext())throw new je.InvalidArgumentException("Emulating viewport is only supported on the top-level context");return await t.setViewport(e.viewport,e.devicePixelRatio),{}}async handleUserPrompt(e){const t=this.#i.getContext(e.context);return await t.handleUserPrompt(e),{}}async close(e){const t=this.#i.getContext(e.context);if(!t.isTopLevelContext())throw new je.InvalidArgumentException(`Non top-level browsing context ${t.id} cannot be closed.`);try{const a=new Promise((t=>{const a=r=>{r.targetId===e.context&&(this.#o.off("Target.detachedFromTarget",a),t())};this.#o.on("Target.detachedFromTarget",a)}));await t.close(),await a}catch(e){if(-32e3!==e.code||"Not attached to an active page"!==e.message)throw e}return{}}#Oe(e){e.on("Target.attachedToTarget",(t=>{this.#Be(t,e)})),e.on("Target.detachedFromTarget",(e=>{this.#ze(e)})),e.on("Target.targetInfoChanged",(e=>{this.#Le(e)})),e.on("Page.frameAttached",(e=>{this.#Ze(e)})),e.on("Page.frameDetached",(e=>{this.#Ue(e)}))}#Ze(e){const t=this.#i.findContext(e.parentFrameId);void 0!==t&&Me.BrowsingContextImpl.create(t.cdpTarget,this.#w,e.frameId,e.parentFrameId,this.#R,this.#i,this.#t)}#Ue(e){"swap"!==e.reason&&this.#i.findContext(e.frameId)?.dispose()}#Be(e,t){const{sessionId:a,targetInfo:r}=e,n=this.#c.getCdpClient(a);if(!this.#qe(r))return void n.sendCommand("Runtime.runIfWaitingForDebugger").then((()=>t.sendCommand("Target.detachFromTarget",e))).catch((e=>this.#t?.(Oe.LogType.debugError,e)));this.#t?.(Oe.LogType.debugInfo,"AttachedToTarget event received:",e),this.#Oe(n);const s=this.#i.findContext(r.targetId),o=Ae.CdpTarget.create(r.targetId,n,this.#o,a,this.#w,this.#R,this.#Ne,this.#oe);s?s.updateCdpTarget(o):Me.BrowsingContextImpl.create(o,this.#w,r.targetId,null,this.#R,this.#i,this.#t)}#ze(e){const t=e.targetId;this.#i.findContext(t)?.dispose(),this.#Ne.find({targetId:t}).map((e=>e.dispose(t)))}#Le(e){const t=e.targetInfo.targetId;this.#i.findContext(t)?.onTargetInfoChanged(e)}#qe(e){return e.targetId!==this.#De&&["page","iframe"].includes(e.type)}};var De={},Be={},ze={};Object.defineProperty(ze,"__esModule",{value:!0}),ze.WheelSource=ze.PointerSource=ze.KeySource=ze.NoneSource=void 0;ze.NoneSource=class{type="none"};ze.KeySource=class{type="key";pressed=new Set;#Ve=0;get modifiers(){return this.#Ve}get alt(){return 1==(1&this.#Ve)}set alt(e){this.#Fe(e,1)}get ctrl(){return 2==(2&this.#Ve)}set ctrl(e){this.#Fe(e,2)}get meta(){return 4==(4&this.#Ve)}set meta(e){this.#Fe(e,4)}get shift(){return 8==(8&this.#Ve)}set shift(e){this.#Fe(e,8)}#Fe(e,t){e?this.#Ve|=t:this.#Ve&=~t}};ze.PointerSource=class{type="pointer";subtype;pointerId;pressed=new Set;x=0;y=0;constructor(e,t){this.pointerId=e,this.subtype=t}get buttons(){let e=0;for(const t of this.pressed)switch(t){case 0:e|=1;break;case 1:e|=4;break;case 2:e|=2;break;case 3:e|=8;break;case 4:e|=16}return e}static ClickContext=class e{static#$e=500;static#Ke=2;count=0;#We;#He;#Je;constructor(e,t,a){this.#We=e,this.#He=t,this.#Je=a}compare(t){return t.#Je-this.#Je>e.#$e||Math.abs(t.#We-this.#We)>e.#Ke||Math.abs(t.#He-this.#He)>e.#Ke}};#Ge=new Map;setClickCount(e,t){let a=this.#Ge.get(e);return a&&!a.compare(t)||(a=t),++a.count,this.#Ge.set(e,a),a.count}getClickCount(e){return this.#Ge.get(e)?.count??0}};ze.WheelSource=class{type="wheel"};var Le={};Object.defineProperty(Le,"__esModule",{value:!0}),Le.getKeyLocation=Le.getKeyCode=Le.getNormalizedKey=void 0,Le.getNormalizedKey=function(e){switch(e){case"\ue000":return"Unidentified";case"\ue001":return"Cancel";case"\ue002":return"Help";case"\ue003":return"Backspace";case"\ue004":return"Tab";case"\ue005":return"Clear";case"\ue006":return"Return";case"\ue007":return"Enter";case"\ue008":case"\ue050":return"Shift";case"\ue009":case"\ue051":return"Control";case"\ue00a":case"\ue052":return"Alt";case"\ue00b":return"Pause";case"\ue00c":return"Escape";case"\ue00d":return" ";case"\ue00e":case"\ue054":return"PageUp";case"\ue00f":case"\ue055":return"PageDown";case"\ue010":case"\ue056":return"End";case"\ue011":case"\ue057":return"Home";case"\ue012":case"\ue058":return"ArrowLeft";case"\ue013":case"\ue059":return"ArrowUp";case"\ue014":case"\ue05a":return"ArrowRight";case"\ue015":case"\ue05b":return"ArrowDown";case"\ue016":case"\ue05c":return"Insert";case"\ue017":case"\ue05d":return"Delete";case"\ue018":return";";case"\ue019":return"=";case"\ue01a":return"0";case"\ue01b":return"1";case"\ue01c":return"2";case"\ue01d":return"3";case"\ue01e":return"4";case"\ue01f":return"5";case"\ue020":return"6";case"\ue021":return"7";case"\ue022":return"8";case"\ue023":return"9";case"\ue024":return"*";case"\ue025":return"+";case"\ue026":return",";case"\ue027":return"-";case"\ue028":return".";case"\ue029":return"/";case"\ue031":return"F1";case"\ue032":return"F2";case"\ue033":return"F3";case"\ue034":return"F4";case"\ue035":return"F5";case"\ue036":return"F6";case"\ue037":return"F7";case"\ue038":return"F8";case"\ue039":return"F9";case"\ue03a":return"F10";case"\ue03b":return"F11";case"\ue03c":return"F12";case"\ue03d":case"\ue053":return"Meta";case"\ue040":return"ZenkakuHankaku";default:return e}},Le.getKeyCode=function(e){switch(e){case"`":case"~":return"Backquote";case"\\":case"|":return"Backslash";case"\ue003":return"Backspace";case"[":case"{":return"BracketLeft";case"]":case"}":return"BracketRight";case",":case"<":return"Comma";case"0":case")":return"Digit0";case"1":case"!":return"Digit1";case"2":case"@":return"Digit2";case"3":case"#":return"Digit3";case"4":case"$":return"Digit4";case"5":case"%":return"Digit5";case"6":case"^":return"Digit6";case"7":case"&":return"Digit7";case"8":case"*":return"Digit8";case"9":case"(":return"Digit9";case"=":case"+":return"Equal";case"a":case"A":return"KeyA";case"b":case"B":return"KeyB";case"c":case"C":return"KeyC";case"d":case"D":return"KeyD";case"e":case"E":return"KeyE";case"f":case"F":return"KeyF";case"g":case"G":return"KeyG";case"h":case"H":return"KeyH";case"i":case"I":return"KeyI";case"j":case"J":return"KeyJ";case"k":case"K":return"KeyK";case"l":case"L":return"KeyL";case"m":case"M":return"KeyM";case"n":case"N":return"KeyN";case"o":case"O":return"KeyO";case"p":case"P":return"KeyP";case"q":case"Q":return"KeyQ";case"r":case"R":return"KeyR";case"s":case"S":return"KeyS";case"t":case"T":return"KeyT";case"u":case"U":return"KeyU";case"v":case"V":return"KeyV";case"w":case"W":return"KeyW";case"x":case"X":return"KeyX";case"y":case"Y":return"KeyY";case"z":case"Z":return"KeyZ";case"-":case"_":return"Minus";case".":return"Period";case"'":case'"':return"Quote";case";":case":":return"Semicolon";case"/":case"?":return"Slash";case"\ue00a":return"AltLeft";case"\ue052":return"AltRight";case"\ue009":return"ControlLeft";case"\ue051":return"ControlRight";case"\ue006":return"Enter";case"\ue03d":return"MetaLeft";case"\ue053":return"MetaRight";case"\ue008":return"ShiftLeft";case"\ue050":return"ShiftRight";case" ":case"\ue00d":return"Space";case"\ue004":return"Tab";case"\ue017":return"Delete";case"\ue010":return"End";case"\ue002":return"Help";case"\ue011":return"Home";case"\ue016":return"Insert";case"\ue00f":return"PageDown";case"\ue00e":return"PageUp";case"\ue015":return"ArrowDown";case"\ue012":return"ArrowLeft";case"\ue014":return"ArrowRight";case"\ue013":return"ArrowUp";case"\ue00c":return"Escape";case"\ue031":return"F1";case"\ue032":return"F2";case"\ue033":return"F3";case"\ue034":return"F4";case"\ue035":return"F5";case"\ue036":return"F6";case"\ue037":return"F7";case"\ue038":return"F8";case"\ue039":return"F9";case"\ue03a":return"F10";case"\ue03b":return"F11";case"\ue03c":return"F12";case"\ue01a":case"\ue05c":return"Numpad0";case"\ue01b":case"\ue056":return"Numpad1";case"\ue01c":case"\ue05b":return"Numpad2";case"\ue01d":case"\ue055":return"Numpad3";case"\ue01e":case"\ue058":return"Numpad4";case"\ue01f":return"Numpad5";case"\ue020":case"\ue05a":return"Numpad6";case"\ue021":case"\ue057":return"Numpad7";case"\ue022":case"\ue059":return"Numpad8";case"\ue023":case"\ue054":return"Numpad9";case"\ue025":return"NumpadAdd";case"\ue026":return"NumpadComma";case"\ue028":case"\ue05d":return"NumpadDecimal";case"\ue029":return"NumpadDivide";case"\ue007":return"NumpadEnter";case"\ue024":return"NumpadMultiply";case"\ue027":return"NumpadSubtract";default:return}},Le.getKeyLocation=function(e){switch(e){case"\ue007":case"\ue008":case"\ue009":case"\ue00a":case"\ue03d":return 1;case"\ue01a":case"\ue01b":case"\ue01c":case"\ue01d":case"\ue01e":case"\ue01f":case"\ue020":case"\ue021":case"\ue022":case"\ue023":case"\ue024":case"\ue025":case"\ue026":case"\ue027":case"\ue028":case"\ue029":case"\ue054":case"\ue055":case"\ue056":case"\ue057":case"\ue058":case"\ue059":case"\ue05a":case"\ue05b":case"\ue05c":case"\ue05d":return 3;case"\ue050":case"\ue051":case"\ue052":case"\ue053":return 2;default:return 0}};var Ze={};Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.KeyToKeyCode=void 0,Ze.KeyToKeyCode={0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,Abort:3,Help:6,Backspace:8,Tab:9,Numpad5:12,NumpadEnter:13,Enter:13,"\\r":13,"\\n":13,ShiftLeft:16,ShiftRight:16,ControlLeft:17,ControlRight:17,AltLeft:18,AltRight:18,Pause:19,CapsLock:20,Escape:27,Convert:28,NonConvert:29,Space:32,Numpad9:33,PageUp:33,Numpad3:34,PageDown:34,End:35,Numpad1:35,Home:36,Numpad7:36,ArrowLeft:37,Numpad4:37,Numpad8:38,ArrowUp:38,ArrowRight:39,Numpad6:39,Numpad2:40,ArrowDown:40,Select:41,Open:43,PrintScreen:44,Insert:45,Numpad0:45,Delete:46,NumpadDecimal:46,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,KeyA:65,KeyB:66,KeyC:67,KeyD:68,KeyE:69,KeyF:70,KeyG:71,KeyH:72,KeyI:73,KeyJ:74,KeyK:75,KeyL:76,KeyM:77,KeyN:78,KeyO:79,KeyP:80,KeyQ:81,KeyR:82,KeyS:83,KeyT:84,KeyU:85,KeyV:86,KeyW:87,KeyX:88,KeyY:89,KeyZ:90,MetaLeft:91,MetaRight:92,ContextMenu:93,NumpadMultiply:106,NumpadAdd:107,NumpadSubtract:109,NumpadDivide:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,F16:127,F17:128,F18:129,F19:130,F20:131,F21:132,F22:133,F23:134,F24:135,NumLock:144,ScrollLock:145,AudioVolumeMute:173,AudioVolumeDown:174,AudioVolumeUp:175,MediaTrackNext:176,MediaTrackPrevious:177,MediaStop:178,MediaPlayPause:179,Semicolon:186,Equal:187,NumpadEqual:187,Comma:188,Minus:189,Period:190,Slash:191,Backquote:192,BracketLeft:219,Backslash:220,BracketRight:221,Quote:222,AltGraph:225,Props:247,Cancel:3,Clear:12,Shift:16,Control:17,Alt:18,Accept:30,ModeChange:31," ":32,Print:42,Execute:43,"\\u0000":46,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,Meta:91,"*":106,"+":107,"-":109,"/":111,";":186,"=":187,",":188,".":190,"`":192,"[":219,"\\\\":220,"]":221,"'":222,Attn:246,CrSel:247,ExSel:248,EraseEof:249,Play:250,ZoomOut:251,")":48,"!":49,"@":50,"#":51,$:52,"%":53,"^":54,"&":55,"(":57,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,":":186,"<":188,_:189,">":190,"?":191,"~":192,"{":219,"|":220,"}":221,'"':222,Camera:44,EndCall:95,VolumeDown:182,VolumeUp:183},Object.defineProperty(Be,"__esModule",{value:!0}),Be.ActionDispatcher=void 0;const Ue=g,qe=j,Ve=ze,Fe=Le,$e=Ze,Ke=(e=>{const t=e.getClientRects()[0],a=Math.max(0,Math.min(t.x,t.x+t.width)),r=Math.min(window.innerWidth,Math.max(t.x,t.x+t.width)),n=Math.max(0,Math.min(t.y,t.y+t.height));return[a+(r-a>>1),n+(Math.min(window.innerHeight,Math.max(t.y,t.y+t.height))-n>>1)]}).toString(),We=(()=>navigator.platform.toLowerCase().includes("mac")).toString();Be.ActionDispatcher=class{static isMacOS=async e=>{const t=await(await e.getOrCreateSandbox(void 0)).callFunction(We,{type:"undefined"},[],!1,"none",{});return(0,qe.assert)("exception"!==t.type),(0,qe.assert)("boolean"===t.result.type),t.result.value};#Xe=0;#Ye=0;#Qe;#ye;#et;constructor(e,t,a){this.#Qe=e,this.#ye=t,this.#et=a}async dispatchActions(e){await this.#Qe.queue.run((async()=>{for(const t of e)await this.dispatchTickActions(t)}))}async dispatchTickActions(e){this.#Xe=performance.now(),this.#Ye=0;for(const{action:t}of e)"duration"in t&&void 0!==t.duration&&(this.#Ye=Math.max(this.#Ye,t.duration));const t=[new Promise((e=>setTimeout(e,this.#Ye)))];for(const a of e)t.push(this.#tt(a));await Promise.all(t)}async#tt({id:e,action:t}){const a=this.#Qe.get(e),r=this.#Qe.getGlobalKeyState();switch(t.type){case"keyDown":await this.#at(a,t),this.#Qe.cancelList.push({id:e,action:{...t,type:"keyUp"}});break;case"keyUp":await this.#rt(a,t);break;case"pause":break;case"pointerDown":await this.#nt(a,r,t),this.#Qe.cancelList.push({id:e,action:{...t,type:"pointerUp"}});break;case"pointerMove":await this.#st(a,r,t);break;case"pointerUp":await this.#ot(a,r,t);break;case"scroll":await this.#it(a,r,t)}}#nt(e,t,a){const{button:r}=a;if(e.pressed.has(r))return;e.pressed.add(r);const{x:n,y:s,subtype:o}=e,{width:i,height:c,pressure:d,twist:u,tangentialPressure:l}=a,{tiltX:h,tiltY:p}=Xe(a),{modifiers:m}=t;switch(o){case"mouse":case"pen":return this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mousePressed",x:n,y:s,modifiers:m,button:Ge(r),buttons:e.buttons,clickCount:e.setClickCount(r,new Ve.PointerSource.ClickContext(n,s,performance.now())),pointerType:o,tangentialPressure:l,tiltX:h,tiltY:p,twist:u,force:d});case"touch":return this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:n,y:s,...Ye(i??1,c??1),tangentialPressure:l,tiltX:h,tiltY:p,twist:u,force:d,id:e.pointerId}],modifiers:m})}}#ot(e,t,a){const{button:r}=a;if(!e.pressed.has(r))return;e.pressed.delete(r);const{x:n,y:s,subtype:o}=e,{modifiers:i}=t;switch(o){case"mouse":case"pen":return this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseReleased",x:n,y:s,modifiers:i,button:Ge(r),buttons:e.buttons,clickCount:e.getClickCount(r),pointerType:o});case"touch":return this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[{x:n,y:s,id:e.pointerId}],modifiers:i})}}async#st(e,t,a){const{x:r,y:n,subtype:s}=e,{width:o,height:i,pressure:c,twist:d,tangentialPressure:u,x:l,y:h,origin:p="viewport",duration:m=this.#Ye}=a,{tiltX:f,tiltY:g}=Xe(a),{targetX:y,targetY:S}=await this.#ct(p,l,h,r,n);if(y<0||S<0)throw new Ue.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${y}, y: ${S})`);let v;do{const a=m>0?(performance.now()-this.#Xe)/m:1;let l,h;if(v=a>=1,v?(l=y,h=S):(l=Math.round(a*(y-r)+r),h=Math.round(a*(S-n)+n)),e.x!==l||e.y!==h){const{modifiers:a}=t;switch(s){case"mouse":await this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseMoved",x:l,y:h,modifiers:a,clickCount:0,button:Ge(e.pressed.values().next().value??5),buttons:e.buttons,pointerType:s,tangentialPressure:u,tiltX:f,tiltY:g,twist:d,force:c});break;case"pen":0!==e.pressed.size&&await this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseMoved",x:l,y:h,modifiers:a,clickCount:0,button:Ge(e.pressed.values().next().value??5),buttons:e.buttons,pointerType:s,tangentialPressure:u,tiltX:f,tiltY:g,twist:d,force:c});break;case"touch":0!==e.pressed.size&&await this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:l,y:h,...Ye(o??1,i??1),tangentialPressure:u,tiltX:f,tiltY:g,twist:d,force:c,id:e.pointerId}],modifiers:a})}e.x=l,e.y=h}}while(!v)}async#ct(e,t,a,r,n){let s,o;switch(e){case"viewport":s=t,o=a;break;case"pointer":s=r+t,o=n+a;break;default:{const{x:r,y:n}=await async function(e,t){const a=await e.getOrCreateSandbox(void 0),r=await a.callFunction(Ke,{type:"undefined"},[t],!1,"none",{});if("exception"===r.type)throw new Ue.NoSuchElementException(`Origin element ${t.sharedId} was not found`);(0,qe.assert)("array"===r.result.type),(0,qe.assert)("number"===r.result.value?.[0]?.type),(0,qe.assert)("number"===r.result.value?.[1]?.type);const{result:{value:[{value:n},{value:s}]}}=r;return{x:n,y:s}}(this.#ye,e.element);s=r+t,o=n+a;break}}return{targetX:s,targetY:o}}async#it(e,t,a){const{deltaX:r,deltaY:n,x:s,y:o,origin:i="viewport",duration:c=this.#Ye}=a;if("pointer"===i)throw new Ue.InvalidArgumentException('"pointer" origin is invalid for scrolling.');const{targetX:d,targetY:u}=await this.#ct(i,s,o,0,0);if(d<0||u<0)throw new Ue.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${d}, y: ${u})`);let l,h=0,p=0;do{const e=c>0?(performance.now()-this.#Xe)/c:1;let a,s;if(l=e>=1,l?(a=r-h,s=n-p):(a=Math.round(e*r-h),s=Math.round(e*n-p)),0!==a||0!==s){const{modifiers:e}=t;await this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseWheel",deltaX:a,deltaY:s,x:d,y:u,modifiers:e}),h+=a,p+=s}}while(!l)}async#at(e,t){if([...t.value].length>1)throw new Ue.InvalidArgumentException(`Invalid key value: ${t.value}`);const a=t.value,r=(0,Fe.getNormalizedKey)(a),n=e.pressed.has(r),s=(0,Fe.getKeyCode)(a),o=(0,Fe.getKeyLocation)(a);switch(r){case"Alt":e.alt=!0;break;case"Shift":e.shift=!0;break;case"Control":e.ctrl=!0;break;case"Meta":e.meta=!0}e.pressed.add(r);const{modifiers:i}=e,c=He(r,e),d=Je(s??"",e)??c;let u;if(this.#et&&e.meta)switch(s){case"KeyA":u="SelectAll";break;case"KeyC":u="Copy";break;case"KeyV":u=e.shift?"PasteAndMatchStyle":"Paste";break;case"KeyX":u="Cut";break;case"KeyZ":u=e.shift?"Redo":"Undo"}const l=[this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchKeyEvent",{type:d?"keyDown":"rawKeyDown",windowsVirtualKeyCode:$e.KeyToKeyCode[r],key:r,code:s,text:d,unmodifiedText:c,autoRepeat:n,isSystemKey:e.alt||void 0,location:o<3?o:void 0,isKeypad:3===o,modifiers:i,commands:u?[u]:void 0})];"Escape"===r&&(e.alt||(!this.#et||e.ctrl||e.meta)&&this.#et||l.push(this.#ye.cdpTarget.cdpClient.sendCommand("Input.cancelDragging"))),await Promise.all(l)}#rt(e,t){if([...t.value].length>1)throw new Ue.InvalidArgumentException(`Invalid key value: ${t.value}`);const a=t.value,r=(0,Fe.getNormalizedKey)(a);if(!e.pressed.has(r))return;const n=(0,Fe.getKeyCode)(a),s=(0,Fe.getKeyLocation)(a);switch(r){case"Alt":e.alt=!1;break;case"Shift":e.shift=!1;break;case"Control":e.ctrl=!1;break;case"Meta":e.meta=!1}e.pressed.delete(r);const{modifiers:o}=e,i=He(r,e),c=Je(n??"",e)??i;return this.#ye.cdpTarget.cdpClient.sendCommand("Input.dispatchKeyEvent",{type:"keyUp",windowsVirtualKeyCode:$e.KeyToKeyCode[r],key:r,code:n,text:c,unmodifiedText:i,location:s<3?s:void 0,isSystemKey:e.alt||void 0,isKeypad:3===s,modifiers:o})}};const He=(e,t)=>"Enter"===e?"\r":1===[...e].length?t.shift?e.toLocaleUpperCase("en-US"):e:void 0,Je=(e,t)=>{if(t.ctrl){switch(e){case"Digit2":if(t.shift)return"\0";break;case"KeyA":return"\x01";case"KeyB":return"\x02";case"KeyC":return"\x03";case"KeyD":return"\x04";case"KeyE":return"\x05";case"KeyF":return"\x06";case"KeyG":return"\x07";case"KeyH":return"\b";case"KeyI":return"\t";case"KeyJ":return"\n";case"KeyK":return"\v";case"KeyL":return"\f";case"KeyM":return"\r";case"KeyN":return"\x0e";case"KeyO":return"\x0f";case"KeyP":return"\x10";case"KeyQ":return"\x11";case"KeyR":return"\x12";case"KeyS":return"\x13";case"KeyT":return"\x14";case"KeyU":return"\x15";case"KeyV":return"\x16";case"KeyW":return"\x17";case"KeyX":return"\x18";case"KeyY":return"\x19";case"KeyZ":return"\x1a";case"BracketLeft":return"\x1b";case"Backslash":return"\x1c";case"BracketRight":return"\x1d";case"Digit6":if(t.shift)return"\x1e";break;case"Minus":return"\x1f"}return""}if(t.alt)return""};function Ge(e){switch(e){case 0:return"left";case 1:return"middle";case 2:return"right";case 3:return"back";case 4:return"forward";default:return"none"}}function Xe(e){const t=e.altitudeAngle??0,a=e.azimuthAngle??0;let r=0,n=0;if(0===t&&(0!==a&&a!==2*Math.PI||(r=Math.PI/2),a===Math.PI/2&&(n=Math.PI/2),a===Math.PI&&(r=-Math.PI/2),a===3*Math.PI/2&&(n=-Math.PI/2),a>0&&a<Math.PI/2&&(r=Math.PI/2,n=Math.PI/2),a>Math.PI/2&&a<Math.PI&&(r=-Math.PI/2,n=Math.PI/2),a>Math.PI&&a<3*Math.PI/2&&(r=-Math.PI/2,n=-Math.PI/2),a>3*Math.PI/2&&a<2*Math.PI&&(r=Math.PI/2,n=-Math.PI/2)),0!==t){const e=Math.tan(t);r=Math.atan(Math.cos(a)/e),n=Math.atan(Math.sin(a)/e)}const s=180/Math.PI;return{tiltX:Math.round(r*s),tiltY:Math.round(n*s)}}function Ye(e,t){return{radiusX:e?e/2:.5,radiusY:t?t/2:.5}}var Qe={},et={},tt={};Object.defineProperty(tt,"__esModule",{value:!0}),tt.Mutex=void 0;tt.Mutex=class{#dt=!1;#ut=[];acquire(){const e={resolved:!1};return this.#dt?new Promise((t=>{this.#ut.push((()=>t(this.#lt.bind(this,e))))})):(this.#dt=!0,Promise.resolve(this.#lt.bind(this,e)))}#lt(e){if(e.resolved)throw new Error("Cannot release more than once.");e.resolved=!0;const t=this.#ut.shift();t?t():this.#dt=!1}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}},Object.defineProperty(et,"__esModule",{value:!0}),et.InputState=void 0;const at=g,rt=tt,nt=ze;et.InputState=class{cancelList=[];#ht=new Map;#pt=new rt.Mutex;getOrCreate(e,t,a){let r=this.#ht.get(e);if(!r){switch(t){case"none":r=new nt.NoneSource;break;case"key":r=new nt.KeySource;break;case"pointer":{let e="mouse"===a?0:2;const t=new Set;for(const[,e]of this.#ht)"pointer"===e.type&&t.add(e.pointerId);for(;t.has(e);)++e;r=new nt.PointerSource(e,a);break}case"wheel":r=new nt.WheelSource;break;default:throw new at.InvalidArgumentException(`Expected "none", "key", "pointer", or "wheel". Found unknown source type ${t}.`)}return this.#ht.set(e,r),r}if(r.type!==t)throw new at.InvalidArgumentException(`Input source type of ${e} is ${r.type}, but received ${t}.`);return r}get(e){const t=this.#ht.get(e);if(!t)throw new at.UnknownErrorException("Internal error.");return t}getGlobalKeyState(){const e=new nt.KeySource;for(const[,t]of this.#ht)if("key"===t.type){for(const a of t.pressed)e.pressed.add(a);e.alt||=t.alt,e.ctrl||=t.ctrl,e.meta||=t.meta,e.shift||=t.shift}return e}get queue(){return this.#pt}},Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.InputStateManager=void 0;const st=j,ot=et;class it extends WeakMap{get(e){return(0,st.assert)(e.isTopLevelContext()),this.has(e)||this.set(e,new ot.InputState),super.get(e)}}Qe.InputStateManager=it,Object.defineProperty(De,"__esModule",{value:!0}),De.InputProcessor=void 0;const ct=g,dt=Be,ut=Qe;De.InputProcessor=class{#i;#mt=new ut.InputStateManager;constructor(e){this.#i=e}async performActions(e){const t=this.#i.getContext(e.context),a=this.#mt.get(t.top),r=this.#ft(e,a),n=new dt.ActionDispatcher(a,t,await dt.ActionDispatcher.isMacOS(t).catch((()=>!1)));return await n.dispatchActions(r),{}}async releaseActions(e){const t=this.#i.getContext(e.context),a=t.top,r=this.#mt.get(a),n=new dt.ActionDispatcher(r,t,await dt.ActionDispatcher.isMacOS(t).catch((()=>!1)));return await n.dispatchTickActions(r.cancelList.reverse()),this.#mt.delete(a),{}}#ft(e,t){const a=[];for(const r of e.actions){switch(r.type){case"pointer":{r.parameters??={pointerType:"mouse"},r.parameters.pointerType??="mouse";const e=t.getOrCreate(r.id,"pointer",r.parameters.pointerType);if(e.subtype!==r.parameters.pointerType)throw new ct.InvalidArgumentException(`Expected input source ${r.id} to be ${e.subtype}; got ${r.parameters.pointerType}.`);break}default:t.getOrCreate(r.id,r.type)}const e=r.actions.map((e=>({id:r.id,action:e})));for(let t=0;t<e.length;t++)a.length===t&&a.push([]),a[t].push(e[t])}return a}};var lt={},ht={},pt={},mt=Object.defineProperty,ft=Object.getOwnPropertyDescriptor,gt=Object.getOwnPropertyNames,yt=Object.prototype.hasOwnProperty,St={};((e,t)=>{for(var a in t)mt(e,a,{get:t[a],enumerable:!0})})(St,{URLPattern:()=>na});var vt,wt=(vt=St,((e,t,a,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of gt(t))!yt.call(e,n)&&n!==a&&mt(e,n,{get:()=>t[n],enumerable:!(r=ft(t,n))||r.enumerable});return e})(mt({},"__esModule",{value:!0}),vt)),bt=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(e,t,a,r,n,s){this.type=e,this.name=t,this.prefix=a,this.value=r,this.suffix=n,this.modifier=s}hasCustomName(){return""!==this.name&&"number"!=typeof this.name}},Ct=/[$_\p{ID_Start}]/u,xt=/[$_\u200C\u200D\p{ID_Continue}]/u,It=".*";function Pt(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function kt(e,t=!1){let a=[],r=0;for(;r<e.length;){let n=e[r],s=function(n){if(!t)throw new TypeError(n);a.push({type:"INVALID_CHAR",index:r,value:e[r++]})};if("*"!==n)if("+"!==n&&"?"!==n)if("\\"!==n)if("{"!==n)if("}"!==n)if(":"!==n)if("("!==n)a.push({type:"CHAR",index:r,value:e[r++]});else{let t=1,n="",o=r+1,i=!1;if("?"===e[o]){s(`Pattern cannot start with "?" at ${o}`);continue}for(;o<e.length;){if(!Pt(e[o],!1)){s(`Invalid character '${e[o]}' at ${o}.`),i=!0;break}if("\\"!==e[o]){if(")"===e[o]){if(t--,0===t){o++;break}}else if("("===e[o]&&(t++,"?"!==e[o+1])){s(`Capturing groups are not allowed at ${o}`),i=!0;break}n+=e[o++]}else n+=e[o++]+e[o++]}if(i)continue;if(t){s(`Unbalanced pattern at ${r}`);continue}if(!n){s(`Missing pattern at ${r}`);continue}a.push({type:"REGEX",index:r,value:n}),r=o}else{let t="",n=r+1;for(;n<e.length;){let a=e.substr(n,1);if(!(n===r+1&&Ct.test(a)||n!==r+1&&xt.test(a)))break;t+=e[n++]}if(!t){s(`Missing parameter name at ${r}`);continue}a.push({type:"NAME",index:r,value:t}),r=n}else a.push({type:"CLOSE",index:r,value:e[r++]});else a.push({type:"OPEN",index:r,value:e[r++]});else a.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});else a.push({type:"OTHER_MODIFIER",index:r,value:e[r++]});else a.push({type:"ASTERISK",index:r,value:e[r++]})}return a.push({type:"END",index:r,value:""}),a}function Rt(e,t={}){let a=kt(e);t.delimiter??="/#?",t.prefixes??="./";let r=`[^${_t(t.delimiter)}]+?`,n=[],s=0,o=0,i=new Set,c=e=>{if(o<a.length&&a[o].type===e)return a[o++].value},d=()=>c("OTHER_MODIFIER")??c("ASTERISK"),u=e=>{let t=c(e);if(void 0!==t)return t;let{type:r,index:n}=a[o];throw new TypeError(`Unexpected ${r} at ${n}, expected ${e}`)},l=()=>{let e,t="";for(;e=c("CHAR")??c("ESCAPED_CHAR");)t+=e;return t},h=t.encodePart||(e=>e),p="",m=e=>{p+=e},f=()=>{p.length&&(n.push(new bt(3,"","",h(p),"",3)),p="")},g=(e,t,a,o,c)=>{let d,u=3;switch(c){case"?":u=1;break;case"*":u=0;break;case"+":u=2}if(!t&&!a&&3===u)return void m(e);if(f(),!t&&!a){if(!e)return;return void n.push(new bt(3,"","",h(e),"",u))}d=a?"*"===a?It:a:r;let l,p=2;if(d===r?(p=1,d=""):d===It&&(p=0,d=""),t?l=t:a&&(l=s++),i.has(l))throw new TypeError(`Duplicate name '${l}'.`);i.add(l),n.push(new bt(p,l,h(e),d,h(o),u))};for(;o<a.length;){let e=c("CHAR"),a=c("NAME"),r=c("REGEX");if(!a&&!r&&(r=c("ASTERISK")),a||r){let n=e??"";-1===t.prefixes.indexOf(n)&&(m(n),n=""),f(),g(n,a,r,"",d());continue}let n=e??c("ESCAPED_CHAR");if(n)m(n);else if(c("OPEN")){let e=l(),t=c("NAME"),a=c("REGEX");!t&&!a&&(a=c("ASTERISK"));let r=l();u("CLOSE"),g(e,t,a,r,d())}else f(),u("END")}return n}function _t(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Et(e){return e&&e.ignoreCase?"ui":"u"}function Tt(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function Nt(e,t,a={}){a.delimiter??="/#?",a.prefixes??="./",a.sensitive??=!1,a.strict??=!1,a.end??=!0,a.start??=!0,a.endsWith="";let r=a.start?"^":"";for(let n of e){if(3===n.type){3===n.modifier?r+=_t(n.value):r+=`(?:${_t(n.value)})${Tt(n.modifier)}`;continue}t&&t.push(n.name);let e=`[^${_t(a.delimiter)}]+?`,s=n.value;(1===n.type?s=e:0===n.type&&(s=It),n.prefix.length||n.suffix.length)?3!==n.modifier&&1!==n.modifier?(r+=`(?:${_t(n.prefix)}`,r+=`((?:${s})(?:`,r+=_t(n.suffix),r+=_t(n.prefix),r+=`(?:${s}))*)${_t(n.suffix)})`,0===n.modifier&&(r+="?")):(r+=`(?:${_t(n.prefix)}(${s})${_t(n.suffix)})`,r+=Tt(n.modifier)):3===n.modifier||1===n.modifier?r+=`(${s})${Tt(n.modifier)}`:r+=`((?:${s})${Tt(n.modifier)})`}let n=`[${_t(a.endsWith)}]|$`,s=`[${_t(a.delimiter)}]`;if(a.end)return a.strict||(r+=`${s}?`),a.endsWith.length?r+=`(?=${n})`:r+="$",new RegExp(r,Et(a));a.strict||(r+=`(?:${s}(?=${n}))?`);let o=!1;if(e.length){let t=e[e.length-1];3===t.type&&3===t.modifier&&(o=a.delimiter.indexOf(t)>-1)}return o||(r+=`(?=${s}|${n})`),new RegExp(r,Et(a))}var jt={delimiter:"",prefixes:"",sensitive:!0,strict:!0},Ot={delimiter:".",prefixes:"",sensitive:!0,strict:!0},Mt={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function At(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Dt(e){return!(!e||e.length<2)&&("["===e[0]||("\\"===e[0]||"{"===e[0])&&"["===e[1])}var Bt=["ftp","file","http","https","ws","wss"];function zt(e){if(!e)return!0;for(let t of Bt)if(e.test(t))return!0;return!1}function Lt(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function Zt(e){if(""===e)return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function Ut(e){if(""===e)return e;let t=new URL("https://example.com");return t.username=e,t.username}function qt(e){if(""===e)return e;let t=new URL("https://example.com");return t.password=e,t.password}function Vt(e){if(""===e)return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function Ft(e){if(""===e)return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function $t(e){if(""===e||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function Kt(e){if(""===e)return e;let t=new URL("https://example.com");return t.pathname="/"!==e[0]?"/-"+e:e,"/"!==e[0]?t.pathname.substring(2,t.pathname.length):t.pathname}function Wt(e){return""===e?e:new URL(`data:${e}`).pathname}function Ht(e){if(""===e)return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function Jt(e){if(""===e)return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var Gt=class{#gt;#yt=[];#St={};#vt=0;#wt=1;#bt=0;#Ct=0;#xt=0;#It=0;#Pt=!1;constructor(e){this.#gt=e}get result(){return this.#St}parse(){for(this.#yt=kt(this.#gt,!0);this.#vt<this.#yt.length;this.#vt+=this.#wt){if(this.#wt=1,"END"===this.#yt[this.#vt].type){if(0===this.#Ct){this.#kt(),this.#Rt()?this.#_t(9,1):this.#Et()?(this.#_t(8,1),this.#St.hash=""):(this.#_t(7,0),this.#St.search="",this.#St.hash="");continue}if(2===this.#Ct){this.#Tt(5);continue}this.#_t(10,0);break}if(this.#xt>0){if(!this.#Nt())continue;this.#xt-=1}if(this.#jt())this.#xt+=1;else switch(this.#Ct){case 0:this.#Ot()&&(this.#St.username="",this.#St.password="",this.#St.hostname="",this.#St.port="",this.#St.pathname="",this.#St.search="",this.#St.hash="",this.#Tt(1));break;case 1:if(this.#Ot()){this.#Mt();let e=7,t=1;this.#Pt&&(this.#St.pathname="/"),this.#At()?(e=2,t=3):this.#Pt&&(e=2),this.#_t(e,t)}break;case 2:this.#We()?this.#Tt(3):(this.#Dt()||this.#Et()||this.#Rt())&&this.#Tt(5);break;case 3:this.#Bt()?this.#_t(4,1):this.#We()&&this.#_t(5,1);break;case 4:this.#We()&&this.#_t(5,1);break;case 5:this.#zt()?this.#It+=1:this.#Lt()&&(this.#It-=1),this.#He()&&!this.#It?this.#_t(6,1):this.#Dt()?this.#_t(7,0):this.#Et()?this.#_t(8,1):this.#Rt()&&this.#_t(9,1);break;case 6:this.#Dt()?this.#_t(7,0):this.#Et()?this.#_t(8,1):this.#Rt()&&this.#_t(9,1);break;case 7:this.#Et()?this.#_t(8,1):this.#Rt()&&this.#_t(9,1);break;case 8:this.#Rt()&&this.#_t(9,1)}}}#_t(e,t){switch(this.#Ct){case 0:case 2:break;case 1:this.#St.protocol=this.#Zt();break;case 3:this.#St.username=this.#Zt();break;case 4:this.#St.password=this.#Zt();break;case 5:this.#St.hostname=this.#Zt();break;case 6:this.#St.port=this.#Zt();break;case 7:this.#St.pathname=this.#Zt();break;case 8:this.#St.search=this.#Zt();break;case 9:this.#St.hash=this.#Zt()}this.#Ut(e,t)}#Ut(e,t){this.#Ct=e,this.#bt=this.#vt+t,this.#vt+=t,this.#wt=0}#kt(){this.#vt=this.#bt,this.#wt=0}#Tt(e){this.#kt(),this.#Ct=e}#qt(e){return e<0&&(e=this.#yt.length-e),e<this.#yt.length?this.#yt[e]:this.#yt[this.#yt.length-1]}#Vt(e,t){let a=this.#qt(e);return a.value===t&&("CHAR"===a.type||"ESCAPED_CHAR"===a.type||"INVALID_CHAR"===a.type)}#Ot(){return this.#Vt(this.#vt,":")}#At(){return this.#Vt(this.#vt+1,"/")&&this.#Vt(this.#vt+2,"/")}#We(){return this.#Vt(this.#vt,"@")}#Bt(){return this.#Vt(this.#vt,":")}#He(){return this.#Vt(this.#vt,":")}#Dt(){return this.#Vt(this.#vt,"/")}#Et(){if(this.#Vt(this.#vt,"?"))return!0;if("?"!==this.#yt[this.#vt].value)return!1;let e=this.#qt(this.#vt-1);return"NAME"!==e.type&&"REGEX"!==e.type&&"CLOSE"!==e.type&&"ASTERISK"!==e.type}#Rt(){return this.#Vt(this.#vt,"#")}#jt(){return"OPEN"==this.#yt[this.#vt].type}#Nt(){return"CLOSE"==this.#yt[this.#vt].type}#zt(){return this.#Vt(this.#vt,"[")}#Lt(){return this.#Vt(this.#vt,"]")}#Zt(){let e=this.#yt[this.#vt],t=this.#qt(this.#bt).index;return this.#gt.substring(t,e.index)}#Mt(){let e={};Object.assign(e,jt),e.encodePart=Zt;let t=function(e,t,a){return Nt(Rt(e,a),t,a)}(this.#Zt(),void 0,e);this.#Pt=zt(t)}},Xt=["protocol","username","password","hostname","port","pathname","search","hash"],Yt="*";function Qt(e,t){if("string"!=typeof e)throw new TypeError("parameter 1 is not of type 'string'.");let a=new URL(e,t);return{protocol:a.protocol.substring(0,a.protocol.length-1),username:a.username,password:a.password,hostname:a.hostname,port:a.port,pathname:a.pathname,search:""!==a.search?a.search.substring(1,a.search.length):void 0,hash:""!==a.hash?a.hash.substring(1,a.hash.length):void 0}}function ea(e,t){return t?aa(e):e}function ta(e,t,a){let r;if("string"==typeof t.baseURL)try{r=new URL(t.baseURL),e.protocol=ea(r.protocol.substring(0,r.protocol.length-1),a),e.username=ea(r.username,a),e.password=ea(r.password,a),e.hostname=ea(r.hostname,a),e.port=ea(r.port,a),e.pathname=ea(r.pathname,a),e.search=ea(r.search.substring(1,r.search.length),a),e.hash=ea(r.hash.substring(1,r.hash.length),a)}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if("string"==typeof t.protocol&&(e.protocol=function(e,t){return e=function(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}(e,":"),t||""===e?e:Zt(e)}(t.protocol,a)),"string"==typeof t.username&&(e.username=function(e,t){if(t||""===e)return e;let a=new URL("https://example.com");return a.username=e,a.username}(t.username,a)),"string"==typeof t.password&&(e.password=function(e,t){if(t||""===e)return e;let a=new URL("https://example.com");return a.password=e,a.password}(t.password,a)),"string"==typeof t.hostname&&(e.hostname=function(e,t){return t||""===e?e:Dt(e)?Ft(e):Vt(e)}(t.hostname,a)),"string"==typeof t.port&&(e.port=function(e,t,a){return Lt(t)===e&&(e=""),a||""===e?e:$t(e)}(t.port,e.protocol,a)),"string"==typeof t.pathname){if(e.pathname=t.pathname,r&&!function(e,t){return!(!e.length||"/"!==e[0]&&(!t||e.length<2||"\\"!=e[0]&&"{"!=e[0]||"/"!=e[1]))}(e.pathname,a)){let t=r.pathname.lastIndexOf("/");t>=0&&(e.pathname=ea(r.pathname.substring(0,t+1),a)+e.pathname)}e.pathname=function(e,t,a){if(a||""===e)return e;if(t&&!Bt.includes(t))return new URL(`${t}:${e}`).pathname;let r="/"==e[0];return e=new URL(r?e:"/-"+e,"https://example.com").pathname,r||(e=e.substring(2,e.length)),e}(e.pathname,e.protocol,a)}return"string"==typeof t.search&&(e.search=function(e,t){if(e=At(e,"?"),t||""===e)return e;let a=new URL("https://example.com");return a.search=e,a.search?a.search.substring(1,a.search.length):""}(t.search,a)),"string"==typeof t.hash&&(e.hash=function(e,t){if(e=At(e,"#"),t||""===e)return e;let a=new URL("https://example.com");return a.hash=e,a.hash?a.hash.substring(1,a.hash.length):""}(t.hash,a)),e}function aa(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function ra(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let a=`[^${function(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}(t.delimiter)}]+?`,r=/[$_\u200C\u200D\p{ID_Continue}]/u,n="";for(let s=0;s<e.length;++s){let o=e[s];if(3===o.type){if(3===o.modifier){n+=aa(o.value);continue}n+=`{${aa(o.value)}}${Tt(o.modifier)}`;continue}let i=o.hasCustomName(),c=!!o.suffix.length||!!o.prefix.length&&(1!==o.prefix.length||!t.prefixes.includes(o.prefix)),d=s>0?e[s-1]:null,u=s<e.length-1?e[s+1]:null;if(!c&&i&&1===o.type&&3===o.modifier&&u&&!u.prefix.length&&!u.suffix.length)if(3===u.type){let e=u.value.length>0?u.value[0]:"";c=r.test(e)}else c=!u.hasCustomName();if(!c&&!o.prefix.length&&d&&3===d.type){let e=d.value[d.value.length-1];c=t.prefixes.includes(e)}c&&(n+="{"),n+=aa(o.prefix),i&&(n+=`:${o.name}`),2===o.type?n+=`(${o.value})`:1===o.type?i||(n+=`(${a})`):0===o.type&&(i||d&&3!==d.type&&3===d.modifier&&!c&&""===o.prefix?n+="(.*)":n+="*"),1===o.type&&i&&o.suffix.length&&r.test(o.suffix[0])&&(n+="\\"),n+=aa(o.suffix),c&&(n+="}"),3!==o.modifier&&(n+=Tt(o.modifier))}return n}var na=class{#gt;#yt={};#St={};#vt={};#wt={};constructor(e={},t,a){try{let r;if("string"==typeof t?r=t:a=t,"string"==typeof e){let t=new Gt(e);if(t.parse(),e=t.result,void 0===r&&"string"!=typeof e.protocol)throw new TypeError("A base URL must be provided for a relative constructor string.");e.baseURL=r}else{if(!e||"object"!=typeof e)throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(r)throw new TypeError("parameter 1 is not of type 'string'.")}typeof a>"u"&&(a={ignoreCase:!1});let n,s={ignoreCase:!0===a.ignoreCase},o={pathname:Yt,protocol:Yt,username:Yt,password:Yt,hostname:Yt,port:Yt,search:Yt,hash:Yt};for(n of(this.#gt=ta(o,e,!0),Lt(this.#gt.protocol)===this.#gt.port&&(this.#gt.port=""),Xt)){if(!(n in this.#gt))continue;let e={},t=this.#gt[n];switch(this.#St[n]=[],n){case"protocol":Object.assign(e,jt),e.encodePart=Zt;break;case"username":Object.assign(e,jt),e.encodePart=Ut;break;case"password":Object.assign(e,jt),e.encodePart=qt;break;case"hostname":Object.assign(e,Ot),Dt(t)?e.encodePart=Ft:e.encodePart=Vt;break;case"port":Object.assign(e,jt),e.encodePart=$t;break;case"pathname":zt(this.#yt.protocol)?(Object.assign(e,Mt,s),e.encodePart=Kt):(Object.assign(e,jt,s),e.encodePart=Wt);break;case"search":Object.assign(e,jt,s),e.encodePart=Ht;break;case"hash":Object.assign(e,jt,s),e.encodePart=Jt}try{this.#wt[n]=Rt(t,e),this.#yt[n]=Nt(this.#wt[n],this.#St[n],e),this.#vt[n]=ra(this.#wt[n],e)}catch{throw new TypeError(`invalid ${n} pattern '${this.#gt[n]}'.`)}}}catch(e){throw new TypeError(`Failed to construct 'URLPattern': ${e.message}`)}}test(e={},t){let a,r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if("string"!=typeof e&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return!1;try{r=ta(r,"object"==typeof e?e:Qt(e,t),!1)}catch{return!1}for(a of Xt)if(!this.#yt[a].exec(r[a]))return!1;return!0}exec(e={},t){let a={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if("string"!=typeof e&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return;try{a=ta(a,"object"==typeof e?e:Qt(e,t),!1)}catch{return null}let r,n={};for(r of(n.inputs=t?[e,t]:[e],Xt)){let e=this.#yt[r].exec(a[r]);if(!e)return null;let t={};for(let[a,n]of this.#St[r].entries())if("string"==typeof n||"number"==typeof n){let r=e[a+1];t[n]=r}n[r]={input:a[r]??"",groups:t}}return n}static compareComponent(e,t,a){let r=(e,t)=>{for(let a of["type","modifier","prefix","value","suffix"]){if(e[a]<t[a])return-1;if(e[a]!==t[a])return 1}return 0},n=new bt(3,"","","","",3),s=new bt(0,"","","","",3),o=(e,t)=>{let a=0;for(;a<Math.min(e.length,t.length);++a){let n=r(e[a],t[a]);if(n)return n}return e.length===t.length?0:r(e[a]??n,t[a]??n)};return t.#vt[e]||a.#vt[e]?t.#vt[e]&&!a.#vt[e]?o(t.#wt[e],[s]):!t.#vt[e]&&a.#vt[e]?o([s],a.#wt[e]):o(t.#wt[e],a.#wt[e]):0}get protocol(){return this.#vt.protocol}get username(){return this.#vt.username}get password(){return this.#vt.password}get hostname(){return this.#vt.hostname}get port(){return this.#vt.port}get pathname(){return this.#vt.pathname}get search(){return this.#vt.search}get hash(){return this.#vt.hash}};const{URLPattern:sa}=wt;var oa={URLPattern:sa};globalThis.URLPattern||(globalThis.URLPattern=sa),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URLPattern=void 0;const t=oa;Object.defineProperty(e,"URLPattern",{enumerable:!0,get:function(){return t.URLPattern}}),"URLPattern"in globalThis&&(t.URLPattern=globalThis.URLPattern)}(pt),Object.defineProperty(ht,"__esModule",{value:!0}),ht.NetworkStorage=void 0;const ia=g,ca=pt,da=z;class ua{#Ft=new Map;#$t=new Map;#Kt=new Map;disposeRequestMap(){for(const e of this.#Ft.values())e.dispose();this.#Ft.clear()}addIntercept(e){for(const[t,{urlPatterns:a,phases:r}]of this.#$t.entries())if(JSON.stringify(e.urlPatterns)===JSON.stringify(a)&&JSON.stringify(e.phases)===JSON.stringify(r))return t;const t=(0,da.uuidv4)();return this.#$t.set(t,e),t}removeIntercept(e){if(!this.#$t.has(e))throw new ia.NoSuchInterceptException(`Intercept '${e}' does not exist.`);this.#$t.delete(e)}hasIntercepts(){return this.#$t.size>0}getFetchEnableParams(){const e=[];for(const t of this.#$t.values())for(const a of t.urlPatterns){const r=ua.cdpFromSpecUrlPattern(a);for(const a of t.phases)e.push({urlPattern:r,requestStage:ua.requestStageFromPhase(a)})}return{patterns:e,handleAuthRequests:[...this.#$t.values()].some((e=>e.phases.includes("authRequired")))}}getRequest(e){return this.#Ft.get(e)}addRequest(e){this.#Ft.set(e.requestId,e)}deleteRequest(e){const t=this.#Ft.get(e);t&&(t.dispose(),this.#Ft.delete(e))}hasNetworkRequests(){return this.#Ft.size>0}hasBlockedRequests(){return this.#Kt.size>0}static cdpFromSpecUrlPattern(e){switch(e.type){case"string":return e.pattern;case"pattern":return ua.buildUrlPatternString(e)}}static buildUrlPatternString({protocol:e,hostname:t,port:a,pathname:r,search:n}){let s="";return e&&(s+=`${e}`,e.endsWith(":")||(s+=":"),ua.isSpecialScheme(e)&&(s+="//")),t&&(s+=t),a&&(s+=`:${a}`),r&&(r.startsWith("/")||(s+="/"),s+=r),n&&(n.startsWith("?")||(s+="?"),s+=`${n}`),s}static requestStageFromPhase(e){switch(e){case"beforeRequestSent":return"Request";case"responseStarted":case"authRequired":return"Response"}}static isSpecialScheme(e){return["ftp","file","http","https","ws","wss"].includes(e.replace(/:$/,""))}addBlockedRequest(e,t){this.#Kt.set(e,t)}removeBlockedRequest(e){this.#Kt.delete(e)}getBlockedRequest(e){return this.#Kt.get(e)}getNetworkIntercepts(e,t){const a=this.#Ft.get(e);if(!a)return[];const r=[];for(const[e,{phases:n,urlPatterns:s}]of this.#$t.entries())t&&n.includes(t)&&(0===s.length||s.some((e=>ua.matchUrlPattern(e,a.url))))&&r.push(e);return r}static matchUrlPattern(e,t){switch(e.type){case"string":return e.pattern===t;case"pattern":return null!==new ca.URLPattern({protocol:e.protocol,hostname:e.hostname,port:e.port,pathname:e.pathname,search:e.search}).exec(t)}}}ht.NetworkStorage=ua,Object.defineProperty(lt,"__esModule",{value:!0}),lt.NetworkProcessor=void 0;const la=g,ha=j,pa=ht,ma=we;class fa{#i;#oe;constructor(e,t){this.#i=e,this.#oe=t}async addIntercept(e){if(0===e.phases.length)throw new la.InvalidArgumentException("At least one phase must be specified.");e.phases.includes("authRequired")&&!e.phases.includes("beforeRequestSent")&&e.phases.unshift("beforeRequestSent");const t=e.urlPatterns??[],a=fa.parseUrlPatterns(t),r=this.#oe.addIntercept({urlPatterns:a,phases:e.phases});return await this.#Wt(),{intercept:r}}async continueRequest(e){const t=e.request,{request:a,phase:r}=this.#Ht(t);if("beforeRequestSent"!==r)throw new la.InvalidArgumentException(`Blocked request for network id '${t}' is not in 'BeforeRequestSent' phase`);void 0!==e.url&&fa.parseUrlString(e.url);const{url:n,method:s,headers:o}=e,i=(0,ma.cdpFetchHeadersFromBidiNetworkHeaders)(o),c=this.#oe.getRequest(t);return(0,ha.assert)(c,`Network request with ID ${t} doesn't exist`),await c.continueRequest(a,n,s,i),this.#oe.removeBlockedRequest(t),{}}async continueResponse(e){const t=e.request,{request:a,phase:r}=this.#Ht(t);if("beforeRequestSent"===r)throw new la.InvalidArgumentException(`Blocked request for network id '${t}' is in 'BeforeRequestSent' phase`);const{statusCode:n,reasonPhrase:s,headers:o}=e,i=(0,ma.cdpFetchHeadersFromBidiNetworkHeaders)(o),c=this.#oe.getRequest(t);return(0,ha.assert)(c,`Network request with ID ${t} doesn't exist`),await c.continueResponse(a,n,s,i),this.#oe.removeBlockedRequest(t),{}}async continueWithAuth(e){const t=e.request,{request:a,phase:r}=this.#Ht(t);if("authRequired"!==r)throw new la.InvalidArgumentException(`Blocked request for network id '${t}' is not in 'AuthRequired' phase`);const n=this.#oe.getRequest(t);let s,o;if((0,ha.assert)(n,`Network request with ID ${t} doesn't exist`),"provideCredentials"===e.action){const{credentials:t}=e;s=e.credentials.username,o=e.credentials.password,(0,ha.assert)("password"===t.type,`Credentials type ${t.type} must be 'password'`)}const i=(0,ma.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction)(e.action);return await n.continueWithAuth(a,i,s,o),{}}async failRequest(e){const t=e.request,a=this.#Ht(t),{request:r,phase:n}=a;if("authRequired"===n)throw new la.InvalidArgumentException(`Blocked request for network id '${t}' is in 'AuthRequired' phase`);const s=this.#oe.getRequest(t);return(0,ha.assert)(s,`Network request with ID ${t} doesn't exist`),await s.failRequest(r,"Failed"),this.#oe.removeBlockedRequest(t),{}}async provideResponse(e){const t=e.request,{request:a}=this.#Ht(t),{statusCode:r,reasonPhrase:n,headers:s,body:o}=e,i=(0,ma.cdpFetchHeadersFromBidiNetworkHeaders)(s),c=this.#oe.getRequest(t);return(0,ha.assert)(c,`Network request with ID ${t} doesn't exist`),await c.provideResponse(a,r??c.statusCode,n,i,o?.value),this.#oe.removeBlockedRequest(t),{}}async removeIntercept(e){return this.#oe.removeIntercept(e.intercept),await this.#Wt(),{}}async#Jt(){await Promise.all(this.#i.getAllContexts().map((async e=>{await e.cdpTarget.fetchEnable()})))}async#Gt(){await Promise.all(this.#i.getAllContexts().map((async e=>{await e.cdpTarget.fetchDisable()})))}async#Wt(){this.#oe.hasIntercepts()||this.#oe.hasBlockedRequests()||this.#oe.hasNetworkRequests()?await this.#Jt():await this.#Gt()}#Ht(e){const t=this.#oe.getBlockedRequest(e);if(!t)throw new la.NoSuchRequestException(`No blocked request found for network id '${e}'`);return t}static parseUrlString(e){try{return new URL(e)}catch(t){throw new la.InvalidArgumentException(`Invalid URL '${e}': ${t}`)}}static parseUrlPatterns(e){return e.map((e=>{switch(e.type){case"string":return fa.parseUrlString(e.pattern),e;case"pattern":if(""===e.protocol)throw new la.InvalidArgumentException("URL pattern must specify a protocol");if(""===e.hostname)throw new la.InvalidArgumentException("URL pattern must specify a hostname");if((e.hostname?.length??0)>0){if(e.protocol?.match(/^file/i))throw new la.InvalidArgumentException("URL pattern protocol cannot be 'file'");if(e.hostname?.includes(":"))throw new la.InvalidArgumentException("URL pattern hostname must not contain a colon")}if(""===e.port)throw new la.InvalidArgumentException("URL pattern must specify a port");try{new URL(pa.NetworkStorage.buildUrlPatternString(e))}catch(e){throw new la.InvalidArgumentException(`${e}`)}return e}}))}}lt.NetworkProcessor=fa;var ga={};Object.defineProperty(ga,"__esModule",{value:!0}),ga.PreloadScriptStorage=void 0;ga.PreloadScriptStorage=class{#Xt=new Set;find(e){return e?[...this.#Xt].filter((t=>(void 0===e.id||e.id===t.id)&&(!(void 0!==e.targetId&&!t.targetIds.has(e.targetId))&&(void 0===e.global||!(e.global&&void 0!==t.contexts||!e.global&&void 0===t.contexts))))):[...this.#Xt]}add(e){this.#Xt.add(e)}remove(e){for(const t of this.find(e))this.#Xt.delete(t)}};var ya={},Sa={};Object.defineProperty(Sa,"__esModule",{value:!0}),Sa.PreloadScript=void 0;const va=z,wa=B;Sa.PreloadScript=class{#m=(0,va.uuidv4)();#Yt=[];#Qt;#ea=new Set;#ta;#aa;#ra;get id(){return this.#m}get targetIds(){return this.#ea}constructor(e,t){this.#ta=e.arguments?.map((e=>new wa.ChannelProxy(e.value,t)))??[],this.#Qt=e.functionDeclaration,this.#aa=e.sandbox,this.#ra=e.contexts}get channels(){return this.#ta}get contexts(){return this.#ra}#na(){const e=`[${this.channels.map((e=>e.getEvalInWindowStr())).join(", ")}]`;return`(()=>{(${this.#Qt})(...${e})})()`}async initInTargets(e,t){await Promise.all(Array.from(e).map((e=>this.initInTarget(e,t))))}async initInTarget(e,t){const a=await e.cdpClient.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:this.#na(),worldName:this.#aa,runImmediately:t});this.#Yt.push({target:e,preloadScriptId:a.identifier}),this.#ea.add(e.targetId)}async remove(){for(const e of this.#Yt){const t=e.target,a=e.preloadScriptId;await t.cdpClient.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:a})}}dispose(e){this.#Yt=this.#Yt.filter((t=>t.target?.targetId!==e)),this.#ea.delete(e)}},Object.defineProperty(ya,"__esModule",{value:!0}),ya.ScriptProcessor=void 0;const ba=g,Ca=Sa;ya.ScriptProcessor=class{#i;#w;#Ne;#t;constructor(e,t,a,r){this.#i=e,this.#w=t,this.#Ne=a,this.#t=r}async addPreloadScript(e){const t=new Set;if(e.contexts){if(0===e.contexts.length)throw new ba.InvalidArgumentException("Contexts list is empty.");for(const a of e.contexts){const e=this.#i.getContext(a);if(!e.isTopLevelContext())throw new ba.InvalidArgumentException(`Non top-level context '${a}' given.`);t.add(e)}}const a=new Ca.PreloadScript(e,this.#t);this.#Ne.add(a);const r=0===t.size?new Set(this.#i.getTopLevelContexts().map((e=>e.cdpTarget))):new Set([...t.values()].map((e=>e.cdpTarget)));return await a.initInTargets(r,!1),{script:a.id}}async removePreloadScript(e){const t=e.script,a=this.#Ne.find({id:t});if(0===a.length)throw new ba.NoSuchScriptException(`No preload script with BiDi ID '${t}'`);return await Promise.all(a.map((e=>e.remove()))),this.#Ne.remove({id:t}),{}}async callFunction(e){const t=await this.#sa(e.target);return await t.callFunction(e.functionDeclaration,e.this??{type:"undefined"},e.arguments??[],e.awaitPromise,e.resultOwnership??"none",e.serializationOptions??{},e.userActivation??!1)}async evaluate(e){const t=await this.#sa(e.target);return await t.evaluate(e.expression,e.awaitPromise,e.resultOwnership??"none",e.serializationOptions??{},e.userActivation??!1)}async disown(e){const t=await this.#sa(e.target);return await Promise.all(e.handles.map((async e=>await t.disown(e)))),{}}getRealms(e){void 0!==e.context&&this.#i.getContext(e.context);return{realms:this.#w.findRealms({browsingContextId:e.context,type:e.type}).map((e=>e.realmInfo))}}async#sa(e){if("realm"in e)return this.#w.getRealm({realmId:e.realm});const t=this.#i.getContext(e.context);return await t.getOrCreateSandbox(e.sandbox)}};var xa={};Object.defineProperty(xa,"__esModule",{value:!0}),xa.SessionProcessor=void 0;xa.SessionProcessor=class{#R;constructor(e){this.#R=e}status(){return{ready:!1,message:"already connected"}}subscribe(e,t=null){return this.#R.subscribe(e.events,e.contexts??[null],t),{}}unsubscribe(e,t=null){return this.#R.unsubscribe(e.events,e.contexts??[null],t),{}}};var Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.OutgoingMessage=void 0;class Pa{#oa;#ia;constructor(e,t=null){this.#oa=e,this.#ia=t}static createFromPromise(e,t){return e.then((e=>"success"===e.kind?{kind:"success",value:new Pa(e.value,t)}:e))}static createResolved(e,t){return Promise.resolve({kind:"success",value:new Pa(e,t)})}get message(){return this.#oa}get channel(){return this.#ia}}Ia.OutgoingMessage=Pa,Object.defineProperty(f,"__esModule",{value:!0}),f.CommandProcessor=void 0;const ka=g,Ra=s,_a=l,Ea=R,Ta=_,Na=E,ja=T,Oa=De,Ma=lt,Aa=ht,Da=ga,Ba=ya,za=xa,La=Ia;class Za extends Ra.EventEmitter{#ca;#da;#ua;#la;#ha;#pa;#ma;#fa;#t;constructor(e,t,a,r,n,s,o=new Ea.BidiNoOpParser,i){super(),this.#fa=o,this.#t=i;const c=new Aa.NetworkStorage,d=new Da.PreloadScriptStorage;this.#ca=new Ta.BrowserProcessor(t),this.#da=new ja.BrowsingContextProcessor(e,t,r,a,n,s,c,d,i),this.#ua=new Na.CdpProcessor(n,e,t),this.#la=new Oa.InputProcessor(n),this.#ha=new Ma.NetworkProcessor(n,c),this.#pa=new Ba.ScriptProcessor(n,s,d,i),this.#ma=new za.SessionProcessor(a)}async#ga(e){switch(e.method){case"session.end":case"session.new":break;case"browser.close":return this.#ca.close();case"browsingContext.activate":return await this.#da.activate(this.#fa.parseActivateParams(e.params));case"browsingContext.captureScreenshot":return await this.#da.captureScreenshot(this.#fa.parseCaptureScreenshotParams(e.params));case"browsingContext.close":return await this.#da.close(this.#fa.parseCloseParams(e.params));case"browsingContext.create":return await this.#da.create(this.#fa.parseCreateParams(e.params));case"browsingContext.getTree":return this.#da.getTree(this.#fa.parseGetTreeParams(e.params));case"browsingContext.handleUserPrompt":return await this.#da.handleUserPrompt(this.#fa.parseHandleUserPromptParams(e.params));case"browsingContext.navigate":return await this.#da.navigate(this.#fa.parseNavigateParams(e.params));case"browsingContext.print":return await this.#da.print(this.#fa.parsePrintParams(e.params));case"browsingContext.reload":return await this.#da.reload(this.#fa.parseReloadParams(e.params));case"browsingContext.setViewport":return await this.#da.setViewport(this.#fa.parseSetViewportParams(e.params));case"cdp.getSession":return this.#ua.getSession(this.#fa.parseGetSessionParams(e.params));case"cdp.sendCommand":return await this.#ua.sendCommand(this.#fa.parseSendCommandParams(e.params));case"input.performActions":return await this.#la.performActions(this.#fa.parsePerformActionsParams(e.params));case"input.releaseActions":return await this.#la.releaseActions(this.#fa.parseReleaseActionsParams(e.params));case"network.addIntercept":return await this.#ha.addIntercept(this.#fa.parseAddInterceptParams(e.params));case"network.continueRequest":return await this.#ha.continueRequest(this.#fa.parseContinueRequestParams(e.params));case"network.continueResponse":return await this.#ha.continueResponse(this.#fa.parseContinueResponseParams(e.params));case"network.continueWithAuth":return await this.#ha.continueWithAuth(this.#fa.parseContinueWithAuthParams(e.params));case"network.failRequest":return await this.#ha.failRequest(this.#fa.parseFailRequestParams(e.params));case"network.provideResponse":return await this.#ha.provideResponse(this.#fa.parseProvideResponseParams(e.params));case"network.removeIntercept":return await this.#ha.removeIntercept(this.#fa.parseRemoveInterceptParams(e.params));case"script.addPreloadScript":return await this.#pa.addPreloadScript(this.#fa.parseAddPreloadScriptParams(e.params));case"script.callFunction":return await this.#pa.callFunction(this.#fa.parseCallFunctionParams(e.params));case"script.disown":return await this.#pa.disown(this.#fa.parseDisownParams(e.params));case"script.evaluate":return await this.#pa.evaluate(this.#fa.parseEvaluateParams(e.params));case"script.getRealms":return this.#pa.getRealms(this.#fa.parseGetRealmsParams(e.params));case"script.removePreloadScript":return await this.#pa.removePreloadScript(this.#fa.parseRemovePreloadScriptParams(e.params));case"session.status":return this.#ma.status();case"session.subscribe":return this.#ma.subscribe(this.#fa.parseSubscribeParams(e.params),e.channel);case"session.unsubscribe":return this.#ma.unsubscribe(this.#fa.parseSubscribeParams(e.params),e.channel)}throw new ka.UnknownCommandException(`Unknown command '${e.method}'.`)}async processCommand(e){try{const t=await this.#ga(e),a={type:"success",id:e.id,result:t};this.emit("response",{message:La.OutgoingMessage.createResolved(a,e.channel),event:e.method})}catch(t){if(t instanceof ka.Exception)this.emit("response",{message:La.OutgoingMessage.createResolved(t.toErrorResponse(e.id),e.channel),event:e.method});else{const a=t;this.#t?.(_a.LogType.bidi,a),this.emit("response",{message:La.OutgoingMessage.createResolved(new ka.UnknownErrorException(a.message,a.stack).toErrorResponse(e.id),e.channel),event:e.method})}}}}f.CommandProcessor=Za;var Ua={};Object.defineProperty(Ua,"__esModule",{value:!0}),Ua.BrowsingContextStorage=void 0;const qa=g;Ua.BrowsingContextStorage=class{#ra=new Map;getTopLevelContexts(){return this.getAllContexts().filter((e=>e.isTopLevelContext()))}getAllContexts(){return Array.from(this.#ra.values())}deleteContextById(e){this.#ra.delete(e)}deleteContext(e){this.#ra.delete(e.id)}addContext(e){this.#ra.set(e.id,e)}hasContext(e){return this.#ra.has(e)}findContext(e){return this.#ra.get(e)}findTopLevelContextId(e){if(null===e)return null;const t=this.findContext(e),a=t?.parentId??null;return null===a?e:this.findTopLevelContextId(a)}getContext(e){const t=this.findContext(e);if(void 0===t)throw new qa.NoSuchFrameException(`Context ${e} not found`);return t}};var Va={},Fa={};Object.defineProperty(Fa,"__esModule",{value:!0}),Fa.Buffer=void 0;Fa.Buffer=class{#ya;#Sa=[];#va;constructor(e,t){this.#ya=e,this.#va=t}get(){return this.#Sa}add(e){for(this.#Sa.push(e);this.#Sa.length>this.#ya;){const e=this.#Sa.shift();void 0!==e&&this.#va?.(e)}}};var $a={};Object.defineProperty($a,"__esModule",{value:!0}),$a.DefaultMap=void 0;class Ka extends Map{#wa;constructor(e,t){super(t),this.#wa=e}get(e){return this.has(e)||this.set(e,this.#wa(e)),super.get(e)}}$a.DefaultMap=Ka;var Wa={};Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.IdWrapper=void 0;class Ha{static#ba=0;#m;constructor(){this.#m=++Ha.#ba}get id(){return this.#m}}Wa.IdWrapper=Ha;var Ja={};Object.defineProperty(Ja,"__esModule",{value:!0}),Ja.assertSupportedEvent=Ja.isCdpEvent=void 0;const Ga=g;function Xa(e){return e.split(".").at(0)?.startsWith(Ga.ChromiumBidi.BiDiModule.Cdp)??!1}Ja.isCdpEvent=Xa,Ja.assertSupportedEvent=function(e){if(!Ga.ChromiumBidi.EVENT_NAMES.has(e)&&!Xa(e))throw new Ga.InvalidArgumentException(`Unknown event: ${e}`)};var Ya={};Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.SubscriptionManager=Ya.unrollEvents=Ya.cartesianProduct=void 0;const Qa=g,er=Ja;function tr(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t].flat()))))))}function ar(e){const t=new Set;function a(e){for(const a of e)t.add(a)}for(const r of e)switch(r){case Qa.ChromiumBidi.BiDiModule.BrowsingContext:a(Object.values(Qa.ChromiumBidi.BrowsingContext.EventNames));break;case Qa.ChromiumBidi.BiDiModule.Log:a(Object.values(Qa.ChromiumBidi.Log.EventNames));break;case Qa.ChromiumBidi.BiDiModule.Network:a(Object.values(Qa.ChromiumBidi.Network.EventNames));break;case Qa.ChromiumBidi.BiDiModule.Script:a(Object.values(Qa.ChromiumBidi.Script.EventNames));break;default:t.add(r)}return[...t.values()]}Ya.cartesianProduct=tr,Ya.unrollEvents=ar;Ya.SubscriptionManager=class{#Ca=0;#xa=new Map;#i;constructor(e){this.#i=e}getChannelsSubscribedToEvent(e,t){return Array.from(this.#xa.keys()).map((a=>({priority:this.#Ia(e,t,a),channel:a}))).filter((({priority:e})=>null!==e)).sort(((e,t)=>e.priority-t.priority)).map((({channel:e})=>e))}#Ia(e,t,a){const r=this.#xa.get(a);if(void 0===r)return null;const n=this.#i.findTopLevelContextId(t),s=[...new Set([null,n])].map((t=>{const a=r.get(t)?.get(e);if((0,er.isCdpEvent)(e)){const e=r.get(t)?.get(Qa.ChromiumBidi.BiDiModule.Cdp);return a&&e?Math.min(a,e):a??e}return a})).filter((e=>void 0!==e));return 0===s.length?null:Math.min(...s)}subscribe(e,t,a){switch(t=this.#i.findTopLevelContextId(t),e){case Qa.ChromiumBidi.BiDiModule.BrowsingContext:return void Object.values(Qa.ChromiumBidi.BrowsingContext.EventNames).map((e=>this.subscribe(e,t,a)));case Qa.ChromiumBidi.BiDiModule.Log:return void Object.values(Qa.ChromiumBidi.Log.EventNames).map((e=>this.subscribe(e,t,a)));case Qa.ChromiumBidi.BiDiModule.Network:return void Object.values(Qa.ChromiumBidi.Network.EventNames).map((e=>this.subscribe(e,t,a)));case Qa.ChromiumBidi.BiDiModule.Script:return void Object.values(Qa.ChromiumBidi.Script.EventNames).map((e=>this.subscribe(e,t,a)))}this.#xa.has(a)||this.#xa.set(a,new Map);const r=this.#xa.get(a);r.has(t)||r.set(t,new Map);const n=r.get(t);n.has(e)||n.set(e,this.#Ca++)}unsubscribeAll(e,t,a){for(const e of t)null!==e&&this.#i.getContext(e);tr(ar(e),t).map((([e,t])=>this.#Pa(e,t,a))).forEach((e=>e()))}unsubscribe(e,t,a){this.unsubscribeAll([e],[t],a)}#Pa(e,t,a){if(t=this.#i.findTopLevelContextId(t),!this.#xa.has(a))throw new Qa.InvalidArgumentException(`Cannot unsubscribe from ${e}, ${null===t?"null":t}. No subscription found.`);const r=this.#xa.get(a);if(!r.has(t))throw new Qa.InvalidArgumentException(`Cannot unsubscribe from ${e}, ${null===t?"null":t}. No subscription found.`);const n=r.get(t);if(!n.has(e))throw new Qa.InvalidArgumentException(`Cannot unsubscribe from ${e}, ${null===t?"null":t}. No subscription found.`);return()=>{n.delete(e),0===n.size&&r.delete(e),0===r.size&&this.#xa.delete(a)}}},Object.defineProperty(Va,"__esModule",{value:!0}),Va.EventManager=void 0;const rr=g,nr=Fa,sr=$a,or=Wa,ir=Ia,cr=Ja,dr=Ya;class ur{#ka=new or.IdWrapper;#Ra;#_a;constructor(e,t){this.#_a=e,this.#Ra=t}get id(){return this.#ka.id}get contextId(){return this.#Ra}get event(){return this.#_a}}const lr=new Map([[rr.ChromiumBidi.Log.EventNames.LogEntryAdded,100]]);class hr{#Ea=new sr.DefaultMap((()=>new Set));#Ta=new Map;#Na=new Map;#ja;#Oa;constructor(e){this.#Oa=e,this.#ja=new dr.SubscriptionManager(e.getBrowsingContextStorage())}static#Ma(e,t,a){return JSON.stringify({eventName:e,browsingContext:t,channel:a})}registerEvent(e,t){this.registerPromiseEvent(Promise.resolve({kind:"success",value:e}),t,e.method)}registerPromiseEvent(e,t,a){const r=new ur(e,t),n=this.#ja.getChannelsSubscribedToEvent(a,t);this.#Aa(r,a);for(const t of n)this.#Oa.emitOutgoingMessage(ir.OutgoingMessage.createFromPromise(e,t),a),this.#Da(r,t,a)}subscribe(e,t,a){for(const t of e)(0,cr.assertSupportedEvent)(t);for(const e of t)null!==e&&this.#Oa.getBrowsingContextStorage().getContext(e);for(const r of e)for(const e of t){this.#ja.subscribe(r,e,a);for(const t of this.#Ba(r,e,a))this.#Oa.emitOutgoingMessage(ir.OutgoingMessage.createFromPromise(t.event,a),r),this.#Da(t,a,r)}}unsubscribe(e,t,a){for(const t of e)(0,cr.assertSupportedEvent)(t);this.#ja.unsubscribeAll(e,t,a)}#Aa(e,t){if(!lr.has(t))return;const a=hr.#Ma(t,e.contextId);this.#Ta.has(a)||this.#Ta.set(a,new nr.Buffer(lr.get(t))),this.#Ta.get(a).add(e),this.#Ea.get(t).add(e.contextId)}#Da(e,t,a){if(!lr.has(a))return;const r=hr.#Ma(a,e.contextId,t);this.#Na.set(r,Math.max(this.#Na.get(r)??0,e.id))}#Ba(e,t,a){const r=hr.#Ma(e,t),n=hr.#Ma(e,t,a),s=this.#Na.get(n)??-1/0,o=this.#Ta.get(r)?.get().filter((e=>e.id>s))??[];return null===t&&Array.from(this.#Ea.get(e).keys()).filter((e=>null!==e&&this.#Oa.getBrowsingContextStorage().hasContext(e))).map((t=>this.#Ba(e,t,a))).forEach((e=>o.push(...e))),o.sort(((e,t)=>e.id-t.id))}}Va.EventManager=hr;var pr={};Object.defineProperty(pr,"__esModule",{value:!0}),pr.RealmStorage=void 0;const mr=g;pr.RealmStorage=class{#za=new Map;#La=new Map;get knownHandlesToRealmMap(){return this.#za}addRealm(e){this.#La.set(e.realmId,e)}findRealms(e){return Array.from(this.#La.values()).filter((t=>(void 0===e.realmId||e.realmId===t.realmId)&&((void 0===e.browsingContextId||e.browsingContextId===t.browsingContextId)&&((void 0===e.navigableId||e.navigableId===t.navigableId)&&((void 0===e.executionContextId||e.executionContextId===t.executionContextId)&&((void 0===e.origin||e.origin===t.origin)&&((void 0===e.type||e.type===t.type)&&((void 0===e.sandbox||e.sandbox===t.sandbox)&&(void 0===e.cdpSessionId||e.cdpSessionId===t.cdpClient.sessionId)))))))))}findRealm(e){const t=this.findRealms(e);if(1===t.length)return t[0]}getRealm(e){const t=this.findRealm(e);if(void 0===t)throw new mr.NoSuchFrameException(`Realm ${JSON.stringify(e)} not found`);return t}deleteRealms(e){this.findRealms(e).map((e=>{e.dispose(),this.#La.delete(e.realmId),Array.from(this.knownHandlesToRealmMap.entries()).filter((([,t])=>t===e.realmId)).map((([e])=>this.knownHandlesToRealmMap.delete(e)))}))}},Object.defineProperty(n,"__esModule",{value:!0}),n.BidiServer=void 0;const fr=s,gr=l,yr=h,Sr=f,vr=Ua,wr=Va,br=pr;class Cr extends fr.EventEmitter{#Za;#Ua;#qa;#i=new vr.BrowsingContextStorage;#t;#Va=e=>{this.#qa.processCommand(e).catch((e=>{this.#t?.(gr.LogType.debugError,e)}))};#Fa=async e=>{const t=e.message;null!==e.channel&&(t.channel=e.channel),await this.#Ua.sendMessage(t)};constructor(e,t,a,r,n,s){super(),this.#t=s,this.#Za=new yr.ProcessingQueue(this.#Fa,this.#t),this.#Ua=e,this.#Ua.setOnMessage(this.#Va),this.#qa=new Sr.CommandProcessor(t,a,new wr.EventManager(this),r,this.#i,new br.RealmStorage,n,this.#t),this.#qa.on("response",(({message:e,event:t})=>{this.emitOutgoingMessage(e,t)}))}static async createAndStart(e,t,a,r,n,s){const o=new Cr(e,t,a,r,n,s);return await a.sendCommand("Target.setDiscoverTargets",{discover:!0}),await a.sendCommand("Target.setAutoAttach",{autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await o.#$a(),o}emitOutgoingMessage(e,t){this.#Za.add(e,t)}close(){this.#Ua.close()}getBrowsingContextStorage(){return this.#i}async#$a(){await Promise.all(this.#i.getTopLevelContexts().map((e=>e.lifecycleLoaded())))}}n.BidiServer=Cr,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.OutgoingMessage=e.EventEmitter=e.BidiServer=void 0;var t=n;Object.defineProperty(e,"BidiServer",{enumerable:!0,get:function(){return t.BidiServer}});var a=s;Object.defineProperty(e,"EventEmitter",{enumerable:!0,get:function(){return a.EventEmitter}});var r=Ia;Object.defineProperty(e,"OutgoingMessage",{enumerable:!0,get:function(){return r.OutgoingMessage}})}(r);var xr={},Ir={};Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.CdpClient=Ir.CloseError=void 0;const Pr=s;class kr extends Error{}Ir.CloseError=kr;class Rr extends Pr.EventEmitter{#c;#Ka;constructor(e,t){super(),this.#c=e,this.#Ka=t}get sessionId(){return this.#Ka}sendCommand(e,...t){return this.#c.sendCommand(e,t[0],this.#Ka)}isCloseError(e){return e instanceof kr}}Ir.CdpClient=Rr,Object.defineProperty(xr,"__esModule",{value:!0}),xr.CdpConnection=void 0;const _r=l,Er=Ir;class Tr{static LOGGER_PREFIX_RECV=`${_r.LogType.cdp}:RECV \u25c2`;static LOGGER_PREFIX_SEND=`${_r.LogType.cdp}:SEND \u25b8`;#Wa;#Ua;#Ha=new Map;#Ja=new Map;#t;#Ga=0;constructor(e,t){this.#Ua=e,this.#t=t,this.#Ua.setOnMessage(this.#Xa),this.#Wa=this.#Ya(void 0)}close(){this.#Ua.close();for(const[,{reject:e,error:t}]of this.#Ja)e(t);this.#Ja.clear(),this.#Ha.clear()}async createBrowserSession(){const{sessionId:e}=await this.#Wa.sendCommand("Target.attachToBrowserTarget");return this.#Ya(e)}getCdpClient(e){const t=this.#Ha.get(e);if(!t)throw new Error(`Unknown CDP session ID: ${e}`);return t}sendCommand(e,t,a){return new Promise(((r,n)=>{const s=this.#Ga++;this.#Ja.set(s,{resolve:r,reject:n,error:new Er.CloseError(`${e} ${JSON.stringify(t)} ${a??""} call rejected because the connection has been closed.`)});const o={id:s,method:e,params:t};a&&(o.sessionId=a),this.#Ua.sendMessage(JSON.stringify(o))?.catch((e=>{this.#t?.(_r.LogType.debugError,e),this.#Ua.close()})),this.#t?.(Tr.LOGGER_PREFIX_SEND,o)}))}#Xa=e=>{const t=JSON.parse(e);if(this.#t?.(Tr.LOGGER_PREFIX_RECV,t),"Target.attachedToTarget"===t.method){const{sessionId:e}=t.params;this.#Ya(e)}if(void 0!==t.id){const e=this.#Ja.get(t.id);this.#Ja.delete(t.id),e&&(t.result?e.resolve(t.result):t.error&&e.reject(t.error))}else if(t.method){const e=this.#Ha.get(t.sessionId??void 0);if(e?.emit(t.method,t.params||{}),"Target.detachedFromTarget"===t.method){const{sessionId:e}=t.params,a=this.#Ha.get(e);a&&(this.#Ha.delete(e),a.removeAllListeners())}}};#Ya(e){const t=new Er.CdpClient(this,e);return this.#Ha.set(e,t),t}}xr.CdpConnection=Tr;var Nr={},jr={},Or={},Mr={},Ar={},Dr={},Br={};!function(e){var t;Object.defineProperty(e,"__esModule",{value:!0}),e.getParsedType=e.ZodParsedType=e.objectUtil=e.util=void 0,function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},e.getValidEnumValues=t=>{const a=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),r={};for(const e of a)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},e.find=(e,t)=>{for(const a of e)if(t(a))return a},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t=e.util||(e.util={})),(e.objectUtil||(e.objectUtil={})).mergeShapes=(e,t)=>({...e,...t}),e.ZodParsedType=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);e.getParsedType=t=>{switch(typeof t){case"undefined":return e.ZodParsedType.undefined;case"string":return e.ZodParsedType.string;case"number":return isNaN(t)?e.ZodParsedType.nan:e.ZodParsedType.number;case"boolean":return e.ZodParsedType.boolean;case"function":return e.ZodParsedType.function;case"bigint":return e.ZodParsedType.bigint;case"symbol":return e.ZodParsedType.symbol;case"object":return Array.isArray(t)?e.ZodParsedType.array:null===t?e.ZodParsedType.null:t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch?e.ZodParsedType.promise:"undefined"!=typeof Map&&t instanceof Map?e.ZodParsedType.map:"undefined"!=typeof Set&&t instanceof Set?e.ZodParsedType.set:"undefined"!=typeof Date&&t instanceof Date?e.ZodParsedType.date:e.ZodParsedType.object;default:return e.ZodParsedType.unknown}}}(Br);var zr={};Object.defineProperty(zr,"__esModule",{value:!0}),zr.ZodError=zr.quotelessJson=zr.ZodIssueCode=void 0;const Lr=Br;zr.ZodIssueCode=Lr.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);zr.quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Zr extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},a={_errors:[]},r=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(r);else if("invalid_return_type"===n.code)r(n.returnTypeError);else if("invalid_arguments"===n.code)r(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,r=0;for(;r<n.path.length;){const a=n.path[r];r===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],r++}}};return r(this),a}toString(){return this.message}get message(){return JSON.stringify(this.issues,Lr.util.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=(e=>e.message)){const t={},a=[];for(const r of this.issues)r.path.length>0?(t[r.path[0]]=t[r.path[0]]||[],t[r.path[0]].push(e(r))):a.push(e(r));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}}zr.ZodError=Zr,Zr.create=e=>new Zr(e),Object.defineProperty(Dr,"__esModule",{value:!0});const Ur=Br,qr=zr;Dr.default=(e,t)=>{let a;switch(e.code){case qr.ZodIssueCode.invalid_type:a=e.received===Ur.ZodParsedType.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case qr.ZodIssueCode.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,Ur.util.jsonStringifyReplacer)}`;break;case qr.ZodIssueCode.unrecognized_keys:a=`Unrecognized key(s) in object: ${Ur.util.joinValues(e.keys,", ")}`;break;case qr.ZodIssueCode.invalid_union:a="Invalid input";break;case qr.ZodIssueCode.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${Ur.util.joinValues(e.options)}`;break;case qr.ZodIssueCode.invalid_enum_value:a=`Invalid enum value. Expected ${Ur.util.joinValues(e.options)}, received '${e.received}'`;break;case qr.ZodIssueCode.invalid_arguments:a="Invalid function arguments";break;case qr.ZodIssueCode.invalid_return_type:a="Invalid function return type";break;case qr.ZodIssueCode.invalid_date:a="Invalid date";break;case qr.ZodIssueCode.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:Ur.util.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case qr.ZodIssueCode.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case qr.ZodIssueCode.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case qr.ZodIssueCode.custom:a="Invalid input";break;case qr.ZodIssueCode.invalid_intersection_types:a="Intersection results could not be merged";break;case qr.ZodIssueCode.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case qr.ZodIssueCode.not_finite:a="Number must be finite";break;default:a=t.defaultError,Ur.util.assertNever(e)}return{message:a}};var Vr=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.getErrorMap=Ar.setErrorMap=Ar.defaultErrorMap=void 0;const Fr=Vr(Dr);Ar.defaultErrorMap=Fr.default;let $r=Fr.default;Ar.setErrorMap=function(e){$r=e},Ar.getErrorMap=function(){return $r};var Kr={};!function(t){var a=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isAsync=t.isValid=t.isDirty=t.isAborted=t.OK=t.DIRTY=t.INVALID=t.ParseStatus=t.addIssueToContext=t.EMPTY_PATH=t.makeIssue=void 0;const r=Ar,n=a(Dr);t.makeIssue=e=>{const{data:t,path:a,errorMaps:r,issueData:n}=e,s=[...a,...n.path||[]],o={...n,path:s};let i="";const c=r.filter((e=>!!e)).slice().reverse();for(const e of c)i=e(o,{data:t,defaultError:i}).message;return{...n,path:s,message:n.message||i}},t.EMPTY_PATH=[],t.addIssueToContext=function(e,a){const s=(0,t.makeIssue)({issueData:a,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,(0,r.getErrorMap)(),n.default].filter((e=>!!e))});e.common.issues.push(s)};class s{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,a){const r=[];for(const n of a){if("aborted"===n.status)return t.INVALID;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const a=[];for(const e of t)a.push({key:await e.key,value:await e.value});return s.mergeObjectSync(e,a)}static mergeObjectSync(e,a){const r={};for(const n of a){const{key:a,value:s}=n;if("aborted"===a.status)return t.INVALID;if("aborted"===s.status)return t.INVALID;"dirty"===a.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===a.value||void 0===s.value&&!n.alwaysSet||(r[a.value]=s.value)}return{status:e.value,value:r}}}t.ParseStatus=s,t.INVALID=Object.freeze({status:"aborted"});t.DIRTY=e=>({status:"dirty",value:e});t.OK=e=>({status:"valid",value:e});t.isAborted=e=>"aborted"===e.status;t.isDirty=e=>"dirty"===e.status;t.isValid=e=>"valid"===e.status;t.isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise}(Kr);var Wr={};Object.defineProperty(Wr,"__esModule",{value:!0});var Hr,Jr={},Gr={};Hr=Gr,Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.errorUtil=void 0,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(Hr.errorUtil||(Hr.errorUtil={})),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.date=e.boolean=e.bigint=e.array=e.any=e.coerce=e.ZodFirstPartyTypeKind=e.late=e.ZodSchema=e.Schema=e.custom=e.ZodReadonly=e.ZodPipeline=e.ZodBranded=e.BRAND=e.ZodNaN=e.ZodCatch=e.ZodDefault=e.ZodNullable=e.ZodOptional=e.ZodTransformer=e.ZodEffects=e.ZodPromise=e.ZodNativeEnum=e.ZodEnum=e.ZodLiteral=e.ZodLazy=e.ZodFunction=e.ZodSet=e.ZodMap=e.ZodRecord=e.ZodTuple=e.ZodIntersection=e.ZodDiscriminatedUnion=e.ZodUnion=e.ZodObject=e.ZodArray=e.ZodVoid=e.ZodNever=e.ZodUnknown=e.ZodAny=e.ZodNull=e.ZodUndefined=e.ZodSymbol=e.ZodDate=e.ZodBoolean=e.ZodBigInt=e.ZodNumber=e.ZodString=e.ZodType=void 0,e.NEVER=e.void=e.unknown=e.union=e.undefined=e.tuple=e.transformer=e.symbol=e.string=e.strictObject=e.set=e.record=e.promise=e.preprocess=e.pipeline=e.ostring=e.optional=e.onumber=e.oboolean=e.object=e.number=e.nullable=e.null=e.never=e.nativeEnum=e.nan=e.map=e.literal=e.lazy=e.intersection=e.instanceof=e.function=e.enum=e.effect=e.discriminatedUnion=void 0;const t=Ar,a=Gr,r=Kr,n=Br,s=zr;class o{constructor(e,t,a,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=r}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const i=(e,t)=>{if((0,r.isValid)(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new s.ZodError(e.common.issues);return this._error=t,this._error}}};function c(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:r,description:n}=e;if(t&&(a||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=r?r:t.defaultError}:{message:null!=a?a:t.defaultError},description:n}}class d{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return(0,n.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,n.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new r.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,n.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if((0,r.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){var a;const r={common:{issues:[],async:null!==(a=null==t?void 0:t.async)&&void 0!==a&&a,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,n.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return i(r,s)}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,n.getParsedType)(e)},s=this._parse({data:e,path:a.path,parent:a}),o=await((0,r.isAsync)(s)?s:Promise.resolve(s));return i(a,o)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,r)=>{const n=e(t),o=()=>r.addIssue({code:s.ZodIssueCode.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(o(),!1))):!!n||(o(),!1)}))}refinement(e,t){return this._refinement(((a,r)=>!!e(a)||(r.addIssue("function"==typeof t?t(a,r):t),!1)))}_refinement(e){return new G({schema:this,typeName:se.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return X.create(this,this._def)}nullable(){return Y.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return N.create(this,this._def)}promise(){return J.create(this,this._def)}or(e){return M.create([this,e],this._def)}and(e){return z.create(this,e,this._def)}transform(e){return new G({...c(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Q({...c(this._def),innerType:this,defaultValue:t,typeName:se.ZodDefault})}brand(){return new ae({typeName:se.ZodBranded,type:this,...c(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ee({...c(this._def),innerType:this,catchValue:t,typeName:se.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return re.create(this,e)}readonly(){return ne.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}e.ZodType=d,e.Schema=d,e.ZodSchema=d;const u=/^c[^\s-]{8,}$/i,l=/^[a-z][a-z0-9]*$/,h=/^[0-9A-HJKMNP-TV-Z]{26}$/,p=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,m=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let f;const g=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,y=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;class S extends d{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==n.ZodParsedType.string){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.string,received:t.parsedType}),r.INVALID}const t=new r.ParseStatus;let a;for(const d of this._def.checks)if("min"===d.kind)e.data.length<d.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),t.dirty());else if("max"===d.kind)e.data.length>d.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),t.dirty());else if("length"===d.kind){const n=e.data.length>d.value,o=e.data.length<d.value;(n||o)&&(a=this._getOrReturnCtx(e,a),n?(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}):o&&(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}),t.dirty())}else if("email"===d.kind)m.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"email",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("emoji"===d.kind)f||(f=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),f.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"emoji",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("uuid"===d.kind)p.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"uuid",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("cuid"===d.kind)u.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"cuid",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("cuid2"===d.kind)l.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"cuid2",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("ulid"===d.kind)h.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"ulid",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("url"===d.kind)try{new URL(e.data)}catch(n){a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"url",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty()}else if("regex"===d.kind){d.regex.lastIndex=0;d.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"regex",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty())}else if("trim"===d.kind)e.data=e.data.trim();else if("includes"===d.kind)e.data.includes(d.value,d.position)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:{includes:d.value,position:d.position},message:d.message}),t.dirty());else if("toLowerCase"===d.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===d.kind)e.data=e.data.toUpperCase();else if("startsWith"===d.kind)e.data.startsWith(d.value)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:{startsWith:d.value},message:d.message}),t.dirty());else if("endsWith"===d.kind)e.data.endsWith(d.value)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:{endsWith:d.value},message:d.message}),t.dirty());else if("datetime"===d.kind){((c=d).precision?c.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${c.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${c.precision}}Z$`):0===c.precision?c.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):c.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$")).test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:"datetime",message:d.message}),t.dirty())}else"ip"===d.kind?(o=e.data,("v4"!==(i=d.version)&&i||!g.test(o))&&("v6"!==i&&i||!y.test(o))&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"ip",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty())):n.util.assertNever(d);var o,i,c;return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:s.ZodIssueCode.invalid_string,...a.errorUtil.errToObj(r)})}_addCheck(e){return new S({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...a.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...a.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...a.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...a.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...a.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...a.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...a.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...a.errorUtil.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,...a.errorUtil.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...a.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...a.errorUtil.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...a.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...a.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...a.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...a.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...a.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,a.errorUtil.errToObj(e))}trim(){return new S({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new S({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new S({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function v(e,t){const a=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,n=a>r?a:r;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}e.ZodString=S,S.create=e=>{var t;return new S({checks:[],typeName:se.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...c(e)})};class w extends d{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==n.ZodParsedType.number){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.number,received:t.parsedType}),r.INVALID}let t;const a=new r.ParseStatus;for(const o of this._def.checks)if("int"===o.kind)n.util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty());else if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty())}else"multipleOf"===o.kind?0!==v(e.data,o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):"finite"===o.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.not_finite,message:o.message}),a.dirty()):n.util.assertNever(o);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,a.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,a.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,a.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,a.errorUtil.toString(t))}setLimit(e,t,r,n){return new w({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:a.errorUtil.toString(n)}]})}_addCheck(e){return new w({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:a.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:a.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:a.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:a.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:a.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:a.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:a.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:a.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:a.errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&n.util.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}}e.ZodNumber=w,w.create=e=>new w({checks:[],typeName:se.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...c(e)});class b extends d{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==n.ZodParsedType.bigint){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.bigint,received:t.parsedType}),r.INVALID}let t;const a=new r.ParseStatus;for(const o of this._def.checks)if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty())}else"multipleOf"===o.kind?e.data%o.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):n.util.assertNever(o);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,a.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,a.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,a.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,a.errorUtil.toString(t))}setLimit(e,t,r,n){return new b({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:a.errorUtil.toString(n)}]})}_addCheck(e){return new b({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:a.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:a.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:a.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:a.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:a.errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}e.ZodBigInt=b,b.create=e=>{var t;return new b({checks:[],typeName:se.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...c(e)})};class C extends d{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==n.ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.boolean,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodBoolean=C,C.create=e=>new C({typeName:se.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...c(e)});class x extends d{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==n.ZodParsedType.date){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.date,received:t.parsedType}),r.INVALID}if(isNaN(e.data.getTime())){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_date}),r.INVALID}const t=new r.ParseStatus;let a;for(const o of this._def.checks)"min"===o.kind?e.data.getTime()<o.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),t.dirty()):"max"===o.kind?e.data.getTime()>o.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),t.dirty()):n.util.assertNever(o);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new x({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:a.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:a.errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}e.ZodDate=x,x.create=e=>new x({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:se.ZodDate,...c(e)});class I extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.symbol,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodSymbol=I,I.create=e=>new I({typeName:se.ZodSymbol,...c(e)});class P extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.undefined,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodUndefined=P,P.create=e=>new P({typeName:se.ZodUndefined,...c(e)});class k extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.null){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.null,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodNull=k,k.create=e=>new k({typeName:se.ZodNull,...c(e)});class R extends d{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,r.OK)(e.data)}}e.ZodAny=R,R.create=e=>new R({typeName:se.ZodAny,...c(e)});class _ extends d{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,r.OK)(e.data)}}e.ZodUnknown=_,_.create=e=>new _({typeName:se.ZodUnknown,...c(e)});class E extends d{_parse(e){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.never,received:t.parsedType}),r.INVALID}}e.ZodNever=E,E.create=e=>new E({typeName:se.ZodNever,...c(e)});class T extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.void,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodVoid=T,T.create=e=>new T({typeName:se.ZodVoid,...c(e)});class N extends d{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),i=this._def;if(t.parsedType!==n.ZodParsedType.array)return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.array,received:t.parsedType}),r.INVALID;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,n=t.data.length<i.exactLength.value;(e||n)&&((0,r.addIssueToContext)(t,{code:e?s.ZodIssueCode.too_big:s.ZodIssueCode.too_small,minimum:n?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),a.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&((0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),a.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&((0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map(((e,a)=>i.type._parseAsync(new o(t,e,t.path,a))))).then((e=>r.ParseStatus.mergeArray(a,e)));const c=[...t.data].map(((e,a)=>i.type._parseSync(new o(t,e,t.path,a))));return r.ParseStatus.mergeArray(a,c)}get element(){return this._def.type}min(e,t){return new N({...this._def,minLength:{value:e,message:a.errorUtil.toString(t)}})}max(e,t){return new N({...this._def,maxLength:{value:e,message:a.errorUtil.toString(t)}})}length(e,t){return new N({...this._def,exactLength:{value:e,message:a.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function j(e){if(e instanceof O){const t={};for(const a in e.shape){const r=e.shape[a];t[a]=X.create(j(r))}return new O({...e._def,shape:()=>t})}return e instanceof N?new N({...e._def,type:j(e.element)}):e instanceof X?X.create(j(e.unwrap())):e instanceof Y?Y.create(j(e.unwrap())):e instanceof L?L.create(e.items.map((e=>j(e)))):e}e.ZodArray=N,N.create=(e,t)=>new N({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...c(t)});class O extends d{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.util.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==n.ZodParsedType.object){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.object,received:t.parsedType}),r.INVALID}const{status:t,ctx:a}=this._processInputParams(e),{shape:i,keys:c}=this._getCached(),d=[];if(!(this._def.catchall instanceof E&&"strip"===this._def.unknownKeys))for(const e in a.data)c.includes(e)||d.push(e);const u=[];for(const e of c){const t=i[e],r=a.data[e];u.push({key:{status:"valid",value:e},value:t._parse(new o(a,r,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof E){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of d)u.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)d.length>0&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.unrecognized_keys,keys:d}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of d){const r=a.data[t];u.push({key:{status:"valid",value:t},value:e._parse(new o(a,r,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of u){const a=await t.key;e.push({key:a,value:await t.value,alwaysSet:t.alwaysSet})}return e})).then((e=>r.ParseStatus.mergeObjectSync(t,e))):r.ParseStatus.mergeObjectSync(t,u)}get shape(){return this._def.shape()}strict(e){return a.errorUtil.errToObj,new O({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,o,i;const c=null!==(o=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==o?o:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=a.errorUtil.errToObj(e).message)&&void 0!==i?i:c}:{message:c}}}:{}})}strip(){return new O({...this._def,unknownKeys:"strip"})}passthrough(){return new O({...this._def,unknownKeys:"passthrough"})}extend(e){return new O({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new O({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:se.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new O({...this._def,catchall:e})}pick(e){const t={};return n.util.objectKeys(e).forEach((a=>{e[a]&&this.shape[a]&&(t[a]=this.shape[a])})),new O({...this._def,shape:()=>t})}omit(e){const t={};return n.util.objectKeys(this.shape).forEach((a=>{e[a]||(t[a]=this.shape[a])})),new O({...this._def,shape:()=>t})}deepPartial(){return j(this)}partial(e){const t={};return n.util.objectKeys(this.shape).forEach((a=>{const r=this.shape[a];e&&!e[a]?t[a]=r:t[a]=r.optional()})),new O({...this._def,shape:()=>t})}required(e){const t={};return n.util.objectKeys(this.shape).forEach((a=>{if(e&&!e[a])t[a]=this.shape[a];else{let e=this.shape[a];for(;e instanceof X;)e=e._def.innerType;t[a]=e}})),new O({...this._def,shape:()=>t})}keyof(){return K(n.util.objectKeys(this.shape))}}e.ZodObject=O,O.create=(e,t)=>new O({shape:()=>e,unknownKeys:"strip",catchall:E.create(),typeName:se.ZodObject,...c(t)}),O.strictCreate=(e,t)=>new O({shape:()=>e,unknownKeys:"strict",catchall:E.create(),typeName:se.ZodObject,...c(t)}),O.lazycreate=(e,t)=>new O({shape:e,unknownKeys:"strip",catchall:E.create(),typeName:se.ZodObject,...c(t)});class M extends d{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map((async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map((e=>new s.ZodError(e.ctx.common.issues)));return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_union,unionErrors:a}),r.INVALID}));{let e;const n=[];for(const r of a){const a={...t,common:{...t.common,issues:[]},parent:null},s=r._parseSync({data:t.data,path:t.path,parent:a});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:a}),a.common.issues.length&&n.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const o=n.map((e=>new s.ZodError(e)));return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_union,unionErrors:o}),r.INVALID}}get options(){return this._def.options}}e.ZodUnion=M,M.create=(e,t)=>new M({options:e,typeName:se.ZodUnion,...c(t)});const A=e=>e instanceof F?A(e.schema):e instanceof G?A(e.innerType()):e instanceof $?[e.value]:e instanceof W?e.options:e instanceof H?Object.keys(e.enum):e instanceof Q?A(e._def.innerType):e instanceof P?[void 0]:e instanceof k?[null]:null;class D extends d{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.ZodParsedType.object)return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.object,received:t.parsedType}),r.INVALID;const a=this.discriminator,o=t.data[a],i=this.optionsMap.get(o);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),r.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,a){const r=new Map;for(const a of t){const t=A(a.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(r.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);r.set(n,a)}}return new D({typeName:se.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...c(a)})}}function B(e,t){const a=(0,n.getParsedType)(e),r=(0,n.getParsedType)(t);if(e===t)return{valid:!0,data:e};if(a===n.ZodParsedType.object&&r===n.ZodParsedType.object){const a=n.util.objectKeys(t),r=n.util.objectKeys(e).filter((e=>-1!==a.indexOf(e))),s={...e,...t};for(const a of r){const r=B(e[a],t[a]);if(!r.valid)return{valid:!1};s[a]=r.data}return{valid:!0,data:s}}if(a===n.ZodParsedType.array&&r===n.ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let r=0;r<e.length;r++){const n=B(e[r],t[r]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}return a===n.ZodParsedType.date&&r===n.ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}e.ZodDiscriminatedUnion=D;class z extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),n=(e,n)=>{if((0,r.isAborted)(e)||(0,r.isAborted)(n))return r.INVALID;const o=B(e.value,n.value);return o.valid?(((0,r.isDirty)(e)||(0,r.isDirty)(n))&&t.dirty(),{status:t.value,value:o.data}):((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_intersection_types}),r.INVALID)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}e.ZodIntersection=z,z.create=(e,t,a)=>new z({left:e,right:t,typeName:se.ZodIntersection,...c(a)});class L extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.array)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.array,received:a.parsedType}),r.INVALID;if(a.data.length<this._def.items.length)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.INVALID;!this._def.rest&&a.data.length>this._def.items.length&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...a.data].map(((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new o(a,e,a.path,t)):null})).filter((e=>!!e));return a.common.async?Promise.all(i).then((e=>r.ParseStatus.mergeArray(t,e))):r.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new L({...this._def,rest:e})}}e.ZodTuple=L,L.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new L({items:e,typeName:se.ZodTuple,rest:null,...c(t)})};class Z extends d{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.object)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.object,received:a.parsedType}),r.INVALID;const i=[],c=this._def.keyType,d=this._def.valueType;for(const e in a.data)i.push({key:c._parse(new o(a,e,a.path,e)),value:d._parse(new o(a,a.data[e],a.path,e))});return a.common.async?r.ParseStatus.mergeObjectAsync(t,i):r.ParseStatus.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,a){return new Z(t instanceof d?{keyType:e,valueType:t,typeName:se.ZodRecord,...c(a)}:{keyType:S.create(),valueType:e,typeName:se.ZodRecord,...c(t)})}}e.ZodRecord=Z;class U extends d{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.map)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.map,received:a.parsedType}),r.INVALID;const i=this._def.keyType,c=this._def.valueType,d=[...a.data.entries()].map((([e,t],r)=>({key:i._parse(new o(a,e,a.path,[r,"key"])),value:c._parse(new o(a,t,a.path,[r,"value"]))})));if(a.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const a of d){const n=await a.key,s=await a.value;if("aborted"===n.status||"aborted"===s.status)return r.INVALID;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const a of d){const n=a.key,s=a.value;if("aborted"===n.status||"aborted"===s.status)return r.INVALID;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}e.ZodMap=U,U.create=(e,t,a)=>new U({valueType:t,keyType:e,typeName:se.ZodMap,...c(a)});class q extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.set)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.set,received:a.parsedType}),r.INVALID;const i=this._def;null!==i.minSize&&a.data.size<i.minSize.value&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&a.data.size>i.maxSize.value&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const c=this._def.valueType;function d(e){const a=new Set;for(const n of e){if("aborted"===n.status)return r.INVALID;"dirty"===n.status&&t.dirty(),a.add(n.value)}return{status:t.value,value:a}}const u=[...a.data.values()].map(((e,t)=>c._parse(new o(a,e,a.path,t))));return a.common.async?Promise.all(u).then((e=>d(e))):d(u)}min(e,t){return new q({...this._def,minSize:{value:e,message:a.errorUtil.toString(t)}})}max(e,t){return new q({...this._def,maxSize:{value:e,message:a.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}e.ZodSet=q,q.create=(e,t)=>new q({valueType:e,minSize:null,maxSize:null,typeName:se.ZodSet,...c(t)});class V extends d{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.function)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.function,received:a.parsedType}),r.INVALID;function o(e,n){return(0,r.makeIssue)({data:e,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,(0,t.getErrorMap)(),t.defaultErrorMap].filter((e=>!!e)),issueData:{code:s.ZodIssueCode.invalid_arguments,argumentsError:n}})}function i(e,n){return(0,r.makeIssue)({data:e,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,(0,t.getErrorMap)(),t.defaultErrorMap].filter((e=>!!e)),issueData:{code:s.ZodIssueCode.invalid_return_type,returnTypeError:n}})}const c={errorMap:a.common.contextualErrorMap},d=a.data;if(this._def.returns instanceof J){const e=this;return(0,r.OK)((async function(...t){const a=new s.ZodError([]),r=await e._def.args.parseAsync(t,c).catch((e=>{throw a.addIssue(o(t,e)),a})),n=await Reflect.apply(d,this,r),u=await e._def.returns._def.type.parseAsync(n,c).catch((e=>{throw a.addIssue(i(n,e)),a}));return u}))}{const e=this;return(0,r.OK)((function(...t){const a=e._def.args.safeParse(t,c);if(!a.success)throw new s.ZodError([o(t,a.error)]);const r=Reflect.apply(d,this,a.data),n=e._def.returns.safeParse(r,c);if(!n.success)throw new s.ZodError([i(r,n.error)]);return n.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new V({...this._def,args:L.create(e).rest(_.create())})}returns(e){return new V({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,a){return new V({args:e||L.create([]).rest(_.create()),returns:t||_.create(),typeName:se.ZodFunction,...c(a)})}}e.ZodFunction=V;class F extends d{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}e.ZodLazy=F,F.create=(e,t)=>new F({getter:e,typeName:se.ZodLazy,...c(t)});class $ extends d{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{received:t.data,code:s.ZodIssueCode.invalid_literal,expected:this._def.value}),r.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function K(e,t){return new W({values:e,typeName:se.ZodEnum,...c(t)})}e.ZodLiteral=$,$.create=(e,t)=>new $({value:e,typeName:se.ZodLiteral,...c(t)});class W extends d{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),a=this._def.values;return(0,r.addIssueToContext)(t,{expected:n.util.joinValues(a),received:t.parsedType,code:s.ZodIssueCode.invalid_type}),r.INVALID}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),a=this._def.values;return(0,r.addIssueToContext)(t,{received:t.data,code:s.ZodIssueCode.invalid_enum_value,options:a}),r.INVALID}return(0,r.OK)(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e){return W.create(e)}exclude(e){return W.create(this.options.filter((t=>!e.includes(t))))}}e.ZodEnum=W,W.create=K;class H extends d{_parse(e){const t=n.util.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==n.ZodParsedType.string&&a.parsedType!==n.ZodParsedType.number){const e=n.util.objectValues(t);return(0,r.addIssueToContext)(a,{expected:n.util.joinValues(e),received:a.parsedType,code:s.ZodIssueCode.invalid_type}),r.INVALID}if(-1===t.indexOf(e.data)){const e=n.util.objectValues(t);return(0,r.addIssueToContext)(a,{received:a.data,code:s.ZodIssueCode.invalid_enum_value,options:e}),r.INVALID}return(0,r.OK)(e.data)}get enum(){return this._def.values}}e.ZodNativeEnum=H,H.create=(e,t)=>new H({values:e,typeName:se.ZodNativeEnum,...c(t)});class J extends d{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.ZodParsedType.promise&&!1===t.common.async)return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.promise,received:t.parsedType}),r.INVALID;const a=t.parsedType===n.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,r.OK)(a.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}e.ZodPromise=J,J.create=(e,t)=>new J({type:e,typeName:se.ZodPromise,...c(t)});class G extends d{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:e=>{(0,r.addIssueToContext)(a,e),e.fatal?t.abort():t.dirty()},get path(){return a.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===s.type){const e=s.transform(a.data,o);return a.common.issues.length?{status:"dirty",value:a.data}:a.common.async?Promise.resolve(e).then((e=>this._def.schema._parseAsync({data:e,path:a.path,parent:a}))):this._def.schema._parseSync({data:e,path:a.path,parent:a})}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,o);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const n=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===n.status?r.INVALID:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((a=>"aborted"===a.status?r.INVALID:("dirty"===a.status&&t.dirty(),e(a.value).then((()=>({status:t.value,value:a.value}))))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!(0,r.isValid)(e))return e;const n=s.transform(e.value,o);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>(0,r.isValid)(e)?Promise.resolve(s.transform(e.value,o)).then((e=>({status:t.value,value:e}))):e))}n.util.assertNever(s)}}e.ZodEffects=G,e.ZodTransformer=G,G.create=(e,t,a)=>new G({schema:e,typeName:se.ZodEffects,effect:t,...c(a)}),G.createWithPreprocess=(e,t,a)=>new G({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...c(a)});class X extends d{_parse(e){return this._getType(e)===n.ZodParsedType.undefined?(0,r.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}e.ZodOptional=X,X.create=(e,t)=>new X({innerType:e,typeName:se.ZodOptional,...c(t)});class Y extends d{_parse(e){return this._getType(e)===n.ZodParsedType.null?(0,r.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}e.ZodNullable=Y,Y.create=(e,t)=>new Y({innerType:e,typeName:se.ZodNullable,...c(t)});class Q extends d{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===n.ZodParsedType.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}e.ZodDefault=Q,Q.create=(e,t)=>new Q({innerType:e,typeName:se.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...c(t)});class ee extends d{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return(0,r.isAsync)(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new s.ZodError(a.common.issues)},input:a.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new s.ZodError(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}e.ZodCatch=ee,ee.create=(e,t)=>new ee({innerType:e,typeName:se.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...c(t)});class te extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.nan){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.nan,received:t.parsedType}),r.INVALID}return{status:"valid",value:e.data}}}e.ZodNaN=te,te.create=e=>new te({typeName:se.ZodNaN,...c(e)}),e.BRAND=Symbol("zod_brand");class ae extends d{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}}e.ZodBranded=ae;class re extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?r.INVALID:"dirty"===e.status?(t.dirty(),(0,r.DIRTY)(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})()}{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?r.INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(e,t){return new re({in:e,out:t,typeName:se.ZodPipeline})}}e.ZodPipeline=re;class ne extends d{_parse(e){const t=this._def.innerType._parse(e);return(0,r.isValid)(t)&&(t.value=Object.freeze(t.value)),t}}e.ZodReadonly=ne,ne.create=(e,t)=>new ne({innerType:e,typeName:se.ZodReadonly,...c(t)});var se;e.custom=(e,t={},a)=>e?R.create().superRefine(((r,n)=>{var s,o;if(!e(r)){const e="function"==typeof t?t(r):"string"==typeof t?{message:t}:t,i=null===(o=null!==(s=e.fatal)&&void 0!==s?s:a)||void 0===o||o,c="string"==typeof e?{message:e}:e;n.addIssue({code:"custom",...c,fatal:i})}})):R.create(),e.late={object:O.lazycreate},function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(se=e.ZodFirstPartyTypeKind||(e.ZodFirstPartyTypeKind={}));e.instanceof=(t,a={message:`Input not instance of ${t.name}`})=>(0,e.custom)((e=>e instanceof t),a);const oe=S.create;e.string=oe;const ie=w.create;e.number=ie;const ce=te.create;e.nan=ce;const de=b.create;e.bigint=de;const ue=C.create;e.boolean=ue;const le=x.create;e.date=le;const he=I.create;e.symbol=he;const pe=P.create;e.undefined=pe;const me=k.create;e.null=me;const fe=R.create;e.any=fe;const ge=_.create;e.unknown=ge;const ye=E.create;e.never=ye;const Se=T.create;e.void=Se;const ve=N.create;e.array=ve;const we=O.create;e.object=we;const be=O.strictCreate;e.strictObject=be;const Ce=M.create;e.union=Ce;const xe=D.create;e.discriminatedUnion=xe;const Ie=z.create;e.intersection=Ie;const Pe=L.create;e.tuple=Pe;const ke=Z.create;e.record=ke;const Re=U.create;e.map=Re;const _e=q.create;e.set=_e;const Ee=V.create;e.function=Ee;const Te=F.create;e.lazy=Te;const Ne=$.create;e.literal=Ne;const je=W.create;e.enum=je;const Oe=H.create;e.nativeEnum=Oe;const Me=J.create;e.promise=Me;const Ae=G.create;e.effect=Ae,e.transformer=Ae;const De=X.create;e.optional=De;const Be=Y.create;e.nullable=Be;const ze=G.createWithPreprocess;e.preprocess=ze;const Le=re.create;e.pipeline=Le;e.ostring=()=>oe().optional();e.onumber=()=>ie().optional();e.oboolean=()=>ue().optional(),e.coerce={string:e=>S.create({...e,coerce:!0}),number:e=>w.create({...e,coerce:!0}),boolean:e=>C.create({...e,coerce:!0}),bigint:e=>b.create({...e,coerce:!0}),date:e=>x.create({...e,coerce:!0})},e.NEVER=r.INVALID}(Jr),function(t){var a=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[a]}})}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),r=e&&e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),r(Ar,t),r(Kr,t),r(Wr,t),r(Br,t),r(Jr,t),r(zr,t)}(Mr),function(t){var a=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[a]}})}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&a(t,e,n);return r(t,e),t},s=e&&e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.z=void 0;const o=n(Mr);t.z=o,s(Mr,t),t.default=o}(Or);var Xr={};!function(t){var a=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Input=t.InputCommandSchema=t.Log=t.LogEventSchema=t.Script=t.ScriptResultSchema=t.ScriptCommandSchema=t.ScriptEventSchema=t.Network=t.NetworkResultSchema=t.NetworkEventSchema=t.NetworkCommandSchema=t.BrowsingContext=t.BrowsingContextResultSchema=t.BrowsingContextEventSchema=t.BrowsingContextCommandSchema=t.Browser=t.BrowserCommandSchema=t.Session=t.SessionResultSchema=t.SessionCommandSchema=t.ErrorCodeSchema=t.JsUintSchema=t.JsIntSchema=t.ExtensibleSchema=t.EmptyResultSchema=t.ErrorResponseSchema=t.MessageSchema=t.EmptyParamsSchema=t.ResultDataSchema=t.CommandDataSchema=t.EventDataSchema=t.CommandResponseSchema=t.CommandSchema=t.EventSchema=void 0;const r=a(Or);var n,s,o,i,c,d,u;t.EventSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("event")}).and(t.EventDataSchema).and(t.ExtensibleSchema))),t.CommandSchema=r.default.lazy((()=>r.default.object({id:t.JsUintSchema}).and(t.CommandDataSchema).and(t.ExtensibleSchema))),t.CommandResponseSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("success"),id:t.JsUintSchema,result:t.ResultDataSchema}).and(t.ExtensibleSchema))),t.EventDataSchema=r.default.lazy((()=>r.default.union([t.BrowsingContextEventSchema,t.LogEventSchema,t.NetworkEventSchema,t.ScriptEventSchema]))),t.CommandDataSchema=r.default.lazy((()=>r.default.union([t.BrowserCommandSchema,t.BrowsingContextCommandSchema,t.InputCommandSchema,t.NetworkCommandSchema,t.ScriptCommandSchema,t.SessionCommandSchema]))),t.ResultDataSchema=r.default.lazy((()=>r.default.union([t.BrowsingContextResultSchema,t.EmptyResultSchema,t.NetworkResultSchema,t.ScriptResultSchema,t.SessionResultSchema]))),t.EmptyParamsSchema=r.default.lazy((()=>t.ExtensibleSchema)),t.MessageSchema=r.default.lazy((()=>r.default.union([t.CommandResponseSchema,t.ErrorResponseSchema,t.EventSchema]))),t.ErrorResponseSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("error"),id:r.default.union([t.JsUintSchema,r.default.null()]),error:t.ErrorCodeSchema,message:r.default.string(),stacktrace:r.default.string().optional()}).and(t.ExtensibleSchema))),t.EmptyResultSchema=r.default.lazy((()=>t.ExtensibleSchema)),t.ExtensibleSchema=r.default.lazy((()=>r.default.record(r.default.string(),r.default.any()))),t.JsIntSchema=r.default.lazy((()=>r.default.number().int().gte(-9007199254740991).lte(9007199254740991))),t.JsUintSchema=r.default.lazy((()=>r.default.number().int().nonnegative().gte(0).lte(9007199254740991))),t.ErrorCodeSchema=r.default.lazy((()=>r.default.enum(["invalid argument","invalid session id","move target out of bounds","no such alert","no such element","no such frame","no such handle","no such intercept","no such node","no such request","no such script","session not created","unable to capture screen","unable to close browser","unknown command","unknown error","unsupported operation"]))),t.SessionCommandSchema=r.default.lazy((()=>r.default.union([n.EndSchema,n.NewSchema,n.StatusSchema,n.SubscribeSchema,n.UnsubscribeSchema]))),t.SessionResultSchema=r.default.lazy((()=>r.default.union([n.NewResultSchema,n.StatusResultSchema]))),function(e){e.CapabilitiesRequestSchema=r.default.lazy((()=>r.default.object({alwaysMatch:e.CapabilityRequestSchema.optional(),firstMatch:r.default.array(e.CapabilityRequestSchema).optional()})))}(n||(t.Session=n={})),function(e){e.CapabilityRequestSchema=r.default.lazy((()=>r.default.object({acceptInsecureCerts:r.default.boolean().optional(),browserName:r.default.string().optional(),browserVersion:r.default.string().optional(),platformName:r.default.string().optional(),proxy:r.default.object({proxyType:r.default.enum(["pac","direct","autodetect","system","manual"]).optional(),proxyAutoconfigUrl:r.default.string().optional(),ftpProxy:r.default.string().optional(),httpProxy:r.default.string().optional(),noProxy:r.default.array(r.default.string()).optional(),sslProxy:r.default.string().optional(),socksProxy:r.default.string().optional(),socksVersion:r.default.number().int().nonnegative().gte(0).lte(255).optional()}).optional()}).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.SubscriptionRequestSchema=r.default.lazy((()=>r.default.object({events:r.default.array(r.default.string()),contexts:r.default.array(o.BrowsingContextSchema).optional()})))}(n||(t.Session=n={})),function(e){e.StatusSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.status"),params:t.EmptyParamsSchema})))}(n||(t.Session=n={})),function(e){e.StatusResultSchema=r.default.lazy((()=>r.default.object({ready:r.default.boolean(),message:r.default.string()})))}(n||(t.Session=n={})),function(e){e.NewSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.new"),params:e.NewParametersSchema})))}(n||(t.Session=n={})),function(e){e.NewParametersSchema=r.default.lazy((()=>r.default.object({capabilities:e.CapabilitiesRequestSchema})))}(n||(t.Session=n={})),function(e){e.NewResultSchema=r.default.lazy((()=>r.default.object({sessionId:r.default.string(),capabilities:r.default.object({acceptInsecureCerts:r.default.boolean(),browserName:r.default.string(),browserVersion:r.default.string(),platformName:r.default.string(),proxy:r.default.object({proxyType:r.default.enum(["pac","direct","autodetect","system","manual"]).optional(),proxyAutoconfigUrl:r.default.string().optional(),ftpProxy:r.default.string().optional(),httpProxy:r.default.string().optional(),noProxy:r.default.array(r.default.string()).optional(),sslProxy:r.default.string().optional(),socksProxy:r.default.string().optional(),socksVersion:r.default.number().int().nonnegative().gte(0).lte(255).optional()}),setWindowRect:r.default.boolean()}).and(t.ExtensibleSchema)})))}(n||(t.Session=n={})),function(e){e.EndSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.end"),params:t.EmptyParamsSchema})))}(n||(t.Session=n={})),function(e){e.SubscribeSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.subscribe"),params:e.SubscriptionRequestSchema})))}(n||(t.Session=n={})),function(e){e.UnsubscribeSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.unsubscribe"),params:e.SubscriptionRequestSchema})))}(n||(t.Session=n={})),t.BrowserCommandSchema=r.default.lazy((()=>s.CloseSchema)),function(e){e.CloseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browser.close"),params:t.EmptyParamsSchema})))}(s||(t.Browser=s={})),t.BrowsingContextCommandSchema=r.default.lazy((()=>r.default.union([o.ActivateSchema,o.CaptureScreenshotSchema,o.CloseSchema,o.CreateSchema,o.GetTreeSchema,o.HandleUserPromptSchema,o.NavigateSchema,o.PrintSchema,o.ReloadSchema,o.SetViewportSchema]))),t.BrowsingContextEventSchema=r.default.lazy((()=>r.default.union([o.ContextCreatedSchema,o.ContextDestroyedSchema,o.DomContentLoadedSchema,o.DownloadWillBeginSchema,o.FragmentNavigatedSchema,o.LoadSchema,o.NavigationAbortedSchema,o.NavigationFailedSchema,o.NavigationStartedSchema,o.UserPromptClosedSchema,o.UserPromptOpenedSchema]))),t.BrowsingContextResultSchema=r.default.lazy((()=>r.default.union([o.CaptureScreenshotResultSchema,o.CreateResultSchema,o.GetTreeResultSchema,o.NavigateResultSchema,o.PrintResultSchema]))),function(e){e.BrowsingContextSchema=r.default.lazy((()=>r.default.string()))}(o||(t.BrowsingContext=o={})),function(e){e.InfoListSchema=r.default.lazy((()=>r.default.array(e.InfoSchema)))}(o||(t.BrowsingContext=o={})),function(e){e.InfoSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,url:r.default.string(),children:r.default.union([e.InfoListSchema,r.default.null()]),parent:r.default.union([e.BrowsingContextSchema,r.default.null()]).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationSchema=r.default.lazy((()=>r.default.string()))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationInfoSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,navigation:r.default.union([e.NavigationSchema,r.default.null()]),timestamp:t.JsUintSchema,url:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.ReadinessStateSchema=r.default.lazy((()=>r.default.enum(["none","interactive","complete"])))}(o||(t.BrowsingContext=o={})),function(e){e.ActivateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.activate"),params:e.ActivateParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ActivateParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CaptureScreenshotParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,origin:r.default.enum(["viewport","document"]).default("viewport").optional(),format:e.ImageFormatSchema.optional(),clip:e.ClipRectangleSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.CaptureScreenshotSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.captureScreenshot"),params:e.CaptureScreenshotParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ImageFormatSchema=r.default.lazy((()=>r.default.object({type:r.default.string(),quality:r.default.number().gte(0).lte(1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.ClipRectangleSchema=r.default.lazy((()=>r.default.union([e.BoxClipRectangleSchema,e.ElementClipRectangleSchema])))}(o||(t.BrowsingContext=o={})),function(e){e.ElementClipRectangleSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("element"),element:c.SharedReferenceSchema,scrollIntoView:r.default.boolean().optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.BoxClipRectangleSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("box"),x:r.default.number(),y:r.default.number(),width:r.default.number(),height:r.default.number()})))}(o||(t.BrowsingContext=o={})),function(e){e.CaptureScreenshotResultSchema=r.default.lazy((()=>r.default.object({data:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.CloseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.close"),params:e.CloseParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CloseParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CreateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.create"),params:e.CreateParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CreateTypeSchema=r.default.lazy((()=>r.default.enum(["tab","window"])))}(o||(t.BrowsingContext=o={})),function(e){e.CreateParametersSchema=r.default.lazy((()=>r.default.object({type:e.CreateTypeSchema,referenceContext:e.BrowsingContextSchema.optional(),background:r.default.boolean().default(!1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.CreateResultSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.GetTreeSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.getTree"),params:e.GetTreeParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.GetTreeParametersSchema=r.default.lazy((()=>r.default.object({maxDepth:t.JsUintSchema.optional(),root:e.BrowsingContextSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.GetTreeResultSchema=r.default.lazy((()=>r.default.object({contexts:e.InfoListSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.HandleUserPromptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.handleUserPrompt"),params:e.HandleUserPromptParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.HandleUserPromptParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,accept:r.default.boolean().optional(),userText:r.default.string().optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigate"),params:e.NavigateParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigateParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,url:r.default.string(),wait:e.ReadinessStateSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigateResultSchema=r.default.lazy((()=>r.default.object({navigation:r.default.union([e.NavigationSchema,r.default.null()]),url:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.print"),params:e.PrintParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,background:r.default.boolean().default(!1).optional(),margin:e.PrintMarginParametersSchema.optional(),orientation:r.default.enum(["portrait","landscape"]).default("portrait").optional(),page:e.PrintPageParametersSchema.optional(),pageRanges:r.default.array(r.default.union([t.JsUintSchema,r.default.string()])).optional(),scale:r.default.number().gte(.1).lte(2).default(1).optional(),shrinkToFit:r.default.boolean().default(!0).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintMarginParametersSchema=r.default.lazy((()=>r.default.object({bottom:r.default.number().gte(0).default(1).optional(),left:r.default.number().gte(0).default(1).optional(),right:r.default.number().gte(0).default(1).optional(),top:r.default.number().gte(0).default(1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintPageParametersSchema=r.default.lazy((()=>r.default.object({height:r.default.number().gte(.0352).default(27.94).optional(),width:r.default.number().gte(.0352).default(21.59).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintResultSchema=r.default.lazy((()=>r.default.object({data:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.ReloadSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.reload"),params:e.ReloadParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ReloadParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,ignoreCache:r.default.boolean().optional(),wait:e.ReadinessStateSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.SetViewportSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.setViewport"),params:e.SetViewportParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.SetViewportParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,viewport:r.default.union([e.ViewportSchema,r.default.null()]).optional(),devicePixelRatio:r.default.union([r.default.number().gt(0),r.default.null()]).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.ViewportSchema=r.default.lazy((()=>r.default.object({width:t.JsUintSchema,height:t.JsUintSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ContextCreatedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.contextCreated"),params:e.InfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ContextDestroyedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.contextDestroyed"),params:e.InfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationStartedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigationStarted"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.FragmentNavigatedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.fragmentNavigated"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.DomContentLoadedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.domContentLoaded"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.LoadSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.load"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.DownloadWillBeginSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.downloadWillBegin"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationAbortedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigationAborted"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationFailedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigationFailed"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptClosedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.userPromptClosed"),params:e.UserPromptClosedParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptClosedParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,accepted:r.default.boolean(),userText:r.default.string().optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptOpenedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.userPromptOpened"),params:e.UserPromptOpenedParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptOpenedParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,type:r.default.enum(["alert","confirm","prompt","beforeunload"]),message:r.default.string(),defaultValue:r.default.string().optional()})))}(o||(t.BrowsingContext=o={})),t.NetworkCommandSchema=r.default.lazy((()=>r.default.union([i.AddInterceptSchema,i.ContinueRequestSchema,i.ContinueResponseSchema,i.ContinueWithAuthSchema,i.FailRequestSchema,i.ProvideResponseSchema,i.RemoveInterceptSchema]))),t.NetworkEventSchema=r.default.lazy((()=>r.default.union([i.AuthRequiredSchema,i.BeforeRequestSentSchema,i.FetchErrorSchema,i.ResponseCompletedSchema,i.ResponseStartedSchema]))),t.NetworkResultSchema=r.default.lazy((()=>i.AddInterceptResultSchema)),function(e){e.AuthChallengeSchema=r.default.lazy((()=>r.default.object({scheme:r.default.string(),realm:r.default.string()})))}(i||(t.Network=i={})),function(e){e.AuthCredentialsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("password"),username:r.default.string(),password:r.default.string()})))}(i||(t.Network=i={})),function(e){e.BaseParametersSchema=r.default.lazy((()=>r.default.object({context:r.default.union([o.BrowsingContextSchema,r.default.null()]),isBlocked:r.default.boolean(),navigation:r.default.union([o.NavigationSchema,r.default.null()]),redirectCount:t.JsUintSchema,request:e.RequestDataSchema,timestamp:t.JsUintSchema,intercepts:r.default.array(e.InterceptSchema).optional()})))}(i||(t.Network=i={})),function(e){e.BytesValueSchema=r.default.lazy((()=>r.default.union([e.StringValueSchema,e.Base64ValueSchema])))}(i||(t.Network=i={})),function(e){e.StringValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("string"),value:r.default.string()})))}(i||(t.Network=i={})),function(e){e.Base64ValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("base64"),value:r.default.string()})))}(i||(t.Network=i={})),function(e){e.CookieSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema,domain:r.default.string(),path:r.default.string(),size:t.JsUintSchema,httpOnly:r.default.boolean(),secure:r.default.boolean(),sameSite:r.default.enum(["strict","lax","none"]),expires:t.JsUintSchema.optional()})))}(i||(t.Network=i={})),function(e){e.CookieHeaderSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema})))}(i||(t.Network=i={})),function(e){e.FetchTimingInfoSchema=r.default.lazy((()=>r.default.object({timeOrigin:r.default.number(),requestTime:r.default.number(),redirectStart:r.default.number(),redirectEnd:r.default.number(),fetchStart:r.default.number(),dnsStart:r.default.number(),dnsEnd:r.default.number(),connectStart:r.default.number(),connectEnd:r.default.number(),tlsStart:r.default.number(),requestStart:r.default.number(),responseStart:r.default.number(),responseEnd:r.default.number()})))}(i||(t.Network=i={})),function(e){e.HeaderSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema})))}(i||(t.Network=i={})),function(e){e.InitiatorSchema=r.default.lazy((()=>r.default.object({type:r.default.enum(["parser","script","preflight","other"]),columnNumber:t.JsUintSchema.optional(),lineNumber:t.JsUintSchema.optional(),stackTrace:c.StackTraceSchema.optional(),request:e.RequestSchema.optional()})))}(i||(t.Network=i={})),function(e){e.InterceptSchema=r.default.lazy((()=>r.default.string()))}(i||(t.Network=i={})),function(e){e.RequestSchema=r.default.lazy((()=>r.default.string()))}(i||(t.Network=i={})),function(e){e.RequestDataSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,url:r.default.string(),method:r.default.string(),headers:r.default.array(e.HeaderSchema),cookies:r.default.array(e.CookieSchema),headersSize:t.JsUintSchema,bodySize:r.default.union([t.JsUintSchema,r.default.null()]),timings:e.FetchTimingInfoSchema})))}(i||(t.Network=i={})),function(e){e.ResponseContentSchema=r.default.lazy((()=>r.default.object({size:t.JsUintSchema})))}(i||(t.Network=i={})),function(e){e.ResponseDataSchema=r.default.lazy((()=>r.default.object({url:r.default.string(),protocol:r.default.string(),status:t.JsUintSchema,statusText:r.default.string(),fromCache:r.default.boolean(),headers:r.default.array(e.HeaderSchema),mimeType:r.default.string(),bytesReceived:t.JsUintSchema,headersSize:r.default.union([t.JsUintSchema,r.default.null()]),bodySize:r.default.union([t.JsUintSchema,r.default.null()]),content:e.ResponseContentSchema,authChallenge:e.AuthChallengeSchema.optional()})))}(i||(t.Network=i={})),function(e){e.SetCookieHeaderSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema,domain:r.default.string().optional(),httpOnly:r.default.boolean().optional(),expires:r.default.string().optional(),maxAge:t.JsIntSchema.optional(),path:r.default.string().optional(),sameSite:r.default.enum(["strict","lax","none"]).optional(),secure:r.default.boolean().optional()})))}(i||(t.Network=i={})),function(e){e.UrlPatternSchema=r.default.lazy((()=>r.default.union([e.UrlPatternPatternSchema,e.UrlPatternStringSchema])))}(i||(t.Network=i={})),function(e){e.UrlPatternPatternSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pattern"),protocol:r.default.string().optional(),hostname:r.default.string().optional(),port:r.default.string().optional(),pathname:r.default.string().optional(),search:r.default.string().optional()})))}(i||(t.Network=i={})),function(e){e.UrlPatternStringSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("string"),pattern:r.default.string()})))}(i||(t.Network=i={})),function(e){e.AddInterceptParametersSchema=r.default.lazy((()=>r.default.object({phases:r.default.array(e.InterceptPhaseSchema),urlPatterns:r.default.array(e.UrlPatternSchema).optional()})))}(i||(t.Network=i={})),function(e){e.AddInterceptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.addIntercept"),params:e.AddInterceptParametersSchema})))}(i||(t.Network=i={})),function(e){e.InterceptPhaseSchema=r.default.lazy((()=>r.default.enum(["beforeRequestSent","responseStarted","authRequired"])))}(i||(t.Network=i={})),function(e){e.AddInterceptResultSchema=r.default.lazy((()=>r.default.object({intercept:e.InterceptSchema})))}(i||(t.Network=i={})),function(e){e.ContinueRequestSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.continueRequest"),params:e.ContinueRequestParametersSchema})))}(i||(t.Network=i={})),function(e){e.ContinueRequestParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,body:e.BytesValueSchema.optional(),cookies:r.default.array(e.CookieHeaderSchema).optional(),headers:r.default.array(e.HeaderSchema).optional(),method:r.default.string().optional(),url:r.default.string().optional()})))}(i||(t.Network=i={})),function(e){e.ContinueResponseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.continueResponse"),params:e.ContinueResponseParametersSchema})))}(i||(t.Network=i={})),function(e){e.ContinueResponseParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,cookies:r.default.array(e.SetCookieHeaderSchema).optional(),credentials:e.AuthCredentialsSchema.optional(),headers:r.default.array(e.HeaderSchema).optional(),reasonPhrase:r.default.string().optional(),statusCode:t.JsUintSchema.optional()})))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.continueWithAuth"),params:e.ContinueWithAuthParametersSchema})))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema}).and(r.default.union([e.ContinueWithAuthCredentialsSchema,e.ContinueWithAuthNoCredentialsSchema]))))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthCredentialsSchema=r.default.lazy((()=>r.default.object({action:r.default.literal("provideCredentials"),credentials:e.AuthCredentialsSchema})))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthNoCredentialsSchema=r.default.lazy((()=>r.default.object({action:r.default.enum(["default","cancel"])})))}(i||(t.Network=i={})),function(e){e.FailRequestSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.failRequest"),params:e.FailRequestParametersSchema})))}(i||(t.Network=i={})),function(e){e.FailRequestParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema})))}(i||(t.Network=i={})),function(e){e.ProvideResponseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.provideResponse"),params:e.ProvideResponseParametersSchema})))}(i||(t.Network=i={})),function(e){e.ProvideResponseParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,body:e.BytesValueSchema.optional(),cookies:r.default.array(e.SetCookieHeaderSchema).optional(),headers:r.default.array(e.HeaderSchema).optional(),reasonPhrase:r.default.string().optional(),statusCode:t.JsUintSchema.optional()})))}(i||(t.Network=i={})),function(e){e.RemoveInterceptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.removeIntercept"),params:e.RemoveInterceptParametersSchema})))}(i||(t.Network=i={})),function(e){e.RemoveInterceptParametersSchema=r.default.lazy((()=>r.default.object({intercept:e.InterceptSchema})))}(i||(t.Network=i={})),t.ScriptEventSchema=r.default.lazy((()=>r.default.union([c.MessageSchema,c.RealmCreatedSchema,c.RealmDestroyedSchema]))),function(e){e.AuthRequiredParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({response:e.ResponseDataSchema}))))}(i||(t.Network=i={})),function(e){e.BeforeRequestSentParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({initiator:e.InitiatorSchema}))))}(i||(t.Network=i={})),function(e){e.FetchErrorParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({errorText:r.default.string()}))))}(i||(t.Network=i={})),function(e){e.ResponseCompletedParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({response:e.ResponseDataSchema}))))}(i||(t.Network=i={})),function(e){e.ResponseStartedParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({response:e.ResponseDataSchema}))))}(i||(t.Network=i={})),t.ScriptCommandSchema=r.default.lazy((()=>r.default.union([c.AddPreloadScriptSchema,c.CallFunctionSchema,c.DisownSchema,c.EvaluateSchema,c.GetRealmsSchema,c.RemovePreloadScriptSchema]))),t.ScriptResultSchema=r.default.lazy((()=>r.default.union([c.AddPreloadScriptResultSchema,c.EvaluateResultSchema,c.GetRealmsResultSchema]))),function(e){e.AuthRequiredSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.authRequired"),params:e.AuthRequiredParametersSchema})))}(i||(t.Network=i={})),function(e){e.BeforeRequestSentSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.beforeRequestSent"),params:e.BeforeRequestSentParametersSchema})))}(i||(t.Network=i={})),function(e){e.FetchErrorSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.fetchError"),params:e.FetchErrorParametersSchema})))}(i||(t.Network=i={})),function(e){e.ResponseCompletedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.responseCompleted"),params:e.ResponseCompletedParametersSchema})))}(i||(t.Network=i={})),function(e){e.ResponseStartedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.responseStarted"),params:e.ResponseStartedParametersSchema})))}(i||(t.Network=i={})),function(e){e.ChannelSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.EvaluateResultSuccessSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("success"),result:e.RemoteValueSchema,realm:e.RealmSchema})))}(c||(t.Script=c={})),function(e){e.ExceptionDetailsSchema=r.default.lazy((()=>r.default.object({columnNumber:t.JsUintSchema,exception:e.RemoteValueSchema,lineNumber:t.JsUintSchema,stackTrace:e.StackTraceSchema,text:r.default.string()})))}(c||(t.Script=c={})),function(e){e.ChannelValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("channel"),value:e.ChannelPropertiesSchema})))}(c||(t.Script=c={})),function(e){e.ChannelPropertiesSchema=r.default.lazy((()=>r.default.object({channel:e.ChannelSchema,serializationOptions:e.SerializationOptionsSchema.optional(),ownership:e.ResultOwnershipSchema.optional()})))}(c||(t.Script=c={})),function(e){e.EvaluateResultSchema=r.default.lazy((()=>r.default.union([e.EvaluateResultSuccessSchema,e.EvaluateResultExceptionSchema])))}(c||(t.Script=c={})),function(e){e.EvaluateResultExceptionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("exception"),exceptionDetails:e.ExceptionDetailsSchema,realm:e.RealmSchema})))}(c||(t.Script=c={})),function(e){e.HandleSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.ListLocalValueSchema=r.default.lazy((()=>r.default.array(e.LocalValueSchema)))}(c||(t.Script=c={})),function(e){e.LocalValueSchema=r.default.lazy((()=>r.default.union([e.RemoteReferenceSchema,e.PrimitiveProtocolValueSchema,e.ChannelValueSchema,e.ArrayLocalValueSchema,e.DateLocalValueSchema,e.MapLocalValueSchema,e.ObjectLocalValueSchema,e.RegExpLocalValueSchema,e.SetLocalValueSchema])))}(c||(t.Script=c={})),function(e){e.ArrayLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("array"),value:e.ListLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.DateLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("date"),value:r.default.string()})))}(c||(t.Script=c={})),function(e){e.MappingLocalValueSchema=r.default.lazy((()=>r.default.array(r.default.tuple([r.default.union([e.LocalValueSchema,r.default.string()]),e.LocalValueSchema]))))}(c||(t.Script=c={})),function(e){e.MapLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("map"),value:e.MappingLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.ObjectLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("object"),value:e.MappingLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.RegExpValueSchema=r.default.lazy((()=>r.default.object({pattern:r.default.string(),flags:r.default.string().optional()})))}(c||(t.Script=c={})),function(e){e.RegExpLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("regexp"),value:e.RegExpValueSchema})))}(c||(t.Script=c={})),function(e){e.SetLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("set"),value:e.ListLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.PreloadScriptSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.RealmSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.PrimitiveProtocolValueSchema=r.default.lazy((()=>r.default.union([e.UndefinedValueSchema,e.NullValueSchema,e.StringValueSchema,e.NumberValueSchema,e.BooleanValueSchema,e.BigIntValueSchema])))}(c||(t.Script=c={})),function(e){e.UndefinedValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("undefined")})))}(c||(t.Script=c={})),function(e){e.NullValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("null")})))}(c||(t.Script=c={})),function(e){e.StringValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("string"),value:r.default.string()})))}(c||(t.Script=c={})),function(e){e.SpecialNumberSchema=r.default.lazy((()=>r.default.enum(["NaN","-0","Infinity","-Infinity"])))}(c||(t.Script=c={})),function(e){e.NumberValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("number"),value:r.default.union([r.default.number(),e.SpecialNumberSchema])})))}(c||(t.Script=c={})),function(e){e.BooleanValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("boolean"),value:r.default.boolean()})))}(c||(t.Script=c={})),function(e){e.BigIntValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("bigint"),value:r.default.string()})))}(c||(t.Script=c={})),function(e){e.RealmInfoSchema=r.default.lazy((()=>r.default.union([e.WindowRealmInfoSchema,e.DedicatedWorkerRealmInfoSchema,e.SharedWorkerRealmInfoSchema,e.ServiceWorkerRealmInfoSchema,e.WorkerRealmInfoSchema,e.PaintWorkletRealmInfoSchema,e.AudioWorkletRealmInfoSchema,e.WorkletRealmInfoSchema])))}(c||(t.Script=c={})),function(e){e.BaseRealmInfoSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema,origin:r.default.string()})))}(c||(t.Script=c={})),function(e){e.WindowRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("window"),context:o.BrowsingContextSchema,sandbox:r.default.string().optional()}))))}(c||(t.Script=c={})),function(e){e.DedicatedWorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("dedicated-worker")}))))}(c||(t.Script=c={})),function(e){e.SharedWorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("shared-worker")}))))}(c||(t.Script=c={})),function(e){e.ServiceWorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("service-worker")}))))}(c||(t.Script=c={})),function(e){e.WorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("worker")}))))}(c||(t.Script=c={})),function(e){e.PaintWorkletRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("paint-worklet")}))))}(c||(t.Script=c={})),function(e){e.AudioWorkletRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("audio-worklet")}))))}(c||(t.Script=c={})),function(e){e.WorkletRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("worklet")}))))}(c||(t.Script=c={})),function(e){e.RealmTypeSchema=r.default.lazy((()=>r.default.enum(["window","dedicated-worker","shared-worker","service-worker","worker","paint-worklet","audio-worklet","worklet"])))}(c||(t.Script=c={})),function(e){e.RemoteValueSchema=r.default.lazy((()=>r.default.union([e.PrimitiveProtocolValueSchema,e.SymbolRemoteValueSchema,e.ArrayRemoteValueSchema,e.ObjectRemoteValueSchema,e.FunctionRemoteValueSchema,e.RegExpRemoteValueSchema,e.DateRemoteValueSchema,e.MapRemoteValueSchema,e.SetRemoteValueSchema,e.WeakMapRemoteValueSchema,e.WeakSetRemoteValueSchema,e.IteratorRemoteValueSchema,e.GeneratorRemoteValueSchema,e.ErrorRemoteValueSchema,e.ProxyRemoteValueSchema,e.PromiseRemoteValueSchema,e.TypedArrayRemoteValueSchema,e.ArrayBufferRemoteValueSchema,e.NodeListRemoteValueSchema,e.HtmlCollectionRemoteValueSchema,e.NodeRemoteValueSchema,e.WindowProxyRemoteValueSchema])))}(c||(t.Script=c={})),function(e){e.RemoteReferenceSchema=r.default.lazy((()=>r.default.union([e.SharedReferenceSchema,e.RemoteObjectReferenceSchema])))}(c||(t.Script=c={})),function(e){e.SharedReferenceSchema=r.default.lazy((()=>r.default.object({sharedId:e.SharedIdSchema,handle:e.HandleSchema.optional()}).and(t.ExtensibleSchema)))}(c||(t.Script=c={})),function(e){e.RemoteObjectReferenceSchema=r.default.lazy((()=>r.default.object({handle:e.HandleSchema,sharedId:e.SharedIdSchema.optional()}).and(t.ExtensibleSchema)))}(c||(t.Script=c={})),function(e){e.InternalIdSchema=r.default.lazy((()=>t.JsUintSchema))}(c||(t.Script=c={})),function(e){e.ListRemoteValueSchema=r.default.lazy((()=>r.default.array(e.RemoteValueSchema)))}(c||(t.Script=c={})),function(e){e.MappingRemoteValueSchema=r.default.lazy((()=>r.default.array(r.default.tuple([r.default.union([e.RemoteValueSchema,r.default.string()]),e.RemoteValueSchema]))))}(c||(t.Script=c={})),function(e){e.SymbolRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("symbol"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ArrayRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("array"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ObjectRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("object"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.MappingRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.FunctionRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("function"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.RegExpRemoteValueSchema=r.default.lazy((()=>r.default.object({handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()}).and(e.RegExpLocalValueSchema)))}(c||(t.Script=c={})),function(e){e.DateRemoteValueSchema=r.default.lazy((()=>r.default.object({handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()}).and(e.DateLocalValueSchema)))}(c||(t.Script=c={})),function(e){e.MapRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("map"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.MappingRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.SetRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("set"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.WeakMapRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("weakmap"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.WeakSetRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("weakset"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.IteratorRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("iterator"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.GeneratorRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("generator"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ErrorRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("error"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ProxyRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("proxy"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.PromiseRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("promise"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.TypedArrayRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("typedarray"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ArrayBufferRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("arraybuffer"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.NodeListRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("nodelist"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.HtmlCollectionRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("htmlcollection"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.NodeRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("node"),sharedId:e.SharedIdSchema.optional(),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.NodePropertiesSchema.optional()})))}(c||(t.Script=c={})),function(e){e.NodePropertiesSchema=r.default.lazy((()=>r.default.object({nodeType:t.JsUintSchema,childNodeCount:t.JsUintSchema,attributes:r.default.record(r.default.string(),r.default.string()).optional(),children:r.default.array(e.NodeRemoteValueSchema).optional(),localName:r.default.string().optional(),mode:r.default.enum(["open","closed"]).optional(),namespaceURI:r.default.string().optional(),nodeValue:r.default.string().optional(),shadowRoot:r.default.union([e.NodeRemoteValueSchema,r.default.null()]).optional()})))}(c||(t.Script=c={})),function(e){e.WindowProxyRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("window"),value:e.WindowProxyPropertiesSchema,handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.WindowProxyPropertiesSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema})))}(c||(t.Script=c={})),function(e){e.ResultOwnershipSchema=r.default.lazy((()=>r.default.enum(["root","none"])))}(c||(t.Script=c={})),function(e){e.SerializationOptionsSchema=r.default.lazy((()=>r.default.object({maxDomDepth:r.default.union([t.JsUintSchema,r.default.null()]).default(0).optional(),maxObjectDepth:r.default.union([t.JsUintSchema,r.default.null()]).default(null).optional(),includeShadowTree:r.default.enum(["none","open","all"]).default("none").optional()})))}(c||(t.Script=c={})),function(e){e.SharedIdSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.StackFrameSchema=r.default.lazy((()=>r.default.object({columnNumber:t.JsUintSchema,functionName:r.default.string(),lineNumber:t.JsUintSchema,url:r.default.string()})))}(c||(t.Script=c={})),function(e){e.StackTraceSchema=r.default.lazy((()=>r.default.object({callFrames:r.default.array(e.StackFrameSchema)})))}(c||(t.Script=c={})),function(e){e.SourceSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema,context:o.BrowsingContextSchema.optional()})))}(c||(t.Script=c={})),function(e){e.RealmTargetSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema})))}(c||(t.Script=c={})),function(e){e.ContextTargetSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema,sandbox:r.default.string().optional()})))}(c||(t.Script=c={})),function(e){e.TargetSchema=r.default.lazy((()=>r.default.union([e.RealmTargetSchema,e.ContextTargetSchema])))}(c||(t.Script=c={})),function(e){e.AddPreloadScriptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.addPreloadScript"),params:e.AddPreloadScriptParametersSchema})))}(c||(t.Script=c={})),function(e){e.AddPreloadScriptParametersSchema=r.default.lazy((()=>r.default.object({functionDeclaration:r.default.string(),arguments:r.default.array(e.ChannelValueSchema).optional(),contexts:r.default.array(o.BrowsingContextSchema).optional(),sandbox:r.default.string().optional()})))}(c||(t.Script=c={})),function(e){e.AddPreloadScriptResultSchema=r.default.lazy((()=>r.default.object({script:e.PreloadScriptSchema})))}(c||(t.Script=c={})),function(e){e.DisownSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.disown"),params:e.DisownParametersSchema})))}(c||(t.Script=c={})),function(e){e.DisownParametersSchema=r.default.lazy((()=>r.default.object({handles:r.default.array(e.HandleSchema),target:e.TargetSchema})))}(c||(t.Script=c={})),function(e){e.CallFunctionParametersSchema=r.default.lazy((()=>r.default.object({functionDeclaration:r.default.string(),awaitPromise:r.default.boolean(),target:e.TargetSchema,arguments:r.default.array(e.LocalValueSchema).optional(),resultOwnership:e.ResultOwnershipSchema.optional(),serializationOptions:e.SerializationOptionsSchema.optional(),this:e.LocalValueSchema.optional(),userActivation:r.default.boolean().default(!1).optional()})))}(c||(t.Script=c={})),function(e){e.CallFunctionSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.callFunction"),params:e.CallFunctionParametersSchema})))}(c||(t.Script=c={})),function(e){e.EvaluateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.evaluate"),params:e.EvaluateParametersSchema})))}(c||(t.Script=c={})),function(e){e.EvaluateParametersSchema=r.default.lazy((()=>r.default.object({expression:r.default.string(),target:e.TargetSchema,awaitPromise:r.default.boolean(),resultOwnership:e.ResultOwnershipSchema.optional(),serializationOptions:e.SerializationOptionsSchema.optional(),userActivation:r.default.boolean().default(!1).optional()})))}(c||(t.Script=c={})),function(e){e.GetRealmsSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.getRealms"),params:e.GetRealmsParametersSchema})))}(c||(t.Script=c={})),function(e){e.GetRealmsParametersSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema.optional(),type:e.RealmTypeSchema.optional()})))}(c||(t.Script=c={})),function(e){e.GetRealmsResultSchema=r.default.lazy((()=>r.default.object({realms:r.default.array(e.RealmInfoSchema)})))}(c||(t.Script=c={})),function(e){e.RemovePreloadScriptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.removePreloadScript"),params:e.RemovePreloadScriptParametersSchema})))}(c||(t.Script=c={})),function(e){e.RemovePreloadScriptParametersSchema=r.default.lazy((()=>r.default.object({script:e.PreloadScriptSchema})))}(c||(t.Script=c={})),function(e){e.MessageParametersSchema=r.default.lazy((()=>r.default.object({channel:e.ChannelSchema,data:e.RemoteValueSchema,source:e.SourceSchema})))}(c||(t.Script=c={})),function(e){e.RealmCreatedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.realmCreated"),params:e.RealmInfoSchema})))}(c||(t.Script=c={})),function(e){e.MessageSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.message"),params:e.MessageParametersSchema})))}(c||(t.Script=c={})),function(e){e.RealmDestroyedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.realmDestroyed"),params:e.RealmDestroyedParametersSchema})))}(c||(t.Script=c={})),function(e){e.RealmDestroyedParametersSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema})))}(c||(t.Script=c={})),t.LogEventSchema=r.default.lazy((()=>d.EntryAddedSchema)),function(e){e.LevelSchema=r.default.lazy((()=>r.default.enum(["debug","info","warn","error"])))}(d||(t.Log=d={})),function(e){e.EntrySchema=r.default.lazy((()=>r.default.union([e.GenericLogEntrySchema,e.ConsoleLogEntrySchema,e.JavascriptLogEntrySchema])))}(d||(t.Log=d={})),function(e){e.BaseLogEntrySchema=r.default.lazy((()=>r.default.object({level:e.LevelSchema,source:c.SourceSchema,text:r.default.union([r.default.string(),r.default.null()]),timestamp:t.JsUintSchema,stackTrace:c.StackTraceSchema.optional()})))}(d||(t.Log=d={})),function(e){e.GenericLogEntrySchema=r.default.lazy((()=>e.BaseLogEntrySchema.and(r.default.object({type:r.default.string()}))))}(d||(t.Log=d={})),function(e){e.ConsoleLogEntrySchema=r.default.lazy((()=>e.BaseLogEntrySchema.and(r.default.object({type:r.default.literal("console"),method:r.default.string(),args:r.default.array(c.RemoteValueSchema)}))))}(d||(t.Log=d={})),function(e){e.JavascriptLogEntrySchema=r.default.lazy((()=>e.BaseLogEntrySchema.and(r.default.object({type:r.default.literal("javascript")}))))}(d||(t.Log=d={})),function(e){e.EntryAddedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("log.entryAdded"),params:e.EntrySchema})))}(d||(t.Log=d={})),t.InputCommandSchema=r.default.lazy((()=>r.default.union([u.PerformActionsSchema,u.ReleaseActionsSchema]))),function(e){e.ElementOriginSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("element"),element:c.SharedReferenceSchema})))}(u||(t.Input=u={})),function(e){e.PerformActionsParametersSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema,actions:r.default.array(e.SourceActionsSchema)})))}(u||(t.Input=u={})),function(e){e.NoneSourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("none"),id:r.default.string(),actions:r.default.array(e.NoneSourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.KeySourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("key"),id:r.default.string(),actions:r.default.array(e.KeySourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.PointerSourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointer"),id:r.default.string(),parameters:e.PointerParametersSchema.optional(),actions:r.default.array(e.PointerSourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.PerformActionsSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("input.performActions"),params:e.PerformActionsParametersSchema})))}(u||(t.Input=u={})),function(e){e.SourceActionsSchema=r.default.lazy((()=>r.default.union([e.NoneSourceActionsSchema,e.KeySourceActionsSchema,e.PointerSourceActionsSchema,e.WheelSourceActionsSchema])))}(u||(t.Input=u={})),function(e){e.NoneSourceActionSchema=r.default.lazy((()=>e.PauseActionSchema))}(u||(t.Input=u={})),function(e){e.KeySourceActionSchema=r.default.lazy((()=>r.default.union([e.PauseActionSchema,e.KeyDownActionSchema,e.KeyUpActionSchema])))}(u||(t.Input=u={})),function(e){e.PointerTypeSchema=r.default.lazy((()=>r.default.enum(["mouse","pen","touch"])))}(u||(t.Input=u={})),function(e){e.PointerParametersSchema=r.default.lazy((()=>r.default.object({pointerType:e.PointerTypeSchema.default("mouse").optional()})))}(u||(t.Input=u={})),function(e){e.WheelSourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("wheel"),id:r.default.string(),actions:r.default.array(e.WheelSourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.PointerSourceActionSchema=r.default.lazy((()=>r.default.union([e.PauseActionSchema,e.PointerDownActionSchema,e.PointerUpActionSchema,e.PointerMoveActionSchema])))}(u||(t.Input=u={})),function(e){e.WheelSourceActionSchema=r.default.lazy((()=>r.default.union([e.PauseActionSchema,e.WheelScrollActionSchema])))}(u||(t.Input=u={})),function(e){e.PauseActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pause"),duration:t.JsUintSchema.optional()})))}(u||(t.Input=u={})),function(e){e.KeyDownActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("keyDown"),value:r.default.string()})))}(u||(t.Input=u={})),function(e){e.KeyUpActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("keyUp"),value:r.default.string()})))}(u||(t.Input=u={})),function(e){e.PointerUpActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointerUp"),button:t.JsUintSchema}).and(e.PointerCommonPropertiesSchema)))}(u||(t.Input=u={})),function(e){e.PointerDownActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointerDown"),button:t.JsUintSchema}).and(e.PointerCommonPropertiesSchema)))}(u||(t.Input=u={})),function(e){e.PointerMoveActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointerMove"),x:t.JsIntSchema,y:t.JsIntSchema,duration:t.JsUintSchema.optional(),origin:e.OriginSchema.optional()}).and(e.PointerCommonPropertiesSchema)))}(u||(t.Input=u={})),function(e){e.WheelScrollActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("scroll"),x:t.JsIntSchema,y:t.JsIntSchema,deltaX:t.JsIntSchema,deltaY:t.JsIntSchema,duration:t.JsUintSchema.optional(),origin:e.OriginSchema.default("viewport").optional()})))}(u||(t.Input=u={})),function(e){e.PointerCommonPropertiesSchema=r.default.lazy((()=>r.default.object({width:t.JsUintSchema.default(1).optional(),height:t.JsUintSchema.default(1).optional(),pressure:r.default.number().default(0).optional(),tangentialPressure:r.default.number().default(0).optional(),twist:r.default.number().int().nonnegative().gte(0).lte(359).default(0).optional(),altitudeAngle:r.default.number().gte(0).lte(1.5707963267948966).default(0).optional(),azimuthAngle:r.default.number().gte(0).lte(6.283185307179586).default(0).optional()})))}(u||(t.Input=u={})),function(e){e.OriginSchema=r.default.lazy((()=>r.default.union([r.default.literal("viewport"),r.default.literal("pointer"),e.ElementOriginSchema])))}(u||(t.Input=u={})),function(e){e.ReleaseActionsSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("input.releaseActions"),params:e.ReleaseActionsParametersSchema})))}(u||(t.Input=u={})),function(e){e.ReleaseActionsParametersSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema})))}(u||(t.Input=u={}))}(Xr);var Yr=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,r,n)}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),Qr=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),en=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&Yr(t,e,a);return Qr(t,e),t};Object.defineProperty(jr,"__esModule",{value:!0}),jr.Cdp=jr.Input=jr.Session=jr.BrowsingContext=jr.Script=jr.Network=jr.parseObject=void 0;const tn=Or,an=g,rn=en(Xr);function nn(e,t){const a=t.safeParse(e);if(a.success)return a.data;const r=a.error.errors.map((e=>`${e.message} in ${e.path.map((e=>JSON.stringify(e))).join("/")}.`)).join(" ");throw new an.InvalidArgumentException(r)}var sn,on,cn,dn,un,ln;jr.parseObject=nn,function(e){e.parseAddInterceptParameters=function(e){return nn(e,rn.Network.AddInterceptParametersSchema)},e.parseContinueRequestParameters=function(e){return nn(e,rn.Network.ContinueRequestParametersSchema)},e.parseContinueResponseParameters=function(e){return nn(e,rn.Network.ContinueResponseParametersSchema)},e.parseContinueWithAuthParameters=function(e){return nn(e,rn.Network.ContinueWithAuthParametersSchema)},e.parseFailRequestParameters=function(e){return nn(e,rn.Network.FailRequestParametersSchema)},e.parseProvideResponseParameters=function(e){return nn(e,rn.Network.ProvideResponseParametersSchema)},e.parseRemoveInterceptParameters=function(e){return nn(e,rn.Network.RemoveInterceptParametersSchema)}}(sn||(jr.Network=sn={})),function(e){e.parseGetRealmsParams=function(e){return nn(e,rn.Script.GetRealmsParametersSchema)},e.parseEvaluateParams=function(e){return nn(e,rn.Script.EvaluateParametersSchema)},e.parseDisownParams=function(e){return nn(e,rn.Script.DisownParametersSchema)},e.parseAddPreloadScriptParams=function(e){return nn(e,rn.Script.AddPreloadScriptParametersSchema)},e.parseRemovePreloadScriptParams=function(e){return nn(e,rn.Script.RemovePreloadScriptParametersSchema)},e.parseCallFunctionParams=function(e){return nn(e,rn.Script.CallFunctionParametersSchema)}}(on||(jr.Script=on={})),function(e){e.parseActivateParams=function(e){return nn(e,rn.BrowsingContext.ActivateParametersSchema)},e.parseGetTreeParams=function(e){return nn(e,rn.BrowsingContext.GetTreeParametersSchema)},e.parseNavigateParams=function(e){return nn(e,rn.BrowsingContext.NavigateParametersSchema)},e.parseReloadParams=function(e){return nn(e,rn.BrowsingContext.ReloadParametersSchema)},e.parseCreateParams=function(e){return nn(e,rn.BrowsingContext.CreateParametersSchema)},e.parseCloseParams=function(e){return nn(e,rn.BrowsingContext.CloseParametersSchema)},e.parseCaptureScreenshotParams=function(e){return nn(e,rn.BrowsingContext.CaptureScreenshotParametersSchema)},e.parsePrintParams=function(e){return nn(e,rn.BrowsingContext.PrintParametersSchema)},e.parseSetViewportParams=function(e){return nn(e,rn.BrowsingContext.SetViewportParametersSchema)},e.parseHandleUserPromptParameters=function(e){return nn(e,rn.BrowsingContext.HandleUserPromptParametersSchema)}}(cn||(jr.BrowsingContext=cn={})),function(e){e.parseSubscribeParams=function(e){return nn(e,rn.Session.SubscriptionRequestSchema)}}(dn||(jr.Session=dn={})),function(e){e.parsePerformActionsParams=function(e){return nn(e,rn.Input.PerformActionsParametersSchema)},e.parseReleaseActionsParams=function(e){return nn(e,rn.Input.ReleaseActionsParametersSchema)}}(un||(jr.Input=un={})),function(e){const t=tn.z.object({method:tn.z.string(),params:tn.z.object({}).passthrough().optional(),session:tn.z.string().optional()}),a=tn.z.object({context:rn.BrowsingContext.BrowsingContextSchema});e.parseSendCommandRequest=function(e){return nn(e,t)},e.parseGetSessionRequest=function(e){return nn(e,a)}}(ln||(jr.Cdp=ln={}));var hn=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,r,n)}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),pn=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),mn=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&hn(t,e,a);return pn(t,e),t};Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.BidiParser=void 0;const fn=mn(jr);Nr.BidiParser=class{parseActivateParams(e){return fn.BrowsingContext.parseActivateParams(e)}parseCaptureScreenshotParams(e){return fn.BrowsingContext.parseCaptureScreenshotParams(e)}parseCloseParams(e){return fn.BrowsingContext.parseCloseParams(e)}parseCreateParams(e){return fn.BrowsingContext.parseCreateParams(e)}parseGetTreeParams(e){return fn.BrowsingContext.parseGetTreeParams(e)}parseHandleUserPromptParams(e){return fn.BrowsingContext.parseHandleUserPromptParameters(e)}parseNavigateParams(e){return fn.BrowsingContext.parseNavigateParams(e)}parsePrintParams(e){return fn.BrowsingContext.parsePrintParams(e)}parseReloadParams(e){return fn.BrowsingContext.parseReloadParams(e)}parseSetViewportParams(e){return fn.BrowsingContext.parseSetViewportParams(e)}parseGetSessionParams(e){return fn.Cdp.parseGetSessionRequest(e)}parseSendCommandParams(e){return fn.Cdp.parseSendCommandRequest(e)}parsePerformActionsParams(e){return fn.Input.parsePerformActionsParams(e)}parseReleaseActionsParams(e){return fn.Input.parseReleaseActionsParams(e)}parseAddInterceptParams(e){return fn.Network.parseAddInterceptParameters(e)}parseContinueRequestParams(e){return fn.Network.parseContinueRequestParameters(e)}parseContinueResponseParams(e){return fn.Network.parseContinueResponseParameters(e)}parseContinueWithAuthParams(e){return fn.Network.parseContinueWithAuthParameters(e)}parseFailRequestParams(e){return fn.Network.parseFailRequestParameters(e)}parseProvideResponseParams(e){return fn.Network.parseProvideResponseParameters(e)}parseRemoveInterceptParams(e){return fn.Network.parseRemoveInterceptParameters(e)}parseAddPreloadScriptParams(e){return fn.Script.parseAddPreloadScriptParams(e)}parseCallFunctionParams(e){return fn.Script.parseCallFunctionParams(e)}parseDisownParams(e){return fn.Script.parseDisownParams(e)}parseEvaluateParams(e){return fn.Script.parseEvaluateParams(e)}parseGetRealmsParams(e){return fn.Script.parseGetRealmsParams(e)}parseRemovePreloadScriptParams(e){return fn.Script.parseRemovePreloadScriptParams(e)}parseSubscribeParams(e){return fn.Session.parseSubscribeParams(e)}};var gn={};Object.defineProperty(gn,"__esModule",{value:!0}),gn.log=gn.generatePage=void 0;const yn=l;function Sn(e){const t=e.split(":")[0],a=`${t}_log`,r=document.getElementById(a);if(r)return r;const n=document.getElementById("details"),s=document.createElement("div");s.className="divider",n.appendChild(s);const o=document.createElement("div");return o.className="item",o.innerHTML=`<h3>${t}</h3><div id="${a}" class="log"></div>`,n.appendChild(o),document.getElementById(a)}function vn(e){return"object"==typeof e?JSON.stringify(e,null,2):e}gn.generatePage=function(){globalThis.document.documentElement&&(globalThis.document.documentElement.innerHTML='<!DOCTYPE html><title>BiDi-CDP Mapper</title><style>body{font-family: Roboto, serif; font-size: 13px; color: #202124;}.log{padding: 12px; font-family: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace; font-size: 11px; line-height: 180%; background: #f1f3f4; border-radius: 4px;}.pre{overflow-wrap: break-word; padding: 10px;}.card{margin: 60px auto; padding: 2px 0; max-width: 900px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15), 0 1px 6px rgba(0, 0, 0, 0.2); border-radius: 8px;}.divider{height: 1px; background: #f0f0f0;}.item{padding: 16px 20px;}</style><div class="card"><div class="item"><h1>BiDi-CDP Mapper is controlling this tab</h1><p>Closing or reloading it will stop the BiDi process. <a target="_blank" title="BiDi-CDP Mapper GitHub Repository" href="https://github.com/GoogleChromeLabs/chromium-bidi">Details.</a></p></div><div class="divider"></div><details id="details"><summary class="item">Debug information</summary></details></div>',Sn(yn.LogType.debugInfo),Sn(yn.LogType.bidi),Sn(yn.LogType.cdp))},gn.log=function(t,...a){if(!globalThis.document.documentElement)return;t.startsWith(yn.LogType.bidi)||e.window?.sendDebugMessage?.(JSON.stringify({logType:t,messages:a}));const r=Sn(t),n=document.createElement("div");n.className="pre",n.textContent=[t,...a].map(vn).join(" "),r.appendChild(n)};var wn={};Object.defineProperty(wn,"__esModule",{value:!0}),wn.WindowCdpTransport=wn.WindowBidiTransport=void 0;const bn=l,Cn=gn;class xn{static LOGGER_PREFIX_RECV=`${bn.LogType.bidi}:RECV \u25c2`;static LOGGER_PREFIX_SEND=`${bn.LogType.bidi}:SEND \u25b8`;#Xa=null;constructor(){window.onBidiMessage=e=>{(0,Cn.log)(xn.LOGGER_PREFIX_RECV,e);try{const t=xn.#Qa(e);this.#Xa?.call(null,t)}catch(t){const a=t instanceof Error?t:new Error(t);this.#er(e,"invalid argument",a,null)}}}setOnMessage(e){this.#Xa=e}sendMessage(e){(0,Cn.log)(xn.LOGGER_PREFIX_SEND,e);const t=JSON.stringify(e);window.sendBidiResponse(t)}close(){this.#Xa=null,window.onBidiMessage=null}#er(e,t,a,r){const n=xn.#tr(e,t,a);r?this.sendMessage({...n,channel:r}):this.sendMessage(n)}static#ar(e){return null===e?"null":Array.isArray(e)?"array":typeof e}static#tr(e,t,a){let r;try{const t=JSON.parse(e);"object"===xn.#ar(t)&&"id"in t&&(r=t.id)}catch{}return{type:"error",id:r,error:t,message:a.message}}static#Qa(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Cannot parse data as JSON")}const a=xn.#ar(t);if("object"!==a)throw new Error(`Expected JSON object but got ${a}`);const{id:r,method:n,params:s}=t,o=xn.#ar(r);if("number"!==o||!Number.isInteger(r)||r<0)throw new Error(`Expected unsigned integer but got ${o}`);const i=xn.#ar(n);if("string"!==i)throw new Error(`Expected string method but got ${i}`);const c=xn.#ar(s);if("object"!==c)throw new Error(`Expected object params but got ${c}`);let d=t.channel;if(void 0!==d){const e=xn.#ar(d);if("string"!==e)throw new Error(`Expected string channel but got ${e}`);""===d&&(d=void 0)}return{id:r,method:n,params:s,channel:d}}}wn.WindowBidiTransport=xn;wn.WindowCdpTransport=class{#Xa=null;constructor(){window.cdp.onmessage=e=>{this.#Xa?.call(null,e)}}setOnMessage(e){this.#Xa=e}sendMessage(e){window.cdp.send(e)}close(){this.#Xa=null,window.cdp.onmessage=null}}, +var mapperTab=function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var a=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};a.prototype=t.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(a,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),a}var a={},r={},n={},s={};var o=Object.freeze({__proto__:null,default:function(e){return{all:e=e||new Map,on:function(t,a){var r=e.get(t);r?r.push(a):e.set(t,[a])},off:function(t,a){var r=e.get(t);r&&(a?r.splice(r.indexOf(a)>>>0,1):e.set(t,[]))},emit:function(t,a){var r=e.get(t);r&&r.slice().map((function(e){e(a)})),(r=e.get("*"))&&r.slice().map((function(e){e(t,a)}))}}}}),i=t(o),c=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(s,"__esModule",{value:!0}),s.EventEmitter=void 0;const d=c(i);s.EventEmitter=class{#e=(0,d.default)();on(e,t){return this.#e.on(e,t),this}once(e,t){const a=r=>{t(r),this.off(e,a)};return this.on(e,a)}off(e,t){return this.#e.off(e,t),this}emit(e,t){this.#e.emit(e,t)}removeAllListeners(e){return e?this.#e.all.delete(e):this.#e.all.clear(),this}};var u,l={};Object.defineProperty(l,"__esModule",{value:!0}),l.LogType=void 0,function(e){e.bidi="bidi",e.cdp="cdp",e.debug="debug",e.debugError="debug:error",e.debugInfo="debug:info"}(u||(l.LogType=u={}));var h={};Object.defineProperty(h,"__esModule",{value:!0}),h.ProcessingQueue=void 0;const p=l;class m{static LOGGER_PREFIX=`${p.LogType.debug}:queue`;#t;#a;#r=[];#n=!1;constructor(e,t){this.#a=e,this.#t=t}add(e,t){this.#r.push([e,t]),this.#s()}async#s(){if(!this.#n){for(this.#n=!0;this.#r.length>0;){const e=this.#r.shift();if(!e)continue;const[t,a]=e;this.#t?.(m.LOGGER_PREFIX,"Processing event:",a),await t.then((e=>{if("error"!==e.kind)return this.#a(e.value);this.#t?.(p.LogType.debugError,"Event threw before sending:",e.error.message,e.error.stack)})).catch((e=>{this.#t?.(p.LogType.debugError,"Event was not processed:",e?.message)}))}this.#n=!1}}}h.ProcessingQueue=m;var f={},g={},y={};Object.defineProperty(y,"__esModule",{value:!0});var S,v,w,b,C,x={};Object.defineProperty(x,"__esModule",{value:!0}),x.EVENT_NAMES=x.Network=x.BrowsingContext=x.Log=x.Script=x.BiDiModule=void 0,function(e){e.Browser="browser",e.BrowsingContext="browsingContext",e.Cdp="cdp",e.Input="input",e.Log="log",e.Network="network",e.Script="script",e.Session="session"}(S||(x.BiDiModule=S={})),function(e){var t;(t=e.EventNames||(e.EventNames={})).Message="script.message",t.RealmCreated="script.realmCreated",t.RealmDestroyed="script.realmDestroyed"}(v||(x.Script=v={})),function(e){(e.EventNames||(e.EventNames={})).LogEntryAdded="log.entryAdded"}(w||(x.Log=w={})),function(e){var t;(t=e.EventNames||(e.EventNames={})).ContextCreated="browsingContext.contextCreated",t.ContextDestroyed="browsingContext.contextDestroyed",t.DomContentLoaded="browsingContext.domContentLoaded",t.DownloadWillBegin="browsingContext.downloadWillBegin",t.FragmentNavigated="browsingContext.fragmentNavigated",t.Load="browsingContext.load",t.NavigationAborted="browsingContext.navigationAborted",t.NavigationFailed="browsingContext.navigationFailed",t.NavigationStarted="browsingContext.navigationStarted",t.UserPromptClosed="browsingContext.userPromptClosed",t.UserPromptOpened="browsingContext.userPromptOpened"}(b||(x.BrowsingContext=b={})),function(e){var t;(t=e.EventNames||(e.EventNames={})).AuthRequired="network.authRequired",t.BeforeRequestSent="network.beforeRequestSent",t.FetchError="network.fetchError",t.ResponseCompleted="network.responseCompleted",t.ResponseStarted="network.responseStarted"}(C||(x.Network=C={})),x.EVENT_NAMES=new Set([...Object.values(S),...Object.values(b.EventNames),...Object.values(w.EventNames),...Object.values(C.EventNames),...Object.values(v.EventNames)]);var I={};Object.defineProperty(I,"__esModule",{value:!0});var P={};Object.defineProperty(P,"__esModule",{value:!0}),P.UnsupportedOperationException=P.UnableToCloseBrowserException=P.UnableToCaptureScreenException=P.UnknownErrorException=P.UnknownCommandException=P.SessionNotCreatedException=P.NoSuchScriptException=P.NoSuchRequestException=P.NoSuchNodeException=P.NoSuchInterceptException=P.NoSuchHistoryEntryException=P.NoSuchHandleException=P.NoSuchFrameException=P.NoSuchElementException=P.NoSuchAlertException=P.MoveTargetOutOfBoundsException=P.InvalidSessionIdException=P.InvalidArgumentException=P.Exception=void 0;class k{error;message;stacktrace;constructor(e,t,a){this.error=e,this.message=t,this.stacktrace=a}toErrorResponse(e){return{type:"error",id:e,error:this.error,message:this.message,stacktrace:this.stacktrace}}}P.Exception=k;P.InvalidArgumentException=class extends k{constructor(e,t){super("invalid argument",e,t)}};P.InvalidSessionIdException=class extends k{constructor(e,t){super("invalid session id",e,t)}};P.MoveTargetOutOfBoundsException=class extends k{constructor(e,t){super("move target out of bounds",e,t)}};P.NoSuchAlertException=class extends k{constructor(e,t){super("no such alert",e,t)}};P.NoSuchElementException=class extends k{constructor(e,t){super("no such element",e,t)}};P.NoSuchFrameException=class extends k{constructor(e,t){super("no such frame",e,t)}};P.NoSuchHandleException=class extends k{constructor(e,t){super("no such handle",e,t)}};P.NoSuchHistoryEntryException=class extends k{constructor(e,t){super("no such history entry",e,t)}};P.NoSuchInterceptException=class extends k{constructor(e,t){super("no such intercept",e,t)}};P.NoSuchNodeException=class extends k{constructor(e,t){super("no such node",e,t)}};P.NoSuchRequestException=class extends k{constructor(e,t){super("no such request",e,t)}};P.NoSuchScriptException=class extends k{constructor(e,t){super("no such script",e,t)}};P.SessionNotCreatedException=class extends k{constructor(e,t){super("session not created",e,t)}};P.UnknownCommandException=class extends k{constructor(e,t){super("unknown command",e,t)}};P.UnknownErrorException=class extends k{constructor(e,t=(new Error).stack){super("unknown error",e,t)}};P.UnableToCaptureScreenException=class extends k{constructor(e,t){super("unable to capture screen",e,t)}};P.UnableToCloseBrowserException=class extends k{constructor(e,t){super("unable to close browser",e,t)}};P.UnsupportedOperationException=class extends k{constructor(e,t){super("unsupported operation",e,t)}},function(t){var a=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,r,n)}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&a(t,e,n);return r(t,e),t},s=e&&e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.ChromiumBidi=t.Cdp=void 0,t.Cdp=n(y),t.ChromiumBidi=n(x),s(I,t),s(P,t)}(g);var R={};Object.defineProperty(R,"__esModule",{value:!0}),R.BidiNoOpParser=void 0;R.BidiNoOpParser=class{parseActivateParams(e){return e}parseCaptureScreenshotParams(e){return e}parseCloseParams(e){return e}parseCreateParams(e){return e}parseGetTreeParams(e){return e}parseHandleUserPromptParams(e){return e}parseNavigateParams(e){return e}parsePrintParams(e){return e}parseReloadParams(e){return e}parseSetViewportParams(e){return e}parseTraverseHistoryParams(e){return e}parseGetSessionParams(e){return e}parseSendCommandParams(e){return e}parseAddPreloadScriptParams(e){return e}parseCallFunctionParams(e){return e}parseDisownParams(e){return e}parseEvaluateParams(e){return e}parseGetRealmsParams(e){return e}parseRemovePreloadScriptParams(e){return e}parsePerformActionsParams(e){return e}parseReleaseActionsParams(e){return e}parseAddInterceptParams(e){return e}parseContinueRequestParams(e){return e}parseContinueResponseParams(e){return e}parseContinueWithAuthParams(e){return e}parseFailRequestParams(e){return e}parseProvideResponseParams(e){return e}parseRemoveInterceptParams(e){return e}parseSubscribeParams(e){return e}};var E={};Object.defineProperty(E,"__esModule",{value:!0}),E.BrowserProcessor=void 0;E.BrowserProcessor=class{#o;constructor(e){this.#o=e}close(){return setTimeout((()=>this.#o.sendCommand("Browser.close")),0),{}}};var _={};Object.defineProperty(_,"__esModule",{value:!0}),_.CdpProcessor=void 0;_.CdpProcessor=class{#i;#c;#o;constructor(e,t,a){this.#i=e,this.#c=t,this.#o=a}getSession(e){const t=e.context,a=this.#i.getContext(t).cdpTarget.cdpSessionId;return void 0===a?{}:{session:a}}async sendCommand(e){const t=e.session?this.#c.getCdpClient(e.session):this.#o;return{result:await t.sendCommand(e.method,e.params),session:e.session}}};var T={},N={},j={};Object.defineProperty(j,"__esModule",{value:!0}),j.assert=void 0,j.assert=function(e,t){if(!e)throw new Error(t??"Internal assertion failed.")};var O={};Object.defineProperty(O,"__esModule",{value:!0}),O.Deferred=void 0;class M{#d=!1;#u;#l;#h;get isFinished(){return this.#d}constructor(){this.#u=new Promise(((e,t)=>{this.#l=e,this.#h=t})),this.#u.catch((e=>{}))}then(e,t){return this.#u.then(e,t)}catch(e){return this.#u.catch(e)}resolve(e){this.#d||(this.#d=!0,this.#l(e))}reject(e){this.#d||(this.#d=!0,this.#h(e))}finally(e){return this.#u.finally(e)}[Symbol.toStringTag]="Promise"}O.Deferred=M;var A={};Object.defineProperty(A,"__esModule",{value:!0}),A.inchesFromCm=void 0,A.inchesFromCm=function(e){return e/2.54};var D={},B={};Object.defineProperty(B,"__esModule",{value:!0}),B.uuidv4=void 0,B.uuidv4=function(){if("crypto"in globalThis&&"randomUUID"in globalThis.crypto)return globalThis.crypto.randomUUID();const e=new Uint8Array(16);"crypto"in globalThis&&"getRandomValues"in globalThis.crypto?globalThis.crypto.getRandomValues(e):require("crypto").webcrypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=e=>e.reduce(((e,t)=>e+t.toString(16).padStart(2,"0")),"");return[t(e.subarray(0,4)),t(e.subarray(4,6)),t(e.subarray(6,8)),t(e.subarray(8,10)),t(e.subarray(10,16))].join("-")};var z={};Object.defineProperty(z,"__esModule",{value:!0}),z.ChannelProxy=void 0;const L=g,Z=l,U=B;class q{#p;#m=(0,U.uuidv4)();#t;constructor(e,t){this.#p=e,this.#t=t}async init(e,t){const a=await q.#f(e),r=await q.#g(e,a);return this.#y(e,a,t),r}async startListenerFromWindow(e,t){try{const a=await this.#S(e);this.#y(e,a,t)}catch(e){this.#t?.(Z.LogType.debugError,e)}}static#v(){return`(${String((()=>{const e=[];let t=null;return{async getMessage(){const a=e.length>0?Promise.resolve():new Promise((e=>{t=e}));return await a,e.shift()},sendMessage(a){e.push(a),null!==t&&(t(),t=null)}}}))})()`}static async#f(e){const t=await e.cdpClient.sendCommand("Runtime.evaluate",{expression:this.#v(),contextId:e.executionContextId,serializationOptions:{serialization:"idOnly"}});if(t.exceptionDetails||void 0===t.result.objectId)throw new Error("Cannot create channel");return t.result.objectId}static async#g(e,t){return(await e.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>e.sendMessage)),arguments:[{objectId:t}],executionContextId:e.executionContextId,serializationOptions:{serialization:"idOnly"}})).result.objectId}async#y(e,t,a){for(;;)try{const r=await e.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((async e=>await e.getMessage())),arguments:[{objectId:t}],awaitPromise:!0,executionContextId:e.executionContextId,serializationOptions:{serialization:"deep",maxDepth:this.#p.serializationOptions?.maxObjectDepth??void 0}});if(r.exceptionDetails)throw r.exceptionDetails;a.registerEvent({type:"event",method:L.ChromiumBidi.Script.EventNames.Message,params:{channel:this.#p.channel,data:e.cdpToBidiValue(r,this.#p.ownership??"none"),source:{realm:e.realmId,context:e.browsingContextId}}},e.browsingContextId)}catch(e){this.#t?.(Z.LogType.debugError,e);break}}async#S(e){const t=await e.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>{const t=window;if(void 0===t[e])return new Promise((a=>t[e]=a));const a=t[e];return delete t[e],a})),arguments:[{value:this.#m}],executionContextId:e.executionContextId,awaitPromise:!0,serializationOptions:{serialization:"idOnly"}});if(void 0!==t.exceptionDetails||void 0===t.result.objectId)throw new Error(`ChannelHandle not found in window["${this.#m}"]`);return t.result.objectId}getEvalInWindowStr(){const e=String(((e,t)=>{const a=window;return void 0===a[e]?a[e]=t:(a[e](t),delete a[e]),t.sendMessage})),t=q.#v();return`(${e})('${this.#m}',${t})`}}z.ChannelProxy=q,Object.defineProperty(D,"__esModule",{value:!0}),D.Realm=void 0;const V=g,F=l,$=B,K=z,H="_element_";class W{#w;#i;#b;#C;#x;#I;#P;#k;#R;sandbox;#t;constructor(e,t,a,r,n,s,o,i,c,d,u){this.#b=a,this.#C=r,this.#x=n,this.sandbox=i,this.#I=s,this.#P=o,this.#k=c,this.#w=e,this.#i=t,this.#R=d,this.#t=u,this.#w.addRealm(this),this.#R.registerEvent({type:"event",method:V.ChromiumBidi.Script.EventNames.RealmCreated,params:this.realmInfo},this.browsingContextId)}cdpToBidiValue(e,t){const a=this.#E(e.result.deepSerializedValue,new Map);if(e.result.objectId){const r=e.result.objectId;"root"===t?(a.handle=r,this.#w.knownHandlesToRealmMap.set(r,this.realmId)):this.#_(r).catch((e=>this.#t?.(F.LogType.debugError,e)))}if("object"===e.result.type)switch(e.result.subtype){case"generator":case"iterator":a.type=e.result.subtype,delete a.value}return a}#E(e,t){if(Object.hasOwn(e,"weakLocalObjectReference")){const a=e.weakLocalObjectReference;t.has(a)||t.set(a,(0,$.uuidv4)()),e.internalId=t.get(a),delete e.weakLocalObjectReference}if("platformobject"===e.type)return{type:"object"};const a=e.value;if(void 0===a)return e;if("node"===e.type){if(Object.hasOwn(a,"backendNodeId")&&(e.sharedId=`${this.navigableId}${H}${a.backendNodeId}`,delete a.backendNodeId),Object.hasOwn(a,"children"))for(const e in a.children)a.children[e]=this.#E(a.children[e],t);Object.hasOwn(a,"shadowRoot")&&null!==a.shadowRoot&&(a.shadowRoot=this.#E(a.shadowRoot,t)),""===a.namespaceURI&&(a.namespaceURI=null)}if(["array","set","htmlcollection","nodelist"].includes(e.type))for(const e in a)a[e]=this.#E(a[e],t);if(["object","map"].includes(e.type))for(const e in a)a[e]=[this.#E(a[e][0],t),this.#E(a[e][1],t)];return e}get realmId(){return this.#b}get navigableId(){return this.#i.findContext(this.#C)?.navigableId??"UNKNOWN"}get browsingContextId(){return this.#C}get executionContextId(){return this.#x}get origin(){return this.#I}get type(){return this.#P}get cdpClient(){return this.#k}get realmInfo(){return{realm:this.realmId,origin:this.origin,type:this.type,context:this.browsingContextId,...void 0===this.sandbox?{}:{sandbox:this.sandbox}}}async evaluate(e,t,a,r,n=!1){await this.#i.getContext(this.browsingContextId).targetUnblockedOrThrow();const s=await this.cdpClient.sendCommand("Runtime.evaluate",{contextId:this.executionContextId,expression:e,awaitPromise:t,serializationOptions:W.#T("deep",r),userGesture:n});return s.exceptionDetails?await this.#N(s.exceptionDetails,0,a):{realm:this.realmId,result:this.cdpToBidiValue(s,a),type:"success"}}async serializeCdpObject(e,t){const a=W.#j(e),r=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>e)),awaitPromise:!1,arguments:[a],serializationOptions:{serialization:"deep"},executionContextId:this.executionContextId});return this.cdpToBidiValue(r,t)}static#j(e){return void 0!==e.objectId?{objectId:e.objectId}:void 0!==e.unserializableValue?{unserializableValue:e.unserializableValue}:{value:e.value}}async stringifyObject(e){const{result:t}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String((e=>String(e))),awaitPromise:!1,arguments:[e],returnByValue:!0,executionContextId:this.executionContextId});return t.value}async#O(e){const t=[];for(const[a,r]of e){let e;e="string"==typeof a?{value:a}:await this.#M(a);const n=await this.#M(r);t.push(e),t.push(n)}return t}async#A(e){return await Promise.all(e.map((e=>this.#M(e))))}async#D(e,t,a){const r=e.stackTrace?.callFrames.map((e=>({url:e.url,functionName:e.functionName,lineNumber:e.lineNumber-t,columnNumber:e.columnNumber})))??[],n=e.exception;return{exception:await this.serializeCdpObject(n,a),columnNumber:e.columnNumber,lineNumber:e.lineNumber-t,stackTrace:{callFrames:r},text:await this.stringifyObject(n)||e.text}}async callFunction(e,t,a,r,n,s,o=!1){await this.#i.getContext(this.browsingContextId).targetUnblockedOrThrow();const i=`(...args) => {\n function callFunction(f, args) {\n const deserializedThis = args.shift();\n const deserializedArgs = args;\n return f.apply(deserializedThis, deserializedArgs);\n }\n return callFunction((\n ${e}\n ), args);\n }`,c=[await this.#M(t),...await Promise.all(a.map((async e=>await this.#M(e))))];let d;try{d=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:i,awaitPromise:r,arguments:c,serializationOptions:W.#T("deep",s),executionContextId:this.executionContextId,userGesture:o})}catch(e){if(-32e3===e.code&&["Could not find object with given id","Argument should belong to the same JavaScript world as target object","Invalid remote object id"].includes(e.message))throw new V.NoSuchHandleException("Handle was not found.");throw e}return d.exceptionDetails?await this.#N(d.exceptionDetails,1,n):{type:"success",result:this.cdpToBidiValue(d,n),realm:this.realmId}}async#M(e){if("sharedId"in e&&e.sharedId){const[t,a]=e.sharedId.split(H),r=parseInt(a??"");if(isNaN(r)||void 0===r||void 0===t)throw new V.NoSuchNodeException(`SharedId "${e.sharedId}" was not found.`);if(this.navigableId!==t)throw new V.NoSuchNodeException(`SharedId "${e.sharedId}" belongs to different document. Current document is ${this.navigableId}.`);try{const{object:e}=await this.cdpClient.sendCommand("DOM.resolveNode",{backendNodeId:r,executionContextId:this.executionContextId});return{objectId:e.objectId}}catch(t){if(-32e3===t.code&&"No node with given id found"===t.message)throw new V.NoSuchNodeException(`SharedId "${e.sharedId}" was not found.`);throw new V.UnknownErrorException(t.message,t.stack)}}else{if("handle"in e&&e.handle)return{objectId:e.handle};if("handle"in e||"sharedId"in e)throw new V.NoSuchHandleException("Handle was not found.")}switch(e.type){case"undefined":return{unserializableValue:"undefined"};case"null":return{unserializableValue:"null"};case"string":return{value:e.value};case"number":return"NaN"===e.value?{unserializableValue:"NaN"}:"-0"===e.value?{unserializableValue:"-0"}:"Infinity"===e.value?{unserializableValue:"Infinity"}:"-Infinity"===e.value?{unserializableValue:"-Infinity"}:{value:e.value};case"boolean":return{value:Boolean(e.value)};case"bigint":return{unserializableValue:`BigInt(${JSON.stringify(e.value)})`};case"date":return{unserializableValue:`new Date(Date.parse(${JSON.stringify(e.value)}))`};case"regexp":return{unserializableValue:`new RegExp(${JSON.stringify(e.value.pattern)}, ${JSON.stringify(e.value.flags)})`};case"map":{const t=await this.#O(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>{const t=new Map;for(let a=0;a<e.length;a+=2)t.set(e[a],e[a+1]);return t})),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"object":{const t=await this.#O(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>{const t={};for(let a=0;a<e.length;a+=2){t[e[a]]=e[a+1]}return t})),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"array":{const t=await this.#A(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>e)),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"set":{const t=await this.#A(e.value),{result:a}=await this.cdpClient.sendCommand("Runtime.callFunctionOn",{functionDeclaration:String(((...e)=>new Set(e))),awaitPromise:!1,arguments:t,returnByValue:!1,executionContextId:this.executionContextId});return{objectId:a.objectId}}case"channel":{const t=new K.ChannelProxy(e.value,this.#t);return{objectId:await t.init(this,this.#R)}}}throw new Error(`Value ${JSON.stringify(e)} is not deserializable.`)}async#N(e,t,a){return{exceptionDetails:await this.#D(e,t,a),realm:this.realmId,type:"exception"}}static#T(e,t){return{serialization:e,additionalParameters:W.#B(t),...W.#z(t)}}static#B(e){const t={};return void 0!==e.maxDomDepth&&(t.maxNodeDepth=null===e.maxDomDepth?1e3:e.maxDomDepth),void 0!==e.includeShadowTree&&(t.includeShadowTree=e.includeShadowTree),t}static#z(e){return void 0===e.maxObjectDepth||null===e.maxObjectDepth?{}:{maxDepth:e.maxObjectDepth}}async#_(e){try{await this.cdpClient.sendCommand("Runtime.releaseObject",{objectId:e})}catch(e){if(-32e3!==e.code||"Invalid remote object id"!==e.message)throw e}}async disown(e){this.#w.knownHandlesToRealmMap.get(e)===this.realmId&&(await this.#_(e),this.#w.knownHandlesToRealmMap.delete(e))}dispose(){this.#R.registerEvent({type:"event",method:V.ChromiumBidi.Script.EventNames.RealmDestroyed,params:{realm:this.realmId}},this.browsingContextId)}}D.Realm=W,Object.defineProperty(N,"__esModule",{value:!0}),N.BrowsingContextImpl=void 0;const J=g,G=j,X=O,Y=l,Q=A,ee=D;class te{static LOGGER_PREFIX=`${Y.LogType.debug}:browsingContext`;#m;#L;#Z=new Set;#i;#U={Page:{navigatedWithinDocument:new X.Deferred,lifecycleEvent:{DOMContentLoaded:new X.Deferred,load:new X.Deferred},frameStartedLoading:new X.Deferred}};#q="about:blank";#R;#w;#V;#F;#$;#t;constructor(e,t,a,r,n,s,o){this.#F=e,this.#w=t,this.#m=a,this.#L=r,this.#R=n,this.#i=s,this.#t=o}static create(e,t,a,r,n,s,o){const i=new te(e,t,a,r,n,s,o);return i.#K(),s.addContext(i),i.isTopLevelContext()||i.parent.addChild(i.id),n.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.ContextCreated,params:i.serializeToBidiValue()},i.id),i}static getTimestamp(){return(new Date).getTime()}get navigableId(){return this.#V}dispose(){this.#H(),this.#w.deleteRealms({browsingContextId:this.id}),this.isTopLevelContext()||this.parent.#Z.delete(this.id),this.#W(),this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.ContextDestroyed,params:this.serializeToBidiValue()},this.id),this.#i.deleteContextById(this.id)}get id(){return this.#m}get parentId(){return this.#L}get parent(){return null===this.parentId?null:this.#i.getContext(this.parentId)}get directChildren(){return[...this.#Z].map((e=>this.#i.getContext(e)))}get allChildren(){const e=this.directChildren;return e.concat(...e.map((e=>e.allChildren)))}isTopLevelContext(){return null===this.#L}get top(){let e=this,t=e.parent;for(;t;)e=t,t=e.parent;return e}addChild(e){this.#Z.add(e)}#H(){this.directChildren.map((e=>e.dispose()))}get#J(){return(0,G.assert)(this.#$,`No default realm for browsing context ${this.#m}`),this.#$}get cdpTarget(){return this.#F}updateCdpTarget(e){this.#F=e,this.#K()}get url(){return this.#q}async lifecycleLoaded(){await this.#U.Page.lifecycleEvent.load}async targetUnblockedOrThrow(){const e=await this.#F.targetUnblocked;if("error"===e.kind)throw e.error}async getOrCreateSandbox(e){if(void 0===e||""===e)return this.#J;let t=this.#w.findRealms({browsingContextId:this.id,sandbox:e});return 0===t.length&&(await this.#F.cdpClient.sendCommand("Page.createIsolatedWorld",{frameId:this.id,worldName:e}),t=this.#w.findRealms({browsingContextId:this.id,sandbox:e}),(0,G.assert)(0!==t.length)),t[0]}serializeToBidiValue(e=0,t=!0){return{context:this.#m,url:this.url,children:e>0?this.directChildren.map((t=>t.serializeToBidiValue(e-1,!1))):null,...t?{parent:this.#L}:{}}}onTargetInfoChanged(e){this.#q=e.targetInfo.url}#K(){this.#F.cdpClient.on("Page.frameNavigated",(e=>{this.id===e.frame.id&&(this.#q=e.frame.url+(e.frame.urlFragment??""),this.#H())})),this.#F.cdpClient.on("Page.navigatedWithinDocument",(e=>{if(this.id!==e.frameId)return;const t=te.getTimestamp();this.#q=e.url,this.#U.Page.navigatedWithinDocument.resolve(e),this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.FragmentNavigated,params:{context:this.id,navigation:null,timestamp:t,url:this.#q}},this.id)})),this.#F.cdpClient.on("Page.frameStartedLoading",(e=>{this.id===e.frameId&&this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.NavigationStarted,params:{context:this.id,navigation:null,timestamp:te.getTimestamp(),url:""}},this.id)})),this.#F.cdpClient.on("Page.lifecycleEvent",(e=>{if(this.id!==e.frameId)return;if("init"===e.name)return void this.#G(e.loaderId);if("commit"===e.name)return void(this.#V=e.loaderId);if(e.loaderId!==this.#V)return;const t=te.getTimestamp();switch(e.name){case"DOMContentLoaded":this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.DomContentLoaded,params:{context:this.id,navigation:this.#V??null,timestamp:t,url:this.#q}},this.id),this.#U.Page.lifecycleEvent.DOMContentLoaded.resolve(e);break;case"load":this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.Load,params:{context:this.id,navigation:this.#V??null,timestamp:t,url:this.#q}},this.id),this.#U.Page.lifecycleEvent.load.resolve(e)}})),this.#F.cdpClient.on("Runtime.executionContextCreated",(e=>{if(e.context.auxData.frameId!==this.id)return;if(!["default","isolated"].includes(e.context.auxData.type))return;const t=new ee.Realm(this.#w,this.#i,e.context.uniqueId,this.id,e.context.id,this.#X(e),"window","isolated"===e.context.auxData.type?e.context.name:void 0,this.#F.cdpClient,this.#R,this.#t);e.context.auxData.isDefault&&(this.#$=t,Promise.all(this.#F.getChannels().map((e=>e.startListenerFromWindow(t,this.#R)))))})),this.#F.cdpClient.on("Runtime.executionContextDestroyed",(e=>{this.#w.deleteRealms({cdpSessionId:this.#F.cdpSessionId,executionContextId:e.executionContextId})})),this.#F.cdpClient.on("Runtime.executionContextsCleared",(()=>{this.#w.deleteRealms({cdpSessionId:this.#F.cdpSessionId})})),this.#F.cdpClient.on("Page.javascriptDialogClosed",(e=>{const t=e.result;this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.UserPromptClosed,params:{context:this.id,accepted:t,userText:t&&e.userInput?e.userInput:void 0}},this.id)})),this.#F.cdpClient.on("Page.javascriptDialogOpening",(e=>{this.#R.registerEvent({type:"event",method:J.ChromiumBidi.BrowsingContext.EventNames.UserPromptOpened,params:{context:this.id,type:e.type,message:e.message,defaultValue:e.defaultPrompt||void 0}},this.id)}))}#X(e){return"isolated"===e.context.auxData.type?this.#J.origin:["://",""].includes(e.context.origin)?"null":e.context.origin}#G(e){void 0!==e&&this.#V!==e?(this.#Y(),this.#V=e):this.#U.Page.navigatedWithinDocument.isFinished?this.#U.Page.navigatedWithinDocument=new X.Deferred:this.#t?.(te.LOGGER_PREFIX,"Document changed (navigatedWithinDocument)")}#Y(){this.#U.Page.lifecycleEvent.DOMContentLoaded.isFinished?this.#U.Page.lifecycleEvent.DOMContentLoaded=new X.Deferred:this.#t?.(te.LOGGER_PREFIX,"Document changed (DOMContentLoaded)"),this.#U.Page.lifecycleEvent.load.isFinished?this.#U.Page.lifecycleEvent.load=new X.Deferred:this.#t?.(te.LOGGER_PREFIX,"Document changed (load)")}#W(){this.#U.Page.lifecycleEvent.DOMContentLoaded.isFinished||this.#U.Page.lifecycleEvent.DOMContentLoaded.reject(new J.UnknownErrorException("navigation canceled")),this.#U.Page.lifecycleEvent.load.isFinished||this.#U.Page.lifecycleEvent.load.reject(new J.UnknownErrorException("navigation canceled"))}async navigate(e,t){try{new URL(e)}catch{throw new J.InvalidArgumentException(`Invalid URL: ${e}`)}await this.targetUnblockedOrThrow();const a=await this.#F.cdpClient.sendCommand("Page.navigate",{url:e,frameId:this.id});if(a.errorText)throw new J.UnknownErrorException(a.errorText);switch(this.#G(a.loaderId),t){case"none":break;case"interactive":void 0===a.loaderId?await this.#U.Page.navigatedWithinDocument:await this.#U.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":void 0===a.loaderId?await this.#U.Page.navigatedWithinDocument:await this.lifecycleLoaded()}return{navigation:a.loaderId??null,url:"none"===t?e:this.#q}}async reload(e,t){switch(await this.targetUnblockedOrThrow(),await this.#F.cdpClient.sendCommand("Page.reload",{ignoreCache:e}),this.#Y(),t){case"none":break;case"interactive":await this.#U.Page.lifecycleEvent.DOMContentLoaded;break;case"complete":await this.lifecycleLoaded()}return{navigation:"none"===t?null:this.navigableId??null,url:this.url}}async setViewport(e,t){if(null===e&&null===t)await this.#F.cdpClient.sendCommand("Emulation.clearDeviceMetricsOverride");else try{await this.#F.cdpClient.sendCommand("Emulation.setDeviceMetricsOverride",{width:e?e.width:0,height:e?e.height:0,deviceScaleFactor:t||0,mobile:!1,dontSetVisibleSize:!0})}catch(e){if(e.message.startsWith("Width and height values must be positive"))throw new J.UnsupportedOperationException("Provided viewport dimensions are not supported");throw e}}async handleUserPrompt(e){await this.#F.cdpClient.sendCommand("Page.handleJavaScriptDialog",{accept:e.accept??!0,promptText:e.userText})}async activate(){await this.#F.cdpClient.sendCommand("Page.bringToFront")}async captureScreenshot(e){if(!this.isTopLevelContext())throw new J.UnsupportedOperationException(`Non-top-level 'context' (${e.context}) is currently not supported`);const t=function(e){const{quality:t,type:a}=e.format??{type:"image/png"};switch(a){case"image/png":return{format:"png"};case"image/jpeg":return{format:"jpeg",...void 0===t?{}:{quality:Math.round(100*t)}};case"image/webp":return{format:"webp",...void 0===t?{}:{quality:Math.round(100*t)}}}throw new J.UnsupportedOperationException(`Image format '${a}' is not a supported format`)}(e);await this.#F.cdpClient.sendCommand("Page.bringToFront");let a,r=!1;switch(e.origin??="viewport",e.origin){case"document":a=String((()=>{const e=document.documentElement;return{x:0,y:0,width:e.scrollWidth,height:e.scrollHeight}})),r=!0;break;case"viewport":a=String((()=>{const e=window.visualViewport;return{x:e.pageLeft,y:e.pageTop,width:e.width,height:e.height}}))}const n=await this.getOrCreateSandbox(void 0),s=await n.callFunction(a,{type:"undefined"},[],!1,"none",{},!1);(0,G.assert)("success"===s.type);const o=ae(s.result);(0,G.assert)(o);const i=e.clip?function(e,t){e=re(e),t=re(t);const a=Math.max(e.x,t.x),r=Math.max(e.y,t.y);return{x:a,y:r,width:Math.max(Math.min(e.x+e.width,t.x+t.width)-a,0),height:Math.max(Math.min(e.y+e.height,t.y+t.height)-r,0)}}(await this.#Q(e.clip),o):o;if(0===i.width||0===i.height)throw new J.UnableToCaptureScreenException(`Unable to capture screenshot with zero dimensions: width=${i.width}, height=${i.height}`);return await this.#F.cdpClient.sendCommand("Page.captureScreenshot",{clip:{...i,scale:1},...t,captureBeyondViewport:r})}async print(e){const t={};if(void 0!==e.background&&(t.printBackground=e.background),void 0!==e.margin?.bottom&&(t.marginBottom=(0,Q.inchesFromCm)(e.margin.bottom)),void 0!==e.margin?.left&&(t.marginLeft=(0,Q.inchesFromCm)(e.margin.left)),void 0!==e.margin?.right&&(t.marginRight=(0,Q.inchesFromCm)(e.margin.right)),void 0!==e.margin?.top&&(t.marginTop=(0,Q.inchesFromCm)(e.margin.top)),void 0!==e.orientation&&(t.landscape="landscape"===e.orientation),void 0!==e.page?.height&&(t.paperHeight=(0,Q.inchesFromCm)(e.page.height)),void 0!==e.page?.width&&(t.paperWidth=(0,Q.inchesFromCm)(e.page.width)),void 0!==e.pageRanges){for(const t of e.pageRanges){if("number"==typeof t)continue;const e=t.split("-");if(e.length<1||e.length>2)throw new J.InvalidArgumentException(`Invalid page range: ${t} is not a valid integer range.`);if(1===e.length){ne(e[0]??"");continue}let a,r;const[n="",s=""]=e;if(a=""===n?1:ne(n),r=""===s?Number.MAX_SAFE_INTEGER:ne(s),a>r)throw new J.InvalidArgumentException(`Invalid page range: ${n} > ${s}`)}t.pageRanges=e.pageRanges.join(",")}void 0!==e.scale&&(t.scale=e.scale),void 0!==e.shrinkToFit&&(t.preferCSSPageSize=!e.shrinkToFit);try{return{data:(await this.#F.cdpClient.sendCommand("Page.printToPDF",t)).data}}catch(e){if("invalid print parameters: content area is empty"===e.message)throw new J.UnsupportedOperationException(e.message);throw e}}async#Q(e){switch(e.type){case"box":return{x:e.x,y:e.y,width:e.width,height:e.height};case"element":{const t=await this.getOrCreateSandbox(void 0),a=await t.callFunction(String((e=>e instanceof Element)),{type:"undefined"},[e.element],!1,"none",{});if("exception"===a.type)throw new J.NoSuchElementException(`Element '${e.element.sharedId}' was not found`);if((0,G.assert)("boolean"===a.result.type),!a.result.value)throw new J.NoSuchElementException(`Node '${e.element.sharedId}' is not an Element`);{const a=await t.callFunction(String((e=>{const t=e.getBoundingClientRect();return{x:t.x,y:t.y,height:t.height,width:t.width}})),{type:"undefined"},[e.element],!1,"none",{});(0,G.assert)("success"===a.type);const r=ae(a.result);if(!r)throw new J.UnableToCaptureScreenException(`Could not get bounding box for Element '${e.element.sharedId}'`);return r}}}}async close(){await this.#F.cdpClient.sendCommand("Page.close")}async traverseHistory(e){if(0===e)return;const t=await this.#F.cdpClient.sendCommand("Page.getNavigationHistory"),a=t.entries[t.currentIndex+e];if(!a)throw new J.NoSuchHistoryEntryException(`No history entry at delta ${e}`);await this.#F.cdpClient.sendCommand("Page.navigateToHistoryEntry",{entryId:a.id})}}function ae(e){if("object"!==e.type||void 0===e.value)return;const t=e.value.find((([e])=>"x"===e))?.[1],a=e.value.find((([e])=>"y"===e))?.[1],r=e.value.find((([e])=>"height"===e))?.[1],n=e.value.find((([e])=>"width"===e))?.[1];return"number"===t?.type&&"number"===a?.type&&"number"===r?.type&&"number"===n?.type?{x:t.value,y:a.value,width:n.value,height:r.value}:void 0}function re(e){return{...e.width<0?{x:e.x+e.width,width:-e.width}:{x:e.x,width:e.width},...e.height<0?{y:e.y+e.height,height:-e.height}:{y:e.y,height:e.height}}}function ne(e){if(e=e.trim(),!/^[0-9]+$/.test(e))throw new J.InvalidArgumentException(`Invalid integer: ${e}`);return parseInt(e)}N.BrowsingContextImpl=te;var se={},oe={},ie={};Object.defineProperty(ie,"__esModule",{value:!0}),ie.getRemoteValuesText=ie.logMessageFormatter=void 0;const ce=j,de=["%s","%d","%i","%f","%o","%O","%c"];function ue(e){return de.some((t=>e.includes(t)))}function le(e){let t="";const a=e[0].value.toString(),r=e.slice(1,void 0),n=a.split(new RegExp(de.map((e=>`(${e})`)).join("|"),"g"));for(const a of n)if(void 0!==a&&""!==a)if(ue(a)){const n=r.shift();(0,ce.assert)(n,`Less value is provided: "${me(e,!1)}"`),"%s"===a?t+=pe(n):"%d"===a||"%i"===a?"bigint"===n.type||"number"===n.type||"string"===n.type?t+=parseInt(n.value.toString(),10):t+="NaN":"%f"===a?"bigint"===n.type||"number"===n.type||"string"===n.type?t+=parseFloat(n.value.toString()):t+="NaN":t+=he(n)}else t+=a;if(r.length>0)throw new Error(`More value is provided: "${me(e,!1)}"`);return t}function he(e){if("array"!==e.type&&"bigint"!==e.type&&"date"!==e.type&&"number"!==e.type&&"object"!==e.type&&"string"!==e.type)return pe(e);if("bigint"===e.type)return`${e.value.toString()}n`;if("number"===e.type)return e.value.toString();if(["date","string"].includes(e.type))return JSON.stringify(e.value);if("object"===e.type)return`{${e.value.map((e=>`${JSON.stringify(e[0])}:${he(e[1])}`)).join(",")}}`;if("array"===e.type)return`[${e.value?.map((e=>he(e))).join(",")??""}]`;throw Error(`Invalid value type: ${e}`)}function pe(e){if(!Object.hasOwn(e,"value"))return e.type;switch(e.type){case"string":case"number":case"boolean":case"bigint":return String(e.value);case"regexp":return`/${e.value.pattern}/${e.value.flags??""}`;case"date":return new Date(e.value).toString();case"object":return`Object(${e.value?.length??""})`;case"array":return`Array(${e.value?.length??""})`;case"map":return`Map(${e.value?.length})`;case"set":return`Set(${e.value?.length})`;default:return e.type}}function me(e,t){const a=e[0];return a?"string"===a.type&&ue(a.value.toString())&&t?le(e):e.map((e=>pe(e))).join(" "):""}ie.logMessageFormatter=le,ie.getRemoteValuesText=me,Object.defineProperty(oe,"__esModule",{value:!0}),oe.LogManager=void 0;const fe=g,ge=ie;function ye(e){const t=e?.callFrames.map((e=>({columnNumber:e.columnNumber,functionName:e.functionName,lineNumber:e.lineNumber,url:e.url})));return t?{callFrames:t}:void 0}class Se{#R;#w;#F;constructor(e,t,a){this.#F=e,this.#w=t,this.#R=a}static create(e,t,a){const r=new Se(e,t,a);return r.#ee(),r}#ee(){this.#F.cdpClient.on("Runtime.consoleAPICalled",(e=>{const t=this.#w.findRealm({cdpSessionId:this.#F.cdpSessionId,executionContextId:e.executionContextId}),a=void 0===t?Promise.resolve(e.args):Promise.all(e.args.map((e=>t.serializeCdpObject(e,"none"))));this.#R.registerPromiseEvent(a.then((a=>{return{kind:"success",value:{type:"event",method:fe.ChromiumBidi.Log.EventNames.LogEntryAdded,params:{level:(r=e.type,["error","assert"].includes(r)?"error":["debug","trace"].includes(r)?"debug":["warn","warning"].includes(r)?"warn":"info"),source:{realm:t?.realmId??"UNKNOWN",context:t?.browsingContextId??"UNKNOWN"},text:(0,ge.getRemoteValuesText)(a,!0),timestamp:Math.round(e.timestamp),stackTrace:ye(e.stackTrace),type:"console",method:"warning"===e.type?"warn":e.type,args:a}}};var r})),t?.browsingContextId??"UNKNOWN",fe.ChromiumBidi.Log.EventNames.LogEntryAdded)})),this.#F.cdpClient.on("Runtime.exceptionThrown",(e=>{const t=this.#w.findRealm({cdpSessionId:this.#F.cdpSessionId,executionContextId:e.exceptionDetails.executionContextId});this.#R.registerPromiseEvent(Se.#te(e,t).then((a=>({kind:"success",value:{type:"event",method:fe.ChromiumBidi.Log.EventNames.LogEntryAdded,params:{level:"error",source:{realm:t?.realmId??"UNKNOWN",context:t?.browsingContextId??"UNKNOWN"},text:a,timestamp:Math.round(e.timestamp),stackTrace:ye(e.exceptionDetails.stackTrace),type:"javascript"}}}))),t?.browsingContextId??"UNKNOWN",fe.ChromiumBidi.Log.EventNames.LogEntryAdded)}))}static async#te(e,t){return e.exceptionDetails.exception?void 0===t?JSON.stringify(e.exceptionDetails.exception):await t.stringifyObject(e.exceptionDetails.exception):e.exceptionDetails.text}}oe.LogManager=Se;var ve={},we={},be={};Object.defineProperty(be,"__esModule",{value:!0}),be.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction=be.cdpFetchHeadersFromBidiNetworkHeaders=be.bidiNetworkHeadersFromCdpFetchHeaders=be.cdpNetworkHeadersFromBidiNetworkHeaders=be.bidiNetworkHeadersFromCdpNetworkHeaders=be.computeHeadersSize=void 0,be.computeHeadersSize=function(e){const t=e.reduce(((e,t)=>`${e}${t.name}: ${t.value.value}\r\n`),"");return(new TextEncoder).encode(t).length},be.bidiNetworkHeadersFromCdpNetworkHeaders=function(e){return e?Object.entries(e).map((([e,t])=>({name:e,value:{type:"string",value:t}}))):[]},be.cdpNetworkHeadersFromBidiNetworkHeaders=function(e){if(void 0!==e)return e.reduce(((e,t)=>(e[t.name]=t.value.value,e)),{})},be.bidiNetworkHeadersFromCdpFetchHeaders=function(e){return e?e.map((({name:e,value:t})=>({name:e,value:{type:"string",value:t}}))):[]},be.cdpFetchHeadersFromBidiNetworkHeaders=function(e){if(void 0!==e)return e.map((({name:e,value:t})=>({name:e,value:t.value})))},be.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction=function(e){switch(e){case"default":return"Default";case"cancel":return"CancelAuth";case"provideCredentials":return"ProvideCredentials"}},Object.defineProperty(we,"__esModule",{value:!0}),we.NetworkRequest=void 0;const Ce=g,xe=j,Ie=O,Pe=be;class ke{static#ae="UNKNOWN";#re;#ne=void 0;#se=!1;#oe;#R;#ie;#ce={};#de={};#ue=new Ie.Deferred;#le=new Ie.Deferred;#he=new Ie.Deferred;#F;constructor(e,t,a,r,n=0){this.#re=e,this.#R=t,this.#ie=a,this.#F=r,this.#oe=n}get requestId(){return this.#re}get url(){return this.#de.info?.url??this.#ce.info?.request.url}get redirectCount(){return this.#oe}get cdpTarget(){return this.#F}isRedirecting(){return Boolean(this.#ce.info)}handleRedirect(e){this.#pe(),this.#me(),this.#de.hasExtraInfo=e.redirectHasExtraInfo,this.#de.info=e.redirectResponse,this.#fe(!0)}#fe(e=!1){const t=e||Boolean(this.#ce.extraInfo)||this.#se||Boolean(this.#de.info&&!this.#de.hasExtraInfo)||"beforeRequestSent"===this.#ne;this.#ce.info&&t&&this.#ue.resolve({kind:"success",value:void 0});const a=Boolean(this.#de.extraInfo)||this.#se||Boolean(this.#de.info&&!this.#de.hasExtraInfo)||"responseStarted"===this.#ne;this.#de.info&&a&&(this.#le.resolve({kind:"success",value:void 0}),this.#he.resolve({kind:"success",value:void 0}))}onRequestWillBeSentEvent(e){this.#ce.info=e,this.#ge(),this.#fe()}onRequestWillBeSentExtraInfoEvent(e){this.#ce.extraInfo=e,this.#fe()}onResponseReceivedExtraInfoEvent(e){this.#de.extraInfo=e,this.#fe()}onResponseReceivedEvent(e){this.#de.hasExtraInfo=e.hasExtraInfo,this.#de.info=e.response,this.#pe(),this.#me(),this.#fe()}onServedFromCache(){this.#se=!0,this.#fe()}onLoadingFailedEvent(e){this.#ue.resolve({kind:"success",value:void 0}),this.#le.resolve({kind:"error",error:new Error("Network event loading failed")}),this.#he.resolve({kind:"error",error:new Error("Network event loading failed")}),this.#R.registerEvent({type:"event",method:Ce.ChromiumBidi.Network.EventNames.FetchError,params:{...this.#ye(),errorText:e.errorText}},this.#Se)}onRequestPaused(e,t){if(this.#ve())return void this.continueRequest(e.requestId).catch((()=>{}));let a;a=void 0===e.responseErrorReason&&void 0===e.responseStatusCode?"beforeRequestSent":401===e.responseStatusCode&&"Unauthorized"===e.responseStatusText?"authRequired":"responseStarted";const r=(0,Pe.bidiNetworkHeadersFromCdpFetchHeaders)(e.responseHeaders);(0,xe.assert)(this.requestId===e.networkId),t.addBlockedRequest(this.requestId,{request:e.requestId,phase:a,response:{url:e.request.url,protocol:"",status:e.responseStatusCode??0,statusText:e.responseStatusText??"",fromCache:!1,headers:r,mimeType:"",bytesReceived:0,headersSize:(0,Pe.computeHeadersSize)(r),bodySize:0,content:{size:0},authChallenge:void 0}}),this.#ne=a,this.#fe()}async failRequest(e,t){await this.#F.cdpClient.sendCommand("Fetch.failRequest",{requestId:e,errorReason:t}),this.#ne=void 0}async continueRequest(e,t,a,r){await this.#F.cdpClient.sendCommand("Fetch.continueRequest",{requestId:e,url:t,method:a,headers:r}),this.#ne=void 0}async continueResponse(e,t,a,r){await this.#F.cdpClient.sendCommand("Fetch.continueResponse",{requestId:e,responseCode:t,responsePhrase:a,responseHeaders:r}),this.#ne=void 0}async continueWithAuth(e,t,a,r){await this.#F.cdpClient.sendCommand("Fetch.continueWithAuth",{requestId:e,authChallengeResponse:{response:t,username:a,password:r}}),this.#ne=void 0}async provideResponse(e,t,a,r,n){await this.#F.cdpClient.sendCommand("Fetch.fulfillRequest",{requestId:e,responseCode:t,responsePhrase:a,responseHeaders:r,...n?{body:btoa(n)}:{}}),this.#ne=void 0}dispose(){const e={kind:"error",error:new Error("Network processor detached")};this.#ue.resolve(e),this.#le.resolve(e),this.#he.resolve(e)}get#Se(){return this.#ce.info?.frameId??null}get statusCode(){return this.#de.info?.status??this.#de.extraInfo?.statusCode??-1}#ye(e){const t=void 0!==e&&e===this.#ne,a=this.#ie.getNetworkIntercepts(this.#re,e);return{isBlocked:t,context:this.#Se,navigation:this.#we(),redirectCount:this.#oe,request:this.#be(),timestamp:Math.round(1e3*(this.#ce.info?.wallTime??0)),intercepts:t?a:void 0}}#we(){return this.#ce.info&&this.#ce.info.loaderId&&this.#ce.info.loaderId===this.#ce.info.requestId?this.#ce.info.loaderId:null}#be(){const e=this.#ce.extraInfo?ke.#Ce(this.#ce.extraInfo.associatedCookies):[],t=(0,Pe.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#ce.info?.request.headers);return{request:this.#ce.info?.requestId??ke.#ae,url:this.#ce.info?.request.url??ke.#ae,method:this.#ce.info?.request.method??ke.#ae,headers:t,cookies:e,headersSize:(0,Pe.computeHeadersSize)(t),bodySize:0,timings:this.#xe()}}#xe(){return{timeOrigin:0,requestTime:0,redirectStart:0,redirectEnd:0,fetchStart:0,dnsStart:0,dnsEnd:0,connectStart:0,connectEnd:0,tlsStart:0,requestStart:0,responseStart:0,responseEnd:0}}#ge(){this.#ve()||this.#R.registerPromiseEvent(this.#ue.then((e=>{if("success"===e.kind)try{return{kind:"success",value:Object.assign(this.#Ie(),{type:"event"})}}catch(e){return{kind:"error",error:e instanceof Error?e:new Error("Unknown")}}return e})),this.#Se,Ce.ChromiumBidi.Network.EventNames.BeforeRequestSent)}#Ie(){return(0,xe.assert)(this.#ce.info,"RequestWillBeSentEvent is not set"),{method:Ce.ChromiumBidi.Network.EventNames.BeforeRequestSent,params:{...this.#ye("beforeRequestSent"),initiator:{type:ke.#Pe(this.#ce.info.initiator.type)}}}}#pe(){this.#ve()||this.#R.registerPromiseEvent(this.#le.then((e=>{if("success"===e.kind)try{return{kind:"success",value:Object.assign(this.#ke(),{type:"event"})}}catch(e){return{kind:"error",error:e instanceof Error?e:new Error("Unknown")}}return e})),this.#Se,Ce.ChromiumBidi.Network.EventNames.ResponseStarted)}#ke(){(0,xe.assert)(this.#ce.info,"RequestWillBeSentEvent is not set"),(0,xe.assert)(this.#de.info,"ResponseReceivedEvent is not set"),this.#de.info.fromDiskCache&&(this.#de.extraInfo=void 0);const e=(0,Pe.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#de.info.headers);return{method:Ce.ChromiumBidi.Network.EventNames.ResponseStarted,params:{...this.#ye(),response:{url:this.#de.info.url??ke.#ae,protocol:this.#de.info.protocol??"",status:this.statusCode,statusText:this.#de.info.statusText,fromCache:this.#de.info.fromDiskCache||this.#de.info.fromPrefetchCache||this.#se,headers:e,mimeType:this.#de.info.mimeType,bytesReceived:this.#de.info.encodedDataLength,headersSize:(0,Pe.computeHeadersSize)(e),bodySize:0,content:{size:0}}}}}#me(){this.#ve()||this.#R.registerPromiseEvent(this.#he.then((e=>{if("success"===e.kind)try{return{kind:"success",value:Object.assign(this.#Re(),{type:"event"})}}catch(e){return{kind:"error",error:e instanceof Error?e:new Error("Unknown")}}return e})),this.#Se,Ce.ChromiumBidi.Network.EventNames.ResponseCompleted)}#Re(){(0,xe.assert)(this.#ce.info,"RequestWillBeSentEvent is not set"),(0,xe.assert)(this.#de.info,"ResponseReceivedEvent is not set"),this.#de.info.fromDiskCache&&(this.#de.extraInfo=void 0);const e=(0,Pe.bidiNetworkHeadersFromCdpNetworkHeaders)(this.#de.info.headers);return{method:Ce.ChromiumBidi.Network.EventNames.ResponseCompleted,params:{...this.#ye(),response:{url:this.#de.info.url??ke.#ae,protocol:this.#de.info.protocol??"",status:this.statusCode,statusText:this.#de.info.statusText,fromCache:this.#de.info.fromDiskCache||this.#de.info.fromPrefetchCache||this.#se,headers:e,mimeType:this.#de.info.mimeType,bytesReceived:this.#de.info.encodedDataLength,headersSize:(0,Pe.computeHeadersSize)(e),bodySize:0,content:{size:0}}}}}#ve(){return this.#ce.info?.request.url.endsWith("/favicon.ico")??!1}static#Pe(e){switch(e){case"parser":case"script":case"preflight":return e;default:return"other"}}static#Ce(e){return e.filter((({blockedReasons:e})=>!Array.isArray(e)||0===e.length)).map((({cookie:e})=>({name:e.name,value:{type:"string",value:e.value},domain:e.domain,path:e.path,expires:e.expires,size:e.size,httpOnly:e.httpOnly,secure:e.secure,sameSite:ke.#Ee(e.sameSite)})))}static#Ee(e){switch(e){case"Strict":return"strict";case"Lax":return"lax";default:return"none"}}}we.NetworkRequest=ke,Object.defineProperty(ve,"__esModule",{value:!0}),ve.NetworkManager=void 0;const Re=we;class Ee{#F;#R;#ie;constructor(e,t,a){this.#F=e,this.#R=t,this.#ie=a}get cdpTarget(){return this.#F}#_e(e,t){let a=this.#ie.getRequest(e);return a||(a=new Re.NetworkRequest(e,this.#R,this.#ie,this.#F,t),this.#ie.addRequest(a),a)}static create(e,t,a){const r=new Ee(e,t,a);return e.browserCdpClient.on("Target.detachedFromTarget",(t=>{e.cdpClient.sessionId===t.sessionId&&r.#ie.disposeRequestMap()})),e.cdpClient.on("Network.requestWillBeSent",(e=>{const t=r.#ie.getRequest(e.requestId);t&&t.isRedirecting()?(t.handleRedirect(e),r.#ie.deleteRequest(e.requestId),r.#_e(e.requestId,t.redirectCount+1).onRequestWillBeSentEvent(e)):t?t.onRequestWillBeSentEvent(e):r.#_e(e.requestId).onRequestWillBeSentEvent(e)})),e.cdpClient.on("Network.requestWillBeSentExtraInfo",(e=>{r.#_e(e.requestId).onRequestWillBeSentExtraInfoEvent(e)})),e.cdpClient.on("Network.responseReceived",(e=>{r.#_e(e.requestId).onResponseReceivedEvent(e)})),e.cdpClient.on("Network.responseReceivedExtraInfo",(e=>{r.#_e(e.requestId).onResponseReceivedExtraInfoEvent(e)})),e.cdpClient.on("Network.requestServedFromCache",(e=>{r.#_e(e.requestId).onServedFromCache()})),e.cdpClient.on("Network.loadingFailed",(e=>{r.#_e(e.requestId).onLoadingFailedEvent(e)})),e.cdpClient.on("Fetch.requestPaused",(e=>{e.networkId&&r.#_e(e.networkId).onRequestPaused(e,r.#ie)})),r}}ve.NetworkManager=Ee,Object.defineProperty(se,"__esModule",{value:!0}),se.CdpTarget=void 0;const _e=O,Te=oe,Ne=ve;class je{#Te;#k;#o;#Ne;#R;#je;#ie;#Oe=new _e.Deferred;#Me;static create(e,t,a,r,n,s,o,i,c){const d=new je(e,t,a,r,s,o,i,c);return Te.LogManager.create(d,n,s),Ne.NetworkManager.create(d,s,i),d.#Ae(),d.#De(),d}constructor(e,t,a,r,n,s,o,i){this.#Te=e,this.#k=t,this.#Ne=r,this.#R=n,this.#je=s,this.#ie=o,this.#o=a,this.#Me=i}get targetUnblocked(){return this.#Oe}get targetId(){return this.#Te}get cdpClient(){return this.#k}get browserCdpClient(){return this.#o}get cdpSessionId(){return this.#Ne}async fetchEnable(){await this.#k.sendCommand("Fetch.enable",this.#ie.getFetchEnableParams())}async fetchDisable(){await this.#k.sendCommand("Fetch.disable")}async#De(){try{await Promise.all([this.#k.sendCommand("Runtime.enable"),this.#k.sendCommand("Page.enable"),this.#k.sendCommand("Page.setLifecycleEventsEnabled",{enabled:!0}),this.#k.sendCommand("Security.setIgnoreCertificateErrors",{ignore:this.#Me}),this.#k.sendCommand("Network.enable"),this.fetchEnable(),this.#k.sendCommand("Target.setAutoAttach",{autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),this.#Be(),this.#k.sendCommand("Runtime.runIfWaitingForDebugger")])}catch(e){if(!this.#k.isCloseError(e))return void this.#Oe.resolve({kind:"error",error:e})}this.#Oe.resolve({kind:"success",value:void 0})}#Ae(){this.#k.on("*",((e,t)=>{"string"==typeof e&&this.#R.registerEvent({type:"event",method:`cdp.${e}`,params:{event:e,params:t,session:this.#Ne}},null)}))}getChannels(){return this.#je.find().flatMap((e=>e.channels))}async#Be(){for(const e of this.#je.find({global:!0}))await e.initInTarget(this,!0)}}se.CdpTarget=je,Object.defineProperty(T,"__esModule",{value:!0}),T.BrowsingContextProcessor=void 0;const Oe=g,Me=l,Ae=N,De=se;T.BrowsingContextProcessor=class{#o;#c;#ze;#R;#i;#ie;#Me;#je;#w;#t;constructor(e,t,a,r,n,s,o,i,c,d){this.#Me=c,this.#c=e,this.#o=t,this.#ze=a,this.#R=r,this.#i=n,this.#je=i,this.#ie=o,this.#w=s,this.#t=d,this.#Ae(t)}getTree(e){return{contexts:(void 0===e.root?this.#i.getTopLevelContexts():[this.#i.getContext(e.root)]).map((t=>t.serializeToBidiValue(e.maxDepth??Number.MAX_VALUE)))}}async create(e){let t,a;if(void 0!==e.referenceContext&&(t=this.#i.getContext(e.referenceContext),!t.isTopLevelContext()))throw new Oe.InvalidArgumentException("referenceContext should be a top-level context");switch(e.type){case"tab":a=await this.#o.sendCommand("Target.createTarget",{url:"about:blank",newWindow:!1});break;case"window":a=await this.#o.sendCommand("Target.createTarget",{url:"about:blank",newWindow:!0})}const r=a.targetId,n=this.#i.getContext(r);return await n.lifecycleLoaded(),{context:n.id}}navigate(e){return this.#i.getContext(e.context).navigate(e.url,e.wait??"none")}reload(e){return this.#i.getContext(e.context).reload(e.ignoreCache??!1,e.wait??"none")}async activate(e){const t=this.#i.getContext(e.context);if(!t.isTopLevelContext())throw new Oe.InvalidArgumentException("Activation is only supported on the top-level context");return await t.activate(),{}}async captureScreenshot(e){const t=this.#i.getContext(e.context);return await t.captureScreenshot(e)}async print(e){const t=this.#i.getContext(e.context);return await t.print(e)}async setViewport(e){const t=this.#i.getContext(e.context);if(!t.isTopLevelContext())throw new Oe.InvalidArgumentException("Emulating viewport is only supported on the top-level context");return await t.setViewport(e.viewport,e.devicePixelRatio),{}}async traverseHistory(e){const t=this.#i.getContext(e.context);if(!t)throw new Oe.InvalidArgumentException(`No browsing context with id ${e.context}`);return await t.traverseHistory(e.delta),{}}async handleUserPrompt(e){const t=this.#i.getContext(e.context);return await t.handleUserPrompt(e),{}}async close(e){const t=this.#i.getContext(e.context);if(!t.isTopLevelContext())throw new Oe.InvalidArgumentException(`Non top-level browsing context ${t.id} cannot be closed.`);try{const a=new Promise((t=>{const a=r=>{r.targetId===e.context&&(this.#o.off("Target.detachedFromTarget",a),t())};this.#o.on("Target.detachedFromTarget",a)}));e.promptUnload?await t.close():await this.#o.sendCommand("Target.closeTarget",{targetId:e.context}),await a}catch(e){if(-32e3!==e.code||"Not attached to an active page"!==e.message)throw e}return{}}#Ae(e){e.on("Target.attachedToTarget",(t=>{this.#Le(t,e)})),e.on("Target.detachedFromTarget",(e=>{this.#Ze(e)})),e.on("Target.targetInfoChanged",(e=>{this.#Ue(e)})),e.on("Page.frameAttached",(e=>{this.#qe(e)})),e.on("Page.frameDetached",(e=>{this.#Ve(e)}))}#qe(e){const t=this.#i.findContext(e.parentFrameId);void 0!==t&&Ae.BrowsingContextImpl.create(t.cdpTarget,this.#w,e.frameId,e.parentFrameId,this.#R,this.#i,this.#t)}#Ve(e){"swap"!==e.reason&&this.#i.findContext(e.frameId)?.dispose()}#Le(e,t){const{sessionId:a,targetInfo:r}=e,n=this.#c.getCdpClient(a);if(!this.#Fe(r))return void n.sendCommand("Runtime.runIfWaitingForDebugger").then((()=>t.sendCommand("Target.detachFromTarget",e))).catch((e=>this.#t?.(Me.LogType.debugError,e)));this.#t?.(Me.LogType.debugInfo,"AttachedToTarget event received:",e),this.#Ae(n);const s=this.#i.findContext(r.targetId),o=De.CdpTarget.create(r.targetId,n,this.#o,a,this.#w,this.#R,this.#je,this.#ie,this.#Me);s?s.updateCdpTarget(o):Ae.BrowsingContextImpl.create(o,this.#w,r.targetId,null,this.#R,this.#i,this.#t)}#Ze(e){const t=e.targetId;this.#i.findContext(t)?.dispose(),this.#je.find({targetId:t}).map((e=>e.dispose(t)))}#Ue(e){const t=e.targetInfo.targetId;this.#i.findContext(t)?.onTargetInfoChanged(e)}#Fe(e){return e.targetId!==this.#ze&&["page","iframe"].includes(e.type)}};var Be={},ze={},Le={};Object.defineProperty(Le,"__esModule",{value:!0}),Le.WheelSource=Le.PointerSource=Le.KeySource=Le.NoneSource=void 0;Le.NoneSource=class{type="none"};Le.KeySource=class{type="key";pressed=new Set;#$e=0;get modifiers(){return this.#$e}get alt(){return 1==(1&this.#$e)}set alt(e){this.#Ke(e,1)}get ctrl(){return 2==(2&this.#$e)}set ctrl(e){this.#Ke(e,2)}get meta(){return 4==(4&this.#$e)}set meta(e){this.#Ke(e,4)}get shift(){return 8==(8&this.#$e)}set shift(e){this.#Ke(e,8)}#Ke(e,t){e?this.#$e|=t:this.#$e&=~t}};Le.PointerSource=class{type="pointer";subtype;pointerId;pressed=new Set;x=0;y=0;constructor(e,t){this.pointerId=e,this.subtype=t}get buttons(){let e=0;for(const t of this.pressed)switch(t){case 0:e|=1;break;case 1:e|=4;break;case 2:e|=2;break;case 3:e|=8;break;case 4:e|=16}return e}static ClickContext=class e{static#He=500;static#We=2;count=0;#Je;#Ge;#Xe;constructor(e,t,a){this.#Je=e,this.#Ge=t,this.#Xe=a}compare(t){return t.#Xe-this.#Xe>e.#He||Math.abs(t.#Je-this.#Je)>e.#We||Math.abs(t.#Ge-this.#Ge)>e.#We}};#Ye=new Map;setClickCount(e,t){let a=this.#Ye.get(e);return a&&!a.compare(t)||(a=t),++a.count,this.#Ye.set(e,a),a.count}getClickCount(e){return this.#Ye.get(e)?.count??0}};Le.WheelSource=class{type="wheel"};var Ze={};Object.defineProperty(Ze,"__esModule",{value:!0}),Ze.getKeyLocation=Ze.getKeyCode=Ze.getNormalizedKey=void 0,Ze.getNormalizedKey=function(e){switch(e){case"\ue000":return"Unidentified";case"\ue001":return"Cancel";case"\ue002":return"Help";case"\ue003":return"Backspace";case"\ue004":return"Tab";case"\ue005":return"Clear";case"\ue006":return"Return";case"\ue007":return"Enter";case"\ue008":case"\ue050":return"Shift";case"\ue009":case"\ue051":return"Control";case"\ue00a":case"\ue052":return"Alt";case"\ue00b":return"Pause";case"\ue00c":return"Escape";case"\ue00d":return" ";case"\ue00e":case"\ue054":return"PageUp";case"\ue00f":case"\ue055":return"PageDown";case"\ue010":case"\ue056":return"End";case"\ue011":case"\ue057":return"Home";case"\ue012":case"\ue058":return"ArrowLeft";case"\ue013":case"\ue059":return"ArrowUp";case"\ue014":case"\ue05a":return"ArrowRight";case"\ue015":case"\ue05b":return"ArrowDown";case"\ue016":case"\ue05c":return"Insert";case"\ue017":case"\ue05d":return"Delete";case"\ue018":return";";case"\ue019":return"=";case"\ue01a":return"0";case"\ue01b":return"1";case"\ue01c":return"2";case"\ue01d":return"3";case"\ue01e":return"4";case"\ue01f":return"5";case"\ue020":return"6";case"\ue021":return"7";case"\ue022":return"8";case"\ue023":return"9";case"\ue024":return"*";case"\ue025":return"+";case"\ue026":return",";case"\ue027":return"-";case"\ue028":return".";case"\ue029":return"/";case"\ue031":return"F1";case"\ue032":return"F2";case"\ue033":return"F3";case"\ue034":return"F4";case"\ue035":return"F5";case"\ue036":return"F6";case"\ue037":return"F7";case"\ue038":return"F8";case"\ue039":return"F9";case"\ue03a":return"F10";case"\ue03b":return"F11";case"\ue03c":return"F12";case"\ue03d":case"\ue053":return"Meta";case"\ue040":return"ZenkakuHankaku";default:return e}},Ze.getKeyCode=function(e){switch(e){case"`":case"~":return"Backquote";case"\\":case"|":return"Backslash";case"\ue003":return"Backspace";case"[":case"{":return"BracketLeft";case"]":case"}":return"BracketRight";case",":case"<":return"Comma";case"0":case")":return"Digit0";case"1":case"!":return"Digit1";case"2":case"@":return"Digit2";case"3":case"#":return"Digit3";case"4":case"$":return"Digit4";case"5":case"%":return"Digit5";case"6":case"^":return"Digit6";case"7":case"&":return"Digit7";case"8":case"*":return"Digit8";case"9":case"(":return"Digit9";case"=":case"+":return"Equal";case"a":case"A":return"KeyA";case"b":case"B":return"KeyB";case"c":case"C":return"KeyC";case"d":case"D":return"KeyD";case"e":case"E":return"KeyE";case"f":case"F":return"KeyF";case"g":case"G":return"KeyG";case"h":case"H":return"KeyH";case"i":case"I":return"KeyI";case"j":case"J":return"KeyJ";case"k":case"K":return"KeyK";case"l":case"L":return"KeyL";case"m":case"M":return"KeyM";case"n":case"N":return"KeyN";case"o":case"O":return"KeyO";case"p":case"P":return"KeyP";case"q":case"Q":return"KeyQ";case"r":case"R":return"KeyR";case"s":case"S":return"KeyS";case"t":case"T":return"KeyT";case"u":case"U":return"KeyU";case"v":case"V":return"KeyV";case"w":case"W":return"KeyW";case"x":case"X":return"KeyX";case"y":case"Y":return"KeyY";case"z":case"Z":return"KeyZ";case"-":case"_":return"Minus";case".":return"Period";case"'":case'"':return"Quote";case";":case":":return"Semicolon";case"/":case"?":return"Slash";case"\ue00a":return"AltLeft";case"\ue052":return"AltRight";case"\ue009":return"ControlLeft";case"\ue051":return"ControlRight";case"\ue006":return"Enter";case"\ue03d":return"MetaLeft";case"\ue053":return"MetaRight";case"\ue008":return"ShiftLeft";case"\ue050":return"ShiftRight";case" ":case"\ue00d":return"Space";case"\ue004":return"Tab";case"\ue017":return"Delete";case"\ue010":return"End";case"\ue002":return"Help";case"\ue011":return"Home";case"\ue016":return"Insert";case"\ue00f":return"PageDown";case"\ue00e":return"PageUp";case"\ue015":return"ArrowDown";case"\ue012":return"ArrowLeft";case"\ue014":return"ArrowRight";case"\ue013":return"ArrowUp";case"\ue00c":return"Escape";case"\ue031":return"F1";case"\ue032":return"F2";case"\ue033":return"F3";case"\ue034":return"F4";case"\ue035":return"F5";case"\ue036":return"F6";case"\ue037":return"F7";case"\ue038":return"F8";case"\ue039":return"F9";case"\ue03a":return"F10";case"\ue03b":return"F11";case"\ue03c":return"F12";case"\ue01a":case"\ue05c":return"Numpad0";case"\ue01b":case"\ue056":return"Numpad1";case"\ue01c":case"\ue05b":return"Numpad2";case"\ue01d":case"\ue055":return"Numpad3";case"\ue01e":case"\ue058":return"Numpad4";case"\ue01f":return"Numpad5";case"\ue020":case"\ue05a":return"Numpad6";case"\ue021":case"\ue057":return"Numpad7";case"\ue022":case"\ue059":return"Numpad8";case"\ue023":case"\ue054":return"Numpad9";case"\ue025":return"NumpadAdd";case"\ue026":return"NumpadComma";case"\ue028":case"\ue05d":return"NumpadDecimal";case"\ue029":return"NumpadDivide";case"\ue007":return"NumpadEnter";case"\ue024":return"NumpadMultiply";case"\ue027":return"NumpadSubtract";default:return}},Ze.getKeyLocation=function(e){switch(e){case"\ue007":case"\ue008":case"\ue009":case"\ue00a":case"\ue03d":return 1;case"\ue01a":case"\ue01b":case"\ue01c":case"\ue01d":case"\ue01e":case"\ue01f":case"\ue020":case"\ue021":case"\ue022":case"\ue023":case"\ue024":case"\ue025":case"\ue026":case"\ue027":case"\ue028":case"\ue029":case"\ue054":case"\ue055":case"\ue056":case"\ue057":case"\ue058":case"\ue059":case"\ue05a":case"\ue05b":case"\ue05c":case"\ue05d":return 3;case"\ue050":case"\ue051":case"\ue052":case"\ue053":return 2;default:return 0}};var Ue={};Object.defineProperty(Ue,"__esModule",{value:!0}),Ue.KeyToKeyCode=void 0,Ue.KeyToKeyCode={0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,Abort:3,Help:6,Backspace:8,Tab:9,Numpad5:12,NumpadEnter:13,Enter:13,"\\r":13,"\\n":13,ShiftLeft:16,ShiftRight:16,ControlLeft:17,ControlRight:17,AltLeft:18,AltRight:18,Pause:19,CapsLock:20,Escape:27,Convert:28,NonConvert:29,Space:32,Numpad9:33,PageUp:33,Numpad3:34,PageDown:34,End:35,Numpad1:35,Home:36,Numpad7:36,ArrowLeft:37,Numpad4:37,Numpad8:38,ArrowUp:38,ArrowRight:39,Numpad6:39,Numpad2:40,ArrowDown:40,Select:41,Open:43,PrintScreen:44,Insert:45,Numpad0:45,Delete:46,NumpadDecimal:46,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,KeyA:65,KeyB:66,KeyC:67,KeyD:68,KeyE:69,KeyF:70,KeyG:71,KeyH:72,KeyI:73,KeyJ:74,KeyK:75,KeyL:76,KeyM:77,KeyN:78,KeyO:79,KeyP:80,KeyQ:81,KeyR:82,KeyS:83,KeyT:84,KeyU:85,KeyV:86,KeyW:87,KeyX:88,KeyY:89,KeyZ:90,MetaLeft:91,MetaRight:92,ContextMenu:93,NumpadMultiply:106,NumpadAdd:107,NumpadSubtract:109,NumpadDivide:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,F16:127,F17:128,F18:129,F19:130,F20:131,F21:132,F22:133,F23:134,F24:135,NumLock:144,ScrollLock:145,AudioVolumeMute:173,AudioVolumeDown:174,AudioVolumeUp:175,MediaTrackNext:176,MediaTrackPrevious:177,MediaStop:178,MediaPlayPause:179,Semicolon:186,Equal:187,NumpadEqual:187,Comma:188,Minus:189,Period:190,Slash:191,Backquote:192,BracketLeft:219,Backslash:220,BracketRight:221,Quote:222,AltGraph:225,Props:247,Cancel:3,Clear:12,Shift:16,Control:17,Alt:18,Accept:30,ModeChange:31," ":32,Print:42,Execute:43,"\\u0000":46,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,Meta:91,"*":106,"+":107,"-":109,"/":111,";":186,"=":187,",":188,".":190,"`":192,"[":219,"\\\\":220,"]":221,"'":222,Attn:246,CrSel:247,ExSel:248,EraseEof:249,Play:250,ZoomOut:251,")":48,"!":49,"@":50,"#":51,$:52,"%":53,"^":54,"&":55,"(":57,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,":":186,"<":188,_:189,">":190,"?":191,"~":192,"{":219,"|":220,"}":221,'"':222,Camera:44,EndCall:95,VolumeDown:182,VolumeUp:183},Object.defineProperty(ze,"__esModule",{value:!0}),ze.ActionDispatcher=void 0;const qe=g,Ve=j,Fe=Le,$e=Ze,Ke=Ue,He=(e=>{const t=e.getClientRects()[0],a=Math.max(0,Math.min(t.x,t.x+t.width)),r=Math.min(window.innerWidth,Math.max(t.x,t.x+t.width)),n=Math.max(0,Math.min(t.y,t.y+t.height));return[a+(r-a>>1),n+(Math.min(window.innerHeight,Math.max(t.y,t.y+t.height))-n>>1)]}).toString(),We=(()=>navigator.platform.toLowerCase().includes("mac")).toString();ze.ActionDispatcher=class{static isMacOS=async e=>{const t=await(await e.getOrCreateSandbox(void 0)).callFunction(We,{type:"undefined"},[],!1,"none",{});return(0,Ve.assert)("exception"!==t.type),(0,Ve.assert)("boolean"===t.result.type),t.result.value};#Qe=0;#et=0;#tt;#Se;#at;constructor(e,t,a){this.#tt=e,this.#Se=t,this.#at=a}async dispatchActions(e){await this.#tt.queue.run((async()=>{for(const t of e)await this.dispatchTickActions(t)}))}async dispatchTickActions(e){this.#Qe=performance.now(),this.#et=0;for(const{action:t}of e)"duration"in t&&void 0!==t.duration&&(this.#et=Math.max(this.#et,t.duration));const t=[new Promise((e=>setTimeout(e,this.#et)))];for(const a of e)t.push(this.#rt(a));await Promise.all(t)}async#rt({id:e,action:t}){const a=this.#tt.get(e),r=this.#tt.getGlobalKeyState();switch(t.type){case"keyDown":await this.#nt(a,t),this.#tt.cancelList.push({id:e,action:{...t,type:"keyUp"}});break;case"keyUp":await this.#st(a,t);break;case"pause":break;case"pointerDown":await this.#ot(a,r,t),this.#tt.cancelList.push({id:e,action:{...t,type:"pointerUp"}});break;case"pointerMove":await this.#it(a,r,t);break;case"pointerUp":await this.#ct(a,r,t);break;case"scroll":await this.#dt(a,r,t)}}#ot(e,t,a){const{button:r}=a;if(e.pressed.has(r))return;e.pressed.add(r);const{x:n,y:s,subtype:o}=e,{width:i,height:c,pressure:d,twist:u,tangentialPressure:l}=a,{tiltX:h,tiltY:p}=Ye(a),{modifiers:m}=t;switch(o){case"mouse":case"pen":return this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mousePressed",x:n,y:s,modifiers:m,button:Xe(r),buttons:e.buttons,clickCount:e.setClickCount(r,new Fe.PointerSource.ClickContext(n,s,performance.now())),pointerType:o,tangentialPressure:l,tiltX:h,tiltY:p,twist:u,force:d});case"touch":return this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:n,y:s,...Qe(i??1,c??1),tangentialPressure:l,tiltX:h,tiltY:p,twist:u,force:d,id:e.pointerId}],modifiers:m})}}#ct(e,t,a){const{button:r}=a;if(!e.pressed.has(r))return;e.pressed.delete(r);const{x:n,y:s,subtype:o}=e,{modifiers:i}=t;switch(o){case"mouse":case"pen":return this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseReleased",x:n,y:s,modifiers:i,button:Xe(r),buttons:e.buttons,clickCount:e.getClickCount(r),pointerType:o});case"touch":return this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[{x:n,y:s,id:e.pointerId}],modifiers:i})}}async#it(e,t,a){const{x:r,y:n,subtype:s}=e,{width:o,height:i,pressure:c,twist:d,tangentialPressure:u,x:l,y:h,origin:p="viewport",duration:m=this.#et}=a,{tiltX:f,tiltY:g}=Ye(a),{targetX:y,targetY:S}=await this.#ut(p,l,h,r,n);if(y<0||S<0)throw new qe.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${y}, y: ${S})`);let v;do{const a=m>0?(performance.now()-this.#Qe)/m:1;let l,h;if(v=a>=1,v?(l=y,h=S):(l=Math.round(a*(y-r)+r),h=Math.round(a*(S-n)+n)),e.x!==l||e.y!==h){const{modifiers:a}=t;switch(s){case"mouse":await this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseMoved",x:l,y:h,modifiers:a,clickCount:0,button:Xe(e.pressed.values().next().value??5),buttons:e.buttons,pointerType:s,tangentialPressure:u,tiltX:f,tiltY:g,twist:d,force:c});break;case"pen":0!==e.pressed.size&&await this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseMoved",x:l,y:h,modifiers:a,clickCount:0,button:Xe(e.pressed.values().next().value??5),buttons:e.buttons,pointerType:s,tangentialPressure:u,tiltX:f,tiltY:g,twist:d,force:c});break;case"touch":0!==e.pressed.size&&await this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:l,y:h,...Qe(o??1,i??1),tangentialPressure:u,tiltX:f,tiltY:g,twist:d,force:c,id:e.pointerId}],modifiers:a})}e.x=l,e.y=h}}while(!v)}async#ut(e,t,a,r,n){let s,o;switch(e){case"viewport":s=t,o=a;break;case"pointer":s=r+t,o=n+a;break;default:{const{x:r,y:n}=await async function(e,t){const a=await e.getOrCreateSandbox(void 0),r=await a.callFunction(He,{type:"undefined"},[t],!1,"none",{});if("exception"===r.type)throw new qe.NoSuchElementException(`Origin element ${t.sharedId} was not found`);(0,Ve.assert)("array"===r.result.type),(0,Ve.assert)("number"===r.result.value?.[0]?.type),(0,Ve.assert)("number"===r.result.value?.[1]?.type);const{result:{value:[{value:n},{value:s}]}}=r;return{x:n,y:s}}(this.#Se,e.element);s=r+t,o=n+a;break}}return{targetX:s,targetY:o}}async#dt(e,t,a){const{deltaX:r,deltaY:n,x:s,y:o,origin:i="viewport",duration:c=this.#et}=a;if("pointer"===i)throw new qe.InvalidArgumentException('"pointer" origin is invalid for scrolling.');const{targetX:d,targetY:u}=await this.#ut(i,s,o,0,0);if(d<0||u<0)throw new qe.MoveTargetOutOfBoundsException(`Cannot move beyond viewport (x: ${d}, y: ${u})`);let l,h=0,p=0;do{const e=c>0?(performance.now()-this.#Qe)/c:1;let a,s;if(l=e>=1,l?(a=r-h,s=n-p):(a=Math.round(e*r-h),s=Math.round(e*n-p)),0!==a||0!==s){const{modifiers:e}=t;await this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchMouseEvent",{type:"mouseWheel",deltaX:a,deltaY:s,x:d,y:u,modifiers:e}),h+=a,p+=s}}while(!l)}async#nt(e,t){if([...t.value].length>1)throw new qe.InvalidArgumentException(`Invalid key value: ${t.value}`);const a=t.value,r=(0,$e.getNormalizedKey)(a),n=e.pressed.has(r),s=(0,$e.getKeyCode)(a),o=(0,$e.getKeyLocation)(a);switch(r){case"Alt":e.alt=!0;break;case"Shift":e.shift=!0;break;case"Control":e.ctrl=!0;break;case"Meta":e.meta=!0}e.pressed.add(r);const{modifiers:i}=e,c=Je(r,e),d=Ge(s??"",e)??c;let u;if(this.#at&&e.meta)switch(s){case"KeyA":u="SelectAll";break;case"KeyC":u="Copy";break;case"KeyV":u=e.shift?"PasteAndMatchStyle":"Paste";break;case"KeyX":u="Cut";break;case"KeyZ":u=e.shift?"Redo":"Undo"}const l=[this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchKeyEvent",{type:d?"keyDown":"rawKeyDown",windowsVirtualKeyCode:Ke.KeyToKeyCode[r],key:r,code:s,text:d,unmodifiedText:c,autoRepeat:n,isSystemKey:e.alt||void 0,location:o<3?o:void 0,isKeypad:3===o,modifiers:i,commands:u?[u]:void 0})];"Escape"===r&&(e.alt||(!this.#at||e.ctrl||e.meta)&&this.#at||l.push(this.#Se.cdpTarget.cdpClient.sendCommand("Input.cancelDragging"))),await Promise.all(l)}#st(e,t){if([...t.value].length>1)throw new qe.InvalidArgumentException(`Invalid key value: ${t.value}`);const a=t.value,r=(0,$e.getNormalizedKey)(a);if(!e.pressed.has(r))return;const n=(0,$e.getKeyCode)(a),s=(0,$e.getKeyLocation)(a);switch(r){case"Alt":e.alt=!1;break;case"Shift":e.shift=!1;break;case"Control":e.ctrl=!1;break;case"Meta":e.meta=!1}e.pressed.delete(r);const{modifiers:o}=e,i=Je(r,e),c=Ge(n??"",e)??i;return this.#Se.cdpTarget.cdpClient.sendCommand("Input.dispatchKeyEvent",{type:"keyUp",windowsVirtualKeyCode:Ke.KeyToKeyCode[r],key:r,code:n,text:c,unmodifiedText:i,location:s<3?s:void 0,isSystemKey:e.alt||void 0,isKeypad:3===s,modifiers:o})}};const Je=(e,t)=>"Enter"===e?"\r":1===[...e].length?t.shift?e.toLocaleUpperCase("en-US"):e:void 0,Ge=(e,t)=>{if(t.ctrl){switch(e){case"Digit2":if(t.shift)return"\0";break;case"KeyA":return"\x01";case"KeyB":return"\x02";case"KeyC":return"\x03";case"KeyD":return"\x04";case"KeyE":return"\x05";case"KeyF":return"\x06";case"KeyG":return"\x07";case"KeyH":return"\b";case"KeyI":return"\t";case"KeyJ":return"\n";case"KeyK":return"\v";case"KeyL":return"\f";case"KeyM":return"\r";case"KeyN":return"\x0e";case"KeyO":return"\x0f";case"KeyP":return"\x10";case"KeyQ":return"\x11";case"KeyR":return"\x12";case"KeyS":return"\x13";case"KeyT":return"\x14";case"KeyU":return"\x15";case"KeyV":return"\x16";case"KeyW":return"\x17";case"KeyX":return"\x18";case"KeyY":return"\x19";case"KeyZ":return"\x1a";case"BracketLeft":return"\x1b";case"Backslash":return"\x1c";case"BracketRight":return"\x1d";case"Digit6":if(t.shift)return"\x1e";break;case"Minus":return"\x1f"}return""}if(t.alt)return""};function Xe(e){switch(e){case 0:return"left";case 1:return"middle";case 2:return"right";case 3:return"back";case 4:return"forward";default:return"none"}}function Ye(e){const t=e.altitudeAngle??0,a=e.azimuthAngle??0;let r=0,n=0;if(0===t&&(0!==a&&a!==2*Math.PI||(r=Math.PI/2),a===Math.PI/2&&(n=Math.PI/2),a===Math.PI&&(r=-Math.PI/2),a===3*Math.PI/2&&(n=-Math.PI/2),a>0&&a<Math.PI/2&&(r=Math.PI/2,n=Math.PI/2),a>Math.PI/2&&a<Math.PI&&(r=-Math.PI/2,n=Math.PI/2),a>Math.PI&&a<3*Math.PI/2&&(r=-Math.PI/2,n=-Math.PI/2),a>3*Math.PI/2&&a<2*Math.PI&&(r=Math.PI/2,n=-Math.PI/2)),0!==t){const e=Math.tan(t);r=Math.atan(Math.cos(a)/e),n=Math.atan(Math.sin(a)/e)}const s=180/Math.PI;return{tiltX:Math.round(r*s),tiltY:Math.round(n*s)}}function Qe(e,t){return{radiusX:e?e/2:.5,radiusY:t?t/2:.5}}var et={},tt={},at={};Object.defineProperty(at,"__esModule",{value:!0}),at.Mutex=void 0;at.Mutex=class{#lt=!1;#ht=[];acquire(){const e={resolved:!1};return this.#lt?new Promise((t=>{this.#ht.push((()=>t(this.#pt.bind(this,e))))})):(this.#lt=!0,Promise.resolve(this.#pt.bind(this,e)))}#pt(e){if(e.resolved)throw new Error("Cannot release more than once.");e.resolved=!0;const t=this.#ht.shift();t?t():this.#lt=!1}async run(e){const t=await this.acquire();try{return await e()}finally{t()}}},Object.defineProperty(tt,"__esModule",{value:!0}),tt.InputState=void 0;const rt=g,nt=at,st=Le;tt.InputState=class{cancelList=[];#mt=new Map;#ft=new nt.Mutex;getOrCreate(e,t,a){let r=this.#mt.get(e);if(!r){switch(t){case"none":r=new st.NoneSource;break;case"key":r=new st.KeySource;break;case"pointer":{let e="mouse"===a?0:2;const t=new Set;for(const[,e]of this.#mt)"pointer"===e.type&&t.add(e.pointerId);for(;t.has(e);)++e;r=new st.PointerSource(e,a);break}case"wheel":r=new st.WheelSource;break;default:throw new rt.InvalidArgumentException(`Expected "none", "key", "pointer", or "wheel". Found unknown source type ${t}.`)}return this.#mt.set(e,r),r}if(r.type!==t)throw new rt.InvalidArgumentException(`Input source type of ${e} is ${r.type}, but received ${t}.`);return r}get(e){const t=this.#mt.get(e);if(!t)throw new rt.UnknownErrorException("Internal error.");return t}getGlobalKeyState(){const e=new st.KeySource;for(const[,t]of this.#mt)if("key"===t.type){for(const a of t.pressed)e.pressed.add(a);e.alt||=t.alt,e.ctrl||=t.ctrl,e.meta||=t.meta,e.shift||=t.shift}return e}get queue(){return this.#ft}},Object.defineProperty(et,"__esModule",{value:!0}),et.InputStateManager=void 0;const ot=j,it=tt;class ct extends WeakMap{get(e){return(0,ot.assert)(e.isTopLevelContext()),this.has(e)||this.set(e,new it.InputState),super.get(e)}}et.InputStateManager=ct,Object.defineProperty(Be,"__esModule",{value:!0}),Be.InputProcessor=void 0;const dt=g,ut=ze,lt=et;Be.InputProcessor=class{#i;#gt=new lt.InputStateManager;constructor(e){this.#i=e}async performActions(e){const t=this.#i.getContext(e.context),a=this.#gt.get(t.top),r=this.#yt(e,a),n=new ut.ActionDispatcher(a,t,await ut.ActionDispatcher.isMacOS(t).catch((()=>!1)));return await n.dispatchActions(r),{}}async releaseActions(e){const t=this.#i.getContext(e.context),a=t.top,r=this.#gt.get(a),n=new ut.ActionDispatcher(r,t,await ut.ActionDispatcher.isMacOS(t).catch((()=>!1)));return await n.dispatchTickActions(r.cancelList.reverse()),this.#gt.delete(a),{}}#yt(e,t){const a=[];for(const r of e.actions){switch(r.type){case"pointer":{r.parameters??={pointerType:"mouse"},r.parameters.pointerType??="mouse";const e=t.getOrCreate(r.id,"pointer",r.parameters.pointerType);if(e.subtype!==r.parameters.pointerType)throw new dt.InvalidArgumentException(`Expected input source ${r.id} to be ${e.subtype}; got ${r.parameters.pointerType}.`);break}default:t.getOrCreate(r.id,r.type)}const e=r.actions.map((e=>({id:r.id,action:e})));for(let t=0;t<e.length;t++)a.length===t&&a.push([]),a[t].push(e[t])}return a}};var ht={},pt={},mt={},ft=Object.defineProperty,gt=Object.getOwnPropertyDescriptor,yt=Object.getOwnPropertyNames,St=Object.prototype.hasOwnProperty,vt={};((e,t)=>{for(var a in t)ft(e,a,{get:t[a],enumerable:!0})})(vt,{URLPattern:()=>sa});var wt,bt=(wt=vt,((e,t,a,r)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let n of yt(t))!St.call(e,n)&&n!==a&&ft(e,n,{get:()=>t[n],enumerable:!(r=gt(t,n))||r.enumerable});return e})(ft({},"__esModule",{value:!0}),wt)),Ct=class{type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(e,t,a,r,n,s){this.type=e,this.name=t,this.prefix=a,this.value=r,this.suffix=n,this.modifier=s}hasCustomName(){return""!==this.name&&"number"!=typeof this.name}},xt=/[$_\p{ID_Start}]/u,It=/[$_\u200C\u200D\p{ID_Continue}]/u,Pt=".*";function kt(e,t){return(t?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(e)}function Rt(e,t=!1){let a=[],r=0;for(;r<e.length;){let n=e[r],s=function(n){if(!t)throw new TypeError(n);a.push({type:"INVALID_CHAR",index:r,value:e[r++]})};if("*"!==n)if("+"!==n&&"?"!==n)if("\\"!==n)if("{"!==n)if("}"!==n)if(":"!==n)if("("!==n)a.push({type:"CHAR",index:r,value:e[r++]});else{let t=1,n="",o=r+1,i=!1;if("?"===e[o]){s(`Pattern cannot start with "?" at ${o}`);continue}for(;o<e.length;){if(!kt(e[o],!1)){s(`Invalid character '${e[o]}' at ${o}.`),i=!0;break}if("\\"!==e[o]){if(")"===e[o]){if(t--,0===t){o++;break}}else if("("===e[o]&&(t++,"?"!==e[o+1])){s(`Capturing groups are not allowed at ${o}`),i=!0;break}n+=e[o++]}else n+=e[o++]+e[o++]}if(i)continue;if(t){s(`Unbalanced pattern at ${r}`);continue}if(!n){s(`Missing pattern at ${r}`);continue}a.push({type:"REGEX",index:r,value:n}),r=o}else{let t="",n=r+1;for(;n<e.length;){let a=e.substr(n,1);if(!(n===r+1&&xt.test(a)||n!==r+1&&It.test(a)))break;t+=e[n++]}if(!t){s(`Missing parameter name at ${r}`);continue}a.push({type:"NAME",index:r,value:t}),r=n}else a.push({type:"CLOSE",index:r,value:e[r++]});else a.push({type:"OPEN",index:r,value:e[r++]});else a.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});else a.push({type:"OTHER_MODIFIER",index:r,value:e[r++]});else a.push({type:"ASTERISK",index:r,value:e[r++]})}return a.push({type:"END",index:r,value:""}),a}function Et(e,t={}){let a=Rt(e);t.delimiter??="/#?",t.prefixes??="./";let r=`[^${_t(t.delimiter)}]+?`,n=[],s=0,o=0,i=new Set,c=e=>{if(o<a.length&&a[o].type===e)return a[o++].value},d=()=>c("OTHER_MODIFIER")??c("ASTERISK"),u=e=>{let t=c(e);if(void 0!==t)return t;let{type:r,index:n}=a[o];throw new TypeError(`Unexpected ${r} at ${n}, expected ${e}`)},l=()=>{let e,t="";for(;e=c("CHAR")??c("ESCAPED_CHAR");)t+=e;return t},h=t.encodePart||(e=>e),p="",m=e=>{p+=e},f=()=>{p.length&&(n.push(new Ct(3,"","",h(p),"",3)),p="")},g=(e,t,a,o,c)=>{let d,u=3;switch(c){case"?":u=1;break;case"*":u=0;break;case"+":u=2}if(!t&&!a&&3===u)return void m(e);if(f(),!t&&!a){if(!e)return;return void n.push(new Ct(3,"","",h(e),"",u))}d=a?"*"===a?Pt:a:r;let l,p=2;if(d===r?(p=1,d=""):d===Pt&&(p=0,d=""),t?l=t:a&&(l=s++),i.has(l))throw new TypeError(`Duplicate name '${l}'.`);i.add(l),n.push(new Ct(p,l,h(e),d,h(o),u))};for(;o<a.length;){let e=c("CHAR"),a=c("NAME"),r=c("REGEX");if(!a&&!r&&(r=c("ASTERISK")),a||r){let n=e??"";-1===t.prefixes.indexOf(n)&&(m(n),n=""),f(),g(n,a,r,"",d());continue}let n=e??c("ESCAPED_CHAR");if(n)m(n);else if(c("OPEN")){let e=l(),t=c("NAME"),a=c("REGEX");!t&&!a&&(a=c("ASTERISK"));let r=l();u("CLOSE"),g(e,t,a,r,d())}else f(),u("END")}return n}function _t(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}function Tt(e){return e&&e.ignoreCase?"ui":"u"}function Nt(e){switch(e){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}function jt(e,t,a={}){a.delimiter??="/#?",a.prefixes??="./",a.sensitive??=!1,a.strict??=!1,a.end??=!0,a.start??=!0,a.endsWith="";let r=a.start?"^":"";for(let n of e){if(3===n.type){3===n.modifier?r+=_t(n.value):r+=`(?:${_t(n.value)})${Nt(n.modifier)}`;continue}t&&t.push(n.name);let e=`[^${_t(a.delimiter)}]+?`,s=n.value;(1===n.type?s=e:0===n.type&&(s=Pt),n.prefix.length||n.suffix.length)?3!==n.modifier&&1!==n.modifier?(r+=`(?:${_t(n.prefix)}`,r+=`((?:${s})(?:`,r+=_t(n.suffix),r+=_t(n.prefix),r+=`(?:${s}))*)${_t(n.suffix)})`,0===n.modifier&&(r+="?")):(r+=`(?:${_t(n.prefix)}(${s})${_t(n.suffix)})`,r+=Nt(n.modifier)):3===n.modifier||1===n.modifier?r+=`(${s})${Nt(n.modifier)}`:r+=`((?:${s})${Nt(n.modifier)})`}let n=`[${_t(a.endsWith)}]|$`,s=`[${_t(a.delimiter)}]`;if(a.end)return a.strict||(r+=`${s}?`),a.endsWith.length?r+=`(?=${n})`:r+="$",new RegExp(r,Tt(a));a.strict||(r+=`(?:${s}(?=${n}))?`);let o=!1;if(e.length){let t=e[e.length-1];3===t.type&&3===t.modifier&&(o=a.delimiter.indexOf(t)>-1)}return o||(r+=`(?=${s}|${n})`),new RegExp(r,Tt(a))}var Ot={delimiter:"",prefixes:"",sensitive:!0,strict:!0},Mt={delimiter:".",prefixes:"",sensitive:!0,strict:!0},At={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Dt(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}function Bt(e){return!(!e||e.length<2)&&("["===e[0]||("\\"===e[0]||"{"===e[0])&&"["===e[1])}var zt=["ftp","file","http","https","ws","wss"];function Lt(e){if(!e)return!0;for(let t of zt)if(e.test(t))return!0;return!1}function Zt(e){switch(e){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}function Ut(e){if(""===e)return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}function qt(e){if(""===e)return e;let t=new URL("https://example.com");return t.username=e,t.username}function Vt(e){if(""===e)return e;let t=new URL("https://example.com");return t.password=e,t.password}function Ft(e){if(""===e)return e;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL("https://example.com");return t.hostname=e,t.hostname}function $t(e){if(""===e)return e;if(/[^0-9a-fA-F[\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}function Kt(e){if(""===e||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}function Ht(e){if(""===e)return e;let t=new URL("https://example.com");return t.pathname="/"!==e[0]?"/-"+e:e,"/"!==e[0]?t.pathname.substring(2,t.pathname.length):t.pathname}function Wt(e){return""===e?e:new URL(`data:${e}`).pathname}function Jt(e){if(""===e)return e;let t=new URL("https://example.com");return t.search=e,t.search.substring(1,t.search.length)}function Gt(e){if(""===e)return e;let t=new URL("https://example.com");return t.hash=e,t.hash.substring(1,t.hash.length)}var Xt=class{#St;#vt=[];#wt={};#bt=0;#Ct=1;#xt=0;#It=0;#Pt=0;#kt=0;#Rt=!1;constructor(e){this.#St=e}get result(){return this.#wt}parse(){for(this.#vt=Rt(this.#St,!0);this.#bt<this.#vt.length;this.#bt+=this.#Ct){if(this.#Ct=1,"END"===this.#vt[this.#bt].type){if(0===this.#It){this.#Et(),this.#_t()?this.#Tt(9,1):this.#Nt()?(this.#Tt(8,1),this.#wt.hash=""):(this.#Tt(7,0),this.#wt.search="",this.#wt.hash="");continue}if(2===this.#It){this.#jt(5);continue}this.#Tt(10,0);break}if(this.#Pt>0){if(!this.#Ot())continue;this.#Pt-=1}if(this.#Mt())this.#Pt+=1;else switch(this.#It){case 0:this.#At()&&(this.#wt.username="",this.#wt.password="",this.#wt.hostname="",this.#wt.port="",this.#wt.pathname="",this.#wt.search="",this.#wt.hash="",this.#jt(1));break;case 1:if(this.#At()){this.#Dt();let e=7,t=1;this.#Rt&&(this.#wt.pathname="/"),this.#Bt()?(e=2,t=3):this.#Rt&&(e=2),this.#Tt(e,t)}break;case 2:this.#Je()?this.#jt(3):(this.#zt()||this.#Nt()||this.#_t())&&this.#jt(5);break;case 3:this.#Lt()?this.#Tt(4,1):this.#Je()&&this.#Tt(5,1);break;case 4:this.#Je()&&this.#Tt(5,1);break;case 5:this.#Zt()?this.#kt+=1:this.#Ut()&&(this.#kt-=1),this.#Ge()&&!this.#kt?this.#Tt(6,1):this.#zt()?this.#Tt(7,0):this.#Nt()?this.#Tt(8,1):this.#_t()&&this.#Tt(9,1);break;case 6:this.#zt()?this.#Tt(7,0):this.#Nt()?this.#Tt(8,1):this.#_t()&&this.#Tt(9,1);break;case 7:this.#Nt()?this.#Tt(8,1):this.#_t()&&this.#Tt(9,1);break;case 8:this.#_t()&&this.#Tt(9,1)}}}#Tt(e,t){switch(this.#It){case 0:case 2:break;case 1:this.#wt.protocol=this.#qt();break;case 3:this.#wt.username=this.#qt();break;case 4:this.#wt.password=this.#qt();break;case 5:this.#wt.hostname=this.#qt();break;case 6:this.#wt.port=this.#qt();break;case 7:this.#wt.pathname=this.#qt();break;case 8:this.#wt.search=this.#qt();break;case 9:this.#wt.hash=this.#qt()}this.#Vt(e,t)}#Vt(e,t){this.#It=e,this.#xt=this.#bt+t,this.#bt+=t,this.#Ct=0}#Et(){this.#bt=this.#xt,this.#Ct=0}#jt(e){this.#Et(),this.#It=e}#Ft(e){return e<0&&(e=this.#vt.length-e),e<this.#vt.length?this.#vt[e]:this.#vt[this.#vt.length-1]}#$t(e,t){let a=this.#Ft(e);return a.value===t&&("CHAR"===a.type||"ESCAPED_CHAR"===a.type||"INVALID_CHAR"===a.type)}#At(){return this.#$t(this.#bt,":")}#Bt(){return this.#$t(this.#bt+1,"/")&&this.#$t(this.#bt+2,"/")}#Je(){return this.#$t(this.#bt,"@")}#Lt(){return this.#$t(this.#bt,":")}#Ge(){return this.#$t(this.#bt,":")}#zt(){return this.#$t(this.#bt,"/")}#Nt(){if(this.#$t(this.#bt,"?"))return!0;if("?"!==this.#vt[this.#bt].value)return!1;let e=this.#Ft(this.#bt-1);return"NAME"!==e.type&&"REGEX"!==e.type&&"CLOSE"!==e.type&&"ASTERISK"!==e.type}#_t(){return this.#$t(this.#bt,"#")}#Mt(){return"OPEN"==this.#vt[this.#bt].type}#Ot(){return"CLOSE"==this.#vt[this.#bt].type}#Zt(){return this.#$t(this.#bt,"[")}#Ut(){return this.#$t(this.#bt,"]")}#qt(){let e=this.#vt[this.#bt],t=this.#Ft(this.#xt).index;return this.#St.substring(t,e.index)}#Dt(){let e={};Object.assign(e,Ot),e.encodePart=Ut;let t=function(e,t,a){return jt(Et(e,a),t,a)}(this.#qt(),void 0,e);this.#Rt=Lt(t)}},Yt=["protocol","username","password","hostname","port","pathname","search","hash"],Qt="*";function ea(e,t){if("string"!=typeof e)throw new TypeError("parameter 1 is not of type 'string'.");let a=new URL(e,t);return{protocol:a.protocol.substring(0,a.protocol.length-1),username:a.username,password:a.password,hostname:a.hostname,port:a.port,pathname:a.pathname,search:""!==a.search?a.search.substring(1,a.search.length):void 0,hash:""!==a.hash?a.hash.substring(1,a.hash.length):void 0}}function ta(e,t){return t?ra(e):e}function aa(e,t,a){let r;if("string"==typeof t.baseURL)try{r=new URL(t.baseURL),e.protocol=ta(r.protocol.substring(0,r.protocol.length-1),a),e.username=ta(r.username,a),e.password=ta(r.password,a),e.hostname=ta(r.hostname,a),e.port=ta(r.port,a),e.pathname=ta(r.pathname,a),e.search=ta(r.search.substring(1,r.search.length),a),e.hash=ta(r.hash.substring(1,r.hash.length),a)}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if("string"==typeof t.protocol&&(e.protocol=function(e,t){return e=function(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}(e,":"),t||""===e?e:Ut(e)}(t.protocol,a)),"string"==typeof t.username&&(e.username=function(e,t){if(t||""===e)return e;let a=new URL("https://example.com");return a.username=e,a.username}(t.username,a)),"string"==typeof t.password&&(e.password=function(e,t){if(t||""===e)return e;let a=new URL("https://example.com");return a.password=e,a.password}(t.password,a)),"string"==typeof t.hostname&&(e.hostname=function(e,t){return t||""===e?e:Bt(e)?$t(e):Ft(e)}(t.hostname,a)),"string"==typeof t.port&&(e.port=function(e,t,a){return Zt(t)===e&&(e=""),a||""===e?e:Kt(e)}(t.port,e.protocol,a)),"string"==typeof t.pathname){if(e.pathname=t.pathname,r&&!function(e,t){return!(!e.length||"/"!==e[0]&&(!t||e.length<2||"\\"!=e[0]&&"{"!=e[0]||"/"!=e[1]))}(e.pathname,a)){let t=r.pathname.lastIndexOf("/");t>=0&&(e.pathname=ta(r.pathname.substring(0,t+1),a)+e.pathname)}e.pathname=function(e,t,a){if(a||""===e)return e;if(t&&!zt.includes(t))return new URL(`${t}:${e}`).pathname;let r="/"==e[0];return e=new URL(r?e:"/-"+e,"https://example.com").pathname,r||(e=e.substring(2,e.length)),e}(e.pathname,e.protocol,a)}return"string"==typeof t.search&&(e.search=function(e,t){if(e=Dt(e,"?"),t||""===e)return e;let a=new URL("https://example.com");return a.search=e,a.search?a.search.substring(1,a.search.length):""}(t.search,a)),"string"==typeof t.hash&&(e.hash=function(e,t){if(e=Dt(e,"#"),t||""===e)return e;let a=new URL("https://example.com");return a.hash=e,a.hash?a.hash.substring(1,a.hash.length):""}(t.hash,a)),e}function ra(e){return e.replace(/([+*?:{}()\\])/g,"\\$1")}function na(e,t){t.delimiter??="/#?",t.prefixes??="./",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith="";let a=`[^${function(e){return e.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}(t.delimiter)}]+?`,r=/[$_\u200C\u200D\p{ID_Continue}]/u,n="";for(let s=0;s<e.length;++s){let o=e[s];if(3===o.type){if(3===o.modifier){n+=ra(o.value);continue}n+=`{${ra(o.value)}}${Nt(o.modifier)}`;continue}let i=o.hasCustomName(),c=!!o.suffix.length||!!o.prefix.length&&(1!==o.prefix.length||!t.prefixes.includes(o.prefix)),d=s>0?e[s-1]:null,u=s<e.length-1?e[s+1]:null;if(!c&&i&&1===o.type&&3===o.modifier&&u&&!u.prefix.length&&!u.suffix.length)if(3===u.type){let e=u.value.length>0?u.value[0]:"";c=r.test(e)}else c=!u.hasCustomName();if(!c&&!o.prefix.length&&d&&3===d.type){let e=d.value[d.value.length-1];c=t.prefixes.includes(e)}c&&(n+="{"),n+=ra(o.prefix),i&&(n+=`:${o.name}`),2===o.type?n+=`(${o.value})`:1===o.type?i||(n+=`(${a})`):0===o.type&&(i||d&&3!==d.type&&3===d.modifier&&!c&&""===o.prefix?n+="(.*)":n+="*"),1===o.type&&i&&o.suffix.length&&r.test(o.suffix[0])&&(n+="\\"),n+=ra(o.suffix),c&&(n+="}"),3!==o.modifier&&(n+=Nt(o.modifier))}return n}var sa=class{#St;#vt={};#wt={};#bt={};#Ct={};constructor(e={},t,a){try{let r;if("string"==typeof t?r=t:a=t,"string"==typeof e){let t=new Xt(e);if(t.parse(),e=t.result,void 0===r&&"string"!=typeof e.protocol)throw new TypeError("A base URL must be provided for a relative constructor string.");e.baseURL=r}else{if(!e||"object"!=typeof e)throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(r)throw new TypeError("parameter 1 is not of type 'string'.")}typeof a>"u"&&(a={ignoreCase:!1});let n,s={ignoreCase:!0===a.ignoreCase},o={pathname:Qt,protocol:Qt,username:Qt,password:Qt,hostname:Qt,port:Qt,search:Qt,hash:Qt};for(n of(this.#St=aa(o,e,!0),Zt(this.#St.protocol)===this.#St.port&&(this.#St.port=""),Yt)){if(!(n in this.#St))continue;let e={},t=this.#St[n];switch(this.#wt[n]=[],n){case"protocol":Object.assign(e,Ot),e.encodePart=Ut;break;case"username":Object.assign(e,Ot),e.encodePart=qt;break;case"password":Object.assign(e,Ot),e.encodePart=Vt;break;case"hostname":Object.assign(e,Mt),Bt(t)?e.encodePart=$t:e.encodePart=Ft;break;case"port":Object.assign(e,Ot),e.encodePart=Kt;break;case"pathname":Lt(this.#vt.protocol)?(Object.assign(e,At,s),e.encodePart=Ht):(Object.assign(e,Ot,s),e.encodePart=Wt);break;case"search":Object.assign(e,Ot,s),e.encodePart=Jt;break;case"hash":Object.assign(e,Ot,s),e.encodePart=Gt}try{this.#Ct[n]=Et(t,e),this.#vt[n]=jt(this.#Ct[n],this.#wt[n],e),this.#bt[n]=na(this.#Ct[n],e)}catch{throw new TypeError(`invalid ${n} pattern '${this.#St[n]}'.`)}}}catch(e){throw new TypeError(`Failed to construct 'URLPattern': ${e.message}`)}}test(e={},t){let a,r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if("string"!=typeof e&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return!1;try{r=aa(r,"object"==typeof e?e:ea(e,t),!1)}catch{return!1}for(a of Yt)if(!this.#vt[a].exec(r[a]))return!1;return!0}exec(e={},t){let a={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if("string"!=typeof e&&t)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof e>"u")return;try{a=aa(a,"object"==typeof e?e:ea(e,t),!1)}catch{return null}let r,n={};for(r of(n.inputs=t?[e,t]:[e],Yt)){let e=this.#vt[r].exec(a[r]);if(!e)return null;let t={};for(let[a,n]of this.#wt[r].entries())if("string"==typeof n||"number"==typeof n){let r=e[a+1];t[n]=r}n[r]={input:a[r]??"",groups:t}}return n}static compareComponent(e,t,a){let r=(e,t)=>{for(let a of["type","modifier","prefix","value","suffix"]){if(e[a]<t[a])return-1;if(e[a]!==t[a])return 1}return 0},n=new Ct(3,"","","","",3),s=new Ct(0,"","","","",3),o=(e,t)=>{let a=0;for(;a<Math.min(e.length,t.length);++a){let n=r(e[a],t[a]);if(n)return n}return e.length===t.length?0:r(e[a]??n,t[a]??n)};return t.#bt[e]||a.#bt[e]?t.#bt[e]&&!a.#bt[e]?o(t.#Ct[e],[s]):!t.#bt[e]&&a.#bt[e]?o([s],a.#Ct[e]):o(t.#Ct[e],a.#Ct[e]):0}get protocol(){return this.#bt.protocol}get username(){return this.#bt.username}get password(){return this.#bt.password}get hostname(){return this.#bt.hostname}get port(){return this.#bt.port}get pathname(){return this.#bt.pathname}get search(){return this.#bt.search}get hash(){return this.#bt.hash}};const{URLPattern:oa}=bt;var ia={URLPattern:oa};globalThis.URLPattern||(globalThis.URLPattern=oa),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.URLPattern=void 0;const t=ia;Object.defineProperty(e,"URLPattern",{enumerable:!0,get:function(){return t.URLPattern}}),"URLPattern"in globalThis&&(t.URLPattern=globalThis.URLPattern)}(mt),Object.defineProperty(pt,"__esModule",{value:!0}),pt.NetworkStorage=void 0;const ca=g,da=mt,ua=B;class la{#Kt=new Map;#Ht=new Map;#Wt=new Map;disposeRequestMap(){for(const e of this.#Kt.values())e.dispose();this.#Kt.clear()}addIntercept(e){for(const[t,{urlPatterns:a,phases:r}]of this.#Ht.entries())if(JSON.stringify(e.urlPatterns)===JSON.stringify(a)&&JSON.stringify(e.phases)===JSON.stringify(r))return t;const t=(0,ua.uuidv4)();return this.#Ht.set(t,e),t}removeIntercept(e){if(!this.#Ht.has(e))throw new ca.NoSuchInterceptException(`Intercept '${e}' does not exist.`);this.#Ht.delete(e)}hasIntercepts(){return this.#Ht.size>0}getFetchEnableParams(){const e=[];for(const t of this.#Ht.values())for(const a of t.phases){const r=la.requestStageFromPhase(a);if(0!==t.urlPatterns.length)for(const a of t.urlPatterns){const t=la.cdpFromSpecUrlPattern(a);e.push({urlPattern:t,requestStage:r})}else e.push({urlPattern:"*",requestStage:r})}return{patterns:e,handleAuthRequests:[...this.#Ht.values()].some((e=>e.phases.includes("authRequired")))}}getRequest(e){return this.#Kt.get(e)}addRequest(e){this.#Kt.set(e.requestId,e)}deleteRequest(e){const t=this.#Kt.get(e);t&&(t.dispose(),this.#Kt.delete(e))}hasNetworkRequests(){return this.#Kt.size>0}hasBlockedRequests(){return this.#Wt.size>0}static cdpFromSpecUrlPattern(e){switch(e.type){case"string":return e.pattern;case"pattern":return la.buildUrlPatternString(e)}}static buildUrlPatternString({protocol:e,hostname:t,port:a,pathname:r,search:n}){if(!(e||t||a||r||n))return"*";let s="";return e&&(s+=`${e}`,e.endsWith(":")||(s+=":"),la.isSpecialScheme(e)&&(s+="//")),t&&(s+=t),a&&(s+=`:${a}`),r&&(r.startsWith("/")||(s+="/"),s+=r),n&&(n.startsWith("?")||(s+="?"),s+=`${n}`),s}static requestStageFromPhase(e){switch(e){case"beforeRequestSent":return"Request";case"responseStarted":case"authRequired":return"Response"}}static isSpecialScheme(e){return["ftp","file","http","https","ws","wss"].includes(e.replace(/:$/,""))}addBlockedRequest(e,t){this.#Wt.set(e,t)}removeBlockedRequest(e){this.#Wt.delete(e)}getBlockedRequest(e){return this.#Wt.get(e)}getNetworkIntercepts(e,t){const a=this.#Kt.get(e);if(!a)return[];const r=[];for(const[e,{phases:n,urlPatterns:s}]of this.#Ht.entries())t&&n.includes(t)&&(0===s.length||s.some((e=>la.matchUrlPattern(e,a.url))))&&r.push(e);return r}static matchUrlPattern(e,t){switch(e.type){case"string":return e.pattern===t;case"pattern":return null!==new da.URLPattern({protocol:e.protocol,hostname:e.hostname,port:e.port,pathname:e.pathname,search:e.search}).exec(t)}}}pt.NetworkStorage=la,Object.defineProperty(ht,"__esModule",{value:!0}),ht.NetworkProcessor=void 0;const ha=g,pa=j,ma=pt,fa=be;class ga{#i;#ie;constructor(e,t){this.#i=e,this.#ie=t}async addIntercept(e){if(0===e.phases.length)throw new ha.InvalidArgumentException("At least one phase must be specified.");e.phases.includes("authRequired")&&!e.phases.includes("beforeRequestSent")&&e.phases.unshift("beforeRequestSent");const t=e.urlPatterns??[],a=ga.parseUrlPatterns(t),r=this.#ie.addIntercept({urlPatterns:a,phases:e.phases});return await this.#Jt(),{intercept:r}}async continueRequest(e){const t=e.request,{request:a,phase:r}=this.#Gt(t);if("beforeRequestSent"!==r)throw new ha.InvalidArgumentException(`Blocked request for network id '${t}' is not in 'BeforeRequestSent' phase`);void 0!==e.url&&ga.parseUrlString(e.url);const{url:n,method:s,headers:o}=e,i=(0,fa.cdpFetchHeadersFromBidiNetworkHeaders)(o),c=this.#ie.getRequest(t);return(0,pa.assert)(c,`Network request with ID ${t} doesn't exist`),await c.continueRequest(a,n,s,i),this.#ie.removeBlockedRequest(t),{}}async continueResponse(e){const t=e.request,{request:a,phase:r}=this.#Gt(t);if("beforeRequestSent"===r)throw new ha.InvalidArgumentException(`Blocked request for network id '${t}' is in 'BeforeRequestSent' phase`);const{statusCode:n,reasonPhrase:s,headers:o}=e,i=(0,fa.cdpFetchHeadersFromBidiNetworkHeaders)(o),c=this.#ie.getRequest(t);return(0,pa.assert)(c,`Network request with ID ${t} doesn't exist`),await c.continueResponse(a,n,s,i),this.#ie.removeBlockedRequest(t),{}}async continueWithAuth(e){const t=e.request,{request:a,phase:r}=this.#Gt(t);if("authRequired"!==r)throw new ha.InvalidArgumentException(`Blocked request for network id '${t}' is not in 'AuthRequired' phase`);const n=this.#ie.getRequest(t);let s,o;if((0,pa.assert)(n,`Network request with ID ${t} doesn't exist`),"provideCredentials"===e.action){const{credentials:t}=e;s=e.credentials.username,o=e.credentials.password,(0,pa.assert)("password"===t.type,`Credentials type ${t.type} must be 'password'`)}const i=(0,fa.cdpAuthChallengeResponseFromBidiAuthContinueWithAuthAction)(e.action);return await n.continueWithAuth(a,i,s,o),{}}async failRequest(e){const t=e.request,a=this.#Gt(t),{request:r,phase:n}=a;if("authRequired"===n)throw new ha.InvalidArgumentException(`Blocked request for network id '${t}' is in 'AuthRequired' phase`);const s=this.#ie.getRequest(t);return(0,pa.assert)(s,`Network request with ID ${t} doesn't exist`),await s.failRequest(r,"Failed"),this.#ie.removeBlockedRequest(t),{}}async provideResponse(e){const t=e.request,{request:a}=this.#Gt(t),{statusCode:r,reasonPhrase:n,headers:s,body:o}=e,i=(0,fa.cdpFetchHeadersFromBidiNetworkHeaders)(s),c=this.#ie.getRequest(t);return(0,pa.assert)(c,`Network request with ID ${t} doesn't exist`),await c.provideResponse(a,r??c.statusCode,n,i,o?.value),this.#ie.removeBlockedRequest(t),{}}async removeIntercept(e){return this.#ie.removeIntercept(e.intercept),await this.#Jt(),{}}async#Xt(){await Promise.all(this.#i.getAllContexts().map((async e=>{await e.cdpTarget.fetchEnable()})))}async#Yt(){await Promise.all(this.#i.getAllContexts().map((async e=>{await e.cdpTarget.fetchDisable()})))}async#Jt(){this.#ie.hasIntercepts()||this.#ie.hasBlockedRequests()||this.#ie.hasNetworkRequests()?await this.#Xt():await this.#Yt()}#Gt(e){const t=this.#ie.getBlockedRequest(e);if(!t)throw new ha.NoSuchRequestException(`No blocked request found for network id '${e}'`);return t}static parseUrlString(e){try{return new URL(e)}catch(t){throw new ha.InvalidArgumentException(`Invalid URL '${e}': ${t}`)}}static parseUrlPatterns(e){return e.map((e=>{switch(e.type){case"string":return ga.parseUrlString(e.pattern),e;case"pattern":if(void 0===e.protocol&&void 0===e.hostname&&void 0===e.port&&void 0===e.pathname&&void 0===e.search)return e;if(""===e.protocol)throw new ha.InvalidArgumentException("URL pattern must specify a protocol");if(""===e.hostname)throw new ha.InvalidArgumentException("URL pattern must specify a hostname");if((e.hostname?.length??0)>0){if(e.protocol?.match(/^file/i))throw new ha.InvalidArgumentException("URL pattern protocol cannot be 'file'");if(e.hostname?.includes(":"))throw new ha.InvalidArgumentException("URL pattern hostname must not contain a colon")}if(""===e.port)throw new ha.InvalidArgumentException("URL pattern must specify a port");try{new URL(ma.NetworkStorage.buildUrlPatternString(e))}catch(e){throw new ha.InvalidArgumentException(`${e}`)}return e}}))}}ht.NetworkProcessor=ga;var ya={};Object.defineProperty(ya,"__esModule",{value:!0}),ya.PreloadScriptStorage=void 0;ya.PreloadScriptStorage=class{#Qt=new Set;find(e){return e?[...this.#Qt].filter((t=>(void 0===e.id||e.id===t.id)&&(!(void 0!==e.targetId&&!t.targetIds.has(e.targetId))&&(void 0===e.global||!(e.global&&void 0!==t.contexts||!e.global&&void 0===t.contexts))))):[...this.#Qt]}add(e){this.#Qt.add(e)}remove(e){for(const t of this.find(e))this.#Qt.delete(t)}};var Sa={},va={};Object.defineProperty(va,"__esModule",{value:!0}),va.PreloadScript=void 0;const wa=B,ba=z;va.PreloadScript=class{#m=(0,wa.uuidv4)();#ea=[];#ta;#aa=new Set;#ra;#na;#sa;get id(){return this.#m}get targetIds(){return this.#aa}constructor(e,t){this.#ra=e.arguments?.map((e=>new ba.ChannelProxy(e.value,t)))??[],this.#ta=e.functionDeclaration,this.#na=e.sandbox,this.#sa=e.contexts}get channels(){return this.#ra}get contexts(){return this.#sa}#oa(){const e=`[${this.channels.map((e=>e.getEvalInWindowStr())).join(", ")}]`;return`(()=>{(${this.#ta})(...${e})})()`}async initInTargets(e,t){await Promise.all(Array.from(e).map((e=>this.initInTarget(e,t))))}async initInTarget(e,t){const a=await e.cdpClient.sendCommand("Page.addScriptToEvaluateOnNewDocument",{source:this.#oa(),worldName:this.#na,runImmediately:t});this.#ea.push({target:e,preloadScriptId:a.identifier}),this.#aa.add(e.targetId)}async remove(){for(const e of this.#ea){const t=e.target,a=e.preloadScriptId;await t.cdpClient.sendCommand("Page.removeScriptToEvaluateOnNewDocument",{identifier:a})}}dispose(e){this.#ea=this.#ea.filter((t=>t.target?.targetId!==e)),this.#aa.delete(e)}},Object.defineProperty(Sa,"__esModule",{value:!0}),Sa.ScriptProcessor=void 0;const Ca=g,xa=va;Sa.ScriptProcessor=class{#i;#w;#je;#t;constructor(e,t,a,r){this.#i=e,this.#w=t,this.#je=a,this.#t=r}async addPreloadScript(e){const t=new Set;if(e.contexts){if(0===e.contexts.length)throw new Ca.InvalidArgumentException("Contexts list is empty.");for(const a of e.contexts){const e=this.#i.getContext(a);if(!e.isTopLevelContext())throw new Ca.InvalidArgumentException(`Non top-level context '${a}' given.`);t.add(e)}}const a=new xa.PreloadScript(e,this.#t);this.#je.add(a);const r=0===t.size?new Set(this.#i.getTopLevelContexts().map((e=>e.cdpTarget))):new Set([...t.values()].map((e=>e.cdpTarget)));return await a.initInTargets(r,!1),{script:a.id}}async removePreloadScript(e){const t=e.script,a=this.#je.find({id:t});if(0===a.length)throw new Ca.NoSuchScriptException(`No preload script with BiDi ID '${t}'`);return await Promise.all(a.map((e=>e.remove()))),this.#je.remove({id:t}),{}}async callFunction(e){const t=await this.#ia(e.target);return await t.callFunction(e.functionDeclaration,e.this??{type:"undefined"},e.arguments??[],e.awaitPromise,e.resultOwnership??"none",e.serializationOptions??{},e.userActivation??!1)}async evaluate(e){const t=await this.#ia(e.target);return await t.evaluate(e.expression,e.awaitPromise,e.resultOwnership??"none",e.serializationOptions??{},e.userActivation??!1)}async disown(e){const t=await this.#ia(e.target);return await Promise.all(e.handles.map((async e=>await t.disown(e)))),{}}getRealms(e){void 0!==e.context&&this.#i.getContext(e.context);return{realms:this.#w.findRealms({browsingContextId:e.context,type:e.type}).map((e=>e.realmInfo))}}async#ia(e){if("realm"in e)return this.#w.getRealm({realmId:e.realm});const t=this.#i.getContext(e.context);return await t.getOrCreateSandbox(e.sandbox)}};var Ia={};Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.SessionProcessor=void 0;Ia.SessionProcessor=class{#R;constructor(e){this.#R=e}status(){return{ready:!1,message:"already connected"}}subscribe(e,t=null){return this.#R.subscribe(e.events,e.contexts??[null],t),{}}unsubscribe(e,t=null){return this.#R.unsubscribe(e.events,e.contexts??[null],t),{}}};var Pa={};Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.OutgoingMessage=void 0;class ka{#ca;#da;constructor(e,t=null){this.#ca=e,this.#da=t}static createFromPromise(e,t){return e.then((e=>"success"===e.kind?{kind:"success",value:new ka(e.value,t)}:e))}static createResolved(e,t){return Promise.resolve({kind:"success",value:new ka(e,t)})}get message(){return this.#ca}get channel(){return this.#da}}Pa.OutgoingMessage=ka,Object.defineProperty(f,"__esModule",{value:!0}),f.CommandProcessor=void 0;const Ra=g,Ea=s,_a=l,Ta=R,Na=E,ja=_,Oa=T,Ma=Be,Aa=ht,Da=pt,Ba=ya,za=Sa,La=Ia,Za=Pa;class Ua extends Ea.EventEmitter{#ua;#la;#ha;#pa;#ma;#fa;#ga;#ya;#t;constructor(e,t,a,r,n,s,o,i=new Ta.BidiNoOpParser,c){super(),this.#ya=i,this.#t=c;const d=new Da.NetworkStorage,u=new Ba.PreloadScriptStorage;this.#ua=new Na.BrowserProcessor(t),this.#la=new Oa.BrowsingContextProcessor(e,t,r,a,n,s,d,u,o,c),this.#ha=new ja.CdpProcessor(n,e,t),this.#pa=new Ma.InputProcessor(n),this.#ma=new Aa.NetworkProcessor(n,d),this.#fa=new za.ScriptProcessor(n,s,u,c),this.#ga=new La.SessionProcessor(a)}async#Sa(e){switch(e.method){case"session.end":case"session.new":break;case"browser.close":return this.#ua.close();case"browsingContext.activate":return await this.#la.activate(this.#ya.parseActivateParams(e.params));case"browsingContext.captureScreenshot":return await this.#la.captureScreenshot(this.#ya.parseCaptureScreenshotParams(e.params));case"browsingContext.close":return await this.#la.close(this.#ya.parseCloseParams(e.params));case"browsingContext.create":return await this.#la.create(this.#ya.parseCreateParams(e.params));case"browsingContext.getTree":return this.#la.getTree(this.#ya.parseGetTreeParams(e.params));case"browsingContext.handleUserPrompt":return await this.#la.handleUserPrompt(this.#ya.parseHandleUserPromptParams(e.params));case"browsingContext.locateNodes":throw new Ra.UnsupportedOperationException(`Command '${e.method}' not yet implemented.`);case"browsingContext.navigate":return await this.#la.navigate(this.#ya.parseNavigateParams(e.params));case"browsingContext.print":return await this.#la.print(this.#ya.parsePrintParams(e.params));case"browsingContext.reload":return await this.#la.reload(this.#ya.parseReloadParams(e.params));case"browsingContext.setViewport":return await this.#la.setViewport(this.#ya.parseSetViewportParams(e.params));case"browsingContext.traverseHistory":return await this.#la.traverseHistory(this.#ya.parseTraverseHistoryParams(e.params));case"cdp.getSession":return this.#ha.getSession(this.#ya.parseGetSessionParams(e.params));case"cdp.sendCommand":return await this.#ha.sendCommand(this.#ya.parseSendCommandParams(e.params));case"input.performActions":return await this.#pa.performActions(this.#ya.parsePerformActionsParams(e.params));case"input.releaseActions":return await this.#pa.releaseActions(this.#ya.parseReleaseActionsParams(e.params));case"network.addIntercept":return await this.#ma.addIntercept(this.#ya.parseAddInterceptParams(e.params));case"network.continueRequest":return await this.#ma.continueRequest(this.#ya.parseContinueRequestParams(e.params));case"network.continueResponse":return await this.#ma.continueResponse(this.#ya.parseContinueResponseParams(e.params));case"network.continueWithAuth":return await this.#ma.continueWithAuth(this.#ya.parseContinueWithAuthParams(e.params));case"network.failRequest":return await this.#ma.failRequest(this.#ya.parseFailRequestParams(e.params));case"network.provideResponse":return await this.#ma.provideResponse(this.#ya.parseProvideResponseParams(e.params));case"network.removeIntercept":return await this.#ma.removeIntercept(this.#ya.parseRemoveInterceptParams(e.params));case"script.addPreloadScript":return await this.#fa.addPreloadScript(this.#ya.parseAddPreloadScriptParams(e.params));case"script.callFunction":return await this.#fa.callFunction(this.#ya.parseCallFunctionParams(e.params));case"script.disown":return await this.#fa.disown(this.#ya.parseDisownParams(e.params));case"script.evaluate":return await this.#fa.evaluate(this.#ya.parseEvaluateParams(e.params));case"script.getRealms":return this.#fa.getRealms(this.#ya.parseGetRealmsParams(e.params));case"script.removePreloadScript":return await this.#fa.removePreloadScript(this.#ya.parseRemovePreloadScriptParams(e.params));case"session.status":return this.#ga.status();case"session.subscribe":return this.#ga.subscribe(this.#ya.parseSubscribeParams(e.params),e.channel);case"session.unsubscribe":return this.#ga.unsubscribe(this.#ya.parseSubscribeParams(e.params),e.channel)}throw new Ra.UnknownCommandException(`Unknown command '${e.method}'.`)}async processCommand(e){try{const t=await this.#Sa(e),a={type:"success",id:e.id,result:t};this.emit("response",{message:Za.OutgoingMessage.createResolved(a,e.channel),event:e.method})}catch(t){if(t instanceof Ra.Exception)this.emit("response",{message:Za.OutgoingMessage.createResolved(t.toErrorResponse(e.id),e.channel),event:e.method});else{const a=t;this.#t?.(_a.LogType.bidi,a),this.emit("response",{message:Za.OutgoingMessage.createResolved(new Ra.UnknownErrorException(a.message,a.stack).toErrorResponse(e.id),e.channel),event:e.method})}}}}f.CommandProcessor=Ua;var qa={};Object.defineProperty(qa,"__esModule",{value:!0}),qa.BrowsingContextStorage=void 0;const Va=g;qa.BrowsingContextStorage=class{#sa=new Map;getTopLevelContexts(){return this.getAllContexts().filter((e=>e.isTopLevelContext()))}getAllContexts(){return Array.from(this.#sa.values())}deleteContextById(e){this.#sa.delete(e)}deleteContext(e){this.#sa.delete(e.id)}addContext(e){this.#sa.set(e.id,e)}hasContext(e){return this.#sa.has(e)}findContext(e){return this.#sa.get(e)}findTopLevelContextId(e){if(null===e)return null;const t=this.findContext(e),a=t?.parentId??null;return null===a?e:this.findTopLevelContextId(a)}getContext(e){const t=this.findContext(e);if(void 0===t)throw new Va.NoSuchFrameException(`Context ${e} not found`);return t}};var Fa={},$a={};Object.defineProperty($a,"__esModule",{value:!0}),$a.Buffer=void 0;$a.Buffer=class{#va;#wa=[];#ba;constructor(e,t){this.#va=e,this.#ba=t}get(){return this.#wa}add(e){for(this.#wa.push(e);this.#wa.length>this.#va;){const e=this.#wa.shift();void 0!==e&&this.#ba?.(e)}}};var Ka={};Object.defineProperty(Ka,"__esModule",{value:!0}),Ka.DefaultMap=void 0;class Ha extends Map{#Ca;constructor(e,t){super(t),this.#Ca=e}get(e){return this.has(e)||this.set(e,this.#Ca(e)),super.get(e)}}Ka.DefaultMap=Ha;var Wa={};Object.defineProperty(Wa,"__esModule",{value:!0}),Wa.IdWrapper=void 0;class Ja{static#xa=0;#m;constructor(){this.#m=++Ja.#xa}get id(){return this.#m}}Wa.IdWrapper=Ja;var Ga={};Object.defineProperty(Ga,"__esModule",{value:!0}),Ga.assertSupportedEvent=Ga.isCdpEvent=void 0;const Xa=g;function Ya(e){return e.split(".").at(0)?.startsWith(Xa.ChromiumBidi.BiDiModule.Cdp)??!1}Ga.isCdpEvent=Ya,Ga.assertSupportedEvent=function(e){if(!Xa.ChromiumBidi.EVENT_NAMES.has(e)&&!Ya(e))throw new Xa.InvalidArgumentException(`Unknown event: ${e}`)};var Qa={};Object.defineProperty(Qa,"__esModule",{value:!0}),Qa.SubscriptionManager=Qa.unrollEvents=Qa.cartesianProduct=void 0;const er=g,tr=Ga;function ar(...e){return e.reduce(((e,t)=>e.flatMap((e=>t.map((t=>[e,t].flat()))))))}function rr(e){const t=new Set;function a(e){for(const a of e)t.add(a)}for(const r of e)switch(r){case er.ChromiumBidi.BiDiModule.BrowsingContext:a(Object.values(er.ChromiumBidi.BrowsingContext.EventNames));break;case er.ChromiumBidi.BiDiModule.Log:a(Object.values(er.ChromiumBidi.Log.EventNames));break;case er.ChromiumBidi.BiDiModule.Network:a(Object.values(er.ChromiumBidi.Network.EventNames));break;case er.ChromiumBidi.BiDiModule.Script:a(Object.values(er.ChromiumBidi.Script.EventNames));break;default:t.add(r)}return[...t.values()]}Qa.cartesianProduct=ar,Qa.unrollEvents=rr;Qa.SubscriptionManager=class{#Ia=0;#Pa=new Map;#i;constructor(e){this.#i=e}getChannelsSubscribedToEvent(e,t){return Array.from(this.#Pa.keys()).map((a=>({priority:this.#ka(e,t,a),channel:a}))).filter((({priority:e})=>null!==e)).sort(((e,t)=>e.priority-t.priority)).map((({channel:e})=>e))}#ka(e,t,a){const r=this.#Pa.get(a);if(void 0===r)return null;const n=this.#i.findTopLevelContextId(t),s=[...new Set([null,n])].map((t=>{const a=r.get(t)?.get(e);if((0,tr.isCdpEvent)(e)){const e=r.get(t)?.get(er.ChromiumBidi.BiDiModule.Cdp);return a&&e?Math.min(a,e):a??e}return a})).filter((e=>void 0!==e));return 0===s.length?null:Math.min(...s)}subscribe(e,t,a){switch(t=this.#i.findTopLevelContextId(t),e){case er.ChromiumBidi.BiDiModule.BrowsingContext:return void Object.values(er.ChromiumBidi.BrowsingContext.EventNames).map((e=>this.subscribe(e,t,a)));case er.ChromiumBidi.BiDiModule.Log:return void Object.values(er.ChromiumBidi.Log.EventNames).map((e=>this.subscribe(e,t,a)));case er.ChromiumBidi.BiDiModule.Network:return void Object.values(er.ChromiumBidi.Network.EventNames).map((e=>this.subscribe(e,t,a)));case er.ChromiumBidi.BiDiModule.Script:return void Object.values(er.ChromiumBidi.Script.EventNames).map((e=>this.subscribe(e,t,a)))}this.#Pa.has(a)||this.#Pa.set(a,new Map);const r=this.#Pa.get(a);r.has(t)||r.set(t,new Map);const n=r.get(t);n.has(e)||n.set(e,this.#Ia++)}unsubscribeAll(e,t,a){for(const e of t)null!==e&&this.#i.getContext(e);ar(rr(e),t).map((([e,t])=>this.#Ra(e,t,a))).forEach((e=>e()))}unsubscribe(e,t,a){this.unsubscribeAll([e],[t],a)}#Ra(e,t,a){if(t=this.#i.findTopLevelContextId(t),!this.#Pa.has(a))throw new er.InvalidArgumentException(`Cannot unsubscribe from ${e}, ${null===t?"null":t}. No subscription found.`);const r=this.#Pa.get(a);if(!r.has(t))throw new er.InvalidArgumentException(`Cannot unsubscribe from ${e}, ${null===t?"null":t}. No subscription found.`);const n=r.get(t);if(!n.has(e))throw new er.InvalidArgumentException(`Cannot unsubscribe from ${e}, ${null===t?"null":t}. No subscription found.`);return()=>{n.delete(e),0===n.size&&r.delete(e),0===r.size&&this.#Pa.delete(a)}}},Object.defineProperty(Fa,"__esModule",{value:!0}),Fa.EventManager=void 0;const nr=g,sr=$a,or=Ka,ir=Wa,cr=Pa,dr=Ga,ur=Qa;class lr{#Ea=new ir.IdWrapper;#_a;#Ta;constructor(e,t){this.#Ta=e,this.#_a=t}get id(){return this.#Ea.id}get contextId(){return this.#_a}get event(){return this.#Ta}}const hr=new Map([[nr.ChromiumBidi.Log.EventNames.LogEntryAdded,100]]);class pr{#Na=new or.DefaultMap((()=>new Set));#ja=new Map;#Oa=new Map;#Ma;#Aa;constructor(e){this.#Aa=e,this.#Ma=new ur.SubscriptionManager(e.getBrowsingContextStorage())}static#Da(e,t,a){return JSON.stringify({eventName:e,browsingContext:t,channel:a})}registerEvent(e,t){this.registerPromiseEvent(Promise.resolve({kind:"success",value:e}),t,e.method)}registerPromiseEvent(e,t,a){const r=new lr(e,t),n=this.#Ma.getChannelsSubscribedToEvent(a,t);this.#Ba(r,a);for(const t of n)this.#Aa.emitOutgoingMessage(cr.OutgoingMessage.createFromPromise(e,t),a),this.#za(r,t,a)}subscribe(e,t,a){for(const t of e)(0,dr.assertSupportedEvent)(t);for(const e of t)null!==e&&this.#Aa.getBrowsingContextStorage().getContext(e);for(const r of e)for(const e of t){this.#Ma.subscribe(r,e,a);for(const t of this.#La(r,e,a))this.#Aa.emitOutgoingMessage(cr.OutgoingMessage.createFromPromise(t.event,a),r),this.#za(t,a,r)}}unsubscribe(e,t,a){for(const t of e)(0,dr.assertSupportedEvent)(t);this.#Ma.unsubscribeAll(e,t,a)}#Ba(e,t){if(!hr.has(t))return;const a=pr.#Da(t,e.contextId);this.#ja.has(a)||this.#ja.set(a,new sr.Buffer(hr.get(t))),this.#ja.get(a).add(e),this.#Na.get(t).add(e.contextId)}#za(e,t,a){if(!hr.has(a))return;const r=pr.#Da(a,e.contextId,t);this.#Oa.set(r,Math.max(this.#Oa.get(r)??0,e.id))}#La(e,t,a){const r=pr.#Da(e,t),n=pr.#Da(e,t,a),s=this.#Oa.get(n)??-1/0,o=this.#ja.get(r)?.get().filter((e=>e.id>s))??[];return null===t&&Array.from(this.#Na.get(e).keys()).filter((e=>null!==e&&this.#Aa.getBrowsingContextStorage().hasContext(e))).map((t=>this.#La(e,t,a))).forEach((e=>o.push(...e))),o.sort(((e,t)=>e.id-t.id))}}Fa.EventManager=pr;var mr={};Object.defineProperty(mr,"__esModule",{value:!0}),mr.RealmStorage=void 0;const fr=g;mr.RealmStorage=class{#Za=new Map;#Ua=new Map;get knownHandlesToRealmMap(){return this.#Za}addRealm(e){this.#Ua.set(e.realmId,e)}findRealms(e){return Array.from(this.#Ua.values()).filter((t=>(void 0===e.realmId||e.realmId===t.realmId)&&((void 0===e.browsingContextId||e.browsingContextId===t.browsingContextId)&&((void 0===e.navigableId||e.navigableId===t.navigableId)&&((void 0===e.executionContextId||e.executionContextId===t.executionContextId)&&((void 0===e.origin||e.origin===t.origin)&&((void 0===e.type||e.type===t.type)&&((void 0===e.sandbox||e.sandbox===t.sandbox)&&(void 0===e.cdpSessionId||e.cdpSessionId===t.cdpClient.sessionId)))))))))}findRealm(e){const t=this.findRealms(e);if(1===t.length)return t[0]}getRealm(e){const t=this.findRealm(e);if(void 0===t)throw new fr.NoSuchFrameException(`Realm ${JSON.stringify(e)} not found`);return t}deleteRealms(e){this.findRealms(e).map((e=>{e.dispose(),this.#Ua.delete(e.realmId),Array.from(this.knownHandlesToRealmMap.entries()).filter((([,t])=>t===e.realmId)).map((([e])=>this.knownHandlesToRealmMap.delete(e)))}))}},Object.defineProperty(n,"__esModule",{value:!0}),n.BidiServer=void 0;const gr=s,yr=l,Sr=h,vr=f,wr=qa,br=Fa,Cr=mr;class xr extends gr.EventEmitter{#qa;#Va;#Fa;#i=new wr.BrowsingContextStorage;#t;#$a=e=>{this.#Fa.processCommand(e).catch((e=>{this.#t?.(yr.LogType.debugError,e)}))};#Ka=async e=>{const t=e.message;null!==e.channel&&(t.channel=e.channel),await this.#Va.sendMessage(t)};constructor(e,t,a,r,n,s,o){super(),this.#t=o,this.#qa=new Sr.ProcessingQueue(this.#Ka,this.#t),this.#Va=e,this.#Va.setOnMessage(this.#$a),this.#Fa=new vr.CommandProcessor(t,a,new br.EventManager(this),r,this.#i,new Cr.RealmStorage,n?.acceptInsecureCerts??!1,s,this.#t),this.#Fa.on("response",(({message:e,event:t})=>{this.emitOutgoingMessage(e,t)}))}static async createAndStart(e,t,a,r,n,s,o){const i=new xr(e,t,a,r,n,s,o);return await a.sendCommand("Target.setDiscoverTargets",{discover:!0}),await a.sendCommand("Target.setAutoAttach",{autoAttach:!0,waitForDebuggerOnStart:!0,flatten:!0}),await i.#Ha(),i}emitOutgoingMessage(e,t){this.#qa.add(e,t)}close(){this.#Va.close()}getBrowsingContextStorage(){return this.#i}async#Ha(){await Promise.all(this.#i.getTopLevelContexts().map((e=>e.lifecycleLoaded())))}}n.BidiServer=xr,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.OutgoingMessage=e.EventEmitter=e.BidiServer=void 0;var t=n;Object.defineProperty(e,"BidiServer",{enumerable:!0,get:function(){return t.BidiServer}});var a=s;Object.defineProperty(e,"EventEmitter",{enumerable:!0,get:function(){return a.EventEmitter}});var r=Pa;Object.defineProperty(e,"OutgoingMessage",{enumerable:!0,get:function(){return r.OutgoingMessage}})}(r);var Ir={},Pr={};Object.defineProperty(Pr,"__esModule",{value:!0}),Pr.CdpClient=Pr.CloseError=void 0;const kr=s;class Rr extends Error{}Pr.CloseError=Rr;class Er extends kr.EventEmitter{#c;#Wa;constructor(e,t){super(),this.#c=e,this.#Wa=t}get sessionId(){return this.#Wa}sendCommand(e,...t){return this.#c.sendCommand(e,t[0],this.#Wa)}isCloseError(e){return e instanceof Rr}}Pr.CdpClient=Er,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.CdpConnection=void 0;const _r=l,Tr=Pr;class Nr{static LOGGER_PREFIX_RECV=`${_r.LogType.cdp}:RECV \u25c2`;static LOGGER_PREFIX_SEND=`${_r.LogType.cdp}:SEND \u25b8`;#Ja;#Va;#Ga=new Map;#Xa=new Map;#t;#Ya=0;constructor(e,t){this.#Va=e,this.#t=t,this.#Va.setOnMessage(this.#Qa),this.#Ja=this.#er(void 0)}close(){this.#Va.close();for(const[,{reject:e,error:t}]of this.#Xa)e(t);this.#Xa.clear(),this.#Ga.clear()}async createBrowserSession(){const{sessionId:e}=await this.#Ja.sendCommand("Target.attachToBrowserTarget");return this.#er(e)}getCdpClient(e){const t=this.#Ga.get(e);if(!t)throw new Error(`Unknown CDP session ID: ${e}`);return t}sendCommand(e,t,a){return new Promise(((r,n)=>{const s=this.#Ya++;this.#Xa.set(s,{resolve:r,reject:n,error:new Tr.CloseError(`${e} ${JSON.stringify(t)} ${a??""} call rejected because the connection has been closed.`)});const o={id:s,method:e,params:t};a&&(o.sessionId=a),this.#Va.sendMessage(JSON.stringify(o))?.catch((e=>{this.#t?.(_r.LogType.debugError,e),this.#Va.close()})),this.#t?.(Nr.LOGGER_PREFIX_SEND,o)}))}#Qa=e=>{const t=JSON.parse(e);if(this.#t?.(Nr.LOGGER_PREFIX_RECV,t),"Target.attachedToTarget"===t.method){const{sessionId:e}=t.params;this.#er(e)}if(void 0!==t.id){const e=this.#Xa.get(t.id);this.#Xa.delete(t.id),e&&(t.result?e.resolve(t.result):t.error&&e.reject(t.error))}else if(t.method){const e=this.#Ga.get(t.sessionId??void 0);if(e?.emit(t.method,t.params||{}),"Target.detachedFromTarget"===t.method){const{sessionId:e}=t.params,a=this.#Ga.get(e);a&&(this.#Ga.delete(e),a.removeAllListeners())}}};#er(e){const t=new Tr.CdpClient(this,e);return this.#Ga.set(e,t),t}}Ir.CdpConnection=Nr;var jr={},Or={},Mr={},Ar={},Dr={},Br={},zr={};!function(e){var t;Object.defineProperty(e,"__esModule",{value:!0}),e.getParsedType=e.ZodParsedType=e.objectUtil=e.util=void 0,function(e){e.assertEqual=e=>e,e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const a of e)t[a]=a;return t},e.getValidEnumValues=t=>{const a=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),r={};for(const e of a)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const a in e)Object.prototype.hasOwnProperty.call(e,a)&&t.push(a);return t},e.find=(e,t)=>{for(const a of e)if(t(a))return a},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(t=e.util||(e.util={})),(e.objectUtil||(e.objectUtil={})).mergeShapes=(e,t)=>({...e,...t}),e.ZodParsedType=t.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);e.getParsedType=t=>{switch(typeof t){case"undefined":return e.ZodParsedType.undefined;case"string":return e.ZodParsedType.string;case"number":return isNaN(t)?e.ZodParsedType.nan:e.ZodParsedType.number;case"boolean":return e.ZodParsedType.boolean;case"function":return e.ZodParsedType.function;case"bigint":return e.ZodParsedType.bigint;case"symbol":return e.ZodParsedType.symbol;case"object":return Array.isArray(t)?e.ZodParsedType.array:null===t?e.ZodParsedType.null:t.then&&"function"==typeof t.then&&t.catch&&"function"==typeof t.catch?e.ZodParsedType.promise:"undefined"!=typeof Map&&t instanceof Map?e.ZodParsedType.map:"undefined"!=typeof Set&&t instanceof Set?e.ZodParsedType.set:"undefined"!=typeof Date&&t instanceof Date?e.ZodParsedType.date:e.ZodParsedType.object;default:return e.ZodParsedType.unknown}}}(zr);var Lr={};Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.ZodError=Lr.quotelessJson=Lr.ZodIssueCode=void 0;const Zr=zr;Lr.ZodIssueCode=Zr.util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);Lr.quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class Ur extends Error{constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const t=e||function(e){return e.message},a={_errors:[]},r=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(r);else if("invalid_return_type"===n.code)r(n.returnTypeError);else if("invalid_arguments"===n.code)r(n.argumentsError);else if(0===n.path.length)a._errors.push(t(n));else{let e=a,r=0;for(;r<n.path.length;){const a=n.path[r];r===n.path.length-1?(e[a]=e[a]||{_errors:[]},e[a]._errors.push(t(n))):e[a]=e[a]||{_errors:[]},e=e[a],r++}}};return r(this),a}toString(){return this.message}get message(){return JSON.stringify(this.issues,Zr.util.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=(e=>e.message)){const t={},a=[];for(const r of this.issues)r.path.length>0?(t[r.path[0]]=t[r.path[0]]||[],t[r.path[0]].push(e(r))):a.push(e(r));return{formErrors:a,fieldErrors:t}}get formErrors(){return this.flatten()}}Lr.ZodError=Ur,Ur.create=e=>new Ur(e),Object.defineProperty(Br,"__esModule",{value:!0});const qr=zr,Vr=Lr;Br.default=(e,t)=>{let a;switch(e.code){case Vr.ZodIssueCode.invalid_type:a=e.received===qr.ZodParsedType.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case Vr.ZodIssueCode.invalid_literal:a=`Invalid literal value, expected ${JSON.stringify(e.expected,qr.util.jsonStringifyReplacer)}`;break;case Vr.ZodIssueCode.unrecognized_keys:a=`Unrecognized key(s) in object: ${qr.util.joinValues(e.keys,", ")}`;break;case Vr.ZodIssueCode.invalid_union:a="Invalid input";break;case Vr.ZodIssueCode.invalid_union_discriminator:a=`Invalid discriminator value. Expected ${qr.util.joinValues(e.options)}`;break;case Vr.ZodIssueCode.invalid_enum_value:a=`Invalid enum value. Expected ${qr.util.joinValues(e.options)}, received '${e.received}'`;break;case Vr.ZodIssueCode.invalid_arguments:a="Invalid function arguments";break;case Vr.ZodIssueCode.invalid_return_type:a="Invalid function return type";break;case Vr.ZodIssueCode.invalid_date:a="Invalid date";break;case Vr.ZodIssueCode.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(a=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(a=`${a} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?a=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?a=`Invalid input: must end with "${e.validation.endsWith}"`:qr.util.assertNever(e.validation):a="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case Vr.ZodIssueCode.too_small:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case Vr.ZodIssueCode.too_big:a="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case Vr.ZodIssueCode.custom:a="Invalid input";break;case Vr.ZodIssueCode.invalid_intersection_types:a="Intersection results could not be merged";break;case Vr.ZodIssueCode.not_multiple_of:a=`Number must be a multiple of ${e.multipleOf}`;break;case Vr.ZodIssueCode.not_finite:a="Number must be finite";break;default:a=t.defaultError,qr.util.assertNever(e)}return{message:a}};var Fr=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(Dr,"__esModule",{value:!0}),Dr.getErrorMap=Dr.setErrorMap=Dr.defaultErrorMap=void 0;const $r=Fr(Br);Dr.defaultErrorMap=$r.default;let Kr=$r.default;Dr.setErrorMap=function(e){Kr=e},Dr.getErrorMap=function(){return Kr};var Hr={};!function(t){var a=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.isAsync=t.isValid=t.isDirty=t.isAborted=t.OK=t.DIRTY=t.INVALID=t.ParseStatus=t.addIssueToContext=t.EMPTY_PATH=t.makeIssue=void 0;const r=Dr,n=a(Br);t.makeIssue=e=>{const{data:t,path:a,errorMaps:r,issueData:n}=e,s=[...a,...n.path||[]],o={...n,path:s};let i="";const c=r.filter((e=>!!e)).slice().reverse();for(const e of c)i=e(o,{data:t,defaultError:i}).message;return{...n,path:s,message:n.message||i}},t.EMPTY_PATH=[],t.addIssueToContext=function(e,a){const s=(0,t.makeIssue)({issueData:a,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,(0,r.getErrorMap)(),n.default].filter((e=>!!e))});e.common.issues.push(s)};class s{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,a){const r=[];for(const n of a){if("aborted"===n.status)return t.INVALID;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const a=[];for(const e of t)a.push({key:await e.key,value:await e.value});return s.mergeObjectSync(e,a)}static mergeObjectSync(e,a){const r={};for(const n of a){const{key:a,value:s}=n;if("aborted"===a.status)return t.INVALID;if("aborted"===s.status)return t.INVALID;"dirty"===a.status&&e.dirty(),"dirty"===s.status&&e.dirty(),"__proto__"===a.value||void 0===s.value&&!n.alwaysSet||(r[a.value]=s.value)}return{status:e.value,value:r}}}t.ParseStatus=s,t.INVALID=Object.freeze({status:"aborted"});t.DIRTY=e=>({status:"dirty",value:e});t.OK=e=>({status:"valid",value:e});t.isAborted=e=>"aborted"===e.status;t.isDirty=e=>"dirty"===e.status;t.isValid=e=>"valid"===e.status;t.isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise}(Hr);var Wr={};Object.defineProperty(Wr,"__esModule",{value:!0});var Jr,Gr={},Xr={};Jr=Xr,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.errorUtil=void 0,function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:null==e?void 0:e.message}(Jr.errorUtil||(Jr.errorUtil={})),function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.date=e.boolean=e.bigint=e.array=e.any=e.coerce=e.ZodFirstPartyTypeKind=e.late=e.ZodSchema=e.Schema=e.custom=e.ZodReadonly=e.ZodPipeline=e.ZodBranded=e.BRAND=e.ZodNaN=e.ZodCatch=e.ZodDefault=e.ZodNullable=e.ZodOptional=e.ZodTransformer=e.ZodEffects=e.ZodPromise=e.ZodNativeEnum=e.ZodEnum=e.ZodLiteral=e.ZodLazy=e.ZodFunction=e.ZodSet=e.ZodMap=e.ZodRecord=e.ZodTuple=e.ZodIntersection=e.ZodDiscriminatedUnion=e.ZodUnion=e.ZodObject=e.ZodArray=e.ZodVoid=e.ZodNever=e.ZodUnknown=e.ZodAny=e.ZodNull=e.ZodUndefined=e.ZodSymbol=e.ZodDate=e.ZodBoolean=e.ZodBigInt=e.ZodNumber=e.ZodString=e.ZodType=void 0,e.NEVER=e.void=e.unknown=e.union=e.undefined=e.tuple=e.transformer=e.symbol=e.string=e.strictObject=e.set=e.record=e.promise=e.preprocess=e.pipeline=e.ostring=e.optional=e.onumber=e.oboolean=e.object=e.number=e.nullable=e.null=e.never=e.nativeEnum=e.nan=e.map=e.literal=e.lazy=e.intersection=e.instanceof=e.function=e.enum=e.effect=e.discriminatedUnion=void 0;const t=Dr,a=Xr,r=Hr,n=zr,s=Lr;class o{constructor(e,t,a,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=a,this._key=r}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const i=(e,t)=>{if((0,r.isValid)(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new s.ZodError(e.common.issues);return this._error=t,this._error}}};function c(e){if(!e)return{};const{errorMap:t,invalid_type_error:a,required_error:r,description:n}=e;if(t&&(a||r))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:n};return{errorMap:(e,t)=>"invalid_type"!==e.code?{message:t.defaultError}:void 0===t.data?{message:null!=r?r:t.defaultError}:{message:null!=a?a:t.defaultError},description:n}}class d{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return(0,n.getParsedType)(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:(0,n.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new r.ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:(0,n.getParsedType)(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if((0,r.isAsync)(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const a=this.safeParse(e,t);if(a.success)return a.data;throw a.error}safeParse(e,t){var a;const r={common:{issues:[],async:null!==(a=null==t?void 0:t.async)&&void 0!==a&&a,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,n.getParsedType)(e)},s=this._parseSync({data:e,path:r.path,parent:r});return i(r,s)}async parseAsync(e,t){const a=await this.safeParseAsync(e,t);if(a.success)return a.data;throw a.error}async safeParseAsync(e,t){const a={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:(0,n.getParsedType)(e)},s=this._parse({data:e,path:a.path,parent:a}),o=await((0,r.isAsync)(s)?s:Promise.resolve(s));return i(a,o)}refine(e,t){const a=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,r)=>{const n=e(t),o=()=>r.addIssue({code:s.ZodIssueCode.custom,...a(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then((e=>!!e||(o(),!1))):!!n||(o(),!1)}))}refinement(e,t){return this._refinement(((a,r)=>!!e(a)||(r.addIssue("function"==typeof t?t(a,r):t),!1)))}_refinement(e){return new G({schema:this,typeName:se.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return X.create(this,this._def)}nullable(){return Y.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return N.create(this,this._def)}promise(){return J.create(this,this._def)}or(e){return M.create([this,e],this._def)}and(e){return z.create(this,e,this._def)}transform(e){return new G({...c(this._def),schema:this,typeName:se.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new Q({...c(this._def),innerType:this,defaultValue:t,typeName:se.ZodDefault})}brand(){return new ae({typeName:se.ZodBranded,type:this,...c(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ee({...c(this._def),innerType:this,catchValue:t,typeName:se.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return re.create(this,e)}readonly(){return ne.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}e.ZodType=d,e.Schema=d,e.ZodSchema=d;const u=/^c[^\s-]{8,}$/i,l=/^[a-z][a-z0-9]*$/,h=/^[0-9A-HJKMNP-TV-Z]{26}$/,p=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,m=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let f;const g=/^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/,y=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;class S extends d{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==n.ZodParsedType.string){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.string,received:t.parsedType}),r.INVALID}const t=new r.ParseStatus;let a;for(const d of this._def.checks)if("min"===d.kind)e.data.length<d.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),t.dirty());else if("max"===d.kind)e.data.length>d.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!1,message:d.message}),t.dirty());else if("length"===d.kind){const n=e.data.length>d.value,o=e.data.length<d.value;(n||o)&&(a=this._getOrReturnCtx(e,a),n?(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}):o&&(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:d.value,type:"string",inclusive:!0,exact:!0,message:d.message}),t.dirty())}else if("email"===d.kind)m.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"email",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("emoji"===d.kind)f||(f=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),f.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"emoji",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("uuid"===d.kind)p.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"uuid",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("cuid"===d.kind)u.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"cuid",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("cuid2"===d.kind)l.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"cuid2",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("ulid"===d.kind)h.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"ulid",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty());else if("url"===d.kind)try{new URL(e.data)}catch(n){a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"url",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty()}else if("regex"===d.kind){d.regex.lastIndex=0;d.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"regex",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty())}else if("trim"===d.kind)e.data=e.data.trim();else if("includes"===d.kind)e.data.includes(d.value,d.position)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:{includes:d.value,position:d.position},message:d.message}),t.dirty());else if("toLowerCase"===d.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===d.kind)e.data=e.data.toUpperCase();else if("startsWith"===d.kind)e.data.startsWith(d.value)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:{startsWith:d.value},message:d.message}),t.dirty());else if("endsWith"===d.kind)e.data.endsWith(d.value)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:{endsWith:d.value},message:d.message}),t.dirty());else if("datetime"===d.kind){((c=d).precision?c.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${c.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${c.precision}}Z$`):0===c.precision?c.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):c.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$")).test(e.data)||(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_string,validation:"datetime",message:d.message}),t.dirty())}else"ip"===d.kind?(o=e.data,("v4"!==(i=d.version)&&i||!g.test(o))&&("v6"!==i&&i||!y.test(o))&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{validation:"ip",code:s.ZodIssueCode.invalid_string,message:d.message}),t.dirty())):n.util.assertNever(d);var o,i,c;return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:s.ZodIssueCode.invalid_string,...a.errorUtil.errToObj(r)})}_addCheck(e){return new S({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...a.errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...a.errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...a.errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...a.errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...a.errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...a.errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...a.errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...a.errorUtil.errToObj(e)})}datetime(e){var t;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,...a.errorUtil.errToObj(null==e?void 0:e.message)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...a.errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...a.errorUtil.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...a.errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...a.errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...a.errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...a.errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...a.errorUtil.errToObj(t)})}nonempty(e){return this.min(1,a.errorUtil.errToObj(e))}trim(){return new S({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new S({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new S({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function v(e,t){const a=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,n=a>r?a:r;return parseInt(e.toFixed(n).replace(".",""))%parseInt(t.toFixed(n).replace(".",""))/Math.pow(10,n)}e.ZodString=S,S.create=e=>{var t;return new S({checks:[],typeName:se.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...c(e)})};class w extends d{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==n.ZodParsedType.number){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.number,received:t.parsedType}),r.INVALID}let t;const a=new r.ParseStatus;for(const o of this._def.checks)if("int"===o.kind)n.util.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty());else if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),a.dirty())}else"multipleOf"===o.kind?0!==v(e.data,o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):"finite"===o.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.not_finite,message:o.message}),a.dirty()):n.util.assertNever(o);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,a.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,a.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,a.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,a.errorUtil.toString(t))}setLimit(e,t,r,n){return new w({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:a.errorUtil.toString(n)}]})}_addCheck(e){return new w({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:a.errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:a.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:a.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:a.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:a.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:a.errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:a.errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:a.errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:a.errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&n.util.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const a of this._def.checks){if("finite"===a.kind||"int"===a.kind||"multipleOf"===a.kind)return!0;"min"===a.kind?(null===t||a.value>t)&&(t=a.value):"max"===a.kind&&(null===e||a.value<e)&&(e=a.value)}return Number.isFinite(t)&&Number.isFinite(e)}}e.ZodNumber=w,w.create=e=>new w({checks:[],typeName:se.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...c(e)});class b extends d{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){this._def.coerce&&(e.data=BigInt(e.data));if(this._getType(e)!==n.ZodParsedType.bigint){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.bigint,received:t.parsedType}),r.INVALID}let t;const a=new r.ParseStatus;for(const o of this._def.checks)if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty())}else"multipleOf"===o.kind?e.data%o.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):n.util.assertNever(o);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,a.errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,a.errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,a.errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,a.errorUtil.toString(t))}setLimit(e,t,r,n){return new b({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:a.errorUtil.toString(n)}]})}_addCheck(e){return new b({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:a.errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:a.errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:a.errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:a.errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:a.errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}e.ZodBigInt=b,b.create=e=>{var t;return new b({checks:[],typeName:se.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...c(e)})};class C extends d{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==n.ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.boolean,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodBoolean=C,C.create=e=>new C({typeName:se.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...c(e)});class x extends d{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==n.ZodParsedType.date){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.date,received:t.parsedType}),r.INVALID}if(isNaN(e.data.getTime())){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_date}),r.INVALID}const t=new r.ParseStatus;let a;for(const o of this._def.checks)"min"===o.kind?e.data.getTime()<o.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),t.dirty()):"max"===o.kind?e.data.getTime()>o.value&&(a=this._getOrReturnCtx(e,a),(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),t.dirty()):n.util.assertNever(o);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new x({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:a.errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:a.errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}e.ZodDate=x,x.create=e=>new x({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:se.ZodDate,...c(e)});class I extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.symbol,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodSymbol=I,I.create=e=>new I({typeName:se.ZodSymbol,...c(e)});class P extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.undefined,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodUndefined=P,P.create=e=>new P({typeName:se.ZodUndefined,...c(e)});class k extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.null){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.null,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodNull=k,k.create=e=>new k({typeName:se.ZodNull,...c(e)});class R extends d{constructor(){super(...arguments),this._any=!0}_parse(e){return(0,r.OK)(e.data)}}e.ZodAny=R,R.create=e=>new R({typeName:se.ZodAny,...c(e)});class E extends d{constructor(){super(...arguments),this._unknown=!0}_parse(e){return(0,r.OK)(e.data)}}e.ZodUnknown=E,E.create=e=>new E({typeName:se.ZodUnknown,...c(e)});class _ extends d{_parse(e){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.never,received:t.parsedType}),r.INVALID}}e.ZodNever=_,_.create=e=>new _({typeName:se.ZodNever,...c(e)});class T extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.void,received:t.parsedType}),r.INVALID}return(0,r.OK)(e.data)}}e.ZodVoid=T,T.create=e=>new T({typeName:se.ZodVoid,...c(e)});class N extends d{_parse(e){const{ctx:t,status:a}=this._processInputParams(e),i=this._def;if(t.parsedType!==n.ZodParsedType.array)return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.array,received:t.parsedType}),r.INVALID;if(null!==i.exactLength){const e=t.data.length>i.exactLength.value,n=t.data.length<i.exactLength.value;(e||n)&&((0,r.addIssueToContext)(t,{code:e?s.ZodIssueCode.too_big:s.ZodIssueCode.too_small,minimum:n?i.exactLength.value:void 0,maximum:e?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),a.dirty())}if(null!==i.minLength&&t.data.length<i.minLength.value&&((0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),a.dirty()),null!==i.maxLength&&t.data.length>i.maxLength.value&&((0,r.addIssueToContext)(t,{code:s.ZodIssueCode.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),a.dirty()),t.common.async)return Promise.all([...t.data].map(((e,a)=>i.type._parseAsync(new o(t,e,t.path,a))))).then((e=>r.ParseStatus.mergeArray(a,e)));const c=[...t.data].map(((e,a)=>i.type._parseSync(new o(t,e,t.path,a))));return r.ParseStatus.mergeArray(a,c)}get element(){return this._def.type}min(e,t){return new N({...this._def,minLength:{value:e,message:a.errorUtil.toString(t)}})}max(e,t){return new N({...this._def,maxLength:{value:e,message:a.errorUtil.toString(t)}})}length(e,t){return new N({...this._def,exactLength:{value:e,message:a.errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function j(e){if(e instanceof O){const t={};for(const a in e.shape){const r=e.shape[a];t[a]=X.create(j(r))}return new O({...e._def,shape:()=>t})}return e instanceof N?new N({...e._def,type:j(e.element)}):e instanceof X?X.create(j(e.unwrap())):e instanceof Y?Y.create(j(e.unwrap())):e instanceof L?L.create(e.items.map((e=>j(e)))):e}e.ZodArray=N,N.create=(e,t)=>new N({type:e,minLength:null,maxLength:null,exactLength:null,typeName:se.ZodArray,...c(t)});class O extends d{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=n.util.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==n.ZodParsedType.object){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.object,received:t.parsedType}),r.INVALID}const{status:t,ctx:a}=this._processInputParams(e),{shape:i,keys:c}=this._getCached(),d=[];if(!(this._def.catchall instanceof _&&"strip"===this._def.unknownKeys))for(const e in a.data)c.includes(e)||d.push(e);const u=[];for(const e of c){const t=i[e],r=a.data[e];u.push({key:{status:"valid",value:e},value:t._parse(new o(a,r,a.path,e)),alwaysSet:e in a.data})}if(this._def.catchall instanceof _){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of d)u.push({key:{status:"valid",value:e},value:{status:"valid",value:a.data[e]}});else if("strict"===e)d.length>0&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.unrecognized_keys,keys:d}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of d){const r=a.data[t];u.push({key:{status:"valid",value:t},value:e._parse(new o(a,r,a.path,t)),alwaysSet:t in a.data})}}return a.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of u){const a=await t.key;e.push({key:a,value:await t.value,alwaysSet:t.alwaysSet})}return e})).then((e=>r.ParseStatus.mergeObjectSync(t,e))):r.ParseStatus.mergeObjectSync(t,u)}get shape(){return this._def.shape()}strict(e){return a.errorUtil.errToObj,new O({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,s,o,i;const c=null!==(o=null===(s=(n=this._def).errorMap)||void 0===s?void 0:s.call(n,t,r).message)&&void 0!==o?o:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(i=a.errorUtil.errToObj(e).message)&&void 0!==i?i:c}:{message:c}}}:{}})}strip(){return new O({...this._def,unknownKeys:"strip"})}passthrough(){return new O({...this._def,unknownKeys:"passthrough"})}extend(e){return new O({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new O({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:se.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new O({...this._def,catchall:e})}pick(e){const t={};return n.util.objectKeys(e).forEach((a=>{e[a]&&this.shape[a]&&(t[a]=this.shape[a])})),new O({...this._def,shape:()=>t})}omit(e){const t={};return n.util.objectKeys(this.shape).forEach((a=>{e[a]||(t[a]=this.shape[a])})),new O({...this._def,shape:()=>t})}deepPartial(){return j(this)}partial(e){const t={};return n.util.objectKeys(this.shape).forEach((a=>{const r=this.shape[a];e&&!e[a]?t[a]=r:t[a]=r.optional()})),new O({...this._def,shape:()=>t})}required(e){const t={};return n.util.objectKeys(this.shape).forEach((a=>{if(e&&!e[a])t[a]=this.shape[a];else{let e=this.shape[a];for(;e instanceof X;)e=e._def.innerType;t[a]=e}})),new O({...this._def,shape:()=>t})}keyof(){return K(n.util.objectKeys(this.shape))}}e.ZodObject=O,O.create=(e,t)=>new O({shape:()=>e,unknownKeys:"strip",catchall:_.create(),typeName:se.ZodObject,...c(t)}),O.strictCreate=(e,t)=>new O({shape:()=>e,unknownKeys:"strict",catchall:_.create(),typeName:se.ZodObject,...c(t)}),O.lazycreate=(e,t)=>new O({shape:e,unknownKeys:"strip",catchall:_.create(),typeName:se.ZodObject,...c(t)});class M extends d{_parse(e){const{ctx:t}=this._processInputParams(e),a=this._def.options;if(t.common.async)return Promise.all(a.map((async e=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const a of e)if("dirty"===a.result.status)return t.common.issues.push(...a.ctx.common.issues),a.result;const a=e.map((e=>new s.ZodError(e.ctx.common.issues)));return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_union,unionErrors:a}),r.INVALID}));{let e;const n=[];for(const r of a){const a={...t,common:{...t.common,issues:[]},parent:null},s=r._parseSync({data:t.data,path:t.path,parent:a});if("valid"===s.status)return s;"dirty"!==s.status||e||(e={result:s,ctx:a}),a.common.issues.length&&n.push(a.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const o=n.map((e=>new s.ZodError(e)));return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_union,unionErrors:o}),r.INVALID}}get options(){return this._def.options}}e.ZodUnion=M,M.create=(e,t)=>new M({options:e,typeName:se.ZodUnion,...c(t)});const A=e=>e instanceof F?A(e.schema):e instanceof G?A(e.innerType()):e instanceof $?[e.value]:e instanceof H?e.options:e instanceof W?Object.keys(e.enum):e instanceof Q?A(e._def.innerType):e instanceof P?[void 0]:e instanceof k?[null]:null;class D extends d{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.ZodParsedType.object)return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.object,received:t.parsedType}),r.INVALID;const a=this.discriminator,o=t.data[a],i=this.optionsMap.get(o);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):((0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),r.INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,a){const r=new Map;for(const a of t){const t=A(a.shape[e]);if(!t)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(r.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);r.set(n,a)}}return new D({typeName:se.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...c(a)})}}function B(e,t){const a=(0,n.getParsedType)(e),r=(0,n.getParsedType)(t);if(e===t)return{valid:!0,data:e};if(a===n.ZodParsedType.object&&r===n.ZodParsedType.object){const a=n.util.objectKeys(t),r=n.util.objectKeys(e).filter((e=>-1!==a.indexOf(e))),s={...e,...t};for(const a of r){const r=B(e[a],t[a]);if(!r.valid)return{valid:!1};s[a]=r.data}return{valid:!0,data:s}}if(a===n.ZodParsedType.array&&r===n.ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const a=[];for(let r=0;r<e.length;r++){const n=B(e[r],t[r]);if(!n.valid)return{valid:!1};a.push(n.data)}return{valid:!0,data:a}}return a===n.ZodParsedType.date&&r===n.ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}e.ZodDiscriminatedUnion=D;class z extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e),n=(e,n)=>{if((0,r.isAborted)(e)||(0,r.isAborted)(n))return r.INVALID;const o=B(e.value,n.value);return o.valid?(((0,r.isDirty)(e)||(0,r.isDirty)(n))&&t.dirty(),{status:t.value,value:o.data}):((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_intersection_types}),r.INVALID)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}}e.ZodIntersection=z,z.create=(e,t,a)=>new z({left:e,right:t,typeName:se.ZodIntersection,...c(a)});class L extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.array)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.array,received:a.parsedType}),r.INVALID;if(a.data.length<this._def.items.length)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.INVALID;!this._def.rest&&a.data.length>this._def.items.length&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...a.data].map(((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new o(a,e,a.path,t)):null})).filter((e=>!!e));return a.common.async?Promise.all(i).then((e=>r.ParseStatus.mergeArray(t,e))):r.ParseStatus.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new L({...this._def,rest:e})}}e.ZodTuple=L,L.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new L({items:e,typeName:se.ZodTuple,rest:null,...c(t)})};class Z extends d{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.object)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.object,received:a.parsedType}),r.INVALID;const i=[],c=this._def.keyType,d=this._def.valueType;for(const e in a.data)i.push({key:c._parse(new o(a,e,a.path,e)),value:d._parse(new o(a,a.data[e],a.path,e))});return a.common.async?r.ParseStatus.mergeObjectAsync(t,i):r.ParseStatus.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,a){return new Z(t instanceof d?{keyType:e,valueType:t,typeName:se.ZodRecord,...c(a)}:{keyType:S.create(),valueType:e,typeName:se.ZodRecord,...c(t)})}}e.ZodRecord=Z;class U extends d{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.map)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.map,received:a.parsedType}),r.INVALID;const i=this._def.keyType,c=this._def.valueType,d=[...a.data.entries()].map((([e,t],r)=>({key:i._parse(new o(a,e,a.path,[r,"key"])),value:c._parse(new o(a,t,a.path,[r,"value"]))})));if(a.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const a of d){const n=await a.key,s=await a.value;if("aborted"===n.status||"aborted"===s.status)return r.INVALID;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const a of d){const n=a.key,s=a.value;if("aborted"===n.status||"aborted"===s.status)return r.INVALID;"dirty"!==n.status&&"dirty"!==s.status||t.dirty(),e.set(n.value,s.value)}return{status:t.value,value:e}}}}e.ZodMap=U,U.create=(e,t,a)=>new U({valueType:t,keyType:e,typeName:se.ZodMap,...c(a)});class q extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.set)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.set,received:a.parsedType}),r.INVALID;const i=this._def;null!==i.minSize&&a.data.size<i.minSize.value&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),null!==i.maxSize&&a.data.size>i.maxSize.value&&((0,r.addIssueToContext)(a,{code:s.ZodIssueCode.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());const c=this._def.valueType;function d(e){const a=new Set;for(const n of e){if("aborted"===n.status)return r.INVALID;"dirty"===n.status&&t.dirty(),a.add(n.value)}return{status:t.value,value:a}}const u=[...a.data.values()].map(((e,t)=>c._parse(new o(a,e,a.path,t))));return a.common.async?Promise.all(u).then((e=>d(e))):d(u)}min(e,t){return new q({...this._def,minSize:{value:e,message:a.errorUtil.toString(t)}})}max(e,t){return new q({...this._def,maxSize:{value:e,message:a.errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}e.ZodSet=q,q.create=(e,t)=>new q({valueType:e,minSize:null,maxSize:null,typeName:se.ZodSet,...c(t)});class V extends d{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:a}=this._processInputParams(e);if(a.parsedType!==n.ZodParsedType.function)return(0,r.addIssueToContext)(a,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.function,received:a.parsedType}),r.INVALID;function o(e,n){return(0,r.makeIssue)({data:e,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,(0,t.getErrorMap)(),t.defaultErrorMap].filter((e=>!!e)),issueData:{code:s.ZodIssueCode.invalid_arguments,argumentsError:n}})}function i(e,n){return(0,r.makeIssue)({data:e,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,(0,t.getErrorMap)(),t.defaultErrorMap].filter((e=>!!e)),issueData:{code:s.ZodIssueCode.invalid_return_type,returnTypeError:n}})}const c={errorMap:a.common.contextualErrorMap},d=a.data;if(this._def.returns instanceof J){const e=this;return(0,r.OK)((async function(...t){const a=new s.ZodError([]),r=await e._def.args.parseAsync(t,c).catch((e=>{throw a.addIssue(o(t,e)),a})),n=await Reflect.apply(d,this,r),u=await e._def.returns._def.type.parseAsync(n,c).catch((e=>{throw a.addIssue(i(n,e)),a}));return u}))}{const e=this;return(0,r.OK)((function(...t){const a=e._def.args.safeParse(t,c);if(!a.success)throw new s.ZodError([o(t,a.error)]);const r=Reflect.apply(d,this,a.data),n=e._def.returns.safeParse(r,c);if(!n.success)throw new s.ZodError([i(r,n.error)]);return n.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new V({...this._def,args:L.create(e).rest(E.create())})}returns(e){return new V({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,a){return new V({args:e||L.create([]).rest(E.create()),returns:t||E.create(),typeName:se.ZodFunction,...c(a)})}}e.ZodFunction=V;class F extends d{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}e.ZodLazy=F,F.create=(e,t)=>new F({getter:e,typeName:se.ZodLazy,...c(t)});class $ extends d{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{received:t.data,code:s.ZodIssueCode.invalid_literal,expected:this._def.value}),r.INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function K(e,t){return new H({values:e,typeName:se.ZodEnum,...c(t)})}e.ZodLiteral=$,$.create=(e,t)=>new $({value:e,typeName:se.ZodLiteral,...c(t)});class H extends d{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),a=this._def.values;return(0,r.addIssueToContext)(t,{expected:n.util.joinValues(a),received:t.parsedType,code:s.ZodIssueCode.invalid_type}),r.INVALID}if(-1===this._def.values.indexOf(e.data)){const t=this._getOrReturnCtx(e),a=this._def.values;return(0,r.addIssueToContext)(t,{received:t.data,code:s.ZodIssueCode.invalid_enum_value,options:a}),r.INVALID}return(0,r.OK)(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e){return H.create(e)}exclude(e){return H.create(this.options.filter((t=>!e.includes(t))))}}e.ZodEnum=H,H.create=K;class W extends d{_parse(e){const t=n.util.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==n.ZodParsedType.string&&a.parsedType!==n.ZodParsedType.number){const e=n.util.objectValues(t);return(0,r.addIssueToContext)(a,{expected:n.util.joinValues(e),received:a.parsedType,code:s.ZodIssueCode.invalid_type}),r.INVALID}if(-1===t.indexOf(e.data)){const e=n.util.objectValues(t);return(0,r.addIssueToContext)(a,{received:a.data,code:s.ZodIssueCode.invalid_enum_value,options:e}),r.INVALID}return(0,r.OK)(e.data)}get enum(){return this._def.values}}e.ZodNativeEnum=W,W.create=(e,t)=>new W({values:e,typeName:se.ZodNativeEnum,...c(t)});class J extends d{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==n.ZodParsedType.promise&&!1===t.common.async)return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.promise,received:t.parsedType}),r.INVALID;const a=t.parsedType===n.ZodParsedType.promise?t.data:Promise.resolve(t.data);return(0,r.OK)(a.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}e.ZodPromise=J,J.create=(e,t)=>new J({type:e,typeName:se.ZodPromise,...c(t)});class G extends d{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===se.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:a}=this._processInputParams(e),s=this._def.effect||null,o={addIssue:e=>{(0,r.addIssueToContext)(a,e),e.fatal?t.abort():t.dirty()},get path(){return a.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===s.type){const e=s.transform(a.data,o);return a.common.issues.length?{status:"dirty",value:a.data}:a.common.async?Promise.resolve(e).then((e=>this._def.schema._parseAsync({data:e,path:a.path,parent:a}))):this._def.schema._parseSync({data:e,path:a.path,parent:a})}if("refinement"===s.type){const e=e=>{const t=s.refinement(e,o);if(a.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===a.common.async){const n=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===n.status?r.INVALID:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((a=>"aborted"===a.status?r.INVALID:("dirty"===a.status&&t.dirty(),e(a.value).then((()=>({status:t.value,value:a.value}))))))}if("transform"===s.type){if(!1===a.common.async){const e=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!(0,r.isValid)(e))return e;const n=s.transform(e.value,o);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then((e=>(0,r.isValid)(e)?Promise.resolve(s.transform(e.value,o)).then((e=>({status:t.value,value:e}))):e))}n.util.assertNever(s)}}e.ZodEffects=G,e.ZodTransformer=G,G.create=(e,t,a)=>new G({schema:e,typeName:se.ZodEffects,effect:t,...c(a)}),G.createWithPreprocess=(e,t,a)=>new G({schema:t,effect:{type:"preprocess",transform:e},typeName:se.ZodEffects,...c(a)});class X extends d{_parse(e){return this._getType(e)===n.ZodParsedType.undefined?(0,r.OK)(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}e.ZodOptional=X,X.create=(e,t)=>new X({innerType:e,typeName:se.ZodOptional,...c(t)});class Y extends d{_parse(e){return this._getType(e)===n.ZodParsedType.null?(0,r.OK)(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}e.ZodNullable=Y,Y.create=(e,t)=>new Y({innerType:e,typeName:se.ZodNullable,...c(t)});class Q extends d{_parse(e){const{ctx:t}=this._processInputParams(e);let a=t.data;return t.parsedType===n.ZodParsedType.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}e.ZodDefault=Q,Q.create=(e,t)=>new Q({innerType:e,typeName:se.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...c(t)});class ee extends d{_parse(e){const{ctx:t}=this._processInputParams(e),a={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return(0,r.isAsync)(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new s.ZodError(a.common.issues)},input:a.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new s.ZodError(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}}e.ZodCatch=ee,ee.create=(e,t)=>new ee({innerType:e,typeName:se.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...c(t)});class te extends d{_parse(e){if(this._getType(e)!==n.ZodParsedType.nan){const t=this._getOrReturnCtx(e);return(0,r.addIssueToContext)(t,{code:s.ZodIssueCode.invalid_type,expected:n.ZodParsedType.nan,received:t.parsedType}),r.INVALID}return{status:"valid",value:e.data}}}e.ZodNaN=te,te.create=e=>new te({typeName:se.ZodNaN,...c(e)}),e.BRAND=Symbol("zod_brand");class ae extends d{_parse(e){const{ctx:t}=this._processInputParams(e),a=t.data;return this._def.type._parse({data:a,path:t.path,parent:t})}unwrap(){return this._def.type}}e.ZodBranded=ae;class re extends d{_parse(e){const{status:t,ctx:a}=this._processInputParams(e);if(a.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?r.INVALID:"dirty"===e.status?(t.dirty(),(0,r.DIRTY)(e.value)):this._def.out._parseAsync({data:e.value,path:a.path,parent:a})})()}{const e=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return"aborted"===e.status?r.INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:a.path,parent:a})}}static create(e,t){return new re({in:e,out:t,typeName:se.ZodPipeline})}}e.ZodPipeline=re;class ne extends d{_parse(e){const t=this._def.innerType._parse(e);return(0,r.isValid)(t)&&(t.value=Object.freeze(t.value)),t}}e.ZodReadonly=ne,ne.create=(e,t)=>new ne({innerType:e,typeName:se.ZodReadonly,...c(t)});var se;e.custom=(e,t={},a)=>e?R.create().superRefine(((r,n)=>{var s,o;if(!e(r)){const e="function"==typeof t?t(r):"string"==typeof t?{message:t}:t,i=null===(o=null!==(s=e.fatal)&&void 0!==s?s:a)||void 0===o||o,c="string"==typeof e?{message:e}:e;n.addIssue({code:"custom",...c,fatal:i})}})):R.create(),e.late={object:O.lazycreate},function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(se=e.ZodFirstPartyTypeKind||(e.ZodFirstPartyTypeKind={}));e.instanceof=(t,a={message:`Input not instance of ${t.name}`})=>(0,e.custom)((e=>e instanceof t),a);const oe=S.create;e.string=oe;const ie=w.create;e.number=ie;const ce=te.create;e.nan=ce;const de=b.create;e.bigint=de;const ue=C.create;e.boolean=ue;const le=x.create;e.date=le;const he=I.create;e.symbol=he;const pe=P.create;e.undefined=pe;const me=k.create;e.null=me;const fe=R.create;e.any=fe;const ge=E.create;e.unknown=ge;const ye=_.create;e.never=ye;const Se=T.create;e.void=Se;const ve=N.create;e.array=ve;const we=O.create;e.object=we;const be=O.strictCreate;e.strictObject=be;const Ce=M.create;e.union=Ce;const xe=D.create;e.discriminatedUnion=xe;const Ie=z.create;e.intersection=Ie;const Pe=L.create;e.tuple=Pe;const ke=Z.create;e.record=ke;const Re=U.create;e.map=Re;const Ee=q.create;e.set=Ee;const _e=V.create;e.function=_e;const Te=F.create;e.lazy=Te;const Ne=$.create;e.literal=Ne;const je=H.create;e.enum=je;const Oe=W.create;e.nativeEnum=Oe;const Me=J.create;e.promise=Me;const Ae=G.create;e.effect=Ae,e.transformer=Ae;const De=X.create;e.optional=De;const Be=Y.create;e.nullable=Be;const ze=G.createWithPreprocess;e.preprocess=ze;const Le=re.create;e.pipeline=Le;e.ostring=()=>oe().optional();e.onumber=()=>ie().optional();e.oboolean=()=>ue().optional(),e.coerce={string:e=>S.create({...e,coerce:!0}),number:e=>w.create({...e,coerce:!0}),boolean:e=>C.create({...e,coerce:!0}),bigint:e=>b.create({...e,coerce:!0}),date:e=>x.create({...e,coerce:!0})},e.NEVER=r.INVALID}(Gr),function(t){var a=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[a]}})}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),r=e&&e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),r(Dr,t),r(Hr,t),r(Wr,t),r(zr,t),r(Gr,t),r(Lr,t)}(Ar),function(t){var a=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a),Object.defineProperty(e,r,{enumerable:!0,get:function(){return t[a]}})}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),r=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&a(t,e,n);return r(t,e),t},s=e&&e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.z=void 0;const o=n(Ar);t.z=o,s(Ar,t),t.default=o}(Mr);var Yr={};!function(t){var a=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Input=t.InputCommandSchema=t.Log=t.LogEventSchema=t.Script=t.ScriptResultSchema=t.ScriptCommandSchema=t.ScriptEventSchema=t.Network=t.NetworkResultSchema=t.NetworkEventSchema=t.NetworkCommandSchema=t.BrowsingContext=t.BrowsingContextResultSchema=t.BrowsingContextEventSchema=t.BrowsingContextCommandSchema=t.Browser=t.BrowserCommandSchema=t.SessionResultSchema=t.Session=t.SessionCommandSchema=t.ErrorCodeSchema=t.JsUintSchema=t.JsIntSchema=t.ExtensibleSchema=t.EmptyResultSchema=t.ErrorResponseSchema=t.MessageSchema=t.EmptyParamsSchema=t.ResultDataSchema=t.CommandDataSchema=t.EventDataSchema=t.CommandResponseSchema=t.CommandSchema=t.EventSchema=void 0;const r=a(Mr);var n,s,o,i,c,d,u;t.EventSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("event")}).and(t.EventDataSchema).and(t.ExtensibleSchema))),t.CommandSchema=r.default.lazy((()=>r.default.object({id:t.JsUintSchema}).and(t.CommandDataSchema).and(t.ExtensibleSchema))),t.CommandResponseSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("success"),id:t.JsUintSchema,result:t.ResultDataSchema}).and(t.ExtensibleSchema))),t.EventDataSchema=r.default.lazy((()=>r.default.union([t.BrowsingContextEventSchema,t.LogEventSchema,t.NetworkEventSchema,t.ScriptEventSchema]))),t.CommandDataSchema=r.default.lazy((()=>r.default.union([t.BrowserCommandSchema,t.BrowsingContextCommandSchema,t.InputCommandSchema,t.NetworkCommandSchema,t.ScriptCommandSchema,t.SessionCommandSchema]))),t.ResultDataSchema=r.default.lazy((()=>r.default.union([t.BrowsingContextResultSchema,t.EmptyResultSchema,t.NetworkResultSchema,t.ScriptResultSchema,t.SessionResultSchema]))),t.EmptyParamsSchema=r.default.lazy((()=>t.ExtensibleSchema)),t.MessageSchema=r.default.lazy((()=>r.default.union([t.CommandResponseSchema,t.ErrorResponseSchema,t.EventSchema]))),t.ErrorResponseSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("error"),id:r.default.union([t.JsUintSchema,r.default.null()]),error:t.ErrorCodeSchema,message:r.default.string(),stacktrace:r.default.string().optional()}).and(t.ExtensibleSchema))),t.EmptyResultSchema=r.default.lazy((()=>t.ExtensibleSchema)),t.ExtensibleSchema=r.default.lazy((()=>r.default.record(r.default.string(),r.default.any()))),t.JsIntSchema=r.default.lazy((()=>r.default.number().int().gte(-9007199254740991).lte(9007199254740991))),t.JsUintSchema=r.default.lazy((()=>r.default.number().int().nonnegative().gte(0).lte(9007199254740991))),t.ErrorCodeSchema=r.default.lazy((()=>r.default.enum(["invalid argument","invalid session id","move target out of bounds","no such alert","no such element","no such frame","no such handle","no such history entry","no such intercept","no such node","no such request","no such script","session not created","unable to capture screen","unable to close browser","unknown command","unknown error","unsupported operation"]))),t.SessionCommandSchema=r.default.lazy((()=>r.default.union([n.EndSchema,n.NewSchema,n.StatusSchema,n.SubscribeSchema,n.UnsubscribeSchema]))),function(e){e.ProxyConfigurationSchema=r.default.lazy((()=>r.default.union([e.AutodetectProxyConfigurationSchema,e.DirectProxyConfigurationSchema,e.ManualProxyConfigurationSchema,e.PacProxyConfigurationSchema,e.SystemProxyConfigurationSchema,r.default.object({})])))}(n||(t.Session=n={})),t.SessionResultSchema=r.default.lazy((()=>r.default.union([n.NewResultSchema,n.StatusResultSchema]))),function(e){e.CapabilitiesRequestSchema=r.default.lazy((()=>r.default.object({alwaysMatch:e.CapabilityRequestSchema.optional(),firstMatch:r.default.array(e.CapabilityRequestSchema).optional()})))}(n||(t.Session=n={})),function(e){e.CapabilityRequestSchema=r.default.lazy((()=>r.default.object({acceptInsecureCerts:r.default.boolean().optional(),browserName:r.default.string().optional(),browserVersion:r.default.string().optional(),platformName:r.default.string().optional(),proxy:e.ProxyConfigurationSchema.optional(),webSocketUrl:r.default.boolean().optional()}).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.AutodetectProxyConfigurationSchema=r.default.lazy((()=>r.default.object({proxyType:r.default.literal("autodetect")}).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.DirectProxyConfigurationSchema=r.default.lazy((()=>r.default.object({proxyType:r.default.literal("direct")}).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.ManualProxyConfigurationSchema=r.default.lazy((()=>r.default.object({proxyType:r.default.literal("manual"),ftpProxy:r.default.string().optional(),httpProxy:r.default.string().optional(),sslProxy:r.default.string().optional()}).and(e.SocksProxyConfigurationSchema.or(r.default.object({}))).and(r.default.object({noProxy:r.default.array(r.default.string()).optional()})).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.SocksProxyConfigurationSchema=r.default.lazy((()=>r.default.object({socksProxy:r.default.string(),socksVersion:r.default.number().int().nonnegative().gte(0).lte(255)})))}(n||(t.Session=n={})),function(e){e.PacProxyConfigurationSchema=r.default.lazy((()=>r.default.object({proxyType:r.default.literal("pac"),proxyAutoconfigUrl:r.default.string()}).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.SystemProxyConfigurationSchema=r.default.lazy((()=>r.default.object({proxyType:r.default.literal("system")}).and(t.ExtensibleSchema)))}(n||(t.Session=n={})),function(e){e.SubscriptionRequestSchema=r.default.lazy((()=>r.default.object({events:r.default.array(r.default.string()),contexts:r.default.array(o.BrowsingContextSchema).optional()})))}(n||(t.Session=n={})),function(e){e.StatusSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.status"),params:t.EmptyParamsSchema})))}(n||(t.Session=n={})),function(e){e.StatusResultSchema=r.default.lazy((()=>r.default.object({ready:r.default.boolean(),message:r.default.string()})))}(n||(t.Session=n={})),function(e){e.NewSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.new"),params:e.NewParametersSchema})))}(n||(t.Session=n={})),function(e){e.NewParametersSchema=r.default.lazy((()=>r.default.object({capabilities:e.CapabilitiesRequestSchema})))}(n||(t.Session=n={})),function(e){e.NewResultSchema=r.default.lazy((()=>r.default.object({sessionId:r.default.string(),capabilities:r.default.object({acceptInsecureCerts:r.default.boolean(),browserName:r.default.string(),browserVersion:r.default.string(),platformName:r.default.string(),setWindowRect:r.default.boolean(),proxy:e.ProxyConfigurationSchema.optional(),webSocketUrl:r.default.union([r.default.string(),r.default.literal(!0)]).optional()}).and(t.ExtensibleSchema)})))}(n||(t.Session=n={})),function(e){e.EndSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.end"),params:t.EmptyParamsSchema})))}(n||(t.Session=n={})),function(e){e.SubscribeSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.subscribe"),params:e.SubscriptionRequestSchema})))}(n||(t.Session=n={})),function(e){e.UnsubscribeSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("session.unsubscribe"),params:e.SubscriptionRequestSchema})))}(n||(t.Session=n={})),t.BrowserCommandSchema=r.default.lazy((()=>s.CloseSchema)),function(e){e.CloseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browser.close"),params:t.EmptyParamsSchema})))}(s||(t.Browser=s={})),t.BrowsingContextCommandSchema=r.default.lazy((()=>r.default.union([o.ActivateSchema,o.CaptureScreenshotSchema,o.CloseSchema,o.CreateSchema,o.GetTreeSchema,o.HandleUserPromptSchema,o.LocateNodesSchema,o.NavigateSchema,o.PrintSchema,o.ReloadSchema,o.SetViewportSchema,o.TraverseHistorySchema]))),t.BrowsingContextEventSchema=r.default.lazy((()=>r.default.union([o.ContextCreatedSchema,o.ContextDestroyedSchema,o.DomContentLoadedSchema,o.DownloadWillBeginSchema,o.FragmentNavigatedSchema,o.LoadSchema,o.NavigationAbortedSchema,o.NavigationFailedSchema,o.NavigationStartedSchema,o.UserPromptClosedSchema,o.UserPromptOpenedSchema]))),t.BrowsingContextResultSchema=r.default.lazy((()=>r.default.union([o.CaptureScreenshotResultSchema,o.CreateResultSchema,o.GetTreeResultSchema,o.LocateNodesResultSchema,o.NavigateResultSchema,o.PrintResultSchema,o.TraverseHistoryResultSchema]))),function(e){e.BrowsingContextSchema=r.default.lazy((()=>r.default.string()))}(o||(t.BrowsingContext=o={})),function(e){e.InfoListSchema=r.default.lazy((()=>r.default.array(e.InfoSchema)))}(o||(t.BrowsingContext=o={})),function(e){e.InfoSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,url:r.default.string(),children:r.default.union([e.InfoListSchema,r.default.null()]),parent:r.default.union([e.BrowsingContextSchema,r.default.null()]).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.LocatorSchema=r.default.lazy((()=>r.default.union([e.CssLocatorSchema,e.InnerTextLocatorSchema,e.XPathLocatorSchema])))}(o||(t.BrowsingContext=o={})),function(e){e.CssLocatorSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("css"),value:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.InnerTextLocatorSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("innerText"),value:r.default.string(),ignoreCase:r.default.boolean().optional(),matchType:r.default.enum(["full","partial"]).optional(),maxDepth:t.JsUintSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.XPathLocatorSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("xpath"),value:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationSchema=r.default.lazy((()=>r.default.string()))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationInfoSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,navigation:r.default.union([e.NavigationSchema,r.default.null()]),timestamp:t.JsUintSchema,url:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.ReadinessStateSchema=r.default.lazy((()=>r.default.enum(["none","interactive","complete"])))}(o||(t.BrowsingContext=o={})),function(e){e.ActivateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.activate"),params:e.ActivateParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ActivateParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CaptureScreenshotParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,origin:r.default.enum(["viewport","document"]).default("viewport").optional(),format:e.ImageFormatSchema.optional(),clip:e.ClipRectangleSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.CaptureScreenshotSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.captureScreenshot"),params:e.CaptureScreenshotParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ImageFormatSchema=r.default.lazy((()=>r.default.object({type:r.default.string(),quality:r.default.number().gte(0).lte(1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.ClipRectangleSchema=r.default.lazy((()=>r.default.union([e.BoxClipRectangleSchema,e.ElementClipRectangleSchema])))}(o||(t.BrowsingContext=o={})),function(e){e.ElementClipRectangleSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("element"),element:c.SharedReferenceSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.BoxClipRectangleSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("box"),x:r.default.number(),y:r.default.number(),width:r.default.number(),height:r.default.number()})))}(o||(t.BrowsingContext=o={})),function(e){e.CaptureScreenshotResultSchema=r.default.lazy((()=>r.default.object({data:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.CloseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.close"),params:e.CloseParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CloseParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,promptUnload:r.default.boolean().default(!1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.CreateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.create"),params:e.CreateParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.CreateTypeSchema=r.default.lazy((()=>r.default.enum(["tab","window"])))}(o||(t.BrowsingContext=o={})),function(e){e.CreateParametersSchema=r.default.lazy((()=>r.default.object({type:e.CreateTypeSchema,referenceContext:e.BrowsingContextSchema.optional(),background:r.default.boolean().default(!1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.CreateResultSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.GetTreeSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.getTree"),params:e.GetTreeParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.GetTreeParametersSchema=r.default.lazy((()=>r.default.object({maxDepth:t.JsUintSchema.optional(),root:e.BrowsingContextSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.GetTreeResultSchema=r.default.lazy((()=>r.default.object({contexts:e.InfoListSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.HandleUserPromptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.handleUserPrompt"),params:e.HandleUserPromptParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.HandleUserPromptParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,accept:r.default.boolean().optional(),userText:r.default.string().optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.LocateNodesParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,locator:e.LocatorSchema,maxNodeCount:t.JsUintSchema.gte(1).optional(),ownership:c.ResultOwnershipSchema.optional(),sandbox:r.default.string().optional(),serializationOptions:c.SerializationOptionsSchema.optional(),startNodes:r.default.array(c.SharedReferenceSchema).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.LocateNodesSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.locateNodes"),params:e.LocateNodesParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.LocateNodesResultSchema=r.default.lazy((()=>r.default.object({nodes:r.default.array(c.NodeRemoteValueSchema)})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigate"),params:e.NavigateParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigateParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,url:r.default.string(),wait:e.ReadinessStateSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigateResultSchema=r.default.lazy((()=>r.default.object({navigation:r.default.union([e.NavigationSchema,r.default.null()]),url:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.print"),params:e.PrintParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,background:r.default.boolean().default(!1).optional(),margin:e.PrintMarginParametersSchema.optional(),orientation:r.default.enum(["portrait","landscape"]).default("portrait").optional(),page:e.PrintPageParametersSchema.optional(),pageRanges:r.default.array(r.default.union([t.JsUintSchema,r.default.string()])).optional(),scale:r.default.number().gte(.1).lte(2).default(1).optional(),shrinkToFit:r.default.boolean().default(!0).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintMarginParametersSchema=r.default.lazy((()=>r.default.object({bottom:r.default.number().gte(0).default(1).optional(),left:r.default.number().gte(0).default(1).optional(),right:r.default.number().gte(0).default(1).optional(),top:r.default.number().gte(0).default(1).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintPageParametersSchema=r.default.lazy((()=>r.default.object({height:r.default.number().gte(.0352).default(27.94).optional(),width:r.default.number().gte(.0352).default(21.59).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.PrintResultSchema=r.default.lazy((()=>r.default.object({data:r.default.string()})))}(o||(t.BrowsingContext=o={})),function(e){e.ReloadSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.reload"),params:e.ReloadParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ReloadParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,ignoreCache:r.default.boolean().optional(),wait:e.ReadinessStateSchema.optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.SetViewportSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.setViewport"),params:e.SetViewportParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.SetViewportParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,viewport:r.default.union([e.ViewportSchema,r.default.null()]).optional(),devicePixelRatio:r.default.union([r.default.number().gt(0),r.default.null()]).optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.ViewportSchema=r.default.lazy((()=>r.default.object({width:t.JsUintSchema,height:t.JsUintSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.TraverseHistorySchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.traverseHistory"),params:e.TraverseHistoryParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.TraverseHistoryParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,delta:t.JsIntSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.TraverseHistoryResultSchema=r.default.lazy((()=>r.default.object({})))}(o||(t.BrowsingContext=o={})),function(e){e.ContextCreatedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.contextCreated"),params:e.InfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.ContextDestroyedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.contextDestroyed"),params:e.InfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationStartedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigationStarted"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.FragmentNavigatedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.fragmentNavigated"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.DomContentLoadedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.domContentLoaded"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.LoadSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.load"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.DownloadWillBeginSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.downloadWillBegin"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationAbortedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigationAborted"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.NavigationFailedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.navigationFailed"),params:e.NavigationInfoSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptClosedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.userPromptClosed"),params:e.UserPromptClosedParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptClosedParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,accepted:r.default.boolean(),userText:r.default.string().optional()})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptOpenedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("browsingContext.userPromptOpened"),params:e.UserPromptOpenedParametersSchema})))}(o||(t.BrowsingContext=o={})),function(e){e.UserPromptOpenedParametersSchema=r.default.lazy((()=>r.default.object({context:e.BrowsingContextSchema,type:r.default.enum(["alert","confirm","prompt","beforeunload"]),message:r.default.string(),defaultValue:r.default.string().optional()})))}(o||(t.BrowsingContext=o={})),t.NetworkCommandSchema=r.default.lazy((()=>r.default.union([i.AddInterceptSchema,i.ContinueRequestSchema,i.ContinueResponseSchema,i.ContinueWithAuthSchema,i.FailRequestSchema,i.ProvideResponseSchema,i.RemoveInterceptSchema]))),t.NetworkEventSchema=r.default.lazy((()=>r.default.union([i.AuthRequiredSchema,i.BeforeRequestSentSchema,i.FetchErrorSchema,i.ResponseCompletedSchema,i.ResponseStartedSchema]))),t.NetworkResultSchema=r.default.lazy((()=>i.AddInterceptResultSchema)),function(e){e.AuthChallengeSchema=r.default.lazy((()=>r.default.object({scheme:r.default.string(),realm:r.default.string()})))}(i||(t.Network=i={})),function(e){e.AuthCredentialsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("password"),username:r.default.string(),password:r.default.string()})))}(i||(t.Network=i={})),function(e){e.BaseParametersSchema=r.default.lazy((()=>r.default.object({context:r.default.union([o.BrowsingContextSchema,r.default.null()]),isBlocked:r.default.boolean(),navigation:r.default.union([o.NavigationSchema,r.default.null()]),redirectCount:t.JsUintSchema,request:e.RequestDataSchema,timestamp:t.JsUintSchema,intercepts:r.default.array(e.InterceptSchema).optional()})))}(i||(t.Network=i={})),function(e){e.BytesValueSchema=r.default.lazy((()=>r.default.union([e.StringValueSchema,e.Base64ValueSchema])))}(i||(t.Network=i={})),function(e){e.StringValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("string"),value:r.default.string()})))}(i||(t.Network=i={})),function(e){e.Base64ValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("base64"),value:r.default.string()})))}(i||(t.Network=i={})),function(e){e.CookieSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema,domain:r.default.string(),path:r.default.string(),size:t.JsUintSchema,httpOnly:r.default.boolean(),secure:r.default.boolean(),sameSite:r.default.enum(["strict","lax","none"]),expiry:t.JsUintSchema.optional()})))}(i||(t.Network=i={})),function(e){e.CookieHeaderSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema})))}(i||(t.Network=i={})),function(e){e.FetchTimingInfoSchema=r.default.lazy((()=>r.default.object({timeOrigin:r.default.number(),requestTime:r.default.number(),redirectStart:r.default.number(),redirectEnd:r.default.number(),fetchStart:r.default.number(),dnsStart:r.default.number(),dnsEnd:r.default.number(),connectStart:r.default.number(),connectEnd:r.default.number(),tlsStart:r.default.number(),requestStart:r.default.number(),responseStart:r.default.number(),responseEnd:r.default.number()})))}(i||(t.Network=i={})),function(e){e.HeaderSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema})))}(i||(t.Network=i={})),function(e){e.InitiatorSchema=r.default.lazy((()=>r.default.object({type:r.default.enum(["parser","script","preflight","other"]),columnNumber:t.JsUintSchema.optional(),lineNumber:t.JsUintSchema.optional(),stackTrace:c.StackTraceSchema.optional(),request:e.RequestSchema.optional()})))}(i||(t.Network=i={})),function(e){e.InterceptSchema=r.default.lazy((()=>r.default.string()))}(i||(t.Network=i={})),function(e){e.RequestSchema=r.default.lazy((()=>r.default.string()))}(i||(t.Network=i={})),function(e){e.RequestDataSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,url:r.default.string(),method:r.default.string(),headers:r.default.array(e.HeaderSchema),cookies:r.default.array(e.CookieSchema),headersSize:t.JsUintSchema,bodySize:r.default.union([t.JsUintSchema,r.default.null()]),timings:e.FetchTimingInfoSchema})))}(i||(t.Network=i={})),function(e){e.ResponseContentSchema=r.default.lazy((()=>r.default.object({size:t.JsUintSchema})))}(i||(t.Network=i={})),function(e){e.ResponseDataSchema=r.default.lazy((()=>r.default.object({url:r.default.string(),protocol:r.default.string(),status:t.JsUintSchema,statusText:r.default.string(),fromCache:r.default.boolean(),headers:r.default.array(e.HeaderSchema),mimeType:r.default.string(),bytesReceived:t.JsUintSchema,headersSize:r.default.union([t.JsUintSchema,r.default.null()]),bodySize:r.default.union([t.JsUintSchema,r.default.null()]),content:e.ResponseContentSchema,authChallenge:e.AuthChallengeSchema.optional()})))}(i||(t.Network=i={})),function(e){e.SetCookieHeaderSchema=r.default.lazy((()=>r.default.object({name:r.default.string(),value:e.BytesValueSchema,domain:r.default.string().optional(),httpOnly:r.default.boolean().optional(),expiry:r.default.string().optional(),maxAge:t.JsIntSchema.optional(),path:r.default.string().optional(),sameSite:r.default.enum(["strict","lax","none"]).optional(),secure:r.default.boolean().optional()})))}(i||(t.Network=i={})),function(e){e.UrlPatternSchema=r.default.lazy((()=>r.default.union([e.UrlPatternPatternSchema,e.UrlPatternStringSchema])))}(i||(t.Network=i={})),function(e){e.UrlPatternPatternSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pattern"),protocol:r.default.string().optional(),hostname:r.default.string().optional(),port:r.default.string().optional(),pathname:r.default.string().optional(),search:r.default.string().optional()})))}(i||(t.Network=i={})),function(e){e.UrlPatternStringSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("string"),pattern:r.default.string()})))}(i||(t.Network=i={})),function(e){e.AddInterceptParametersSchema=r.default.lazy((()=>r.default.object({phases:r.default.array(e.InterceptPhaseSchema),urlPatterns:r.default.array(e.UrlPatternSchema).optional()})))}(i||(t.Network=i={})),function(e){e.AddInterceptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.addIntercept"),params:e.AddInterceptParametersSchema})))}(i||(t.Network=i={})),function(e){e.InterceptPhaseSchema=r.default.lazy((()=>r.default.enum(["beforeRequestSent","responseStarted","authRequired"])))}(i||(t.Network=i={})),function(e){e.AddInterceptResultSchema=r.default.lazy((()=>r.default.object({intercept:e.InterceptSchema})))}(i||(t.Network=i={})),function(e){e.ContinueRequestSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.continueRequest"),params:e.ContinueRequestParametersSchema})))}(i||(t.Network=i={})),function(e){e.ContinueRequestParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,body:e.BytesValueSchema.optional(),cookies:r.default.array(e.CookieHeaderSchema).optional(),headers:r.default.array(e.HeaderSchema).optional(),method:r.default.string().optional(),url:r.default.string().optional()})))}(i||(t.Network=i={})),function(e){e.ContinueResponseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.continueResponse"),params:e.ContinueResponseParametersSchema})))}(i||(t.Network=i={})),function(e){e.ContinueResponseParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,cookies:r.default.array(e.SetCookieHeaderSchema).optional(),credentials:e.AuthCredentialsSchema.optional(),headers:r.default.array(e.HeaderSchema).optional(),reasonPhrase:r.default.string().optional(),statusCode:t.JsUintSchema.optional()})))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.continueWithAuth"),params:e.ContinueWithAuthParametersSchema})))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema}).and(r.default.union([e.ContinueWithAuthCredentialsSchema,e.ContinueWithAuthNoCredentialsSchema]))))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthCredentialsSchema=r.default.lazy((()=>r.default.object({action:r.default.literal("provideCredentials"),credentials:e.AuthCredentialsSchema})))}(i||(t.Network=i={})),function(e){e.ContinueWithAuthNoCredentialsSchema=r.default.lazy((()=>r.default.object({action:r.default.enum(["default","cancel"])})))}(i||(t.Network=i={})),function(e){e.FailRequestSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.failRequest"),params:e.FailRequestParametersSchema})))}(i||(t.Network=i={})),function(e){e.FailRequestParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema})))}(i||(t.Network=i={})),function(e){e.ProvideResponseSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.provideResponse"),params:e.ProvideResponseParametersSchema})))}(i||(t.Network=i={})),function(e){e.ProvideResponseParametersSchema=r.default.lazy((()=>r.default.object({request:e.RequestSchema,body:e.BytesValueSchema.optional(),cookies:r.default.array(e.SetCookieHeaderSchema).optional(),headers:r.default.array(e.HeaderSchema).optional(),reasonPhrase:r.default.string().optional(),statusCode:t.JsUintSchema.optional()})))}(i||(t.Network=i={})),function(e){e.RemoveInterceptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.removeIntercept"),params:e.RemoveInterceptParametersSchema})))}(i||(t.Network=i={})),function(e){e.RemoveInterceptParametersSchema=r.default.lazy((()=>r.default.object({intercept:e.InterceptSchema})))}(i||(t.Network=i={})),t.ScriptEventSchema=r.default.lazy((()=>r.default.union([c.MessageSchema,c.RealmCreatedSchema,c.RealmDestroyedSchema]))),function(e){e.AuthRequiredParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({response:e.ResponseDataSchema}))))}(i||(t.Network=i={})),function(e){e.BeforeRequestSentParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({initiator:e.InitiatorSchema}))))}(i||(t.Network=i={})),function(e){e.FetchErrorParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({errorText:r.default.string()}))))}(i||(t.Network=i={})),function(e){e.ResponseCompletedParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({response:e.ResponseDataSchema}))))}(i||(t.Network=i={})),function(e){e.ResponseStartedParametersSchema=r.default.lazy((()=>e.BaseParametersSchema.and(r.default.object({response:e.ResponseDataSchema}))))}(i||(t.Network=i={})),t.ScriptCommandSchema=r.default.lazy((()=>r.default.union([c.AddPreloadScriptSchema,c.CallFunctionSchema,c.DisownSchema,c.EvaluateSchema,c.GetRealmsSchema,c.RemovePreloadScriptSchema]))),t.ScriptResultSchema=r.default.lazy((()=>r.default.union([c.AddPreloadScriptResultSchema,c.EvaluateResultSchema,c.GetRealmsResultSchema]))),function(e){e.AuthRequiredSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.authRequired"),params:e.AuthRequiredParametersSchema})))}(i||(t.Network=i={})),function(e){e.BeforeRequestSentSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.beforeRequestSent"),params:e.BeforeRequestSentParametersSchema})))}(i||(t.Network=i={})),function(e){e.FetchErrorSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.fetchError"),params:e.FetchErrorParametersSchema})))}(i||(t.Network=i={})),function(e){e.ResponseCompletedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.responseCompleted"),params:e.ResponseCompletedParametersSchema})))}(i||(t.Network=i={})),function(e){e.ResponseStartedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("network.responseStarted"),params:e.ResponseStartedParametersSchema})))}(i||(t.Network=i={})),function(e){e.ChannelSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.EvaluateResultSuccessSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("success"),result:e.RemoteValueSchema,realm:e.RealmSchema})))}(c||(t.Script=c={})),function(e){e.ExceptionDetailsSchema=r.default.lazy((()=>r.default.object({columnNumber:t.JsUintSchema,exception:e.RemoteValueSchema,lineNumber:t.JsUintSchema,stackTrace:e.StackTraceSchema,text:r.default.string()})))}(c||(t.Script=c={})),function(e){e.ChannelValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("channel"),value:e.ChannelPropertiesSchema})))}(c||(t.Script=c={})),function(e){e.ChannelPropertiesSchema=r.default.lazy((()=>r.default.object({channel:e.ChannelSchema,serializationOptions:e.SerializationOptionsSchema.optional(),ownership:e.ResultOwnershipSchema.optional()})))}(c||(t.Script=c={})),function(e){e.EvaluateResultSchema=r.default.lazy((()=>r.default.union([e.EvaluateResultSuccessSchema,e.EvaluateResultExceptionSchema])))}(c||(t.Script=c={})),function(e){e.EvaluateResultExceptionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("exception"),exceptionDetails:e.ExceptionDetailsSchema,realm:e.RealmSchema})))}(c||(t.Script=c={})),function(e){e.HandleSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.InternalIdSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.ListLocalValueSchema=r.default.lazy((()=>r.default.array(e.LocalValueSchema)))}(c||(t.Script=c={})),function(e){e.LocalValueSchema=r.default.lazy((()=>r.default.union([e.RemoteReferenceSchema,e.PrimitiveProtocolValueSchema,e.ChannelValueSchema,e.ArrayLocalValueSchema,e.DateLocalValueSchema,e.MapLocalValueSchema,e.ObjectLocalValueSchema,e.RegExpLocalValueSchema,e.SetLocalValueSchema])))}(c||(t.Script=c={})),function(e){e.ArrayLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("array"),value:e.ListLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.DateLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("date"),value:r.default.string()})))}(c||(t.Script=c={})),function(e){e.MappingLocalValueSchema=r.default.lazy((()=>r.default.array(r.default.tuple([r.default.union([e.LocalValueSchema,r.default.string()]),e.LocalValueSchema]))))}(c||(t.Script=c={})),function(e){e.MapLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("map"),value:e.MappingLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.ObjectLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("object"),value:e.MappingLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.RegExpValueSchema=r.default.lazy((()=>r.default.object({pattern:r.default.string(),flags:r.default.string().optional()})))}(c||(t.Script=c={})),function(e){e.RegExpLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("regexp"),value:e.RegExpValueSchema})))}(c||(t.Script=c={})),function(e){e.SetLocalValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("set"),value:e.ListLocalValueSchema})))}(c||(t.Script=c={})),function(e){e.PreloadScriptSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.RealmSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.PrimitiveProtocolValueSchema=r.default.lazy((()=>r.default.union([e.UndefinedValueSchema,e.NullValueSchema,e.StringValueSchema,e.NumberValueSchema,e.BooleanValueSchema,e.BigIntValueSchema])))}(c||(t.Script=c={})),function(e){e.UndefinedValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("undefined")})))}(c||(t.Script=c={})),function(e){e.NullValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("null")})))}(c||(t.Script=c={})),function(e){e.StringValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("string"),value:r.default.string()})))}(c||(t.Script=c={})),function(e){e.SpecialNumberSchema=r.default.lazy((()=>r.default.enum(["NaN","-0","Infinity","-Infinity"])))}(c||(t.Script=c={})),function(e){e.NumberValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("number"),value:r.default.union([r.default.number(),e.SpecialNumberSchema])})))}(c||(t.Script=c={})),function(e){e.BooleanValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("boolean"),value:r.default.boolean()})))}(c||(t.Script=c={})),function(e){e.BigIntValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("bigint"),value:r.default.string()})))}(c||(t.Script=c={})),function(e){e.RealmInfoSchema=r.default.lazy((()=>r.default.union([e.WindowRealmInfoSchema,e.DedicatedWorkerRealmInfoSchema,e.SharedWorkerRealmInfoSchema,e.ServiceWorkerRealmInfoSchema,e.WorkerRealmInfoSchema,e.PaintWorkletRealmInfoSchema,e.AudioWorkletRealmInfoSchema,e.WorkletRealmInfoSchema])))}(c||(t.Script=c={})),function(e){e.BaseRealmInfoSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema,origin:r.default.string()})))}(c||(t.Script=c={})),function(e){e.WindowRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("window"),context:o.BrowsingContextSchema,sandbox:r.default.string().optional()}))))}(c||(t.Script=c={})),function(e){e.DedicatedWorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("dedicated-worker")}))))}(c||(t.Script=c={})),function(e){e.SharedWorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("shared-worker")}))))}(c||(t.Script=c={})),function(e){e.ServiceWorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("service-worker")}))))}(c||(t.Script=c={})),function(e){e.WorkerRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("worker")}))))}(c||(t.Script=c={})),function(e){e.PaintWorkletRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("paint-worklet")}))))}(c||(t.Script=c={})),function(e){e.AudioWorkletRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("audio-worklet")}))))}(c||(t.Script=c={})),function(e){e.WorkletRealmInfoSchema=r.default.lazy((()=>e.BaseRealmInfoSchema.and(r.default.object({type:r.default.literal("worklet")}))))}(c||(t.Script=c={})),function(e){e.RealmTypeSchema=r.default.lazy((()=>r.default.enum(["window","dedicated-worker","shared-worker","service-worker","worker","paint-worklet","audio-worklet","worklet"])))}(c||(t.Script=c={})),function(e){e.ListRemoteValueSchema=r.default.lazy((()=>r.default.array(e.RemoteValueSchema)))}(c||(t.Script=c={})),function(e){e.MappingRemoteValueSchema=r.default.lazy((()=>r.default.array(r.default.tuple([r.default.union([e.RemoteValueSchema,r.default.string()]),e.RemoteValueSchema]))))}(c||(t.Script=c={})),function(e){e.RemoteValueSchema=r.default.lazy((()=>r.default.union([e.PrimitiveProtocolValueSchema,e.SymbolRemoteValueSchema,e.ArrayRemoteValueSchema,e.ObjectRemoteValueSchema,e.FunctionRemoteValueSchema,e.RegExpRemoteValueSchema,e.DateRemoteValueSchema,e.MapRemoteValueSchema,e.SetRemoteValueSchema,e.WeakMapRemoteValueSchema,e.WeakSetRemoteValueSchema,e.IteratorRemoteValueSchema,e.GeneratorRemoteValueSchema,e.ErrorRemoteValueSchema,e.ProxyRemoteValueSchema,e.PromiseRemoteValueSchema,e.TypedArrayRemoteValueSchema,e.ArrayBufferRemoteValueSchema,e.NodeListRemoteValueSchema,e.HtmlCollectionRemoteValueSchema,e.NodeRemoteValueSchema,e.WindowProxyRemoteValueSchema])))}(c||(t.Script=c={})),function(e){e.RemoteReferenceSchema=r.default.lazy((()=>r.default.union([e.SharedReferenceSchema,e.RemoteObjectReferenceSchema])))}(c||(t.Script=c={})),function(e){e.SharedReferenceSchema=r.default.lazy((()=>r.default.object({sharedId:e.SharedIdSchema,handle:e.HandleSchema.optional()}).and(t.ExtensibleSchema)))}(c||(t.Script=c={})),function(e){e.RemoteObjectReferenceSchema=r.default.lazy((()=>r.default.object({handle:e.HandleSchema,sharedId:e.SharedIdSchema.optional()}).and(t.ExtensibleSchema)))}(c||(t.Script=c={})),function(e){e.SymbolRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("symbol"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ArrayRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("array"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ObjectRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("object"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.MappingRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.FunctionRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("function"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.RegExpRemoteValueSchema=r.default.lazy((()=>r.default.object({handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()}).and(e.RegExpLocalValueSchema)))}(c||(t.Script=c={})),function(e){e.DateRemoteValueSchema=r.default.lazy((()=>r.default.object({handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()}).and(e.DateLocalValueSchema)))}(c||(t.Script=c={})),function(e){e.MapRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("map"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.MappingRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.SetRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("set"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.WeakMapRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("weakmap"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.WeakSetRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("weakset"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.IteratorRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("iterator"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.GeneratorRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("generator"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ErrorRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("error"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ProxyRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("proxy"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.PromiseRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("promise"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.TypedArrayRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("typedarray"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.ArrayBufferRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("arraybuffer"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.NodeListRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("nodelist"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.HtmlCollectionRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("htmlcollection"),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.ListRemoteValueSchema.optional()})))}(c||(t.Script=c={})),function(e){e.NodeRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("node"),sharedId:e.SharedIdSchema.optional(),handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional(),value:e.NodePropertiesSchema.optional()})))}(c||(t.Script=c={})),function(e){e.NodePropertiesSchema=r.default.lazy((()=>r.default.object({nodeType:t.JsUintSchema,childNodeCount:t.JsUintSchema,attributes:r.default.record(r.default.string(),r.default.string()).optional(),children:r.default.array(e.NodeRemoteValueSchema).optional(),localName:r.default.string().optional(),mode:r.default.enum(["open","closed"]).optional(),namespaceURI:r.default.string().optional(),nodeValue:r.default.string().optional(),shadowRoot:r.default.union([e.NodeRemoteValueSchema,r.default.null()]).optional()})))}(c||(t.Script=c={})),function(e){e.WindowProxyRemoteValueSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("window"),value:e.WindowProxyPropertiesSchema,handle:e.HandleSchema.optional(),internalId:e.InternalIdSchema.optional()})))}(c||(t.Script=c={})),function(e){e.WindowProxyPropertiesSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema})))}(c||(t.Script=c={})),function(e){e.ResultOwnershipSchema=r.default.lazy((()=>r.default.enum(["root","none"])))}(c||(t.Script=c={})),function(e){e.SerializationOptionsSchema=r.default.lazy((()=>r.default.object({maxDomDepth:r.default.union([t.JsUintSchema,r.default.null()]).default(0).optional(),maxObjectDepth:r.default.union([t.JsUintSchema,r.default.null()]).default(null).optional(),includeShadowTree:r.default.enum(["none","open","all"]).default("none").optional()})))}(c||(t.Script=c={})),function(e){e.SharedIdSchema=r.default.lazy((()=>r.default.string()))}(c||(t.Script=c={})),function(e){e.StackFrameSchema=r.default.lazy((()=>r.default.object({columnNumber:t.JsUintSchema,functionName:r.default.string(),lineNumber:t.JsUintSchema,url:r.default.string()})))}(c||(t.Script=c={})),function(e){e.StackTraceSchema=r.default.lazy((()=>r.default.object({callFrames:r.default.array(e.StackFrameSchema)})))}(c||(t.Script=c={})),function(e){e.SourceSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema,context:o.BrowsingContextSchema.optional()})))}(c||(t.Script=c={})),function(e){e.RealmTargetSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema})))}(c||(t.Script=c={})),function(e){e.ContextTargetSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema,sandbox:r.default.string().optional()})))}(c||(t.Script=c={})),function(e){e.TargetSchema=r.default.lazy((()=>r.default.union([e.RealmTargetSchema,e.ContextTargetSchema])))}(c||(t.Script=c={})),function(e){e.AddPreloadScriptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.addPreloadScript"),params:e.AddPreloadScriptParametersSchema})))}(c||(t.Script=c={})),function(e){e.AddPreloadScriptParametersSchema=r.default.lazy((()=>r.default.object({functionDeclaration:r.default.string(),arguments:r.default.array(e.ChannelValueSchema).optional(),contexts:r.default.array(o.BrowsingContextSchema).optional(),sandbox:r.default.string().optional()})))}(c||(t.Script=c={})),function(e){e.AddPreloadScriptResultSchema=r.default.lazy((()=>r.default.object({script:e.PreloadScriptSchema})))}(c||(t.Script=c={})),function(e){e.DisownSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.disown"),params:e.DisownParametersSchema})))}(c||(t.Script=c={})),function(e){e.DisownParametersSchema=r.default.lazy((()=>r.default.object({handles:r.default.array(e.HandleSchema),target:e.TargetSchema})))}(c||(t.Script=c={})),function(e){e.CallFunctionParametersSchema=r.default.lazy((()=>r.default.object({functionDeclaration:r.default.string(),awaitPromise:r.default.boolean(),target:e.TargetSchema,arguments:r.default.array(e.LocalValueSchema).optional(),resultOwnership:e.ResultOwnershipSchema.optional(),serializationOptions:e.SerializationOptionsSchema.optional(),this:e.LocalValueSchema.optional(),userActivation:r.default.boolean().default(!1).optional()})))}(c||(t.Script=c={})),function(e){e.CallFunctionSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.callFunction"),params:e.CallFunctionParametersSchema})))}(c||(t.Script=c={})),function(e){e.EvaluateSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.evaluate"),params:e.EvaluateParametersSchema})))}(c||(t.Script=c={})),function(e){e.EvaluateParametersSchema=r.default.lazy((()=>r.default.object({expression:r.default.string(),target:e.TargetSchema,awaitPromise:r.default.boolean(),resultOwnership:e.ResultOwnershipSchema.optional(),serializationOptions:e.SerializationOptionsSchema.optional(),userActivation:r.default.boolean().default(!1).optional()})))}(c||(t.Script=c={})),function(e){e.GetRealmsSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.getRealms"),params:e.GetRealmsParametersSchema})))}(c||(t.Script=c={})),function(e){e.GetRealmsParametersSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema.optional(),type:e.RealmTypeSchema.optional()})))}(c||(t.Script=c={})),function(e){e.GetRealmsResultSchema=r.default.lazy((()=>r.default.object({realms:r.default.array(e.RealmInfoSchema)})))}(c||(t.Script=c={})),function(e){e.RemovePreloadScriptSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.removePreloadScript"),params:e.RemovePreloadScriptParametersSchema})))}(c||(t.Script=c={})),function(e){e.RemovePreloadScriptParametersSchema=r.default.lazy((()=>r.default.object({script:e.PreloadScriptSchema})))}(c||(t.Script=c={})),function(e){e.MessageParametersSchema=r.default.lazy((()=>r.default.object({channel:e.ChannelSchema,data:e.RemoteValueSchema,source:e.SourceSchema})))}(c||(t.Script=c={})),function(e){e.RealmCreatedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.realmCreated"),params:e.RealmInfoSchema})))}(c||(t.Script=c={})),function(e){e.MessageSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.message"),params:e.MessageParametersSchema})))}(c||(t.Script=c={})),function(e){e.RealmDestroyedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("script.realmDestroyed"),params:e.RealmDestroyedParametersSchema})))}(c||(t.Script=c={})),function(e){e.RealmDestroyedParametersSchema=r.default.lazy((()=>r.default.object({realm:e.RealmSchema})))}(c||(t.Script=c={})),t.LogEventSchema=r.default.lazy((()=>d.EntryAddedSchema)),function(e){e.LevelSchema=r.default.lazy((()=>r.default.enum(["debug","info","warn","error"])))}(d||(t.Log=d={})),function(e){e.EntrySchema=r.default.lazy((()=>r.default.union([e.GenericLogEntrySchema,e.ConsoleLogEntrySchema,e.JavascriptLogEntrySchema])))}(d||(t.Log=d={})),function(e){e.BaseLogEntrySchema=r.default.lazy((()=>r.default.object({level:e.LevelSchema,source:c.SourceSchema,text:r.default.union([r.default.string(),r.default.null()]),timestamp:t.JsUintSchema,stackTrace:c.StackTraceSchema.optional()})))}(d||(t.Log=d={})),function(e){e.GenericLogEntrySchema=r.default.lazy((()=>e.BaseLogEntrySchema.and(r.default.object({type:r.default.string()}))))}(d||(t.Log=d={})),function(e){e.ConsoleLogEntrySchema=r.default.lazy((()=>e.BaseLogEntrySchema.and(r.default.object({type:r.default.literal("console"),method:r.default.string(),args:r.default.array(c.RemoteValueSchema)}))))}(d||(t.Log=d={})),function(e){e.JavascriptLogEntrySchema=r.default.lazy((()=>e.BaseLogEntrySchema.and(r.default.object({type:r.default.literal("javascript")}))))}(d||(t.Log=d={})),function(e){e.EntryAddedSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("log.entryAdded"),params:e.EntrySchema})))}(d||(t.Log=d={})),t.InputCommandSchema=r.default.lazy((()=>r.default.union([u.PerformActionsSchema,u.ReleaseActionsSchema]))),function(e){e.ElementOriginSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("element"),element:c.SharedReferenceSchema})))}(u||(t.Input=u={})),function(e){e.PerformActionsParametersSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema,actions:r.default.array(e.SourceActionsSchema)})))}(u||(t.Input=u={})),function(e){e.NoneSourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("none"),id:r.default.string(),actions:r.default.array(e.NoneSourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.KeySourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("key"),id:r.default.string(),actions:r.default.array(e.KeySourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.PointerSourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointer"),id:r.default.string(),parameters:e.PointerParametersSchema.optional(),actions:r.default.array(e.PointerSourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.PerformActionsSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("input.performActions"),params:e.PerformActionsParametersSchema})))}(u||(t.Input=u={})),function(e){e.SourceActionsSchema=r.default.lazy((()=>r.default.union([e.NoneSourceActionsSchema,e.KeySourceActionsSchema,e.PointerSourceActionsSchema,e.WheelSourceActionsSchema])))}(u||(t.Input=u={})),function(e){e.NoneSourceActionSchema=r.default.lazy((()=>e.PauseActionSchema))}(u||(t.Input=u={})),function(e){e.KeySourceActionSchema=r.default.lazy((()=>r.default.union([e.PauseActionSchema,e.KeyDownActionSchema,e.KeyUpActionSchema])))}(u||(t.Input=u={})),function(e){e.PointerTypeSchema=r.default.lazy((()=>r.default.enum(["mouse","pen","touch"])))}(u||(t.Input=u={})),function(e){e.PointerParametersSchema=r.default.lazy((()=>r.default.object({pointerType:e.PointerTypeSchema.default("mouse").optional()})))}(u||(t.Input=u={})),function(e){e.WheelSourceActionsSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("wheel"),id:r.default.string(),actions:r.default.array(e.WheelSourceActionSchema)})))}(u||(t.Input=u={})),function(e){e.PointerSourceActionSchema=r.default.lazy((()=>r.default.union([e.PauseActionSchema,e.PointerDownActionSchema,e.PointerUpActionSchema,e.PointerMoveActionSchema])))}(u||(t.Input=u={})),function(e){e.WheelSourceActionSchema=r.default.lazy((()=>r.default.union([e.PauseActionSchema,e.WheelScrollActionSchema])))}(u||(t.Input=u={})),function(e){e.PauseActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pause"),duration:t.JsUintSchema.optional()})))}(u||(t.Input=u={})),function(e){e.KeyDownActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("keyDown"),value:r.default.string()})))}(u||(t.Input=u={})),function(e){e.KeyUpActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("keyUp"),value:r.default.string()})))}(u||(t.Input=u={})),function(e){e.PointerUpActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointerUp"),button:t.JsUintSchema}).and(e.PointerCommonPropertiesSchema)))}(u||(t.Input=u={})),function(e){e.PointerDownActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointerDown"),button:t.JsUintSchema}).and(e.PointerCommonPropertiesSchema)))}(u||(t.Input=u={})),function(e){e.PointerMoveActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("pointerMove"),x:t.JsIntSchema,y:t.JsIntSchema,duration:t.JsUintSchema.optional(),origin:e.OriginSchema.optional()}).and(e.PointerCommonPropertiesSchema)))}(u||(t.Input=u={})),function(e){e.WheelScrollActionSchema=r.default.lazy((()=>r.default.object({type:r.default.literal("scroll"),x:t.JsIntSchema,y:t.JsIntSchema,deltaX:t.JsIntSchema,deltaY:t.JsIntSchema,duration:t.JsUintSchema.optional(),origin:e.OriginSchema.default("viewport").optional()})))}(u||(t.Input=u={})),function(e){e.PointerCommonPropertiesSchema=r.default.lazy((()=>r.default.object({width:t.JsUintSchema.default(1).optional(),height:t.JsUintSchema.default(1).optional(),pressure:r.default.number().default(0).optional(),tangentialPressure:r.default.number().default(0).optional(),twist:r.default.number().int().nonnegative().gte(0).lte(359).default(0).optional(),altitudeAngle:r.default.number().gte(0).lte(1.5707963267948966).default(0).optional(),azimuthAngle:r.default.number().gte(0).lte(6.283185307179586).default(0).optional()})))}(u||(t.Input=u={})),function(e){e.OriginSchema=r.default.lazy((()=>r.default.union([r.default.literal("viewport"),r.default.literal("pointer"),e.ElementOriginSchema])))}(u||(t.Input=u={})),function(e){e.ReleaseActionsSchema=r.default.lazy((()=>r.default.object({method:r.default.literal("input.releaseActions"),params:e.ReleaseActionsParametersSchema})))}(u||(t.Input=u={})),function(e){e.ReleaseActionsParametersSchema=r.default.lazy((()=>r.default.object({context:o.BrowsingContextSchema})))}(u||(t.Input=u={}))}(Yr);var Qr=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,r,n)}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),en=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),tn=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&Qr(t,e,a);return en(t,e),t};Object.defineProperty(Or,"__esModule",{value:!0}),Or.Cdp=Or.Input=Or.Session=Or.BrowsingContext=Or.Script=Or.Network=Or.parseObject=void 0;const an=Mr,rn=g,nn=tn(Yr);function sn(e,t){const a=t.safeParse(e);if(a.success)return a.data;const r=a.error.errors.map((e=>`${e.message} in ${e.path.map((e=>JSON.stringify(e))).join("/")}.`)).join(" ");throw new rn.InvalidArgumentException(r)}var on,cn,dn,un,ln,hn;Or.parseObject=sn,function(e){e.parseAddInterceptParameters=function(e){return sn(e,nn.Network.AddInterceptParametersSchema)},e.parseContinueRequestParameters=function(e){return sn(e,nn.Network.ContinueRequestParametersSchema)},e.parseContinueResponseParameters=function(e){return sn(e,nn.Network.ContinueResponseParametersSchema)},e.parseContinueWithAuthParameters=function(e){return sn(e,nn.Network.ContinueWithAuthParametersSchema)},e.parseFailRequestParameters=function(e){return sn(e,nn.Network.FailRequestParametersSchema)},e.parseProvideResponseParameters=function(e){return sn(e,nn.Network.ProvideResponseParametersSchema)},e.parseRemoveInterceptParameters=function(e){return sn(e,nn.Network.RemoveInterceptParametersSchema)}}(on||(Or.Network=on={})),function(e){e.parseGetRealmsParams=function(e){return sn(e,nn.Script.GetRealmsParametersSchema)},e.parseEvaluateParams=function(e){return sn(e,nn.Script.EvaluateParametersSchema)},e.parseDisownParams=function(e){return sn(e,nn.Script.DisownParametersSchema)},e.parseAddPreloadScriptParams=function(e){return sn(e,nn.Script.AddPreloadScriptParametersSchema)},e.parseRemovePreloadScriptParams=function(e){return sn(e,nn.Script.RemovePreloadScriptParametersSchema)},e.parseCallFunctionParams=function(e){return sn(e,nn.Script.CallFunctionParametersSchema)}}(cn||(Or.Script=cn={})),function(e){e.parseActivateParams=function(e){return sn(e,nn.BrowsingContext.ActivateParametersSchema)},e.parseGetTreeParams=function(e){return sn(e,nn.BrowsingContext.GetTreeParametersSchema)},e.parseNavigateParams=function(e){return sn(e,nn.BrowsingContext.NavigateParametersSchema)},e.parseReloadParams=function(e){return sn(e,nn.BrowsingContext.ReloadParametersSchema)},e.parseCreateParams=function(e){return sn(e,nn.BrowsingContext.CreateParametersSchema)},e.parseCloseParams=function(e){return sn(e,nn.BrowsingContext.CloseParametersSchema)},e.parseCaptureScreenshotParams=function(e){return sn(e,nn.BrowsingContext.CaptureScreenshotParametersSchema)},e.parsePrintParams=function(e){return sn(e,nn.BrowsingContext.PrintParametersSchema)},e.parseSetViewportParams=function(e){return sn(e,nn.BrowsingContext.SetViewportParametersSchema)},e.parseTraverseHistoryParams=function(e){return sn(e,nn.BrowsingContext.TraverseHistoryParametersSchema)},e.parseHandleUserPromptParameters=function(e){return sn(e,nn.BrowsingContext.HandleUserPromptParametersSchema)}}(dn||(Or.BrowsingContext=dn={})),function(e){e.parseSubscribeParams=function(e){return sn(e,nn.Session.SubscriptionRequestSchema)}}(un||(Or.Session=un={})),function(e){e.parsePerformActionsParams=function(e){return sn(e,nn.Input.PerformActionsParametersSchema)},e.parseReleaseActionsParams=function(e){return sn(e,nn.Input.ReleaseActionsParametersSchema)}}(ln||(Or.Input=ln={})),function(e){const t=an.z.object({method:an.z.string(),params:an.z.object({}).passthrough().optional(),session:an.z.string().optional()}),a=an.z.object({context:nn.BrowsingContext.BrowsingContextSchema});e.parseSendCommandRequest=function(e){return sn(e,t)},e.parseGetSessionRequest=function(e){return sn(e,a)}}(hn||(Or.Cdp=hn={}));var pn=e&&e.__createBinding||(Object.create?function(e,t,a,r){void 0===r&&(r=a);var n=Object.getOwnPropertyDescriptor(t,a);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,r,n)}:function(e,t,a,r){void 0===r&&(r=a),e[r]=t[a]}),mn=e&&e.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),fn=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&pn(t,e,a);return mn(t,e),t};Object.defineProperty(jr,"__esModule",{value:!0}),jr.BidiParser=void 0;const gn=fn(Or);jr.BidiParser=class{parseActivateParams(e){return gn.BrowsingContext.parseActivateParams(e)}parseCaptureScreenshotParams(e){return gn.BrowsingContext.parseCaptureScreenshotParams(e)}parseCloseParams(e){return gn.BrowsingContext.parseCloseParams(e)}parseCreateParams(e){return gn.BrowsingContext.parseCreateParams(e)}parseGetTreeParams(e){return gn.BrowsingContext.parseGetTreeParams(e)}parseHandleUserPromptParams(e){return gn.BrowsingContext.parseHandleUserPromptParameters(e)}parseNavigateParams(e){return gn.BrowsingContext.parseNavigateParams(e)}parsePrintParams(e){return gn.BrowsingContext.parsePrintParams(e)}parseReloadParams(e){return gn.BrowsingContext.parseReloadParams(e)}parseSetViewportParams(e){return gn.BrowsingContext.parseSetViewportParams(e)}parseTraverseHistoryParams(e){return gn.BrowsingContext.parseTraverseHistoryParams(e)}parseGetSessionParams(e){return gn.Cdp.parseGetSessionRequest(e)}parseSendCommandParams(e){return gn.Cdp.parseSendCommandRequest(e)}parsePerformActionsParams(e){return gn.Input.parsePerformActionsParams(e)}parseReleaseActionsParams(e){return gn.Input.parseReleaseActionsParams(e)}parseAddInterceptParams(e){return gn.Network.parseAddInterceptParameters(e)}parseContinueRequestParams(e){return gn.Network.parseContinueRequestParameters(e)}parseContinueResponseParams(e){return gn.Network.parseContinueResponseParameters(e)}parseContinueWithAuthParams(e){return gn.Network.parseContinueWithAuthParameters(e)}parseFailRequestParams(e){return gn.Network.parseFailRequestParameters(e)}parseProvideResponseParams(e){return gn.Network.parseProvideResponseParameters(e)}parseRemoveInterceptParams(e){return gn.Network.parseRemoveInterceptParameters(e)}parseAddPreloadScriptParams(e){return gn.Script.parseAddPreloadScriptParams(e)}parseCallFunctionParams(e){return gn.Script.parseCallFunctionParams(e)}parseDisownParams(e){return gn.Script.parseDisownParams(e)}parseEvaluateParams(e){return gn.Script.parseEvaluateParams(e)}parseGetRealmsParams(e){return gn.Script.parseGetRealmsParams(e)}parseRemovePreloadScriptParams(e){return gn.Script.parseRemovePreloadScriptParams(e)}parseSubscribeParams(e){return gn.Session.parseSubscribeParams(e)}};var yn={};Object.defineProperty(yn,"__esModule",{value:!0}),yn.log=yn.generatePage=void 0;const Sn=l;function vn(e){const t=e.split(":")[0],a=`${t}_log`,r=document.getElementById(a);if(r)return r;const n=document.getElementById("details"),s=document.createElement("div");s.className="divider",n.appendChild(s);const o=document.createElement("div");return o.className="item",o.innerHTML=`<h3>${t}</h3><div id="${a}" class="log"></div>`,n.appendChild(o),document.getElementById(a)}function wn(e){return"object"==typeof e?JSON.stringify(e,null,2):e}yn.generatePage=function(){globalThis.document.documentElement&&(globalThis.document.documentElement.innerHTML='<!DOCTYPE html><title>BiDi-CDP Mapper</title><style>body{font-family: Roboto, serif; font-size: 13px; color: #202124;}.log{padding: 12px; font-family: Menlo, Consolas, Monaco, Liberation Mono, Lucida Console, monospace; font-size: 11px; line-height: 180%; background: #f1f3f4; border-radius: 4px;}.pre{overflow-wrap: break-word; padding: 10px;}.card{margin: 60px auto; padding: 2px 0; max-width: 900px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15), 0 1px 6px rgba(0, 0, 0, 0.2); border-radius: 8px;}.divider{height: 1px; background: #f0f0f0;}.item{padding: 16px 20px;}</style><div class="card"><div class="item"><h1>BiDi-CDP Mapper is controlling this tab</h1><p>Closing or reloading it will stop the BiDi process. <a target="_blank" title="BiDi-CDP Mapper GitHub Repository" href="https://github.com/GoogleChromeLabs/chromium-bidi">Details.</a></p></div><div class="divider"></div><details id="details"><summary class="item">Debug information</summary></details></div>',vn(Sn.LogType.debugInfo),vn(Sn.LogType.bidi),vn(Sn.LogType.cdp))},yn.log=function(t,...a){if(!globalThis.document.documentElement)return;t.startsWith(Sn.LogType.bidi)||e.window?.sendDebugMessage?.(JSON.stringify({logType:t,messages:a}));const r=vn(t),n=document.createElement("div");n.className="pre",n.textContent=[t,...a].map(wn).join(" "),r.appendChild(n)};var bn={};Object.defineProperty(bn,"__esModule",{value:!0}),bn.WindowCdpTransport=bn.WindowBidiTransport=void 0;const Cn=l,xn=yn;class In{static LOGGER_PREFIX_RECV=`${Cn.LogType.bidi}:RECV \u25c2`;static LOGGER_PREFIX_SEND=`${Cn.LogType.bidi}:SEND \u25b8`;#Qa=null;constructor(){window.onBidiMessage=e=>{(0,xn.log)(In.LOGGER_PREFIX_RECV,e);try{const t=In.#tr(e);this.#Qa?.call(null,t)}catch(t){const a=t instanceof Error?t:new Error(t);this.#ar(e,"invalid argument",a,null)}}}setOnMessage(e){this.#Qa=e}sendMessage(e){(0,xn.log)(In.LOGGER_PREFIX_SEND,e);const t=JSON.stringify(e);window.sendBidiResponse(t)}close(){this.#Qa=null,window.onBidiMessage=null}#ar(e,t,a,r){const n=In.#rr(e,t,a);r?this.sendMessage({...n,channel:r}):this.sendMessage(n)}static#nr(e){return null===e?"null":Array.isArray(e)?"array":typeof e}static#rr(e,t,a){let r;try{const t=JSON.parse(e);"object"===In.#nr(t)&&"id"in t&&(r=t.id)}catch{}return{type:"error",id:r,error:t,message:a.message}}static#tr(e){let t;try{t=JSON.parse(e)}catch{throw new Error("Cannot parse data as JSON")}const a=In.#nr(t);if("object"!==a)throw new Error(`Expected JSON object but got ${a}`);const{id:r,method:n,params:s}=t,o=In.#nr(r);if("number"!==o||!Number.isInteger(r)||r<0)throw new Error(`Expected unsigned integer but got ${o}`);const i=In.#nr(n);if("string"!==i)throw new Error(`Expected string method but got ${i}`);const c=In.#nr(s);if("object"!==c)throw new Error(`Expected object params but got ${c}`);let d=t.channel;if(void 0!==d){const e=In.#nr(d);if("string"!==e)throw new Error(`Expected string channel but got ${e}`);""===d&&(d=void 0)}return{id:r,method:n,params:s,channel:d}}}bn.WindowBidiTransport=In;bn.WindowCdpTransport=class{#Qa=null;constructor(){window.cdp.onmessage=e=>{this.#Qa?.call(null,e)}}setOnMessage(e){this.#Qa=e}sendMessage(e){window.cdp.send(e)}close(){this.#Qa=null,window.cdp.onmessage=null}}, /** * Copyright 2021 Google LLC. * Copyright (c) Microsoft Corporation. @@ -17,5 +17,5 @@ * * @license */ -Object.defineProperty(a,"__esModule",{value:!0});const In=r,Pn=xr,kn=l,Rn=Nr,_n=gn,En=wn;(0,_n.generatePage)();const Tn=new En.WindowBidiTransport,Nn=new En.WindowCdpTransport,jn=new Pn.CdpConnection(Nn,_n.log);async function On(e){console.log("Launching Mapper instance with selfTargetId:",e);const t=await In.BidiServer.createAndStart(Tn,jn,await jn.createBrowserSession(),e,new Rn.BidiParser,_n.log);return(0,_n.log)(kn.LogType.debugInfo,"Mapper instance has been launched"),t}return window.runMapperInstance=async e=>{await On(e)},window.setSelfTargetId=async e=>{(await On(e)).emitOutgoingMessage(In.OutgoingMessage.createResolved({launched:!0}),"launched")},a}(); +Object.defineProperty(a,"__esModule",{value:!0});const Pn=r,kn=Ir,Rn=l,En=jr,_n=yn,Tn=bn;(0,_n.generatePage)();const Nn=new Tn.WindowBidiTransport,jn=new Tn.WindowCdpTransport,On=new kn.CdpConnection(jn,_n.log);async function Mn(e,t){console.log("Launching Mapper instance with selfTargetId:",e);const a=await Pn.BidiServer.createAndStart(Nn,On,await On.createBrowserSession(),e,t,new En.BidiParser,_n.log);return(0,_n.log)(Rn.LogType.debugInfo,"Mapper instance has been launched"),a}return window.runMapperInstance=async(e,t)=>{await Mn(e,t)},window.setSelfTargetId=async e=>{(await Mn(e)).emitOutgoingMessage(Pn.OutgoingMessage.createResolved({launched:!0}),"launched")},a}(); //# sourceMappingURL=mapperTab.js.map
diff --git a/third_party/blink/common/mediastream/media_devices.cc b/third_party/blink/common/mediastream/media_devices.cc index 1bf395a9..f15f1fe0 100644 --- a/third_party/blink/common/mediastream/media_devices.cc +++ b/third_party/blink/common/mediastream/media_devices.cc
@@ -19,19 +19,22 @@ const std::string& label, const std::string& group_id, const media::VideoCaptureControlSupport& video_control_support, - blink::mojom::FacingMode video_facing) + blink::mojom::FacingMode video_facing, + absl::optional<media::CameraAvailability> availability) : device_id(device_id), label(label), group_id(group_id), video_control_support(video_control_support), - video_facing(video_facing) {} + video_facing(video_facing), + availability(std::move(availability)) {} WebMediaDeviceInfo::WebMediaDeviceInfo( const media::VideoCaptureDeviceDescriptor& descriptor) : device_id(descriptor.device_id), label(descriptor.GetNameAndModel()), video_control_support(descriptor.control_support()), - video_facing(static_cast<blink::mojom::FacingMode>(descriptor.facing)) {} + video_facing(static_cast<blink::mojom::FacingMode>(descriptor.facing)), + availability(descriptor.availability) {} WebMediaDeviceInfo::~WebMediaDeviceInfo() = default;
diff --git a/third_party/blink/public/common/mediastream/media_devices.h b/third_party/blink/public/common/mediastream/media_devices.h index bd77571..c23744c 100644 --- a/third_party/blink/public/common/mediastream/media_devices.h +++ b/third_party/blink/public/common/mediastream/media_devices.h
@@ -25,18 +25,25 @@ const std::string& group_id, const media::VideoCaptureControlSupport& video_control_support = media::VideoCaptureControlSupport(), - blink::mojom::FacingMode video_facing = blink::mojom::FacingMode::kNone); + blink::mojom::FacingMode video_facing = blink::mojom::FacingMode::kNone, + absl::optional<media::CameraAvailability> availability = absl::nullopt); explicit WebMediaDeviceInfo( const media::VideoCaptureDeviceDescriptor& descriptor); ~WebMediaDeviceInfo(); WebMediaDeviceInfo& operator=(const WebMediaDeviceInfo& other); WebMediaDeviceInfo& operator=(WebMediaDeviceInfo&& other); + bool IsAvailable() const { + return !availability || + *availability == media::CameraAvailability::kAvailable; + } + std::string device_id; std::string label; std::string group_id; media::VideoCaptureControlSupport video_control_support; blink::mojom::FacingMode video_facing = blink::mojom::FacingMode::kNone; + absl::optional<media::CameraAvailability> availability; }; using WebMediaDeviceInfoArray = std::vector<WebMediaDeviceInfo>;
diff --git a/third_party/blink/public/mojom/mediastream/media_devices.mojom b/third_party/blink/public/mojom/mediastream/media_devices.mojom index 986b7669..080a692 100644 --- a/third_party/blink/public/mojom/mediastream/media_devices.mojom +++ b/third_party/blink/public/mojom/mediastream/media_devices.mojom
@@ -34,6 +34,7 @@ media.mojom.VideoCaptureControlSupport control_support; array<media.mojom.VideoCaptureFormat> formats; FacingMode facing_mode; + media.mojom.CameraAvailability? availability; }; struct AudioInputDeviceCapabilities {
diff --git a/third_party/blink/renderer/core/css/parser/css_variable_parser.cc b/third_party/blink/renderer/core/css/parser/css_variable_parser.cc index b261fde..ccb0ef0 100644 --- a/third_party/blink/renderer/core/css/parser/css_variable_parser.cc +++ b/third_party/blink/renderer/core/css/parser/css_variable_parser.cc
@@ -4,6 +4,7 @@ #include "third_party/blink/renderer/core/css/parser/css_variable_parser.h" +#include "base/containers/contains.h" #include "third_party/blink/renderer/core/css/css_custom_property_declaration.h" #include "third_party/blink/renderer/core/css/css_variable_reference_value.h" #include "third_party/blink/renderer/core/css/parser/css_parser_token_range.h" @@ -288,8 +289,7 @@ // (i.e. not CSSOM, where we just get a string), we know we can't // have unfinished comments, so consider piping that knowledge all // the way through here. - if (text.Is8Bit() && - memchr(text.Characters8(), '/', text.length()) == nullptr) { + if (text.Is8Bit() && !base::Contains(text.Span8(), '/')) { // No comments, so we can strip whitespace only. while (!text.empty() && IsHTMLSpace(text[text.length() - 1])) { text = StringView(text, 0, text.length() - 1);
diff --git a/third_party/blink/renderer/core/css/resolver/style_cascade.cc b/third_party/blink/renderer/core/css/resolver/style_cascade.cc index bf99c180..9fa9775 100644 --- a/third_party/blink/renderer/core/css/resolver/style_cascade.cc +++ b/third_party/blink/renderer/core/css/resolver/style_cascade.cc
@@ -1091,8 +1091,7 @@ builder.Append(value.CustomCSSText()); builder.Append(")"); - LOG(DFATAL) << builder.ToString(); - NOTREACHED(); + DUMP_WILL_BE_NOTREACHED_NORETURN() << builder.ToString(); return cssvalue::CSSUnsetValue::Create(); }
diff --git a/third_party/blink/renderer/core/css/resolver/style_resolver.cc b/third_party/blink/renderer/core/css/resolver/style_resolver.cc index 6cf9855..af13e77b 100644 --- a/third_party/blink/renderer/core/css/resolver/style_resolver.cc +++ b/third_party/blink/renderer/core/css/resolver/style_resolver.cc
@@ -146,10 +146,10 @@ // position-fallback, we can fall back to the default behavior (in // CSSAnimations) of using the current style on Element as the old style. // - // TODO(futhark): We also need to check whether we are a descendant of an - // element with position-fallback to cover the case where the descendant - // explicitly inherits insets or other valid @try properties from the - // element with position-fallback. + // TODO(crbug.com/1502666): We also need to check whether we are a descendant + // of an element with position-fallback to cover the case where the descendant + // explicitly inherits insets or other valid @try properties from the element + // with position-fallback. return (style_recalc_context.container || style_recalc_context.position_fallback || (RuntimeEnabledFeatures:: @@ -2150,9 +2150,14 @@ if (!cached_matched_properties) { return false; } - return !base::ValuesEquivalent( - cached_matched_properties->computed_style->InheritedVariables(), - builder.InheritedVariables()); + if (RuntimeEnabledFeatures::CSSMPCImprovementsEnabled()) { + return !base::ValuesEquivalent( + cached_matched_properties->computed_style->InheritedVariables(), + builder.InheritedVariables()); + } else { + return cached_matched_properties->computed_style->InheritedVariables() != + builder.InheritedVariables(); + } } bool StyleResolver::CacheSuccess::LineHeightChanged( @@ -2289,7 +2294,8 @@ const MatchResult& match_result) { state.LoadPendingResources(); - // NOTE: We replace everything that isn't a full cache hit. There are cases + // NOTE: We replace everything that isn't a full cache hit (unless the + // CSSMPCImprovements runtime flag has been disabled). There are cases // where this would be bad (e.g., every other element we style with the same // key has a different parent computed style), but it seems a much more common // case, if we don't replace elements giving partial hits, is that a @@ -2297,7 +2303,9 @@ // from there because it's never replaced. (Or, similarly, a partial // hit where we have to reapply the inherited properties, or where we trash // the “partner cache” in StyleInheritedVariables.) - if (cache_success.key.IsValid() && + if ((RuntimeEnabledFeatures::CSSMPCImprovementsEnabled() || + !cache_success.cached_matched_properties) && + cache_success.key.IsValid() && MatchedPropertiesCache::IsCacheable(state)) { INCREMENT_STYLE_STATS_COUNTER(GetDocument().GetStyleEngine(), matched_property_cache_added, 1);
diff --git a/third_party/blink/renderer/core/dom/element.cc b/third_party/blink/renderer/core/dom/element.cc index 7cff4c97..35b3a02 100644 --- a/third_party/blink/renderer/core/dom/element.cc +++ b/third_party/blink/renderer/core/dom/element.cc
@@ -505,7 +505,7 @@ bool WillUpdateSizeContainerDuringLayout(const LayoutObject& layout_object) { // When a size-container LayoutObject is marked as needs layout, - // NGBlockNode::Layout() will resume style recalc with an up-to-date size in + // BlockNode::Layout() will resume style recalc with an up-to-date size in // StyleEngine::UpdateStyleAndLayoutTreeForContainer(). return layout_object.NeedsLayout() && layout_object.IsEligibleForSizeContainment(); @@ -3182,7 +3182,8 @@ style = context->AdjustElementStyle(style); } - if (style->DependsOnSizeContainerQueries()) { + // TODO(crbug.com/1502666): Descendants can also depend on position-fallback. + if (style->DependsOnSizeContainerQueries() || style->PositionFallback()) { GetDocument().GetStyleEngine().SetStyleAffectedByLayout(); }
diff --git a/third_party/blink/renderer/core/editing/editing_utilities.cc b/third_party/blink/renderer/core/editing/editing_utilities.cc index 50deda2a..101a8a60 100644 --- a/third_party/blink/renderer/core/editing/editing_utilities.cc +++ b/third_party/blink/renderer/core/editing/editing_utilities.cc
@@ -1444,12 +1444,14 @@ if (!node) return false; LayoutObject* layout_object = node->GetLayoutObject(); + if (!layout_object) { + return false; + } bool is_hr = RuntimeEnabledFeatures::RubyInlinifyEnabled() ? (layout_object->IsHR() && !layout_object->IsInline()) : layout_object->IsHR(); - return layout_object && - ((layout_object->IsTable() && !layout_object->IsInline()) || - (layout_object->IsImage() && !layout_object->IsInline()) || is_hr); + return (layout_object->IsTable() && !layout_object->IsInline()) || + (layout_object->IsImage() && !layout_object->IsInline()) || is_hr; } bool IsNonTableCellHTMLBlockElement(const Node* node) {
diff --git a/third_party/blink/renderer/core/editing/editing_utilities.h b/third_party/blink/renderer/core/editing/editing_utilities.h index e47a705..e549562 100644 --- a/third_party/blink/renderer/core/editing/editing_utilities.h +++ b/third_party/blink/renderer/core/editing/editing_utilities.h
@@ -177,7 +177,7 @@ bool IsListItemTag(const Node*); bool IsListElementTag(const Node*); bool IsPresentationalHTMLElement(const Node*); -bool IsRenderedAsNonInlineTableImageOrHR(const Node*); +CORE_EXPORT bool IsRenderedAsNonInlineTableImageOrHR(const Node*); bool IsNonTableCellHTMLBlockElement(const Node*); bool IsBlockFlowElement(const Node&); bool IsInPasswordField(const Position&);
diff --git a/third_party/blink/renderer/core/editing/editing_utilities_test.cc b/third_party/blink/renderer/core/editing/editing_utilities_test.cc index 2aef62f..9afead3 100644 --- a/third_party/blink/renderer/core/editing/editing_utilities_test.cc +++ b/third_party/blink/renderer/core/editing/editing_utilities_test.cc
@@ -1088,4 +1088,11 @@ PositionMoveType::kBackwardDeletion)); } +// crbug.com/1503530 +TEST_F(EditingUtilitiesTest, IsRenderedAsNonInlineTableImageOrHR) { + SetBodyContent("<p id='target' hidden></p>"); + IsRenderedAsNonInlineTableImageOrHR(GetElementById("target")); + // Pass if no crash. +} + } // namespace blink
diff --git a/third_party/blink/renderer/core/frame/local_frame_view.h b/third_party/blink/renderer/core/frame/local_frame_view.h index 316f5b9..88dd206 100644 --- a/third_party/blink/renderer/core/frame/local_frame_view.h +++ b/third_party/blink/renderer/core/frame/local_frame_view.h
@@ -186,7 +186,7 @@ unsigned LayoutCountForTesting() const { return layout_count_for_testing_; } // Returns the number of block layout calls. - // * It's incremented when NGBlockNode::Layout() is called with NeedsLayout() + // * It's incremented when BlockNode::Layout() is called with NeedsLayout() // * It can overflow. Do not use it in production. uint32_t BlockLayoutCountForTesting() const { return block_layout_count_for_testing_;
diff --git a/third_party/blink/renderer/core/frame/web_frame_test.cc b/third_party/blink/renderer/core/frame/web_frame_test.cc index 0c89407..f84d5509 100644 --- a/third_party/blink/renderer/core/frame/web_frame_test.cc +++ b/third_party/blink/renderer/core/frame/web_frame_test.cc
@@ -6610,9 +6610,9 @@ v8::Array& expected_result = *v8::Array::Cast(*result); ASSERT_GE(expected_result.Length(), 10u); - v8::Local<v8::Context> context = web_view_helper_.GetAgentGroupScheduler() - .Isolate() - ->GetCurrentContext(); + v8::Local<v8::Context> context = + expected_result.GetCreationContext().ToLocalChecked(); + v8::Context::Scope v8_context_scope(context); int start_edge_start_in_layer_x = expected_result.Get(context, 1) .ToLocalChecked()
diff --git a/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc b/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc index 4bbc6ae..310934f 100644 --- a/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc +++ b/third_party/blink/renderer/core/layout/custom/css_layout_definition.cc
@@ -38,12 +38,12 @@ namespace { -void GatherChildren(const NGBlockNode& node, +void GatherChildren(const BlockNode& node, CustomLayoutScope* custom_layout_scope, HeapVector<Member<CustomLayoutChild>>* children) { // TODO(ikilpatrick): Determine if knowing the size of the array ahead of // time improves performance in any noticeable way. - for (NGLayoutInputNode child = node.FirstChild(); child; + for (LayoutInputNode child = node.FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) continue; @@ -87,7 +87,7 @@ bool CSSLayoutDefinition::Instance::Layout( const NGConstraintSpace& space, const Document& document, - const NGBlockNode& node, + const BlockNode& node, const LogicalSize& border_box_size, const BoxStrut& border_scrollbar_padding, CustomLayoutScope* custom_layout_scope, @@ -229,7 +229,7 @@ bool CSSLayoutDefinition::Instance::IntrinsicSizes( const NGConstraintSpace& space, const Document& document, - const NGBlockNode& node, + const BlockNode& node, const LogicalSize& border_box_size, const BoxStrut& border_scrollbar_padding, const LayoutUnit child_available_block_size,
diff --git a/third_party/blink/renderer/core/layout/custom/css_layout_definition.h b/third_party/blink/renderer/core/layout/custom/css_layout_definition.h index afa4466..6c30112 100644 --- a/third_party/blink/renderer/core/layout/custom/css_layout_definition.h +++ b/third_party/blink/renderer/core/layout/custom/css_layout_definition.h
@@ -15,11 +15,11 @@ namespace blink { +class BlockNode; class CustomLayoutScope; class FragmentResultOptions; class IntrinsicSizesResultOptions; class LayoutUnit; -class NGBlockNode; class NGConstraintSpace; class ScriptState; class SerializedScriptValue; @@ -57,7 +57,7 @@ // fragment_result_data. bool Layout(const NGConstraintSpace&, const Document&, - const NGBlockNode&, + const BlockNode&, const LogicalSize& border_box_size, const BoxStrut& border_scrollbar_padding, CustomLayoutScope*, @@ -68,7 +68,7 @@ // succeeded. It populates the IntrinsicSizesResultOptions dictionary. bool IntrinsicSizes(const NGConstraintSpace&, const Document&, - const NGBlockNode&, + const BlockNode&, const LogicalSize& border_box_size, const BoxStrut& border_scrollbar_padding, const LayoutUnit child_available_block_size,
diff --git a/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.cc b/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.cc index 3d73dff1..dace6c7 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.cc +++ b/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.cc
@@ -17,7 +17,7 @@ min_content_size_(min_content_size), max_content_size_(max_content_size) {} -const NGLayoutInputNode& CustomIntrinsicSizes::GetLayoutNode() const { +const LayoutInputNode& CustomIntrinsicSizes::GetLayoutNode() const { return child_->GetLayoutNode(); }
diff --git a/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.h b/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.h index 8f81331..0902d00 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.h +++ b/third_party/blink/renderer/core/layout/custom/custom_intrinsic_sizes.h
@@ -10,8 +10,8 @@ namespace blink { -class NGLayoutInputNode; class CustomLayoutChild; +class LayoutInputNode; // This represents the result of intrinsicSizes (on a LayoutChild). // @@ -33,7 +33,7 @@ double minContentSize() const { return min_content_size_; } double maxContentSize() const { return max_content_size_; } - const NGLayoutInputNode& GetLayoutNode() const; + const LayoutInputNode& GetLayoutNode() const; bool IsValid() const { return token_->IsValid(); }
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.cc b/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.cc index ce550f9..d79822f3 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.cc
@@ -53,12 +53,12 @@ LogicalSize border_box_size{ container_builder_.InlineSize(), ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), - CalculateDefaultBlockSize(ConstraintSpace(), Node(), BreakToken(), + GetConstraintSpace(), Style(), BorderPadding(), + CalculateDefaultBlockSize(GetConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding()), container_builder_.InlineSize())}; if (!instance->IntrinsicSizes( - ConstraintSpace(), document, Node(), border_box_size, + GetConstraintSpace(), document, Node(), border_box_size, BorderScrollbarPadding(), ChildAvailableSize().block_size, &scope, &intrinsic_sizes_result_options, &depends_on_block_constraints)) { // TODO(ikilpatrick): Report this error to the developer. @@ -107,11 +107,11 @@ LogicalSize border_box_size{ container_builder_.InlineSize(), ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), - CalculateDefaultBlockSize(ConstraintSpace(), Node(), BreakToken(), + GetConstraintSpace(), Style(), BorderPadding(), + CalculateDefaultBlockSize(GetConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding()), container_builder_.InlineSize())}; - if (!instance->Layout(ConstraintSpace(), document, Node(), border_box_size, + if (!instance->Layout(GetConstraintSpace(), document, Node(), border_box_size, BorderScrollbarPadding(), &scope, fragment_result_options, &fragment_result_data)) { // TODO(ikilpatrick): Report this error to the developer. @@ -121,7 +121,7 @@ const HeapVector<Member<CustomLayoutFragment>>& child_fragments = fragment_result_options->childFragments(); - NGLayoutInputNode child = Node().FirstChild(); + LayoutInputNode child = Node().FirstChild(); for (auto fragment : child_fragments) { if (!fragment->IsValid()) { // TODO(ikilpatrick): Report this error to the developer. @@ -167,7 +167,7 @@ BorderScrollbarPadding().BlockSum(), LayoutUnit::FromDoubleRound(fragment_result_options->autoBlockSize())); LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), auto_block_size, + GetConstraintSpace(), Style(), BorderPadding(), auto_block_size, container_builder_.InitialBorderBoxSize().inline_size); // TODO(ikilpatrick): Allow setting both the first/last baseline instead of a @@ -182,7 +182,7 @@ container_builder_.SetIntrinsicBlockSize(auto_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -192,11 +192,11 @@ // // |child| will end up being the next inflow child, or empty. void CustomLayoutAlgorithm::AddAnyOutOfFlowPositionedChildren( - NGLayoutInputNode* child) { + LayoutInputNode* child) { DCHECK(child); while (*child && child->IsOutOfFlowPositioned()) { container_builder_.AddOutOfFlowChildCandidate( - To<NGBlockNode>(*child), BorderScrollbarPadding().StartOffset()); + To<BlockNode>(*child), BorderScrollbarPadding().StartOffset()); *child = child->NextSibling(); } }
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.h b/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.h index 89636c20..2833c32 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_algorithm.h
@@ -14,7 +14,7 @@ class NGBlockBreakToken; class CORE_EXPORT CustomLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -24,7 +24,7 @@ const NGLayoutResult* Layout() override; private: - void AddAnyOutOfFlowPositionedChildren(NGLayoutInputNode* child); + void AddAnyOutOfFlowPositionedChildren(LayoutInputNode* child); MinMaxSizesResult FallbackMinMaxSizes(const MinMaxSizesFloatInput&) const; const NGLayoutResult* FallbackLayout();
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc b/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc index 60bb577..9dc4aa7d4 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_child.cc
@@ -22,7 +22,7 @@ } // namespace CustomLayoutChild::CustomLayoutChild(const CSSLayoutDefinition& definition, - NGLayoutInputNode node) + LayoutInputNode node) : node_(node), style_map_(MakeGarbageCollected<PrepopulatedComputedStylePropertyMap>( node.GetDocument(),
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_child.h b/third_party/blink/renderer/core/layout/custom/custom_layout_child.h index 8b58385..620dc15 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_child.h +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_child.h
@@ -28,7 +28,7 @@ DEFINE_WRAPPERTYPEINFO(); public: - CustomLayoutChild(const CSSLayoutDefinition&, NGLayoutInputNode); + CustomLayoutChild(const CSSLayoutDefinition&, LayoutInputNode); CustomLayoutChild(const CustomLayoutChild&) = delete; CustomLayoutChild& operator=(const CustomLayoutChild&) = delete; ~CustomLayoutChild() override = default; @@ -42,7 +42,7 @@ const CustomLayoutConstraintsOptions*, ExceptionState&); - const NGLayoutInputNode& GetLayoutNode() const { + const LayoutInputNode& GetLayoutNode() const { DCHECK(node_); return node_; } @@ -53,7 +53,7 @@ void Trace(Visitor*) const override; private: - NGLayoutInputNode node_; + LayoutInputNode node_; Member<PrepopulatedComputedStylePropertyMap> style_map_; Member<CustomLayoutToken> token_; };
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.cc b/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.cc index da579f0..f08fed3 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.cc +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.cc
@@ -35,7 +35,7 @@ return *layout_result_; } -const NGLayoutInputNode& CustomLayoutFragment::GetLayoutNode() const { +const LayoutInputNode& CustomLayoutFragment::GetLayoutNode() const { return child_->GetLayoutNode(); }
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h b/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h index 9213282..fe44d8f 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_fragment.h
@@ -13,13 +13,13 @@ namespace blink { -class NGLayoutInputNode; class CustomLayoutChild; class LayoutBox; -struct LogicalSize; +class LayoutInputNode; class NGLayoutResult; class ScriptState; class ScriptValue; +struct LogicalSize; // This represents the result of a layout (on a LayoutChild). // @@ -59,7 +59,7 @@ ScriptValue data(ScriptState*) const; const NGLayoutResult& GetLayoutResult() const; - const NGLayoutInputNode& GetLayoutNode() const; + const LayoutInputNode& GetLayoutNode() const; bool IsValid() const { return token_->IsValid(); }
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.cc b/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.cc index 73af505..530f5cfb 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.cc +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.cc
@@ -53,7 +53,7 @@ const LayoutUnit child_available_block_size, bool* child_depends_on_block_constraints) { DCHECK(token_->IsValid()); - NGLayoutInputNode child = child_->GetLayoutNode(); + LayoutInputNode child = child_->GetLayoutNode(); if (type_ == CustomLayoutWorkTask::TaskType::kIntrinsicSizes) { RunIntrinsicSizesTask(parent_space, parent_style, @@ -68,7 +68,7 @@ void CustomLayoutWorkTask::RunLayoutFragmentTask( const NGConstraintSpace& parent_space, const ComputedStyle& parent_style, - NGLayoutInputNode child) { + LayoutInputNode child) { DCHECK_EQ(type_, CustomLayoutWorkTask::TaskType::kLayoutFragment); DCHECK(options_ && resolver_); @@ -137,8 +137,7 @@ builder.SetCustomLayoutData(std::move(constraint_data_)); } auto space = builder.ToConstraintSpace(); - auto* result = - To<NGBlockNode>(child).Layout(space, nullptr /* break_token */); + auto* result = To<BlockNode>(child).Layout(space, nullptr /* break_token */); LogicalBoxFragment fragment( parent_space.GetWritingDirection(), @@ -153,7 +152,7 @@ const NGConstraintSpace& parent_space, const ComputedStyle& parent_style, const LayoutUnit child_available_block_size, - NGLayoutInputNode child, + LayoutInputNode child, bool* child_depends_on_block_constraints) { DCHECK_EQ(type_, CustomLayoutWorkTask::TaskType::kIntrinsicSizes); DCHECK(resolver_); @@ -164,7 +163,7 @@ const auto space = builder.ToConstraintSpace(); MinMaxSizesResult result = ComputeMinAndMaxContentContribution( - parent_style, To<NGBlockNode>(child), space); + parent_style, To<BlockNode>(child), space); resolver_->Resolve(MakeGarbageCollected<CustomIntrinsicSizes>( child_, token_, result.sizes.min_size, result.sizes.max_size));
diff --git a/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.h b/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.h index cac6568..79d0257 100644 --- a/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.h +++ b/third_party/blink/renderer/core/layout/custom/custom_layout_work_task.h
@@ -14,9 +14,9 @@ class ComputedStyle; class CustomLayoutChild; class CustomLayoutToken; +class LayoutInputNode; class LayoutUnit; class NGConstraintSpace; -class NGLayoutInputNode; class SerializedScriptValue; class ScriptPromiseResolver; @@ -62,11 +62,11 @@ void RunLayoutFragmentTask(const NGConstraintSpace& parent_space, const ComputedStyle& parent_style, - NGLayoutInputNode child); + LayoutInputNode child); void RunIntrinsicSizesTask(const NGConstraintSpace& parent_space, const ComputedStyle& parent_style, const LayoutUnit child_available_block_size, - NGLayoutInputNode child, + LayoutInputNode child, bool* child_depends_on_block_constraints); };
diff --git a/third_party/blink/renderer/core/layout/flex/flex_child_iterator.cc b/third_party/blink/renderer/core/layout/flex/flex_child_iterator.cc index 62193f259..d5572bc 100644 --- a/third_party/blink/renderer/core/layout/flex/flex_child_iterator.cc +++ b/third_party/blink/renderer/core/layout/flex/flex_child_iterator.cc
@@ -6,7 +6,7 @@ namespace blink { -FlexChildIterator::FlexChildIterator(const NGBlockNode node) { +FlexChildIterator::FlexChildIterator(const BlockNode node) { bool is_deprecated_webkit_box = node.Style().IsDeprecatedWebkitBox(); int initial_order = is_deprecated_webkit_box ? ComputedStyleInitialValues::InitialBoxOrdinalGroup() @@ -15,12 +15,12 @@ // Collect all our children, and order them by either their // -webkit-box-ordinal-group/order property. - for (NGLayoutInputNode child = node.FirstChild(); child; + for (LayoutInputNode child = node.FirstChild(); child; child = child.NextSibling()) { int order = is_deprecated_webkit_box ? child.Style().BoxOrdinalGroup() : child.Style().Order(); needs_sort |= order != initial_order; - children_.emplace_back(To<NGBlockNode>(child), order); + children_.emplace_back(To<BlockNode>(child), order); } // We only need to sort this vector if we encountered a non-initial
diff --git a/third_party/blink/renderer/core/layout/flex/flex_child_iterator.h b/third_party/blink/renderer/core/layout/flex/flex_child_iterator.h index 6f84402..94dde505 100644 --- a/third_party/blink/renderer/core/layout/flex/flex_child_iterator.h +++ b/third_party/blink/renderer/core/layout/flex/flex_child_iterator.h
@@ -20,10 +20,10 @@ STACK_ALLOCATED(); public: - FlexChildIterator(const NGBlockNode node); + FlexChildIterator(const BlockNode node); // Returns the next block node which should be laid out. - NGBlockNode NextChild() { + BlockNode NextChild() { DCHECK(position_ <= children_.size()); if (position_ == children_.size()) return nullptr; @@ -34,10 +34,10 @@ DISALLOW_NEW(); public: - ChildWithOrder(NGBlockNode child, int order) : child(child), order(order) {} + ChildWithOrder(BlockNode child, int order) : child(child), order(order) {} void Trace(Visitor* visitor) const { visitor->Trace(child); } - NGBlockNode child; + BlockNode child; int order; };
diff --git a/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.cc b/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.cc index 4e57d24..4e455300 100644 --- a/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.cc
@@ -140,7 +140,7 @@ is_horizontal_flow_(FlexibleBoxAlgorithm::IsHorizontalFlow(Style())), is_cross_size_definite_(IsContainerCrossSizeDefinite()), child_percentage_size_( - CalculateChildPercentageSize(ConstraintSpace(), + CalculateChildPercentageSize(GetConstraintSpace(), Node(), ChildAvailableSize())), algorithm_(&Style(), @@ -154,7 +154,7 @@ layout_info_for_devtools_ = std::make_unique<DevtoolsFlexInfo>(); } -bool FlexLayoutAlgorithm::MainAxisIsInlineAxis(const NGBlockNode& child) const { +bool FlexLayoutAlgorithm::MainAxisIsInlineAxis(const BlockNode& child) const { return child.Style().IsHorizontalWritingMode() == is_horizontal_flow_; } @@ -173,7 +173,7 @@ if (container_builder_.InlineSize() != kIndefiniteSize) inline_size = container_builder_.InlineSize(); return ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), + GetConstraintSpace(), Style(), BorderPadding(), sum_hypothetical_main_size.ClampNegativeToZero() + border_scrollbar_padding, inline_size) - @@ -262,12 +262,12 @@ // Recompute the total block size in case |total_intrinsic_block_size_| // changed as a result of fragmentation. total_block_size_ = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), + GetConstraintSpace(), Style(), BorderPadding(), total_intrinsic_block_size_, container_builder_.InlineSize()); } else { LayoutUnit center = total_block_size_ / 2; should_process_block_center = center - previous_consumed_block_size <= - FragmentainerCapacity(ConstraintSpace()); + FragmentainerCapacity(GetConstraintSpace()); } } @@ -284,7 +284,7 @@ ShrinkLogicalSize(total_fragment_size, border_scrollbar_padding); for (LayoutBox* oof_child : oofs) { - NGBlockNode child(oof_child); + BlockNode child(oof_child); AxisEdge main_axis_edge = MainAxisStaticPositionEdge(Style(), is_column_); AxisEdge cross_axis_edge = @@ -391,7 +391,7 @@ return ChildAvailableSize().block_size != kIndefiniteSize; } -bool FlexLayoutAlgorithm::DoesItemStretch(const NGBlockNode& child) const { +bool FlexLayoutAlgorithm::DoesItemStretch(const BlockNode& child) const { // Note: Unresolvable % cross size doesn't count as auto for stretchability. // As discussed in https://github.com/w3c/csswg-drafts/issues/4312. if (!DoesItemCrossSizeComputeToAuto(child)) @@ -411,7 +411,7 @@ } bool FlexLayoutAlgorithm::IsUsedFlexBasisDefinite( - const NGBlockNode& child, + const BlockNode& child, Length* out_flex_basis = nullptr) const { const Length& flex_basis = GetUsedFlexBasis(child); if (out_flex_basis) @@ -425,7 +425,7 @@ } bool FlexLayoutAlgorithm::IsItemCrossAxisLengthDefinite( - const NGBlockNode& child, + const BlockNode& child, const Length& length) const { // We don't consider inline value of 'auto' for the cross-axis min/main/max // size to be definite. Block value of 'auto' is always indefinite. @@ -437,7 +437,7 @@ } bool FlexLayoutAlgorithm::DoesItemCrossSizeComputeToAuto( - const NGBlockNode& child) const { + const BlockNode& child) const { const ComputedStyle& child_style = child.Style(); if (is_horizontal_flow_) { return child_style.UsedHeight().IsAuto(); @@ -446,7 +446,7 @@ } bool FlexLayoutAlgorithm::AspectRatioProvidesMainSize( - const NGBlockNode& child) const { + const BlockNode& child) const { const Length& cross_axis_length = is_horizontal_flow_ ? child.Style().UsedHeight() : child.Style().UsedWidth(); @@ -456,14 +456,14 @@ } bool FlexLayoutAlgorithm::WillChildCrossSizeBeContainerCrossSize( - const NGBlockNode& child) const { + const BlockNode& child) const { return !algorithm_.IsMultiline() && is_cross_size_definite_ && DoesItemStretch(child); } NGConstraintSpace FlexLayoutAlgorithm::BuildSpaceForIntrinsicInlineSize( - const NGBlockNode& child) const { - NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), child, + const BlockNode& child) const { + NGMinMaxConstraintSpaceBuilder builder(GetConstraintSpace(), Style(), child, /* is_new_fc */ true); builder.SetAvailableBlockSize(ChildAvailableSize().block_size); builder.SetPercentageResolutionBlockSize(child_percentage_size_.block_size); @@ -475,10 +475,10 @@ } NGConstraintSpace FlexLayoutAlgorithm::BuildSpaceForIntrinsicBlockSize( - const NGBlockNode& flex_item, + const BlockNode& flex_item, absl::optional<LayoutUnit> override_inline_size) const { const ComputedStyle& child_style = flex_item.Style(); - NGConstraintSpaceBuilder space_builder(ConstraintSpace(), + NGConstraintSpaceBuilder space_builder(GetConstraintSpace(), child_style.GetWritingDirection(), /* is_new_fc */ true); SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item, &space_builder); @@ -515,9 +515,9 @@ } NGConstraintSpace FlexLayoutAlgorithm::BuildSpaceForFlexBasis( - const NGBlockNode& flex_item) const { + const BlockNode& flex_item) const { NGConstraintSpaceBuilder space_builder( - ConstraintSpace(), flex_item.Style().GetWritingDirection(), + GetConstraintSpace(), flex_item.Style().GetWritingDirection(), /* is_new_fc */ true); SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item, &space_builder); @@ -530,7 +530,7 @@ } // This can return an indefinite Length. -Length FlexLayoutAlgorithm::GetUsedFlexBasis(const NGBlockNode& child) const { +Length FlexLayoutAlgorithm::GetUsedFlexBasis(const BlockNode& child) const { const ComputedStyle& child_style = child.Style(); const Length& specified_length_in_main_axis = is_horizontal_flow_ ? child_style.UsedWidth() : child_style.UsedHeight(); @@ -550,14 +550,14 @@ } NGConstraintSpace FlexLayoutAlgorithm::BuildSpaceForLayout( - const NGBlockNode& flex_item_node, + const BlockNode& flex_item_node, LayoutUnit item_main_axis_final_size, absl::optional<LayoutUnit> override_inline_size, absl::optional<LayoutUnit> line_cross_size_for_stretch, absl::optional<LayoutUnit> block_offset_for_fragmentation, bool min_block_size_should_encompass_intrinsic_size) const { const ComputedStyle& child_style = flex_item_node.Style(); - NGConstraintSpaceBuilder space_builder(ConstraintSpace(), + NGConstraintSpaceBuilder space_builder(GetConstraintSpace(), child_style.GetWritingDirection(), /* is_new_fc */ true); SetOrthogonalFallbackInlineSizeIfNeeded(Style(), flex_item_node, @@ -615,11 +615,11 @@ // layout will reuse this "measure" result if it can. space_builder.SetCacheSlot(NGCacheSlot::kMeasure); } else if (block_offset_for_fragmentation && - ConstraintSpace().HasBlockFragmentation()) { + GetConstraintSpace().HasBlockFragmentation()) { if (min_block_size_should_encompass_intrinsic_size) space_builder.SetMinBlockSizeShouldEncompassIntrinsicSize(); SetupSpaceBuilderForFragmentation( - ConstraintSpace(), flex_item_node, *block_offset_for_fragmentation, + GetConstraintSpace(), flex_item_node, *block_offset_for_fragmentation, &space_builder, /* is_new_fc */ true, container_builder_.RequiresContentBeforeBreaking()); @@ -635,7 +635,7 @@ // child. See the bottom of GiveItemsFinalPositionAndSize(). if (Node().IsButton()) { space_builder.SetBaselineAlgorithmType( - ConstraintSpace().BaselineAlgorithmType()); + GetConstraintSpace().BaselineAlgorithmType()); } return space_builder.ToConstraintSpace(); @@ -663,7 +663,7 @@ bool is_wrap_reverse = Style().FlexWrap() == EFlexWrap::kWrapReverse; FlexChildIterator iterator(Node()); - for (NGBlockNode child = iterator.NextChild(); child; + for (BlockNode child = iterator.NextChild(); child; child = iterator.NextChild()) { if (child.IsOutOfFlowPositioned()) { if (phase == Phase::kLayout) { @@ -680,7 +680,7 @@ ComputeMinAndMaxContentContribution(Style(), child, space); max_content_contribution = child_contributions.sizes.max_size; BoxStrut child_margins = - ComputeMarginsFor(space, child.Style(), ConstraintSpace()); + ComputeMarginsFor(space, child.Style(), GetConstraintSpace()); child_contributions.sizes += child_margins.InlineSum(); largest_min_content_contribution_ = @@ -993,7 +993,7 @@ const BoxStrut scrollbars = ComputeScrollbarsForNonAnonymous(child); const auto container_writing_direction = - ConstraintSpace().GetWritingDirection(); + GetConstraintSpace().GetWritingDirection(); bool is_last_baseline = FlexibleBoxAlgorithm::AlignmentForChild(Style(), child_style) == ItemPosition::kLastBaseline; @@ -1037,7 +1037,7 @@ } LayoutUnit FlexLayoutAlgorithm::AdjustMainSizeForAspectRatioCrossAxisMinAndMax( - const NGBlockNode& child, + const BlockNode& child, LayoutUnit main_axis_size, const MinMaxSizes& cross_min_max, const BoxStrut& border_padding_in_child_writing_mode) { @@ -1062,7 +1062,7 @@ case NGLayoutResult::kNeedsRelayoutWithNoChildScrollbarChanges: return RelayoutIgnoringChildScrollbarChanges(); case NGLayoutResult::kDisableFragmentation: - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(GetConstraintSpace().HasBlockFragmentation()); return RelayoutWithoutFragmentation<FlexLayoutAlgorithm>(); case NGLayoutResult::kNeedsRelayoutWithRowCrossSizeChanges: return RelayoutWithNewRowSizes(); @@ -1075,8 +1075,8 @@ FlexLayoutAlgorithm::RelayoutIgnoringChildScrollbarChanges() { DCHECK(!ignore_child_scrollbar_changes_); LayoutAlgorithmParams params( - Node(), container_builder_.InitialFragmentGeometry(), ConstraintSpace(), - BreakToken(), /* early_break */ nullptr); + Node(), container_builder_.InitialFragmentGeometry(), + GetConstraintSpace(), BreakToken(), /* early_break */ nullptr); FlexLayoutAlgorithm algorithm(params); algorithm.ignore_child_scrollbar_changes_ = true; return algorithm.Layout(); @@ -1086,8 +1086,9 @@ const NGLayoutResult* previous_result) { DCHECK(previous_result->GetEarlyBreak()); LayoutAlgorithmParams params( - Node(), container_builder_.InitialFragmentGeometry(), ConstraintSpace(), - BreakToken(), previous_result->GetEarlyBreak(), &column_early_breaks_); + Node(), container_builder_.InitialFragmentGeometry(), + GetConstraintSpace(), BreakToken(), previous_result->GetEarlyBreak(), + &column_early_breaks_); FlexLayoutAlgorithm algorithm_with_break(params); algorithm_with_break.ignore_child_scrollbar_changes_ = ignore_child_scrollbar_changes_; @@ -1131,8 +1132,8 @@ } total_block_size_ = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), total_intrinsic_block_size_, - container_builder_.InlineSize()); + GetConstraintSpace(), Style(), BorderPadding(), + total_intrinsic_block_size_, container_builder_.InlineSize()); if (!IsBreakInside(BreakToken())) { ApplyFinalAlignmentAndReversals(&flex_line_outputs); @@ -1163,11 +1164,11 @@ return container_builder_.Abort(status); intrinsic_block_size_ = ClampIntrinsicBlockSize( - ConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), + GetConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), intrinsic_block_size_ + BorderScrollbarPadding().block_end); block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), + GetConstraintSpace(), Style(), BorderPadding(), previously_consumed_block_size + intrinsic_block_size_, container_builder_.InlineSize()); } else { @@ -1187,8 +1188,8 @@ if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) { NGBreakStatus break_status = FinishFragmentation( - Node(), ConstraintSpace(), BorderPadding().block_end, - FragmentainerSpaceLeft(ConstraintSpace()), &container_builder_); + Node(), GetConstraintSpace(), BorderPadding().block_end, + FragmentainerSpaceLeft(GetConstraintSpace()), &container_builder_); if (break_status != NGBreakStatus::kContinue) { if (break_status == NGBreakStatus::kNeedsEarlierBreak) return container_builder_.Abort(NGLayoutResult::kNeedsEarlierBreak); @@ -1210,13 +1211,13 @@ // of columns as a single row and propagate the combined break-before rules // for the first items in each column and break-after rules for last items in // each column. - if (ConstraintSpace().ShouldPropagateChildBreakValues()) { + if (GetConstraintSpace().ShouldPropagateChildBreakValues()) { DCHECK(!row_break_between_outputs.empty()); container_builder_.SetInitialBreakBefore(row_break_between_outputs.front()); container_builder_.SetPreviousBreakAfter(row_break_between_outputs.back()); } - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { container_builder_.SetBreakTokenData( MakeGarbageCollected<FlexBreakTokenData>( container_builder_.GetBreakTokenData(), flex_line_outputs, @@ -1231,7 +1232,7 @@ // Un-freeze descendant scrollbars before we run the OOF layout part. freeze_scrollbars.reset(); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -1353,7 +1354,7 @@ total_intrinsic_block_size_ += algorithm_.IntrinsicContentBlockSize(); total_intrinsic_block_size_ = ClampIntrinsicBlockSize( - ConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), + GetConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), total_intrinsic_block_size_ + BorderScrollbarPadding().block_end); } @@ -1418,7 +1419,7 @@ } bool should_propagate_row_break_values = - ConstraintSpace().ShouldPropagateChildBreakValues(); + GetConstraintSpace().ShouldPropagateChildBreakValues(); if (should_propagate_row_break_values) { DCHECK(row_break_between_outputs); // The last row break between will store the final break-after to be @@ -1514,7 +1515,7 @@ const auto& physical_fragment = To<NGPhysicalBoxFragment>(layout_result->PhysicalFragment()); - const auto writing_direction = ConstraintSpace().GetWritingDirection(); + const auto writing_direction = GetConstraintSpace().GetWritingDirection(); LogicalBoxFragment fragment(writing_direction, physical_fragment); if (!InvolvedInBlockFragmentation(container_builder_)) { container_builder_.AddResult( @@ -1569,7 +1570,7 @@ false); bool needs_earlier_break_in_column = false; NGLayoutResult::EStatus status = NGLayoutResult::kSuccess; - LayoutUnit fragmentainer_space = FragmentainerSpaceLeft(ConstraintSpace()); + LayoutUnit fragmentainer_space = FragmentainerSpaceLeft(GetConstraintSpace()); HeapVector<NGFlexColumnBreakInfo> column_break_info; if (is_column_) { @@ -1795,7 +1796,7 @@ NGBreakStatus break_status = NGBreakStatus::kContinue; NGFlexColumnBreakInfo* current_column_break_info = nullptr; - if (!early_break_ && ConstraintSpace().HasBlockFragmentation()) { + if (!early_break_ && GetConstraintSpace().HasBlockFragmentation()) { bool has_container_separation = false; if (!is_column_) { has_container_separation = @@ -1851,8 +1852,8 @@ } } break_status = BreakBeforeChildIfNeeded( - ConstraintSpace(), flex_item->ng_input_node, *layout_result, - ConstraintSpace().FragmentainerOffset() + offset.block_offset, + GetConstraintSpace(), flex_item->ng_input_node, *layout_result, + GetConstraintSpace().FragmentainerOffset() + offset.block_offset, has_container_separation, &container_builder_, !is_column_, current_column_break_info); @@ -1903,7 +1904,7 @@ const auto& physical_fragment = To<NGPhysicalBoxFragment>(layout_result->PhysicalFragment()); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), physical_fragment); bool is_at_block_end = !physical_fragment.BreakToken() || @@ -2056,9 +2057,10 @@ LogicalSize logical_flexbox_size = LogicalSize(container_builder_.InlineSize(), total_block_size_); PhysicalSize flexbox_size = ToPhysicalSize( - logical_flexbox_size, ConstraintSpace().GetWritingMode()); - item_rect.offset = offset.ConvertToPhysical( - ConstraintSpace().GetWritingDirection(), flexbox_size, item_rect.size); + logical_flexbox_size, GetConstraintSpace().GetWritingMode()); + item_rect.offset = + offset.ConvertToPhysical(GetConstraintSpace().GetWritingDirection(), + flexbox_size, item_rect.size); // devtools uses margin box. item_rect.Expand(flex_item->physical_margins_); DCHECK_GE(layout_info_for_devtools_->lines.size(), 1u); @@ -2129,7 +2131,7 @@ DCHECK_EQ(children.size(), 1u); const LogicalFragmentLink& child = children[0]; DCHECK(!child.fragment->IsLineBox()); - const NGConstraintSpace& space = ConstraintSpace(); + const auto& space = GetConstraintSpace(); LogicalBoxFragment fragment(space.GetWritingDirection(), To<NGPhysicalBoxFragment>(*child.fragment)); absl::optional<LayoutUnit> child_baseline = @@ -2198,7 +2200,7 @@ LayoutUnit largest_outer_min_content_contribution; for (const FlexItem& item : algorithm_.all_items_) { - const NGBlockNode& child = item.ng_input_node_; + const BlockNode& child = item.ng_input_node_; const NGConstraintSpace space = BuildSpaceForIntrinsicInlineSize(child); MinMaxSizesResult min_max_content_contributions = @@ -2307,7 +2309,7 @@ int number_of_items = 0; FlexChildIterator iterator(Node()); - for (NGBlockNode child = iterator.NextChild(); child; + for (BlockNode child = iterator.NextChild(); child; child = iterator.NextChild()) { if (child.IsOutOfFlowPositioned()) continue; @@ -2317,7 +2319,7 @@ MinMaxSizesResult child_result = ComputeMinAndMaxContentContribution(Style(), child, space); BoxStrut child_margins = - ComputeMarginsFor(space, child.Style(), ConstraintSpace()); + ComputeMarginsFor(space, child.Style(), GetConstraintSpace()); child_result.sizes += child_margins.InlineSum(); depends_on_block_constraints |= child_result.depends_on_block_constraints; @@ -2352,7 +2354,7 @@ LayoutUnit FlexLayoutAlgorithm::FragmentainerSpaceAvailable( LayoutUnit block_offset) const { - return (FragmentainerSpaceLeft(ConstraintSpace()) - block_offset) + return (FragmentainerSpaceLeft(GetConstraintSpace()) - block_offset) .ClampNegativeToZero(); } @@ -2374,8 +2376,9 @@ intrinsic_block_size + previously_consumed_block_size; } - if (!ConstraintSpace().HasKnownFragmentainerBlockSize()) + if (!GetConstraintSpace().HasKnownFragmentainerBlockSize()) { return; + } // The remaining part of the fragmentainer (the unusable space for child // content, due to the break) should still be occupied by this container. intrinsic_block_size_ += FragmentainerSpaceAvailable(intrinsic_block_size_); @@ -2386,18 +2389,18 @@ LayoutUnit row_block_offset, EBreakBetween row_break_between, wtf_size_t row_index, - NGLayoutInputNode child, + LayoutInputNode child, bool has_container_separation, bool is_first_for_row) { DCHECK(!is_column_); DCHECK(InvolvedInBlockFragmentation(container_builder_)); LayoutUnit fragmentainer_block_offset = - ConstraintSpace().FragmentainerOffset() + row_block_offset; + GetConstraintSpace().FragmentainerOffset() + row_block_offset; if (has_container_separation) { - if (IsForcedBreakValue(ConstraintSpace(), row_break_between)) { - BreakBeforeChild(ConstraintSpace(), child, /* layout_result */ nullptr, + if (IsForcedBreakValue(GetConstraintSpace(), row_break_between)) { + BreakBeforeChild(GetConstraintSpace(), child, /* layout_result */ nullptr, fragmentainer_block_offset, kBreakAppealPerfect, /* is_forced_break */ true, &container_builder_, row.line_cross_size); @@ -2406,10 +2409,11 @@ } bool breakable_at_start_of_container = IsBreakableAtStartOfResumedContainer( - ConstraintSpace(), container_builder_, is_first_for_row); + GetConstraintSpace(), container_builder_, is_first_for_row); NGBreakAppeal appeal_before = CalculateBreakAppealBefore( - ConstraintSpace(), NGLayoutResult::EStatus::kSuccess, row_break_between, - has_container_separation, breakable_at_start_of_container); + GetConstraintSpace(), NGLayoutResult::EStatus::kSuccess, + row_break_between, has_container_separation, + breakable_at_start_of_container); // Attempt to move past the break point, and if we can do that, also assess // the appeal of breaking there, even if we didn't. @@ -2421,10 +2425,12 @@ // We're out of space. Figure out where to insert a soft break. It will either // be before this row, or before an earlier sibling, if there's a more // appealing breakpoint there. - if (!AttemptSoftBreak(ConstraintSpace(), child, /* layout_result */ nullptr, - fragmentainer_block_offset, appeal_before, - &container_builder_, row.line_cross_size)) + if (!AttemptSoftBreak(GetConstraintSpace(), child, + /* layout_result */ nullptr, fragmentainer_block_offset, + appeal_before, &container_builder_, + row.line_cross_size)) { return NGBreakStatus::kNeedsEarlierBreak; + } return NGBreakStatus::kBrokeBefore; } @@ -2436,14 +2442,14 @@ wtf_size_t row_index, bool has_container_separation, bool breakable_at_start_of_container) { - if (!ConstraintSpace().HasKnownFragmentainerBlockSize()) { + if (!GetConstraintSpace().HasKnownFragmentainerBlockSize()) { // We only care about soft breaks if we have a fragmentainer block-size. // During column balancing this may be unknown. return true; } LayoutUnit space_left = - FragmentainerCapacity(ConstraintSpace()) - fragmentainer_block_offset; + FragmentainerCapacity(GetConstraintSpace()) - fragmentainer_block_offset; // If the row starts past the end of the fragmentainer, we must break before // it. @@ -2458,7 +2464,7 @@ if (must_break_before) { #if DCHECK_IS_ON() bool refuse_break_before = - space_left >= FragmentainerCapacity(ConstraintSpace()); + space_left >= FragmentainerCapacity(GetConstraintSpace()); DCHECK(!refuse_break_before); #endif return false; @@ -2504,9 +2510,10 @@ DCHECK(!row_cross_size_updates_.empty()); DCHECK_LE(row_cross_size_updates_.size(), 2u); - LayoutAlgorithmParams params( - Node(), container_builder_.InitialFragmentGeometry(), ConstraintSpace(), - BreakToken(), early_break_, additional_early_breaks_); + LayoutAlgorithmParams params(Node(), + container_builder_.InitialFragmentGeometry(), + GetConstraintSpace(), BreakToken(), early_break_, + additional_early_breaks_); FlexLayoutAlgorithm algorithm_with_row_cross_sizes(params, &row_cross_size_updates_); auto& new_builder = algorithm_with_row_cross_sizes.container_builder_; @@ -2544,7 +2551,7 @@ // NOTE: We currently assume that writing-mode roots are monolithic, but // this may change in the future. - DCHECK_EQ(ConstraintSpace().GetWritingDirection().GetWritingMode(), + DCHECK_EQ(GetConstraintSpace().GetWritingDirection().GetWritingMode(), item_style.GetWritingMode()); if (is_column_) {
diff --git a/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.h b/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.h index 46327a0..5894e693 100644 --- a/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm.h
@@ -14,13 +14,13 @@ namespace blink { -class NGBlockNode; +class BlockNode; class NGBlockBreakToken; struct DevtoolsFlexInfo; struct NGFlexItem; class CORE_EXPORT FlexLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -44,22 +44,22 @@ void CalculateTotalIntrinsicBlockSize(bool use_empty_line_block_size); - Length GetUsedFlexBasis(const NGBlockNode& child) const; + Length GetUsedFlexBasis(const BlockNode& child) const; // This has an optional out parameter so that callers can avoid a subsequent // redundant call to GetUsedFlexBasis. - bool IsUsedFlexBasisDefinite(const NGBlockNode& child, + bool IsUsedFlexBasisDefinite(const BlockNode& child, Length* flex_basis) const; - bool DoesItemCrossSizeComputeToAuto(const NGBlockNode& child) const; - bool IsItemCrossAxisLengthDefinite(const NGBlockNode& child, + bool DoesItemCrossSizeComputeToAuto(const BlockNode& child) const; + bool IsItemCrossAxisLengthDefinite(const BlockNode& child, const Length& length) const; - bool AspectRatioProvidesMainSize(const NGBlockNode& child) const; - bool DoesItemStretch(const NGBlockNode& child) const; + bool AspectRatioProvidesMainSize(const BlockNode& child) const; + bool DoesItemStretch(const BlockNode& child) const; // This checks for one of the scenarios where a flex-item box has a definite // size that would be indefinite if the box weren't a flex item. // See https://drafts.csswg.org/css-flexbox/#definite-sizes - bool WillChildCrossSizeBeContainerCrossSize(const NGBlockNode& child) const; + bool WillChildCrossSizeBeContainerCrossSize(const BlockNode& child) const; LayoutUnit AdjustMainSizeForAspectRatioCrossAxisMinAndMax( - const NGBlockNode& child, + const BlockNode& child, LayoutUnit main_size, const MinMaxSizes& cross_min_max, const BoxStrut& border_padding_in_child_writing_mode); @@ -69,17 +69,17 @@ enum class Phase { kLayout, kRowIntrinsicSize, kColumnWrapIntrinsicSize }; NGConstraintSpace BuildSpaceForIntrinsicInlineSize( - const NGBlockNode& flex_item) const; - NGConstraintSpace BuildSpaceForFlexBasis(const NGBlockNode& flex_item) const; + const BlockNode& flex_item) const; + NGConstraintSpace BuildSpaceForFlexBasis(const BlockNode& flex_item) const; NGConstraintSpace BuildSpaceForIntrinsicBlockSize( - const NGBlockNode& flex_item, + const BlockNode& flex_item, absl::optional<LayoutUnit> override_inline_size) const; // |line_cross_size_for_stretch| should only be set when running the final // layout pass for stretch, when the line cross size is definite. // |block_offset_for_fragmentation| should only be set when running the final // layout pass for fragmentation. Both may be set at the same time. NGConstraintSpace BuildSpaceForLayout( - const NGBlockNode& flex_item_node, + const BlockNode& flex_item_node, LayoutUnit item_main_axis_final_size, absl::optional<LayoutUnit> override_inline_size = absl::nullopt, absl::optional<LayoutUnit> line_cross_size_for_stretch = absl::nullopt, @@ -106,7 +106,7 @@ // This is same method as FlexItem but we need that logic before FlexItem is // constructed. - bool MainAxisIsInlineAxis(const NGBlockNode& child) const; + bool MainAxisIsInlineAxis(const BlockNode& child) const; LayoutUnit MainAxisContentExtent(LayoutUnit sum_hypothetical_main_size) const; void HandleOutOfFlowPositionedItems( @@ -142,7 +142,7 @@ LayoutUnit row_block_offset, EBreakBetween row_break_between, wtf_size_t row_index, - NGLayoutInputNode child, + LayoutInputNode child, bool has_container_separation, bool is_first_for_row);
diff --git a/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm_test.cc index 6bb86bad..2fefec9 100644 --- a/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/flex/flex_layout_algorithm_test.cc
@@ -52,7 +52,7 @@ NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(100), kIndefiniteSize)); - NGBlockNode box(GetDocument().body()->GetLayoutBox()); + BlockNode box(GetDocument().body()->GetLayoutBox()); const NGPhysicalBoxFragment* fragment = RunBlockLayoutAlgorithm(box, space); EXPECT_EQ(PhysicalSize(84, 22), fragment->Size());
diff --git a/third_party/blink/renderer/core/layout/flex/flexible_box_algorithm.h b/third_party/blink/renderer/core/layout/flex/flexible_box_algorithm.h index b6af0b2..d8cad0b 100644 --- a/third_party/blink/renderer/core/layout/flex/flexible_box_algorithm.h +++ b/third_party/blink/renderer/core/layout/flex/flexible_box_algorithm.h
@@ -174,7 +174,7 @@ // The above fields are used by the flex algorithm. The following fields, by // contrast, are just convenient storage. - NGBlockNode ng_input_node_; + BlockNode ng_input_node_; Member<const NGLayoutResult> layout_result_; absl::optional<LayoutUnit> max_content_contribution_; };
diff --git a/third_party/blink/renderer/core/layout/flex/ng_flex_line.h b/third_party/blink/renderer/core/layout/flex/ng_flex_line.h index 8bc04b07..70e683f1 100644 --- a/third_party/blink/renderer/core/layout/flex/ng_flex_line.h +++ b/third_party/blink/renderer/core/layout/flex/ng_flex_line.h
@@ -30,7 +30,7 @@ LayoutUnit total_remaining_block_size; FlexOffset offset; bool has_descendant_that_depends_on_percentage_block_size = false; - NGBlockNode ng_input_node; + BlockNode ng_input_node; }; struct NGFlexLine {
diff --git a/third_party/blink/renderer/core/layout/grid/grid_item.cc b/third_party/blink/renderer/core/layout/grid/grid_item.cc index 70e8c6c..48337c9 100644 --- a/third_party/blink/renderer/core/layout/grid/grid_item.cc +++ b/third_party/blink/renderer/core/layout/grid/grid_item.cc
@@ -125,7 +125,7 @@ } // namespace GridItemData::GridItemData( - NGBlockNode node, + BlockNode node, const ComputedStyle& root_grid_style, FontBaseline parent_grid_font_baseline, bool parent_must_consider_grid_items_for_column_sizing,
diff --git a/third_party/blink/renderer/core/layout/grid/grid_item.h b/third_party/blink/renderer/core/layout/grid/grid_item.h index b4176b2a..02243a3 100644 --- a/third_party/blink/renderer/core/layout/grid/grid_item.h +++ b/third_party/blink/renderer/core/layout/grid/grid_item.h
@@ -35,7 +35,7 @@ GridItemData(const GridItemData&) = default; GridItemData& operator=(const GridItemData&) = default; - GridItemData(NGBlockNode node, + GridItemData(BlockNode node, const ComputedStyle& root_grid_style, FontBaseline parent_grid_font_baseline, bool parent_must_consider_grid_items_for_column_sizing = false, @@ -226,7 +226,7 @@ void Trace(Visitor* visitor) const { visitor->Trace(node); } - NGBlockNode node; + BlockNode node; GridArea resolved_position; bool has_subgridded_columns : 1;
diff --git a/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm.cc b/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm.cc index aa7559fd..57c98f4 100644 --- a/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm.cc
@@ -22,7 +22,7 @@ const auto& node = Node(); const auto& style = Style(); - const auto& constraint_space = ConstraintSpace(); + const auto& constraint_space = GetConstraintSpace(); // At various stages of the algorithm we need to know the grid available-size. // If it's initially indefinite, we need to know the min/max sizes as well. @@ -207,7 +207,7 @@ const NGLayoutResult* GridLayoutAlgorithm::Layout() { const auto* result = LayoutInternal(); if (result->Status() == NGLayoutResult::kDisableFragmentation) { - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(GetConstraintSpace().HasBlockFragmentation()); return RelayoutWithoutFragmentation<GridLayoutAlgorithm>(); } return result; @@ -276,7 +276,7 @@ const auto& node = Node(); const auto& border_padding = BorderPadding(); - const auto& constraint_space = ConstraintSpace(); + const auto& constraint_space = GetConstraintSpace(); const auto block_size = ComputeBlockSizeForFragment( constraint_space, Style(), border_padding, intrinsic_block_size, @@ -369,7 +369,8 @@ return FixedMinMaxSizes(override_intrinsic_inline_size); } - if (const auto* layout_subtree = ConstraintSpace().GetGridLayoutSubtree()) { + if (const auto* layout_subtree = + GetConstraintSpace().GetGridLayoutSubtree()) { return FixedMinMaxSizes( layout_subtree->LayoutData().Columns().ComputeSetSpanSize()); } @@ -478,7 +479,7 @@ const auto& node = Node(); const auto& style = node.Style(); - const auto writing_mode = ConstraintSpace().GetWritingMode(); + const auto writing_mode = GetConstraintSpace().GetWritingMode(); const auto subgrid_area = SubgriddedAreaInParent(opt_subgrid_data); const wtf_size_t column_auto_repetitions = @@ -631,7 +632,8 @@ HeapVector<Member<LayoutBox>>* oof_children) const { GridSizingTree sizing_tree; - if (const auto* layout_subtree = ConstraintSpace().GetGridLayoutSubtree()) { + if (const auto* layout_subtree = + GetConstraintSpace().GetGridLayoutSubtree()) { auto& [grid_items, layout_data, subtree_size] = sizing_tree.CreateSizingData(); @@ -809,7 +811,7 @@ DCHECK(intrinsic_block_size); DCHECK_NE(grid_available_size_.inline_size, kIndefiniteSize); - const auto& constraint_space = ConstraintSpace(); + const auto& constraint_space = GetConstraintSpace(); const bool is_standalone_grid = !constraint_space.GetGridLayoutSubtree(); bool needs_additional_pass = false; @@ -1036,7 +1038,7 @@ const auto& node = grid_item->node; const auto& item_style = node.Style(); - const auto& constraint_space = ConstraintSpace(); + const auto& constraint_space = GetConstraintSpace(); const bool is_for_columns = track_direction == kForColumns; const bool is_parallel_with_track_direction = @@ -1515,7 +1517,7 @@ return; } - const auto writing_mode = ConstraintSpace().GetWritingMode(); + const auto writing_mode = GetConstraintSpace().GetWritingMode(); track_collection.ResetBaselines(); for (auto& grid_item : sizing_data.grid_items) { @@ -1631,7 +1633,7 @@ parent_track_collection.CreateSubgridTrackCollection( range_indices.begin, range_indices.end, GutterSize(track_direction, parent_track_collection.GutterSize()), - ComputeMarginsForSelf(ConstraintSpace(), Style()), + ComputeMarginsForSelf(GetConstraintSpace(), Style()), BorderScrollbarPadding(), track_direction, is_for_columns_in_parent ? subgrid_data->is_opposite_direction_in_root_grid_columns @@ -2029,7 +2031,7 @@ DCHECK(next_subgrid_subtree); callback_func(subgrid_algorithm, next_subgrid_subtree, SubgriddedItemData(grid_item, layout_data, - ConstraintSpace().GetWritingMode())); + GetConstraintSpace().GetWritingMode())); next_subgrid_subtree = next_subgrid_subtree.NextSibling(); } @@ -3190,7 +3192,7 @@ GridLayoutSubtree&& opt_layout_subtree, bool min_block_size_should_encompass_intrinsic_size, absl::optional<LayoutUnit> opt_fragment_relative_block_offset) const { - const auto& container_constraint_space = ConstraintSpace(); + const auto& container_constraint_space = GetConstraintSpace(); NGConstraintSpaceBuilder builder( container_constraint_space, grid_item.node.Style().GetWritingDirection(), @@ -3270,7 +3272,7 @@ containing_grid_area_size, ComputeMarginsFor(grid_item.node.Style(), containing_grid_area_size.inline_size, - ConstraintSpace().GetWritingDirection())); + GetConstraintSpace().GetWritingDirection())); fixed_available_size = { grid_item.has_subgridded_columns ? fixed_inline_size : kIndefiniteSize, @@ -3291,7 +3293,7 @@ DCHECK(!subgridded_item.IsSubgrid()); LogicalSize containing_grid_area_size(kIndefiniteSize, kIndefiniteSize); - const auto writing_mode = ConstraintSpace().GetWritingMode(); + const auto writing_mode = GetConstraintSpace().GetWritingMode(); if (track_direction == kForColumns) { containing_grid_area_size.block_size = ComputeGridItemAvailableSize( @@ -3309,7 +3311,7 @@ const SubgriddedItemData& subgrid_data) const { DCHECK(subgrid_data.IsSubgrid()); - const auto writing_mode = ConstraintSpace().GetWritingMode(); + const auto writing_mode = GetConstraintSpace().GetWritingMode(); const LogicalSize containing_grid_area_size( ComputeGridItemAvailableSize(*subgrid_data, @@ -3321,7 +3323,7 @@ containing_grid_area_size, ComputeMarginsFor(subgrid_data->node.Style(), containing_grid_area_size.inline_size, - ConstraintSpace().GetWritingDirection())); + GetConstraintSpace().GetWritingDirection())); return CreateConstraintSpace(NGCacheSlot::kMeasure, *subgrid_data, containing_grid_area_size, fixed_available_size); @@ -3469,7 +3471,7 @@ Vector<GridItemPlacementData>* out_grid_items_placement_data) { DCHECK(out_row_break_between); - const auto& container_space = ConstraintSpace(); + const auto& container_space = GetConstraintSpace(); const auto& [grid_items, layout_data, tree_size] = sizing_tree.TreeRootData(); const auto* cached_layout_subtree = container_space.GetGridLayoutSubtree(); @@ -3633,7 +3635,7 @@ intrinsic_block_size && consumed_grid_block_size); // TODO(ikilpatrick): Update |SetHasSeenAllChildren| and early exit if true. - const auto& constraint_space = ConstraintSpace(); + const auto& constraint_space = GetConstraintSpace(); const auto& [grid_items, layout_data, tree_size] = sizing_tree.TreeRootData(); const auto* cached_layout_subtree = constraint_space.GetGridLayoutSubtree(); @@ -4073,7 +4075,7 @@ ShrinkLogicalSize(total_fragment_size, BorderScrollbarPadding()); for (LayoutBox* oof_child : oofs) { - NGBlockNode child(oof_child); + BlockNode child(oof_child); DCHECK(child.IsOutOfFlowPositioned()); absl::optional<LogicalRect> containing_block_rect; @@ -4114,7 +4116,8 @@ // items or items with a grid-area that is not in the first or last // fragment, we could end up with an incorrect static position. if (should_process_block_end || - child_offset.block_offset <= FragmentainerCapacity(ConstraintSpace())) { + child_offset.block_offset <= + FragmentainerCapacity(GetConstraintSpace())) { container_builder_.AddOutOfFlowChildCandidate( out_of_flow_item.node, child_offset, inline_edge, block_edge); } else {
diff --git a/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm_test.cc index 8790c4d..dd8baff 100644 --- a/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/grid/grid_layout_algorithm_test.cc
@@ -125,7 +125,7 @@ } const NGPhysicalBoxFragment* RunBlockLayoutAlgorithm(Element* element) { - NGBlockNode container(element->GetLayoutBox()); + BlockNode container(element->GetLayoutBox()); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); @@ -169,7 +169,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -206,7 +206,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -253,7 +253,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -322,7 +322,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -381,7 +381,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -439,7 +439,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -487,7 +487,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid1")); + BlockNode node(GetLayoutBoxByElementId("grid1")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -564,7 +564,7 @@ )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid")); + BlockNode node(GetLayoutBoxByElementId("grid")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -690,7 +690,7 @@ )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid")); + BlockNode node(GetLayoutBoxByElementId("grid")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -772,7 +772,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid")); + BlockNode node(GetLayoutBoxByElementId("grid")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -816,7 +816,7 @@ <div id="grid"></div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid")); + BlockNode node(GetLayoutBoxByElementId("grid")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(100), kIndefiniteSize), @@ -893,7 +893,7 @@ </div> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("grid")); + BlockNode node(GetLayoutBoxByElementId("grid")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(100), kIndefiniteSize), @@ -1544,8 +1544,8 @@ </div> )HTML"); - NGBlockNode grid_node(GetLayoutBoxByElementId("grid")); - NGBlockNode subgrid_node(GetLayoutBoxByElementId("subgrid")); + BlockNode grid_node(GetLayoutBoxByElementId("grid")); + BlockNode subgrid_node(GetLayoutBoxByElementId("subgrid")); const ComputedStyle& grid_style = grid_node.Style(); const ComputedStyle& subgrid_style = subgrid_node.Style(); @@ -1577,7 +1577,7 @@ </div> )HTML"); - NGBlockNode subgrid_node(GetLayoutBoxByElementId("subgrid")); + BlockNode subgrid_node(GetLayoutBoxByElementId("subgrid")); const ComputedStyle& subgrid_style = subgrid_node.Style(); const ComputedGridTrackList& computed_grid_column_track_list = subgrid_style.GridTemplateColumns(); @@ -1622,7 +1622,7 @@ </div> )HTML"); - NGBlockNode subgrid_node(GetLayoutBoxByElementId("subgrid")); + BlockNode subgrid_node(GetLayoutBoxByElementId("subgrid")); const ComputedStyle& subgrid_style = subgrid_node.Style(); const ComputedGridTrackList& computed_grid_column_track_list = subgrid_style.GridTemplateColumns();
diff --git a/third_party/blink/renderer/core/layout/grid/grid_node.cc b/third_party/blink/renderer/core/layout/grid/grid_node.cc index 1afe322..31665af5 100644 --- a/third_party/blink/renderer/core/layout/grid/grid_node.cc +++ b/third_party/blink/renderer/core/layout/grid/grid_node.cc
@@ -66,7 +66,7 @@ } auto grid_item = std::make_unique<GridItemData>( - To<NGBlockNode>(child), root_grid_style, + To<BlockNode>(child), root_grid_style, parent_grid_style.GetFontBaseline(), must_consider_grid_items_for_column_sizing, must_consider_grid_items_for_row_sizing);
diff --git a/third_party/blink/renderer/core/layout/grid/grid_node.h b/third_party/blink/renderer/core/layout/grid/grid_node.h index 7d71604..e93c87b7 100644 --- a/third_party/blink/renderer/core/layout/grid/grid_node.h +++ b/third_party/blink/renderer/core/layout/grid/grid_node.h
@@ -12,10 +12,10 @@ namespace blink { -// Grid specific extensions to NGBlockNode. -class CORE_EXPORT GridNode final : public NGBlockNode { +// Grid specific extensions to BlockNode. +class CORE_EXPORT GridNode final : public BlockNode { public: - explicit GridNode(LayoutBox* box) : NGBlockNode(box) { + explicit GridNode(LayoutBox* box) : BlockNode(box) { DCHECK(box); DCHECK(box->IsLayoutGrid()); } @@ -42,7 +42,7 @@ template <> struct DowncastTraits<GridNode> { - static bool AllowFrom(const NGLayoutInputNode& node) { return node.IsGrid(); } + static bool AllowFrom(const LayoutInputNode& node) { return node.IsGrid(); } }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/inline/README.md b/third_party/blink/renderer/core/layout/inline/README.md index 3478284..947b7d5 100644 --- a/third_party/blink/renderer/core/layout/inline/README.md +++ b/third_party/blink/renderer/core/layout/inline/README.md
@@ -41,9 +41,9 @@ </div> ``` -### NGLayoutInputNode ### +### LayoutInputNode ### -* NGBlockNode +* BlockNode - InlineNode - InlineItem (open tag, span) - InlineItem (text, "Hello") @@ -269,7 +269,7 @@ 1. Users of baseline should request what kind and type of the baseline they need by calling [NGConstraintSpaceBuilder]`::AddBaselineRequest()`. -2. Call [NGLayoutInputNode]`::Layout()`, +2. Call [LayoutInputNode]`::Layout()`, that calls appropriate layout algorithm. 3. Each layout algorithm computes baseline according to the requests. 4. Users retrieve the result by [NGPhysicalBoxFragment]`::Baseline()`, @@ -370,6 +370,7 @@ [UAX#9 Reordering Resolved Levels]: http://www.unicode.org/reports/tr9/#Reordering_Resolved_Levels [BidiParagraph]: ../../../platform/text/bidi_paragraph.h +[BlockNode]: ../ng/ng_block_node.h [FontBaseline]: ../../../platform/fonts/font_baseline.h [FragmentItem]: ng_fragment_item.h [FragmentItems]: ng_fragment_items.h @@ -378,17 +379,16 @@ [InlineItemResult]: ng_inline_item_result.h [InlineLayoutAlgorithm]: ng_inline_layout_algorithm.h [InlineNode]: ng_inline_node.h +[LayoutInputNode]: ../ng/ng_layout_input_node.h [LineBreaker]: ng_line_breaker.h [LogicalLineItem]: ng_logical_line_item.h [LogicalLineItems]: ng_logical_line_items.h [NGBaselineAlgorithmType]: ng_baseline.h [NGBaselineRequest]: ng_baseline.h -[NGBlockNode]: ../ng/ng_block_node.h [NGBoxFragment]: ../ng/ng_box_fragment.h [NGBoxFragmentBuilder]: ../ng/ng_box_fragment_builder.h [NGConstraintSpace]: ../ng/ng_constraint_space_builder.h [NGConstraintSpaceBuilder]: ../ng/ng_constraint_space_builder.h -[NGLayoutInputNode]: ../ng/ng_layout_input_node.h [NGPhysicalBoxFragment]: ../ng/ng_physical_box_fragment.h [NGPhysicalFragment]: ../ng/ng_physical_fragment.h [NGPhysicalTextFragment]: ng_physical_text_fragment.h
diff --git a/third_party/blink/renderer/core/layout/inline/inline_box_state.cc b/third_party/blink/renderer/core/layout/inline/inline_box_state.cc index 6a2287e..9aa1ed0c 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_box_state.cc +++ b/third_party/blink/renderer/core/layout/inline/inline_box_state.cc
@@ -860,8 +860,7 @@ if (child.out_of_flow_positioned_box) { DCHECK(item->GetLayoutObject()->IsLayoutInline()); - NGBlockNode oof_box( - To<LayoutBox>(child.out_of_flow_positioned_box.Get())); + BlockNode oof_box(To<LayoutBox>(child.out_of_flow_positioned_box.Get())); // child.offset is the static position wrt. the linebox. As we are adding // this as a child of an inline level fragment, we adjust the static
diff --git a/third_party/blink/renderer/core/layout/inline/inline_break_token.h b/third_party/blink/renderer/core/layout/inline/inline_break_token.h index 6da7269..0146c08 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_break_token.h +++ b/third_party/blink/renderer/core/layout/inline/inline_break_token.h
@@ -87,7 +87,7 @@ unsigned flags /* InlineBreakTokenFlags */, const NGBlockBreakToken* sub_break_token); - explicit InlineBreakToken(PassKey, NGLayoutInputNode node); + explicit InlineBreakToken(PassKey, LayoutInputNode node); #if DCHECK_IS_ON() String ToString() const;
diff --git a/third_party/blink/renderer/core/layout/inline/inline_child_layout_context.cc b/third_party/blink/renderer/core/layout/inline/inline_child_layout_context.cc index 6e8e443..35fcf1f 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_child_layout_context.cc +++ b/third_party/blink/renderer/core/layout/inline/inline_child_layout_context.cc
@@ -35,7 +35,7 @@ // determine whether it's reasonable to pre-allocate a buffer for all the // estimated fragment items inside the node. bool IsBlockFragmented(const NGBoxFragmentBuilder& fragment_builder) { - const NGConstraintSpace& space = fragment_builder.ConstraintSpace(); + const NGConstraintSpace& space = fragment_builder.GetConstraintSpace(); return space.HasBlockFragmentation() && space.HasKnownFragmentainerBlockSize(); }
diff --git a/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm.cc b/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm.cc index f418acf1..2bf37c5 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm.cc
@@ -261,7 +261,7 @@ LogicalLineItems* line_box, InlineLayoutStateStack* box_states) const { InlineBoxState* box = box_states->OnOpenTag( - ConstraintSpace(), item, item_result, baseline_type_, line_box); + GetConstraintSpace(), item, item_result, baseline_type_, line_box); // Compute text metrics for all inline boxes since even empty inlines // influence the line height, except when quirks mode and the box is empty // for the purpose of empty block calculation. @@ -285,8 +285,8 @@ InlineBoxState* box) { if (UNLIKELY(quirks_mode_ && !item.IsEmptyItem())) box->EnsureTextMetrics(*item.Style(), *box->font, baseline_type_); - box = - box_states_->OnCloseTag(ConstraintSpace(), line_box, box, baseline_type_); + box = box_states_->OnCloseTag(GetConstraintSpace(), line_box, box, + baseline_type_); // Just clear |NeedsLayout| flags. Culled inline boxes do not need paint // invalidations. If this object produces box fragments, // |InlineBoxStateStack| takes care of invalidations. @@ -366,7 +366,7 @@ quirks_mode_, &line_box); for (const InlineItem* item : open_items) { InlineItemResult item_result; - LineBreaker::ComputeOpenTagResult(*item, ConstraintSpace(), + LineBreaker::ComputeOpenTagResult(*item, GetConstraintSpace(), Node().IsSvgText(), &item_result); HandleOpenTag(*item, item_result, &line_box, box_states); } @@ -506,7 +506,7 @@ TextDirection direction = item.GetLayoutObject()->StyleRef().IsOriginalDisplayInlineType() ? item.Direction() - : ConstraintSpace().Direction(); + : GetConstraintSpace().Direction(); line_box->AddChild(item.GetLayoutObject(), item.BidiLevel(), direction); has_out_of_flow_positioned_items = true; @@ -541,7 +541,7 @@ } } - box_states_->OnEndPlaceItems(ConstraintSpace(), line_box, baseline_type_); + box_states_->OnEndPlaceItems(GetConstraintSpace(), line_box, baseline_type_); if (UNLIKELY(Node().IsBidiEnabled())) { box_states_->PrepareForReorder(line_box); @@ -566,9 +566,9 @@ // - 'text-overflow: ellipsis' is set and we *aren't* a line-clamp context. // - If we've reached the line-clamp limit. if (UNLIKELY(((line_info->HasOverflow() && - !ConstraintSpace().IsLineClampContext() && + !GetConstraintSpace().IsLineClampContext() && node_.GetLayoutBlockFlow()->ShouldTruncateOverflowingText()) || - ConstraintSpace().LinesUntilClamp() == 1) && + GetConstraintSpace().LinesUntilClamp() == 1) && !line_info->IsBlockInInline())) { DCHECK(!line_info->IsBlockInInline()); LineTruncator truncator(*line_info); @@ -588,7 +588,7 @@ if (line_info->IsBlockInInline()) { container_builder_.SetBfcLineOffset( - ConstraintSpace().GetBfcOffset().line_offset); + GetConstraintSpace().GetBfcOffset().line_offset); } else { // Other 'text-align' values than 'justify' move line boxes as a whole, but // indivisual items do not change their relative position to the line box. @@ -674,7 +674,7 @@ PlaceRelativePositionedItems(line_box); // Apply any relative positioned offsets to any boxes (and their children). - box_states_->ApplyRelativePositioning(ConstraintSpace(), line_box); + box_states_->ApplyRelativePositioning(GetConstraintSpace(), line_box); // Create box fragments if needed. After this point forward, |line_box| is a // tree structure. @@ -682,7 +682,7 @@ // the children have their layout_result, fragment, (or similar) set to null, // creating a "hole" in the array. if (box_states_->HasBoxFragments()) { - box_states_->CreateBoxFragments(ConstraintSpace(), line_box, + box_states_->CreateBoxFragments(GetConstraintSpace(), line_box, line_info->IsBlockInInline()); } @@ -804,7 +804,7 @@ layout_object->SetIsTruncated(false); InlineBoxState* box = box_states_->OnOpenTag( - ConstraintSpace(), item, *item_result, baseline_type_, *line_box); + GetConstraintSpace(), item, *item_result, baseline_type_, *line_box); if (LIKELY(!IsA<LayoutTextCombine>(layout_object))) { PlaceLayoutResult(item_result, line_box, box, box->margin_inline_start); @@ -822,7 +822,7 @@ item_result->inline_size, /* children_count */ 0, item.BidiLevel()); } - return box_states_->OnCloseTag(ConstraintSpace(), line_box, box, + return box_states_->OnCloseTag(GetConstraintSpace(), line_box, box, baseline_type_); } @@ -836,7 +836,7 @@ const InlineItem& item = *item_result->item; DCHECK(item.Style()); FontHeight metrics = - LogicalBoxFragment(ConstraintSpace().GetWritingDirection(), + LogicalBoxFragment(GetConstraintSpace().GetWritingDirection(), To<NGPhysicalBoxFragment>( item_result->layout_result->PhysicalFragment())) .BaselineMetrics(item_result->margins, baseline_type_); @@ -863,7 +863,7 @@ const NGLayoutResult& result = *item_result->layout_result; const auto& box_fragment = To<NGPhysicalBoxFragment>(result.PhysicalFragment()); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), box_fragment); // Setup |container_builder_|. Set it up here instead of in |CreateLine|, @@ -939,16 +939,16 @@ // Similarly this uses the available size to determine which edge to align // to, and *does not* avoid floats. LayoutUnit block_level_line_location = - IsLtr(ConstraintSpace().Direction()) + IsLtr(GetConstraintSpace().Direction()) ? LayoutUnit() - : ConstraintSpace().AvailableSize().inline_size; + : GetConstraintSpace().AvailableSize().inline_size; // This offset represents the position of the "next" line, relative to the // line we are currently creating, (this takes into account text-indent, etc). LayoutUnit block_level_inline_offset = block_level_line_location - (container_builder_.BfcLineOffset() - - ConstraintSpace().GetBfcOffset().line_offset); + GetConstraintSpace().GetBfcOffset().line_offset); // To correctly determine which "line" block-level out-of-flow positioned // object is placed on, we need to keep track of if there is any inline-level @@ -1035,7 +1035,7 @@ LayoutUnit bfc_line_offset = container_builder_.BfcLineOffset(); LayoutUnit bfc_block_offset = line_info->IsEmptyLine() - ? ConstraintSpace().ExpectedBfcBlockOffset() + ? GetConstraintSpace().ExpectedBfcBlockOffset() : line_info->GetBfcOffset().block_offset + ruby_block_start_adjust; for (LogicalLineItem& child : *line_box) { @@ -1077,8 +1077,8 @@ child.bfc_offset.block_offset - bfc_block_offset + baseline_adjustment; // We need to manually account for the flipped-lines writing mode here :(. - if (IsFlippedLinesWritingMode(ConstraintSpace().GetWritingMode())) { - LogicalFragment fragment(ConstraintSpace().GetWritingDirection(), + if (IsFlippedLinesWritingMode(GetConstraintSpace().GetWritingMode())) { + LogicalFragment fragment(GetConstraintSpace().GetWritingDirection(), child.layout_result->PhysicalFragment()); block_offset = -fragment.BlockSize() - block_offset; @@ -1096,7 +1096,7 @@ if (!physical_fragment) continue; child.rect.offset += ComputeRelativeOffsetForInline( - ConstraintSpace(), physical_fragment->Style()); + GetConstraintSpace(), physical_fragment->Style()); } } @@ -1292,9 +1292,10 @@ LayoutUnit block_offset_shift = annotation_overflow_block_start; // If the previous line has block-end annotation overflow and this line has // block-start annotation space, shift up the block offset of this line. - if (ConstraintSpace().BlockStartAnnotationSpace() < LayoutUnit() && + if (GetConstraintSpace().BlockStartAnnotationSpace() < LayoutUnit() && annotation_space_block_start) { - const LayoutUnit overflow = -ConstraintSpace().BlockStartAnnotationSpace(); + const LayoutUnit overflow = + -GetConstraintSpace().BlockStartAnnotationSpace(); block_offset_shift = -std::min(annotation_space_block_start, overflow); } @@ -1302,9 +1303,9 @@ // has block-end annotation space, borrow the block-end space of the // previous line and shift down the block offset by |overflow - space|. if (annotation_overflow_block_start && - ConstraintSpace().BlockStartAnnotationSpace() > LayoutUnit()) { + GetConstraintSpace().BlockStartAnnotationSpace() > LayoutUnit()) { block_offset_shift = (annotation_overflow_block_start - - ConstraintSpace().BlockStartAnnotationSpace()) + GetConstraintSpace().BlockStartAnnotationSpace()) .ClampNegativeToZero(); } @@ -1351,7 +1352,7 @@ bfc_offset.block_offset - block_end_offset_without_clearence); } - if (ConstraintSpace().HasBlockFragmentation() && + if (GetConstraintSpace().HasBlockFragmentation() && GetExclusionSpace().NeedsClearancePastFragmentainer(clear_type)) { return false; } @@ -1360,17 +1361,18 @@ } const NGLayoutResult* InlineLayoutAlgorithm::Layout() { - ExclusionSpace initial_exclusion_space(ConstraintSpace().GetExclusionSpace()); + const auto& constraint_space = GetConstraintSpace(); + ExclusionSpace initial_exclusion_space(constraint_space.GetExclusionSpace()); // Clear break tokens (for fragmented floats) propagated from the previous // line (or even the *current* line, in cases where we retry layout after // having resolved the BFC offset). context_->ClearParallelFlowBreakTokens(); - end_margin_strut_ = ConstraintSpace().GetMarginStrut(); + end_margin_strut_ = constraint_space.GetMarginStrut(); container_builder_.SetAdjoiningObjectTypes( - ConstraintSpace().AdjoiningObjectTypes()); - lines_until_clamp_ = ConstraintSpace().LinesUntilClamp(); + constraint_space.AdjoiningObjectTypes()); + lines_until_clamp_ = constraint_space.LinesUntilClamp(); // In order to get the correct list of layout opportunities, we need to // position any "leading" floats within the exclusion space first. @@ -1381,14 +1383,14 @@ // we might be an empty line. bool is_pushed_by_floats = false; LayoutUnit bfc_block_offset = - ConstraintSpace().ForcedBfcBlockOffset().value_or( - ConstraintSpace().GetBfcOffset().block_offset + - ConstraintSpace().GetMarginStrut().Sum()); + constraint_space.ForcedBfcBlockOffset().value_or( + constraint_space.GetBfcOffset().block_offset + + constraint_space.GetMarginStrut().Sum()); // Also apply clearance if necessary. - if (ConstraintSpace().HasClearanceOffset() && - bfc_block_offset < ConstraintSpace().ClearanceOffset()) { - bfc_block_offset = ConstraintSpace().ClearanceOffset(); + if (constraint_space.HasClearanceOffset() && + bfc_block_offset < constraint_space.ClearanceOffset()) { + bfc_block_offset = constraint_space.ClearanceOffset(); is_pushed_by_floats = true; } @@ -1405,9 +1407,9 @@ const EClear clear_type = UNLIKELY(Node().HasInitialLetterBox()) ? EClear::kBoth - : Node().Style().Clear(ConstraintSpace().Direction()); + : Node().Style().Clear(constraint_space.Direction()); const LayoutUnit initial_letter_clearance = - ConstraintSpace().GetExclusionSpace().InitialLetterClearanceOffset( + constraint_space.GetExclusionSpace().InitialLetterClearanceOffset( clear_type); if (initial_letter_clearance > bfc_block_offset) { // The initial letter box causes container separation to reuse layout @@ -1426,8 +1428,8 @@ // front, as if the line breaker may add floats and change the opportunities. const LayoutOpportunityVector& opportunities = initial_exclusion_space.AllLayoutOpportunities( - {ConstraintSpace().GetBfcOffset().line_offset, bfc_block_offset}, - ConstraintSpace().AvailableSize().inline_size); + {constraint_space.GetBfcOffset().line_offset, bfc_block_offset}, + constraint_space.AvailableSize().inline_size); const InlineBreakToken* break_token = BreakToken(); @@ -1462,7 +1464,7 @@ // to check if the inline-size got saturated first). if (opportunity.rect.InlineSize() != LayoutUnit::Max()) { DCHECK_EQ(opportunity.rect.InlineSize(), - ConstraintSpace().AvailableSize().inline_size); + constraint_space.AvailableSize().inline_size); } DCHECK_EQ(opportunity.rect.BlockSize(), LayoutUnit::Max()); } @@ -1474,11 +1476,11 @@ is_line_created = false; LineLayoutOpportunity line_opportunity = - opportunity.ComputeLineLayoutOpportunity(ConstraintSpace(), + opportunity.ComputeLineLayoutOpportunity(constraint_space, line_block_size, block_delta); if (UNLIKELY(line_break_strategy.NeedsToPrepare())) { line_break_strategy.Prepare( - context_, Node(), ConstraintSpace(), + context_, Node(), constraint_space, base::make_span(opportunities_it, opportunities.end()), line_opportunity, leading_floats, break_token, &GetExclusionSpace()); } @@ -1492,7 +1494,7 @@ line_opportunity.bfc_block_offset}); } else { LineBreaker line_breaker(Node(), LineBreakerMode::kContent, - ConstraintSpace(), line_opportunity, + constraint_space, line_opportunity, leading_floats, break_token, column_spanner_path_, &GetExclusionSpace()); line_break_strategy.SetupLineBreaker(context_, line_breaker); @@ -1542,7 +1544,7 @@ // Abort if something before needs to know the correct BFC block-offset. if (container_builder_.AdjoiningObjectTypes() && - bfc_block_offset != ConstraintSpace().ExpectedBfcBlockOffset()) { + bfc_block_offset != constraint_space.ExpectedBfcBlockOffset()) { items_builder->ReleaseCurrentLogicalLineItems(); return container_builder_.Abort( NGLayoutResult::kBfcBlockOffsetResolved); @@ -1554,7 +1556,7 @@ // container autowraps, continue to the next opportunity. if (line_info.HasOverflow() && !line_opportunity.IsEqualToAvailableFloatInlineSize( - ConstraintSpace().AvailableSize().inline_size) && + constraint_space.AvailableSize().inline_size) && Node().Style().ShouldWrapLine()) { DCHECK(!line_info.IsBlockInInline()); @@ -1639,7 +1641,7 @@ !line_info.IsEmptyLine())) { LineLayoutOpportunity line_opportunity_with_height = opportunity.ComputeLineLayoutOpportunity( - ConstraintSpace(), total_block_size, block_delta); + constraint_space, total_block_size, block_delta); if (line_opportunity_with_height.AvailableInlineSize() != line_opportunity.AvailableInlineSize()) { @@ -1683,7 +1685,7 @@ // Finally respect the forced BFC block-offset if present. if (auto forced_bfc_block_offset = - ConstraintSpace().ForcedBfcBlockOffset()) { + constraint_space.ForcedBfcBlockOffset()) { container_builder_.SetBfcBlockOffset(*forced_bfc_block_offset); container_builder_.SetLineBoxBfcBlockOffset(*forced_bfc_block_offset); } @@ -1751,18 +1753,18 @@ container_builder_.AddAdjoiningObjectTypes( item.GetLayoutObject()->StyleRef().Floating( - ConstraintSpace().Direction()) == EFloat::kLeft + GetConstraintSpace().Direction()) == EFloat::kLeft ? kAdjoiningFloatLeft : kAdjoiningFloatRight); // Place any floats at the "expected" BFC block-offset, this may be an // optimistic guess. const LayoutUnit origin_bfc_block_offset = - ConstraintSpace().ExpectedBfcBlockOffset(); + GetConstraintSpace().ExpectedBfcBlockOffset(); PositionedFloat positioned_float = PositionFloat( origin_bfc_block_offset, item.GetLayoutObject(), &exclusion_space); - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { // Propagate any breaks before or inside floats to the block container. if (const auto* float_break_token = positioned_float.BreakToken()) { const auto* parallel_token = @@ -1782,15 +1784,16 @@ LayoutUnit origin_bfc_block_offset, LayoutObject* floating_object, ExclusionSpace* exclusion_space) { - BfcOffset origin_bfc_offset = {ConstraintSpace().GetBfcOffset().line_offset, + const auto& space = GetConstraintSpace(); + BfcOffset origin_bfc_offset = {space.GetBfcOffset().line_offset, origin_bfc_block_offset}; UnpositionedFloat unpositioned_float( - NGBlockNode(To<LayoutBox>(floating_object)), - /* break_token */ nullptr, ConstraintSpace().AvailableSize(), - ConstraintSpace().PercentageResolutionSize(), - ConstraintSpace().ReplacedPercentageResolutionSize(), origin_bfc_offset, - ConstraintSpace(), Style()); + BlockNode(To<LayoutBox>(floating_object)), + /* break_token */ nullptr, space.AvailableSize(), + space.PercentageResolutionSize(), + space.ReplacedPercentageResolutionSize(), origin_bfc_offset, space, + Style()); PositionedFloat positioned_float = ::blink::PositionFloat(&unpositioned_float, exclusion_space);
diff --git a/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm_test.cc index f36e8b85..a635d92a 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/inline/inline_layout_algorithm_test.cc
@@ -358,7 +358,7 @@ } // A block with inline children generates fragment tree as follows: -// - A box fragment created by NGBlockNode +// - A box fragment created by BlockNode // - A wrapper box fragment created by InlineNode // - Line box fragments. // This test verifies that borders/paddings are applied to the wrapper box.
diff --git a/third_party/blink/renderer/core/layout/inline/inline_node.cc b/third_party/blink/renderer/core/layout/inline/inline_node.cc index 2f6625e..6582c1f 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_node.cc +++ b/third_party/blink/renderer/core/layout/inline/inline_node.cc
@@ -494,7 +494,7 @@ } // namespace InlineNode::InlineNode(LayoutBlockFlow* block) - : NGLayoutInputNode(block, kInline) { + : LayoutInputNode(block, kInline) { DCHECK(block); DCHECK(block->IsLayoutNGObject()); if (!block->GetInlineNodeData()) { @@ -1890,7 +1890,7 @@ LayoutObject* floating_object = item.GetLayoutObject(); DCHECK(floating_object && floating_object->IsFloating()); - NGBlockNode float_node(To<LayoutBox>(floating_object)); + BlockNode float_node(To<LayoutBox>(floating_object)); NGMinMaxConstraintSpaceBuilder builder(space, style, float_node, /* is_new_fc */ true);
diff --git a/third_party/blink/renderer/core/layout/inline/inline_node.h b/third_party/blink/renderer/core/layout/inline/inline_node.h index c9c7841..067b762 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_node.h +++ b/third_party/blink/renderer/core/layout/inline/inline_node.h
@@ -27,10 +27,10 @@ // Represents an anonymous block box to be laid out, that contains consecutive // inline nodes and their descendants. -class CORE_EXPORT InlineNode : public NGLayoutInputNode { +class CORE_EXPORT InlineNode : public LayoutInputNode { public: explicit InlineNode(LayoutBlockFlow*); - explicit InlineNode(std::nullptr_t) : NGLayoutInputNode(nullptr) {} + explicit InlineNode(std::nullptr_t) : LayoutInputNode(nullptr) {} LayoutBlockFlow* GetLayoutBlockFlow() const { return To<LayoutBlockFlow>(box_.Get()); @@ -216,9 +216,7 @@ template <> struct DowncastTraits<InlineNode> { - static bool AllowFrom(const NGLayoutInputNode& node) { - return node.IsInline(); - } + static bool AllowFrom(const LayoutInputNode& node) { return node.IsInline(); } }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/inline/inline_node_test.cc b/third_party/blink/renderer/core/layout/inline/inline_node_test.cc index 4be265b..812f11e 100644 --- a/third_party/blink/renderer/core/layout/inline/inline_node_test.cc +++ b/third_party/blink/renderer/core/layout/inline/inline_node_test.cc
@@ -1588,7 +1588,7 @@ sample.GetPseudoElement(kPseudoIdFirstLetter)->GetLayoutObject()); EXPECT_TRUE(InlineNode(&block_flow).HasInitialLetterBox()); - EXPECT_TRUE(NGBlockNode(&initial_letter_box).IsInitialLetterBox()); + EXPECT_TRUE(BlockNode(&initial_letter_box).IsInitialLetterBox()); EXPECT_TRUE(InlineNode(&initial_letter_box).IsInitialLetterBox()); EXPECT_TRUE(initial_letter_box.GetPhysicalFragment(0)->IsInitialLetterBox());
diff --git a/third_party/blink/renderer/core/layout/inline/line_box_fragment_builder.cc b/third_party/blink/renderer/core/layout/inline/line_box_fragment_builder.cc index dbb0e093..889ae2c 100644 --- a/third_party/blink/renderer/core/layout/inline/line_box_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/inline/line_box_fragment_builder.cc
@@ -54,10 +54,10 @@ PropagateFromLayoutResultAndFragment( *child.layout_result, child.Offset() - - ComputeRelativeOffsetForInline(ConstraintSpace(), + ComputeRelativeOffsetForInline(GetConstraintSpace(), child.PhysicalFragment()->Style()), ComputeRelativeOffsetForOOFInInline( - ConstraintSpace(), child.PhysicalFragment()->Style())); + GetConstraintSpace(), child.PhysicalFragment()->Style())); // Skip over any children, the information should have already been // propagated into this layout result. @@ -68,7 +68,7 @@ } if (child.out_of_flow_positioned_box) { AddOutOfFlowInlineChildCandidate( - NGBlockNode(To<LayoutBox>(child.out_of_flow_positioned_box.Get())), + BlockNode(To<LayoutBox>(child.out_of_flow_positioned_box.Get())), child.Offset(), child.container_direction); child.out_of_flow_positioned_box = nullptr; }
diff --git a/third_party/blink/renderer/core/layout/inline/line_breaker.cc b/third_party/blink/renderer/core/layout/inline/line_breaker.cc index cf14c1b..1db925f 100644 --- a/third_party/blink/renderer/core/layout/inline/line_breaker.cc +++ b/third_party/blink/renderer/core/layout/inline/line_breaker.cc
@@ -2586,7 +2586,7 @@ // > The first line of a table-cell or inline-block cannot be the first // > formatted line of an ancestor element. item_result->layout_result = - NGBlockNode(To<LayoutBox>(item.GetLayoutObject())) + BlockNode(To<LayoutBox>(item.GetLayoutObject())) .LayoutAtomicInline(constraint_space_, node_.Style(), /* use_first_line_style */ false, baseline_algorithm_type); @@ -2657,7 +2657,7 @@ } DCHECK(mode_ == LineBreakerMode::kMinContent || !max_size_cache_); - NGBlockNode child(To<LayoutBox>(item.GetLayoutObject())); + BlockNode child(To<LayoutBox>(item.GetLayoutObject())); NGMinMaxConstraintSpaceBuilder builder(constraint_space_, node_.Style(), child, /* is_new_fc */ true); @@ -2714,7 +2714,7 @@ constraint_space_.GetExclusionSpace().MoveAndUpdateDerivedGeometry( *exclusion_space_); - NGBlockNode block_node(To<LayoutBox>(item.GetLayoutObject())); + BlockNode block_node(To<LayoutBox>(item.GetLayoutObject())); const NGColumnSpannerPath* spanner_path_for_child = FollowColumnSpannerPath(column_spanner_path_, block_node); const NGLayoutResult* layout_result = @@ -2870,7 +2870,7 @@ LayoutUnit bfc_block_offset = line_opportunity_.bfc_block_offset; UnpositionedFloat unpositioned_float( - NGBlockNode(To<LayoutBox>(item.GetLayoutObject())), float_break_token, + BlockNode(To<LayoutBox>(item.GetLayoutObject())), float_break_token, constraint_space_.AvailableSize(), constraint_space_.PercentageResolutionSize(), constraint_space_.ReplacedPercentageResolutionSize(),
diff --git a/third_party/blink/renderer/core/layout/inline/score_line_breaker.cc b/third_party/blink/renderer/core/layout/inline/score_line_breaker.cc index e1e5137..a8b7f29 100644 --- a/third_party/blink/renderer/core/layout/inline/score_line_breaker.cc +++ b/third_party/blink/renderer/core/layout/inline/score_line_breaker.cc
@@ -79,10 +79,10 @@ // Compute line breaks and cache the results (`LineInfo`) up to // `LineInfoList::kCapacity` lines. LayoutUnit line_width = line_widths_[line_index]; - LineBreaker line_breaker(node_, LineBreakerMode::kContent, ConstraintSpace(), - LineLayoutOpportunity(line_width), leading_floats, - break_token_, - /* column_spanner_path */ nullptr, exclusion_space_); + LineBreaker line_breaker( + node_, LineBreakerMode::kContent, GetConstraintSpace(), + LineLayoutOpportunity(line_width), leading_floats, break_token_, + /* column_spanner_path */ nullptr, exclusion_space_); const int lines_until_clamp = space_.LinesUntilClamp().value_or(0); for (;;) { LineInfo& line_info = line_info_list.Append();
diff --git a/third_party/blink/renderer/core/layout/inline/score_line_breaker.h b/third_party/blink/renderer/core/layout/inline/score_line_breaker.h index fa9ffec..e697ffe 100644 --- a/third_party/blink/renderer/core/layout/inline/score_line_breaker.h +++ b/third_party/blink/renderer/core/layout/inline/score_line_breaker.h
@@ -60,7 +60,7 @@ return is_balanced_ ? kMaxLinesForBalance : kMaxLinesForOptimal; } - const NGConstraintSpace& ConstraintSpace() const { return space_; } + const NGConstraintSpace& GetConstraintSpace() const { return space_; } const InlineBreakToken* BreakToken() const { return break_token_; } // The primary entry point of doing all the work described in the class
diff --git a/third_party/blink/renderer/core/layout/layout_block.h b/third_party/blink/renderer/core/layout/layout_block.h index 4add0067..926e0b7 100644 --- a/third_party/blink/renderer/core/layout/layout_block.h +++ b/third_party/blink/renderer/core/layout/layout_block.h
@@ -34,8 +34,8 @@ namespace blink { +class BlockNode; struct PaintInfo; -class NGBlockNode; typedef HeapLinkedHashSet<Member<LayoutBox>> TrackedLayoutBoxLinkedHashSet; typedef HeapHashMap<WeakMember<const LayoutBlock>, @@ -297,7 +297,7 @@ // This is necessary for now for interoperability between the old and new // layout code. Primarily for calling layoutPositionedObjects at the moment. - friend class NGBlockNode; + friend class BlockNode; }; template <>
diff --git a/third_party/blink/renderer/core/layout/layout_box.cc b/third_party/blink/renderer/core/layout/layout_box.cc index 857f1e9..52622ed 100644 --- a/third_party/blink/renderer/core/layout/layout_box.cc +++ b/third_party/blink/renderer/core/layout/layout_box.cc
@@ -257,7 +257,7 @@ NGConstraintSpaceBuilder builder(mode, button_style.GetWritingDirection(), /* is_new_fc */ true); LayoutUnit max = - NGBlockNode(button_box) + BlockNode(button_box) .ComputeMinMaxSizes(mode, MinMaxSizesType::kIntrinsic, builder.ToConstraintSpace()) .sizes.max_size; @@ -914,7 +914,7 @@ DCHECK(previous_result); auto space = previous_result->GetConstraintSpaceForCaching(); DCHECK_EQ(space.GetWritingMode(), StyleRef().GetWritingMode()); - const NGLayoutResult* result = NGBlockNode(this).Layout(space); + const NGLayoutResult* result = BlockNode(this).Layout(space); GetDocument().GetFrame()->GetInputMethodController().DidLayoutSubtree(*this); if (IsOutOfFlowPositioned()) { @@ -3866,7 +3866,7 @@ return; EnsureRareData().layout_child_ = - MakeGarbageCollected<CustomLayoutChild>(*definition, NGBlockNode(this)); + MakeGarbageCollected<CustomLayoutChild>(*definition, BlockNode(this)); } void LayoutBox::ClearCustomLayoutChild() {
diff --git a/third_party/blink/renderer/core/layout/layout_box.h b/third_party/blink/renderer/core/layout/layout_box.h index edc8e58..c8b4c78 100644 --- a/third_party/blink/renderer/core/layout/layout_box.h +++ b/third_party/blink/renderer/core/layout/layout_box.h
@@ -699,7 +699,7 @@ // // |out_cache_status| indicates what type of layout pass is required. // - // TODO(ikilpatrick): Move this function into NGBlockNode. + // TODO(ikilpatrick): Move this function into BlockNode. const NGLayoutResult* CachedLayoutResult( const NGConstraintSpace&, const NGBlockBreakToken*,
diff --git a/third_party/blink/renderer/core/layout/layout_box_hot.cc b/third_party/blink/renderer/core/layout/layout_box_hot.cc index 8476a01..bc6c649 100644 --- a/third_party/blink/renderer/core/layout/layout_box_hot.cc +++ b/third_party/blink/renderer/core/layout/layout_box_hot.cc
@@ -151,7 +151,7 @@ cache_status = NGLayoutCacheStatus::kCanReuseLines; } - NGBlockNode node(this); + BlockNode node(this); NGLayoutCacheStatus size_cache_status = CalculateSizeBasedLayoutCacheStatus( node, break_token, *cached_layout_result, new_space, initial_fragment_geometry); @@ -518,7 +518,7 @@ // // As a result, the cached layout result always needs to contain the previous // percentage resolution size in order for the first-tier cache to work. - // See |NGBlockNode::CachedLayoutResultForOutOfFlowPositioned|. + // See |BlockNode::CachedLayoutResultForOutOfFlowPositioned|. bool needs_cached_result_update = node.IsOutOfFlowPositioned() && new_space.PercentageResolutionSize() !=
diff --git a/third_party/blink/renderer/core/layout/layout_view.cc b/third_party/blink/renderer/core/layout/layout_view.cc index 2d4f91a..c7f6ac6 100644 --- a/third_party/blink/renderer/core/layout/layout_view.cc +++ b/third_party/blink/renderer/core/layout/layout_view.cc
@@ -265,7 +265,7 @@ WritingMode mode = style.GetWritingMode(); NGConstraintSpaceBuilder builder(mode, style.GetWritingDirection(), /* is_new_fc */ true); - return NGBlockNode(this) + return BlockNode(this) .ComputeMinMaxSizes(mode, MinMaxSizesType::kIntrinsic, builder.ToConstraintSpace()) .sizes.min_size; @@ -853,7 +853,7 @@ builder.SetIsFixedInlineSize(true); builder.SetIsFixedBlockSize(true); - NGBlockNode(this).Layout(builder.ToConstraintSpace()); + BlockNode(this).Layout(builder.ToConstraintSpace()); initial_containing_block_resize_handled_list_ = nullptr; }
diff --git a/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.cc b/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.cc index cbf5b81aa..134eea0c 100644 --- a/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.cc +++ b/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.cc
@@ -17,7 +17,7 @@ UnpositionedListMarker::UnpositionedListMarker(LayoutOutsideListMarker* marker) : marker_layout_object_(marker) {} -UnpositionedListMarker::UnpositionedListMarker(const NGBlockNode& node) +UnpositionedListMarker::UnpositionedListMarker(const BlockNode& node) : UnpositionedListMarker(To<LayoutOutsideListMarker>(node.GetLayoutBox())) { } @@ -41,7 +41,7 @@ const ComputedStyle& parent_style, FontBaseline baseline_type) const { DCHECK(marker_layout_object_); - NGBlockNode marker_node(marker_layout_object_); + BlockNode marker_node(marker_layout_object_); // We need the first-line baseline from the list-marker, instead of the // typical atomic-inline baseline.
diff --git a/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.h b/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.h index 952c199..7705dc7 100644 --- a/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.h +++ b/third_party/blink/renderer/core/layout/list/unpositioned_list_marker.h
@@ -17,10 +17,10 @@ namespace blink { +class BlockNode; class ComputedStyle; class LayoutOutsideListMarker; class LayoutUnit; -class NGBlockNode; class NGConstraintSpace; class NGBoxFragmentBuilder; class NGLayoutResult; @@ -54,7 +54,7 @@ public: UnpositionedListMarker() : marker_layout_object_(nullptr) {} explicit UnpositionedListMarker(LayoutOutsideListMarker*); - explicit UnpositionedListMarker(const NGBlockNode&); + explicit UnpositionedListMarker(const BlockNode&); explicit operator bool() const { return marker_layout_object_ != nullptr; }
diff --git a/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.cc index e7c1d7c..2cf87bdc 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.cc
@@ -125,11 +125,11 @@ container_builder_.SetIsMathMLFraction(); } -void MathFractionLayoutAlgorithm::GatherChildren(NGBlockNode* numerator, - NGBlockNode* denominator) { - for (NGLayoutInputNode child = Node().FirstChild(); child; +void MathFractionLayoutAlgorithm::GatherChildren(BlockNode* numerator, + BlockNode* denominator) { + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { - NGBlockNode block_child = To<NGBlockNode>(child); + BlockNode block_child = To<BlockNode>(child); if (child.IsOutOfFlowPositioned()) { container_builder_.AddOutOfFlowChildCandidate( block_child, BorderScrollbarPadding().StartOffset()); @@ -154,28 +154,28 @@ const NGLayoutResult* MathFractionLayoutAlgorithm::Layout() { DCHECK(!BreakToken()); - NGBlockNode numerator = nullptr; - NGBlockNode denominator = nullptr; + BlockNode numerator = nullptr; + BlockNode denominator = nullptr; GatherChildren(&numerator, &denominator); const auto numerator_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), numerator); + Node(), ChildAvailableSize(), GetConstraintSpace(), numerator); const NGLayoutResult* numerator_layout_result = numerator.Layout(numerator_space); - const auto numerator_margins = - ComputeMarginsFor(numerator_space, numerator.Style(), ConstraintSpace()); + const auto numerator_margins = ComputeMarginsFor( + numerator_space, numerator.Style(), GetConstraintSpace()); const auto denominator_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), denominator); + Node(), ChildAvailableSize(), GetConstraintSpace(), denominator); const NGLayoutResult* denominator_layout_result = denominator.Layout(denominator_space); const auto denominator_margins = ComputeMarginsFor( - denominator_space, denominator.Style(), ConstraintSpace()); + denominator_space, denominator.Style(), GetConstraintSpace()); const LogicalBoxFragment numerator_fragment( - ConstraintSpace().GetWritingDirection(), + GetConstraintSpace().GetWritingDirection(), To<NGPhysicalBoxFragment>(numerator_layout_result->PhysicalFragment())); const LogicalBoxFragment denominator_fragment( - ConstraintSpace().GetWritingDirection(), + GetConstraintSpace().GetWritingDirection(), To<NGPhysicalBoxFragment>(denominator_layout_result->PhysicalFragment())); const auto baseline_type = Style().GetFontBaseline(); @@ -259,13 +259,13 @@ denominator_margins); LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -279,13 +279,13 @@ MinMaxSizes sizes; bool depends_on_block_constraints = false; - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) continue; const auto child_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), To<NGBlockNode>(child), + Style(), GetConstraintSpace(), To<BlockNode>(child), ChildAvailableSize().block_size); sizes.Encompass(child_result.sizes);
diff --git a/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.h index ae8d6a3..640fae7 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_fraction_layout_algorithm.h
@@ -11,7 +11,7 @@ namespace blink { class CORE_EXPORT MathFractionLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -22,7 +22,7 @@ MinMaxSizesResult ComputeMinMaxSizes(const MinMaxSizesFloatInput&) final; - void GatherChildren(NGBlockNode* numerator, NGBlockNode* denominator); + void GatherChildren(BlockNode* numerator, BlockNode* denominator); }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/mathml/math_layout_utils.cc b/third_party/blink/renderer/core/layout/mathml/math_layout_utils.cc index bc37c7c8..628e447 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_layout_utils.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_layout_utils.cc
@@ -18,10 +18,10 @@ namespace blink { NGConstraintSpace CreateConstraintSpaceForMathChild( - const NGBlockNode& parent_node, + const BlockNode& parent_node, const LogicalSize& child_available_size, const NGConstraintSpace& parent_space, - const NGLayoutInputNode& child, + const LayoutInputNode& child, NGCacheSlot cache_slot, const absl::optional<NGConstraintSpace::MathTargetStretchBlockSizes> target_stretch_block_sizes, @@ -47,7 +47,7 @@ MinMaxSizesResult ComputeMinAndMaxContentContributionForMathChild( const ComputedStyle& parent_style, const NGConstraintSpace& parent_space, - const NGBlockNode& child, + const BlockNode& child, LayoutUnit child_available_block_size) { DCHECK(child.CreatesNewFormattingContext()); NGMinMaxConstraintSpaceBuilder builder(parent_space, parent_style, child, @@ -65,35 +65,35 @@ return result; } -NGLayoutInputNode FirstChildInFlow(const NGBlockNode& node) { - NGLayoutInputNode child = node.FirstChild(); +LayoutInputNode FirstChildInFlow(const BlockNode& node) { + LayoutInputNode child = node.FirstChild(); while (child && child.IsOutOfFlowPositioned()) child = child.NextSibling(); return child; } -NGLayoutInputNode NextSiblingInFlow(const NGBlockNode& node) { - NGLayoutInputNode sibling = node.NextSibling(); +LayoutInputNode NextSiblingInFlow(const BlockNode& node) { + LayoutInputNode sibling = node.NextSibling(); while (sibling && sibling.IsOutOfFlowPositioned()) sibling = sibling.NextSibling(); return sibling; } -inline bool InFlowChildCountIs(const NGBlockNode& node, unsigned count) { +inline bool InFlowChildCountIs(const BlockNode& node, unsigned count) { DCHECK(count == 2 || count == 3); - auto child = To<NGBlockNode>(FirstChildInFlow(node)); + auto child = To<BlockNode>(FirstChildInFlow(node)); while (count && child) { - child = To<NGBlockNode>(NextSiblingInFlow(child)); + child = To<BlockNode>(NextSiblingInFlow(child)); count--; } return !count && !child; } -bool IsValidMathMLFraction(const NGBlockNode& node) { +bool IsValidMathMLFraction(const BlockNode& node) { return InFlowChildCountIs(node, 2); } -static bool IsPrescriptDelimiter(const NGBlockNode& block_node) { +static bool IsPrescriptDelimiter(const BlockNode& block_node) { auto* node = block_node.GetDOMNode(); return node && IsA<MathMLElement>(node) && node->HasTagName(mathml_names::kMprescriptsTag); @@ -101,14 +101,14 @@ // Valid according to: // https://w3c.github.io/mathml-core/#prescripts-and-tensor-indices-mmultiscripts -inline bool IsValidMultiscript(const NGBlockNode& node) { - auto child = To<NGBlockNode>(FirstChildInFlow(node)); +inline bool IsValidMultiscript(const BlockNode& node) { + auto child = To<BlockNode>(FirstChildInFlow(node)); if (!child || IsPrescriptDelimiter(child)) return false; bool number_of_scripts_is_even = true; bool prescript_delimiter_found = false; while (child) { - child = To<NGBlockNode>(NextSiblingInFlow(child)); + child = To<BlockNode>(NextSiblingInFlow(child)); if (!child) continue; if (IsPrescriptDelimiter(child)) { @@ -122,7 +122,7 @@ return number_of_scripts_is_even; } -bool IsValidMathMLScript(const NGBlockNode& node) { +bool IsValidMathMLScript(const BlockNode& node) { switch (node.ScriptType()) { case MathScriptType::kUnder: case MathScriptType::kOver: @@ -140,7 +140,7 @@ } } -bool IsValidMathMLRadical(const NGBlockNode& node) { +bool IsValidMathMLRadical(const BlockNode& node) { auto* radical = DynamicTo<MathMLRadicalElement>(node.GetDOMNode()); return !radical->HasIndex() || InFlowChildCountIs(node, 2); @@ -223,18 +223,18 @@ return sizes; } -bool IsUnderOverLaidOutAsSubSup(const NGBlockNode& node) { +bool IsUnderOverLaidOutAsSubSup(const BlockNode& node) { DCHECK(IsValidMathMLScript(node)); if (HasDisplayStyle(node.Style())) return false; if (!node.IsBlock() || !node.IsMathML()) return false; - const auto base = To<NGBlockNode>(FirstChildInFlow(node)); + const auto base = To<BlockNode>(FirstChildInFlow(node)); const auto base_properties = GetMathMLEmbellishedOperatorProperties(base); return base_properties && base_properties->has_movablelimits; } -bool IsTextOnlyToken(const NGBlockNode& node) { +bool IsTextOnlyToken(const BlockNode& node) { if (!node.IsBlock() || !node.IsMathML() || !node.FirstChild().IsInline()) return false; if (auto* element = DynamicTo<MathMLTokenElement>(node.GetDOMNode())) @@ -242,7 +242,7 @@ return false; } -bool IsOperatorWithSpecialShaping(const NGBlockNode& node) { +bool IsOperatorWithSpecialShaping(const BlockNode& node) { if (!IsTextOnlyToken(node)) return false; // https://w3c.github.io/mathml-core/#layout-of-operators @@ -302,7 +302,7 @@ // This function has bad theoretical worst-case complexity. However, real-life // MathML formulas don't use deeply nested space-like expressions so it should // be fine in in practice. See https://github.com/w3c/mathml/issues/115 -static bool IsSpaceLike(const NGBlockNode& node) { +static bool IsSpaceLike(const BlockNode& node) { DCHECK(node); if (!node.IsMathML()) return false; @@ -319,8 +319,8 @@ if ((element && (element->IsGroupingElement() || element->HasTagName(mathml_names::kMpaddedTag))) || node.IsAnonymous()) { - for (auto child = To<NGBlockNode>(FirstChildInFlow(node)); child; - child = To<NGBlockNode>(NextSiblingInFlow(child))) { + for (auto child = To<BlockNode>(FirstChildInFlow(node)); child; + child = To<BlockNode>(NextSiblingInFlow(child))) { if (!IsSpaceLike(child)) return false; } @@ -333,7 +333,7 @@ // MathML formulas don't use deeply nested expressions that are embellished // operators or that are essentially made of space-like descendants, so it // should be fine in in practice. See https://github.com/w3c/mathml/issues/115 -MathMLOperatorElement* GetCoreOperator(const NGBlockNode& node) { +MathMLOperatorElement* GetCoreOperator(const BlockNode& node) { if (!node || !node.IsMathML()) return nullptr; @@ -348,8 +348,8 @@ // 2. A scripted element or an <mfrac>, whose first in-flow child exists // and is an embellished operator; auto first_child = FirstChildInFlow(node); - return IsA<NGBlockNode>(first_child) - ? GetCoreOperator(To<NGBlockNode>(first_child)) + return IsA<BlockNode>(first_child) + ? GetCoreOperator(To<BlockNode>(first_child)) : nullptr; } if ((element && (element->IsGroupingElement() || @@ -361,8 +361,8 @@ // Note: This also handles the case of anonymous <mrow>'s generated by // <msqrt> and <mpadded> elements. MathMLOperatorElement* core_operator = nullptr; - for (auto child = To<NGBlockNode>(FirstChildInFlow(node)); child; - child = To<NGBlockNode>(NextSiblingInFlow(child))) { + for (auto child = To<BlockNode>(FirstChildInFlow(node)); child; + child = To<BlockNode>(NextSiblingInFlow(child))) { // Skip space-like children as they don't affect whether the parent is an // embellished operator. if (IsSpaceLike(child)) @@ -387,7 +387,7 @@ } // namespace absl::optional<MathMLEmbellishedOperatorProperties> -GetMathMLEmbellishedOperatorProperties(const NGBlockNode& node) { +GetMathMLEmbellishedOperatorProperties(const BlockNode& node) { auto* core_operator = GetCoreOperator(node); if (!core_operator) return absl::nullopt; @@ -423,8 +423,7 @@ return properties; } -bool IsStretchyOperator(const NGBlockNode& node, - bool stretch_axis_is_vertical) { +bool IsStretchyOperator(const BlockNode& node, bool stretch_axis_is_vertical) { const auto properties = GetMathMLEmbellishedOperatorProperties(node); return properties && properties->is_stretchy && properties->is_vertical == stretch_axis_is_vertical;
diff --git a/third_party/blink/renderer/core/layout/mathml/math_layout_utils.h b/third_party/blink/renderer/core/layout/mathml/math_layout_utils.h index f311bab2..9798438 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_layout_utils.h +++ b/third_party/blink/renderer/core/layout/mathml/math_layout_utils.h
@@ -12,20 +12,20 @@ namespace blink { +class BlockNode; +class LayoutInputNode; +class NGConstraintSpace; +class SimpleFontData; struct LogicalSize; struct MinMaxSizes; struct MinMaxSizesResult; -class NGBlockNode; -class NGConstraintSpace; -class NGLayoutInputNode; -class SimpleFontData; // Creates a new constraint space for the current child. NGConstraintSpace CreateConstraintSpaceForMathChild( - const NGBlockNode& parent_node, + const BlockNode& parent_node, const LogicalSize& child_available_size, const NGConstraintSpace& parent_constraint_space, - const NGLayoutInputNode&, + const LayoutInputNode&, const NGCacheSlot = NGCacheSlot::kLayout, const absl::optional<NGConstraintSpace::MathTargetStretchBlockSizes> target_stretch_block_sizes = absl::nullopt, @@ -35,15 +35,15 @@ MinMaxSizesResult ComputeMinAndMaxContentContributionForMathChild( const ComputedStyle& parent_style, const NGConstraintSpace& parent_constraint_space, - const NGBlockNode& child, + const BlockNode& child, LayoutUnit child_available_block_size); -NGLayoutInputNode FirstChildInFlow(const NGBlockNode&); -NGLayoutInputNode NextSiblingInFlow(const NGBlockNode&); +LayoutInputNode FirstChildInFlow(const BlockNode&); +LayoutInputNode NextSiblingInFlow(const BlockNode&); -bool IsValidMathMLFraction(const NGBlockNode&); -bool IsValidMathMLScript(const NGBlockNode&); -bool IsValidMathMLRadical(const NGBlockNode&); +bool IsValidMathMLFraction(const BlockNode&); +bool IsValidMathMLScript(const BlockNode&); +bool IsValidMathMLRadical(const BlockNode&); // https://w3c.github.io/mathml-core/#dfn-default-rule-thickness inline float RuleThicknessFallback(const ComputedStyle& style) { @@ -96,9 +96,9 @@ MinMaxSizes GetMinMaxSizesForVerticalStretchyOperator(const ComputedStyle&, UChar character); -bool IsUnderOverLaidOutAsSubSup(const NGBlockNode& node); -bool IsTextOnlyToken(const NGBlockNode& node); -bool IsOperatorWithSpecialShaping(const NGBlockNode& node); +bool IsUnderOverLaidOutAsSubSup(const BlockNode& node); +bool IsTextOnlyToken(const BlockNode& node); +bool IsOperatorWithSpecialShaping(const BlockNode& node); LayoutUnit MathTableBaseline(const ComputedStyle&, LayoutUnit block_offset); @@ -114,13 +114,13 @@ LayoutUnit rspace; }; absl::optional<MathMLEmbellishedOperatorProperties> -GetMathMLEmbellishedOperatorProperties(const NGBlockNode&); +GetMathMLEmbellishedOperatorProperties(const BlockNode&); -bool IsStretchyOperator(const NGBlockNode& node, bool stretch_axis_is_vertical); -inline bool IsBlockAxisStretchyOperator(const NGBlockNode& node) { +bool IsStretchyOperator(const BlockNode& node, bool stretch_axis_is_vertical); +inline bool IsBlockAxisStretchyOperator(const BlockNode& node) { return IsStretchyOperator(node, true); } -inline bool IsInlineAxisStretchyOperator(const NGBlockNode& node) { +inline bool IsInlineAxisStretchyOperator(const BlockNode& node) { return IsStretchyOperator(node, false); }
diff --git a/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.cc index 1fd13505..8d1a781 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.cc
@@ -39,16 +39,16 @@ // "large" or "stretched" version, from which we perform measurement and // painting. // See https://w3c.github.io/mathml-core/#layout-of-operators - NGLayoutInputNode child = Node().FirstChild(); + LayoutInputNode child = Node().FirstChild(); DCHECK(child && child.IsInline()); DCHECK(!child.NextSibling()); DCHECK(!child.IsOutOfFlowPositioned()); SimpleInlineChildLayoutContext context(To<InlineNode>(child), &container_builder_); - const NGLayoutResult* child_layout_result = - To<InlineNode>(child).Layout(ConstraintSpace(), /* break_token */ nullptr, - /* column_spanner_path */ nullptr, &context); + const NGLayoutResult* child_layout_result = To<InlineNode>(child).Layout( + GetConstraintSpace(), /* break_token */ nullptr, + /* column_spanner_path */ nullptr, &context); container_builder_.AddResult(*child_layout_result, {}); // https://w3c.github.io/mathml-core/#layout-of-operators @@ -59,12 +59,13 @@ // "If the operator has the stretchy property:" if (!element->IsVertical()) { // "If the stretch axis of the operator is inline." - if (ConstraintSpace().HasTargetStretchInlineSize()) - operator_target_size = ConstraintSpace().TargetStretchInlineSize(); + if (GetConstraintSpace().HasTargetStretchInlineSize()) { + operator_target_size = GetConstraintSpace().TargetStretchInlineSize(); + } } else { // "Otherwise, the stretch axis of the operator is block." if (auto target_stretch_block_sizes = - ConstraintSpace().TargetStretchBlockSizes()) { + GetConstraintSpace().TargetStretchBlockSizes()) { target_stretch_ascent = target_stretch_block_sizes->ascent; target_stretch_descent = target_stretch_block_sizes->descent; if (element->HasBooleanProperty(MathMLOperatorElement::kSymmetric)) { @@ -167,7 +168,7 @@ } LayoutUnit intrinsic_block_size = ascent + descent; LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetBaselines(ascent); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size);
diff --git a/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.h index b9e3154..a4823d4 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_operator_layout_algorithm.h
@@ -14,7 +14,7 @@ namespace blink { class CORE_EXPORT MathOperatorLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.cc index 6707464..74dc553 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.cc
@@ -44,33 +44,33 @@ } void MathPaddedLayoutAlgorithm::GetContentAsAnonymousMrow( - NGBlockNode* content) const { + BlockNode* content) const { // Node() is a LayoutNGMathMLBlockWithAnonymousMrow node, which is either // empty or contains a single anonymous mrow child. - if (NGLayoutInputNode child = Node().FirstChild()) { + if (LayoutInputNode child = Node().FirstChild()) { DCHECK(!child.NextSibling()); DCHECK(!child.IsOutOfFlowPositioned()); - *content = To<NGBlockNode>(child); + *content = To<BlockNode>(child); } } const NGLayoutResult* MathPaddedLayoutAlgorithm::Layout() { DCHECK(!BreakToken()); - NGBlockNode content = nullptr; + BlockNode content = nullptr; GetContentAsAnonymousMrow(&content); LayoutUnit content_ascent, content_descent; BoxStrut content_margins; const NGLayoutResult* content_layout_result = nullptr; if (content) { NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), content); + Node(), ChildAvailableSize(), GetConstraintSpace(), content); content_layout_result = content.Layout(constraint_space); const auto& content_fragment = To<NGPhysicalBoxFragment>(content_layout_result->PhysicalFragment()); - content_margins = - ComputeMarginsFor(constraint_space, content.Style(), ConstraintSpace()); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + content_margins = ComputeMarginsFor(constraint_space, content.Style(), + GetConstraintSpace()); + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), content_fragment); content_ascent = content_margins.block_start + fragment.FirstBaseline().value_or(fragment.BlockSize()); @@ -95,13 +95,13 @@ LayoutUnit intrinsic_block_size = ascent + descent; LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -112,12 +112,11 @@ Node(), BorderScrollbarPadding())) return *result; - - NGBlockNode content = nullptr; + BlockNode content = nullptr; GetContentAsAnonymousMrow(&content); const auto content_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), content, ChildAvailableSize().block_size); + Style(), GetConstraintSpace(), content, ChildAvailableSize().block_size); bool depends_on_block_constraints = content_result.depends_on_block_constraints;
diff --git a/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.h index e21343d..10cec39 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_padded_layout_algorithm.h
@@ -12,7 +12,7 @@ namespace blink { class CORE_EXPORT MathPaddedLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -28,7 +28,7 @@ absl::optional<LayoutUnit> RequestedAscent(LayoutUnit content_ascent) const; absl::optional<LayoutUnit> RequestedDescent(LayoutUnit content_descent) const; - void GetContentAsAnonymousMrow(NGBlockNode* content) const; + void GetContentAsAnonymousMrow(BlockNode* content) const; }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.cc index 5663707e..f33b1ed1 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.cc
@@ -30,12 +30,12 @@ } void MathRadicalLayoutAlgorithm::GatherChildren( - NGBlockNode* base, - NGBlockNode* index, + BlockNode* base, + BlockNode* index, NGBoxFragmentBuilder* container_builder) const { - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { - NGBlockNode block_child = To<NGBlockNode>(child); + BlockNode block_child = To<BlockNode>(child); if (child.IsOutOfFlowPositioned()) { if (container_builder) { container_builder->AddOutOfFlowChildCandidate( @@ -73,8 +73,8 @@ base_descent; RadicalHorizontalParameters horizontal; BoxStrut index_margins, base_margins; - NGBlockNode base = nullptr; - NGBlockNode index = nullptr; + BlockNode base = nullptr; + BlockNode index = nullptr; GatherChildren(&base, &index, &container_builder_); const NGLayoutResult* base_layout_result = nullptr; @@ -83,13 +83,13 @@ // Handle layout of base child. For <msqrt> the base is anonymous and uses // the row layout algorithm. NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), base); + Node(), ChildAvailableSize(), GetConstraintSpace(), base); base_layout_result = base.Layout(constraint_space); const auto& base_fragment = To<NGPhysicalBoxFragment>(base_layout_result->PhysicalFragment()); base_margins = - ComputeMarginsFor(constraint_space, base.Style(), ConstraintSpace()); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + ComputeMarginsFor(constraint_space, base.Style(), GetConstraintSpace()); + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), base_fragment); base_ascent = base_margins.block_start + fragment.FirstBaselineOrSynthesize(baseline_type); @@ -99,13 +99,13 @@ // Handle layout of index child. // (https://w3c.github.io/mathml-core/#root-with-index). NGConstraintSpace constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), index); + Node(), ChildAvailableSize(), GetConstraintSpace(), index); index_layout_result = index.Layout(constraint_space); const auto& index_fragment = To<NGPhysicalBoxFragment>(index_layout_result->PhysicalFragment()); - index_margins = - ComputeMarginsFor(constraint_space, index.Style(), ConstraintSpace()); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + index_margins = ComputeMarginsFor(constraint_space, index.Style(), + GetConstraintSpace()); + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), index_fragment); index_inline_size = fragment.InlineSize() + index_margins.InlineSum(); index_ascent = index_margins.block_start + @@ -184,13 +184,13 @@ auto total_block_size = ascent + descent + BorderScrollbarPadding().block_end; LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), total_block_size, + GetConstraintSpace(), Style(), BorderPadding(), total_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(total_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -199,8 +199,8 @@ const MinMaxSizesFloatInput&) { DCHECK(IsValidMathMLRadical(Node())); - NGBlockNode base = nullptr; - NGBlockNode index = nullptr; + BlockNode base = nullptr; + BlockNode index = nullptr; GatherChildren(&base, &index); MinMaxSizes sizes; @@ -210,7 +210,7 @@ sizes += horizontal.kern_before_degree.ClampNegativeToZero(); const auto index_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), index, ChildAvailableSize().block_size); + Style(), GetConstraintSpace(), index, ChildAvailableSize().block_size); depends_on_block_constraints |= index_result.depends_on_block_constraints; sizes += index_result.sizes; @@ -227,7 +227,7 @@ } if (base) { const auto base_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), base, ChildAvailableSize().block_size); + Style(), GetConstraintSpace(), base, ChildAvailableSize().block_size); depends_on_block_constraints |= base_result.depends_on_block_constraints; sizes += base_result.sizes; }
diff --git a/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.h index d81d7f6c..d03e4c49 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_radical_layout_algorithm.h
@@ -12,7 +12,7 @@ // This algorithm handles msqrt and mroot elements. class CORE_EXPORT MathRadicalLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -25,8 +25,8 @@ private: bool HasIndex() const; - void GatherChildren(NGBlockNode* base, - NGBlockNode* index, + void GatherChildren(BlockNode* base, + BlockNode* index, NGBoxFragmentBuilder* = nullptr) const; };
diff --git a/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.cc index 49579b3..1698c9d 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.cc
@@ -29,7 +29,7 @@ return LayoutUnit(); } -static void DetermineOperatorSpacing(const NGBlockNode& node, +static void DetermineOperatorSpacing(const BlockNode& node, LayoutUnit* lspace, LayoutUnit* rspace) { if (auto properties = GetMathMLEmbellishedOperatorProperties(node)) { @@ -44,22 +44,23 @@ const LayoutAlgorithmParams& params) : LayoutAlgorithm(params) { DCHECK(params.space.IsNewFormattingContext()); - DCHECK(!ConstraintSpace().HasBlockFragmentation()); + DCHECK(!GetConstraintSpace().HasBlockFragmentation()); } void MathRowLayoutAlgorithm::LayoutRowItems(ChildrenVector* children, LayoutUnit* max_row_block_baseline, LogicalSize* row_total_size) { + const auto& constraint_space = GetConstraintSpace(); const bool should_add_space = Node().IsMathRoot() || !GetMathMLEmbellishedOperatorProperties(Node()); const auto baseline_type = Style().GetFontBaseline(); // https://w3c.github.io/mathml-core/#dfn-algorithm-for-stretching-operators-along-the-block-axis const bool inherits_block_stretch_size_constraint = - ConstraintSpace().TargetStretchBlockSizes().has_value(); + constraint_space.TargetStretchBlockSizes().has_value(); const bool inherits_inline_stretch_size_constraint = !inherits_block_stretch_size_constraint && - ConstraintSpace().HasTargetStretchInlineSize(); + constraint_space.HasTargetStretchInlineSize(); NGConstraintSpace::MathTargetStretchBlockSizes stretch_sizes; if (!inherits_block_stretch_size_constraint && @@ -67,7 +68,7 @@ auto UpdateBlockStretchSizes = [&](const NGLayoutResult* result) { LogicalBoxFragment fragment( - ConstraintSpace().GetWritingDirection(), + constraint_space.GetWritingDirection(), To<NGPhysicalBoxFragment>(result->PhysicalFragment())); LayoutUnit ascent = fragment.FirstBaselineOrSynthesize(baseline_type); stretch_sizes.ascent = std::max(stretch_sizes.ascent, ascent), @@ -78,15 +79,16 @@ // "Perform layout without any stretch size constraint on all the items of // LNotToStretch." bool should_layout_remaining_items_with_zero_block_stretch_size = true; - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned() || - IsBlockAxisStretchyOperator(To<NGBlockNode>(child))) + IsBlockAxisStretchyOperator(To<BlockNode>(child))) { continue; + } const auto child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kMeasure); - const auto* child_layout_result = To<NGBlockNode>(child).Layout( + const auto* child_layout_result = To<BlockNode>(child).Layout( child_constraint_space, nullptr /* break_token */); UpdateBlockStretchSizes(child_layout_result); should_layout_remaining_items_with_zero_block_stretch_size = false; @@ -95,16 +97,16 @@ if (UNLIKELY(should_layout_remaining_items_with_zero_block_stretch_size)) { // "If LNotToStretch is empty, perform layout with stretch size constraint // 0 on all the items of LToStretch." - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) continue; - DCHECK(IsBlockAxisStretchyOperator(To<NGBlockNode>(child))); + DCHECK(IsBlockAxisStretchyOperator(To<BlockNode>(child))); NGConstraintSpace::MathTargetStretchBlockSizes zero_stretch_sizes; const auto child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kMeasure, zero_stretch_sizes); - const auto* child_layout_result = To<NGBlockNode>(child).Layout( + const auto* child_layout_result = To<BlockNode>(child).Layout( child_constraint_space, nullptr /* break_token */); UpdateBlockStretchSizes(child_layout_result); } @@ -113,50 +115,50 @@ // Layout in-flow children in a row. LayoutUnit inline_offset, max_row_ascent, max_row_descent; - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) { // TODO(rbuis): OOF should be "where child would have been if not // absolutely positioned". // Issue: https://github.com/mathml-refresh/mathml/issues/16 container_builder_.AddOutOfFlowChildCandidate( - To<NGBlockNode>(child), BorderScrollbarPadding().StartOffset()); + To<BlockNode>(child), BorderScrollbarPadding().StartOffset()); continue; } NGConstraintSpace child_constraint_space; if (inherits_block_stretch_size_constraint && - IsBlockAxisStretchyOperator(To<NGBlockNode>(child))) { + IsBlockAxisStretchyOperator(To<BlockNode>(child))) { child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, - NGCacheSlot::kLayout, *ConstraintSpace().TargetStretchBlockSizes()); + Node(), ChildAvailableSize(), constraint_space, child, + NGCacheSlot::kLayout, *constraint_space.TargetStretchBlockSizes()); } else if (inherits_inline_stretch_size_constraint && - IsInlineAxisStretchyOperator(To<NGBlockNode>(child))) { + IsInlineAxisStretchyOperator(To<BlockNode>(child))) { child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kLayout, absl::nullopt, - ConstraintSpace().TargetStretchInlineSize()); + constraint_space.TargetStretchInlineSize()); } else if (!inherits_block_stretch_size_constraint && !inherits_inline_stretch_size_constraint && - IsBlockAxisStretchyOperator(To<NGBlockNode>(child))) { + IsBlockAxisStretchyOperator(To<BlockNode>(child))) { child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kLayout, stretch_sizes); } else { child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child); + Node(), ChildAvailableSize(), constraint_space, child); } - const auto* child_layout_result = To<NGBlockNode>(child).Layout( + const auto* child_layout_result = To<BlockNode>(child).Layout( child_constraint_space, nullptr /* break_token */); LayoutUnit lspace, rspace; if (should_add_space) - DetermineOperatorSpacing(To<NGBlockNode>(child), &lspace, &rspace); + DetermineOperatorSpacing(To<BlockNode>(child), &lspace, &rspace); const auto& physical_fragment = To<NGPhysicalBoxFragment>(child_layout_result->PhysicalFragment()); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + LogicalBoxFragment fragment(constraint_space.GetWritingDirection(), physical_fragment); BoxStrut margins = ComputeMarginsFor(child_constraint_space, child.Style(), - ConstraintSpace()); + constraint_space); inline_offset += margins.inline_start; LayoutUnit ascent = @@ -168,7 +170,7 @@ inline_offset += lspace; children->emplace_back( - To<NGBlockNode>(child), margins, + To<BlockNode>(child), margins, LogicalOffset{inline_offset, margins.block_start - ascent}, std::move(child_layout_result)); @@ -219,12 +221,12 @@ auto intrinsic_block_size = max_row_size.block_size + BorderScrollbarPadding().BlockSum(); auto block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, border_box_size.inline_size); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -241,18 +243,18 @@ const bool should_add_space = Node().IsMathRoot() || !GetMathMLEmbellishedOperatorProperties(Node()); - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) continue; const auto child_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), To<NGBlockNode>(child), + Style(), GetConstraintSpace(), To<BlockNode>(child), ChildAvailableSize().block_size); sizes += child_result.sizes; if (should_add_space) { LayoutUnit lspace, rspace; - DetermineOperatorSpacing(To<NGBlockNode>(child), &lspace, &rspace); + DetermineOperatorSpacing(To<BlockNode>(child), &lspace, &rspace); sizes += lspace + rspace; } depends_on_block_constraints |= child_result.depends_on_block_constraints;
diff --git a/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.h index 2e1e033..2633fef 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_row_layout_algorithm.h
@@ -16,7 +16,7 @@ class LayoutUnit; class CORE_EXPORT MathRowLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -24,7 +24,7 @@ struct ChildWithOffsetAndMargins { DISALLOW_NEW(); - ChildWithOffsetAndMargins(const NGBlockNode& child, + ChildWithOffsetAndMargins(const BlockNode& child, const BoxStrut& margins, LogicalOffset offset, const NGLayoutResult* result) @@ -38,7 +38,7 @@ visitor->Trace(result); } - NGBlockNode child; + BlockNode child; BoxStrut margins; LogicalOffset offset; Member<const NGLayoutResult> result;
diff --git a/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.cc index 4f8a9c5d..136ed660 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.cc
@@ -16,7 +16,7 @@ using MathConstants = OpenTypeMathSupport::MathConstants; -static bool IsPrescriptDelimiter(const NGBlockNode& blockNode) { +static bool IsPrescriptDelimiter(const BlockNode& blockNode) { auto* node = blockNode.GetDOMNode(); return node && IsA<MathMLElement>(node) && node->HasTagName(mathml_names::kMprescriptsTag); @@ -94,17 +94,17 @@ } void MathScriptsLayoutAlgorithm::GatherChildren( - NGBlockNode* base, + BlockNode* base, HeapVector<SubSupPair>* sub_sup_pairs, - NGBlockNode* prescripts, + BlockNode* prescripts, unsigned* first_prescript_index, NGBoxFragmentBuilder* container_builder) const { auto script_type = Node().ScriptType(); bool number_of_scripts_is_even = true; sub_sup_pairs->resize(1); - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { - NGBlockNode block_child = To<NGBlockNode>(child); + BlockNode block_child = To<BlockNode>(child); if (child.IsOutOfFlowPositioned()) { if (container_builder) { container_builder->AddOutOfFlowChildCandidate( @@ -267,18 +267,18 @@ } MathScriptsLayoutAlgorithm::ChildAndMetrics -MathScriptsLayoutAlgorithm::LayoutAndGetMetrics(NGBlockNode child) const { +MathScriptsLayoutAlgorithm::LayoutAndGetMetrics(BlockNode child) const { ChildAndMetrics child_and_metrics; auto constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child); + Node(), ChildAvailableSize(), GetConstraintSpace(), child); child_and_metrics.result = child.Layout(constraint_space, nullptr /*break_token*/); LogicalBoxFragment fragment( - ConstraintSpace().GetWritingDirection(), + GetConstraintSpace().GetWritingDirection(), To<NGPhysicalBoxFragment>(child_and_metrics.result->PhysicalFragment())); child_and_metrics.inline_size = fragment.InlineSize(); child_and_metrics.margins = - ComputeMarginsFor(constraint_space, child.Style(), ConstraintSpace()); + ComputeMarginsFor(constraint_space, child.Style(), GetConstraintSpace()); child_and_metrics.ascent = fragment.FirstBaselineOrSynthesize(Style().GetFontBaseline()); child_and_metrics.descent = fragment.BlockSize() - child_and_metrics.ascent + @@ -291,8 +291,8 @@ const NGLayoutResult* MathScriptsLayoutAlgorithm::Layout() { DCHECK(!BreakToken()); - NGBlockNode base = nullptr; - NGBlockNode prescripts = nullptr; + BlockNode base = nullptr; + BlockNode prescripts = nullptr; wtf_size_t first_prescript_index = 0; HeapVector<SubSupPair> sub_sup_pairs; @@ -404,13 +404,13 @@ LayoutUnit intrinsic_block_size = ascent + descent; LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -421,8 +421,8 @@ Node(), BorderScrollbarPadding())) return *result; - NGBlockNode base = nullptr; - NGBlockNode prescripts = nullptr; + BlockNode base = nullptr; + BlockNode prescripts = nullptr; unsigned first_prescript_index = 0; HeapVector<SubSupPair> sub_sup_pairs; @@ -438,7 +438,7 @@ // within ComputeMinMaxSizes, (or setup in an interoperable constraint-space). LayoutUnit base_italic_correction; const auto base_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), base, ChildAvailableSize().block_size); + Style(), GetConstraintSpace(), base, ChildAvailableSize().block_size); sizes = base_result.sizes; depends_on_block_constraints |= base_result.depends_on_block_constraints; @@ -449,12 +449,12 @@ case MathScriptType::kUnder: case MathScriptType::kOver: case MathScriptType::kSuper: { - const NGBlockNode sub = sub_sup_pairs[0].sub; - const NGBlockNode sup = sub_sup_pairs[0].sup; + const BlockNode sub = sub_sup_pairs[0].sub; + const BlockNode sup = sub_sup_pairs[0].sup; const auto first_post_script = sub ? sub : sup; const auto first_post_script_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), first_post_script, + Style(), GetConstraintSpace(), first_post_script, ChildAvailableSize().block_size); sizes += first_post_script_result.sizes; @@ -475,7 +475,8 @@ if (!sub) continue; auto sub_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), sub, ChildAvailableSize().block_size); + Style(), GetConstraintSpace(), sub, + ChildAvailableSize().block_size); sub_result.sizes -= base_italic_correction; sub_sup_pair_size.Encompass(sub_result.sizes); @@ -483,7 +484,8 @@ if (!sup) continue; const auto sup_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), sup, ChildAvailableSize().block_size); + Style(), GetConstraintSpace(), sup, + ChildAvailableSize().block_size); sub_sup_pair_size.Encompass(sup_result.sizes); sizes += sub_sup_pair_size;
diff --git a/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.h index d38f21b..aac76f1 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_scripts_layout_algorithm.h
@@ -12,11 +12,11 @@ namespace blink { -class NGBlockNode; +class BlockNode; // This algorithm handles msub, msup and msubsup elements. class CORE_EXPORT MathScriptsLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -32,7 +32,7 @@ LayoutUnit inline_size; LayoutUnit base_italic_correction; BoxStrut margins; - NGBlockNode node = nullptr; + BlockNode node = nullptr; void Trace(Visitor* visitor) const { visitor->Trace(result); @@ -49,14 +49,14 @@ visitor->Trace(sup); } - NGBlockNode sub = nullptr; - NGBlockNode sup = nullptr; + BlockNode sub = nullptr; + BlockNode sup = nullptr; }; private: - void GatherChildren(NGBlockNode* base, + void GatherChildren(BlockNode* base, HeapVector<SubSupPair>*, - NGBlockNode* prescripts, + BlockNode* prescripts, unsigned* first_prescript_index, NGBoxFragmentBuilder* = nullptr) const; @@ -64,7 +64,7 @@ typedef HeapVector<ChildAndMetrics, 4> ChildrenAndMetrics; - ChildAndMetrics LayoutAndGetMetrics(NGBlockNode child) const; + ChildAndMetrics LayoutAndGetMetrics(BlockNode child) const; struct VerticalMetrics { STACK_ALLOCATED();
diff --git a/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.cc index 92504a11..deea982a 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.cc
@@ -20,7 +20,7 @@ LayoutUnit intrinsic_block_size = BorderScrollbarPadding().BlockSum(); LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size);
diff --git a/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.h index d27dc8b..1cb7a16 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_space_layout_algorithm.h
@@ -12,7 +12,7 @@ namespace blink { class CORE_EXPORT MathSpaceLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.cc index 26667f46..9e9121b 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.cc
@@ -23,7 +23,7 @@ const NGLayoutResult* MathTokenLayoutAlgorithm::Layout() { DCHECK(!IsBreakInside(BreakToken())); - NGLayoutInputNode child = Node().FirstChild(); + LayoutInputNode child = Node().FirstChild(); DCHECK(child && child.IsInline()); DCHECK(!child.NextSibling()); DCHECK(!child.IsOutOfFlowPositioned()); @@ -40,9 +40,9 @@ SimpleInlineChildLayoutContext context(To<InlineNode>(child), &container_builder_); - const NGLayoutResult* child_layout_result = - To<InlineNode>(child).Layout(ConstraintSpace(), /* break_token */ nullptr, - /* column_spanner_path */ nullptr, &context); + const NGLayoutResult* child_layout_result = To<InlineNode>(child).Layout( + GetConstraintSpace(), /* break_token */ nullptr, + /* column_spanner_path */ nullptr, &context); const auto& line_box = To<PhysicalLineBoxFragment>(child_layout_result->PhysicalFragment()); @@ -53,7 +53,7 @@ LayoutUnit intrinsic_block_size = ascent + descent; LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + GetConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, container_builder_.InitialBorderBoxSize().inline_size); container_builder_.SetBaselines(ascent); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); @@ -64,7 +64,7 @@ MinMaxSizesResult MathTokenLayoutAlgorithm::ComputeMinMaxSizes( const MinMaxSizesFloatInput& input) { - NGLayoutInputNode child = Node().FirstChild(); + LayoutInputNode child = Node().FirstChild(); DCHECK(child && child.IsInline()); DCHECK(!child.NextSibling()); DCHECK(!child.IsOutOfFlowPositioned()); @@ -73,7 +73,7 @@ sizes += BorderScrollbarPadding().InlineSum(); const auto child_result = To<InlineNode>(child).ComputeMinMaxSizes( - Style().GetWritingMode(), ConstraintSpace(), MinMaxSizesFloatInput()); + Style().GetWritingMode(), GetConstraintSpace(), MinMaxSizesFloatInput()); sizes += child_result.sizes; return MinMaxSizesResult(sizes, /* depends_on_block_constraints */ false);
diff --git a/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.h index 78ffa20..842b2e7 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_token_layout_algorithm.h
@@ -15,7 +15,7 @@ namespace blink { class CORE_EXPORT MathTokenLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.cc b/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.cc index dcb3680..0cb1a3e 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.cc
@@ -122,7 +122,7 @@ } // https://w3c.github.io/mathml-core/#underscripts-and-overscripts-munder-mover-munderover -bool HasAccent(const NGBlockNode& node, bool accent_under) { +bool HasAccent(const BlockNode& node, bool accent_under) { DCHECK(node); auto* underover = To<MathMLUnderOverElement>(node.GetDOMNode()); auto script_type = underover->GetScriptType(); @@ -143,13 +143,13 @@ DCHECK(params.space.IsNewFormattingContext()); } -void MathUnderOverLayoutAlgorithm::GatherChildren(NGBlockNode* base, - NGBlockNode* over, - NGBlockNode* under) { +void MathUnderOverLayoutAlgorithm::GatherChildren(BlockNode* base, + BlockNode* over, + BlockNode* under) { auto script_type = Node().ScriptType(); - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { - NGBlockNode block_child = To<NGBlockNode>(child); + BlockNode block_child = To<BlockNode>(child); if (child.IsOutOfFlowPositioned()) { container_builder_.AddOutOfFlowChildCandidate( block_child, BorderScrollbarPadding().StartOffset()); @@ -186,9 +186,9 @@ DCHECK(!BreakToken()); DCHECK(IsValidMathMLScript(Node())); - NGBlockNode base = nullptr; - NGBlockNode over = nullptr; - NGBlockNode under = nullptr; + BlockNode base = nullptr; + BlockNode over = nullptr; + BlockNode under = nullptr; GatherChildren(&base, &over, &under); const LogicalSize border_box_size = container_builder_.InitialBorderBoxSize(); @@ -205,11 +205,12 @@ const bool is_base_stretchy_in_inline_axis = base_properties && base_properties->is_stretchy && !base_properties->is_vertical; + const auto& constraint_space = GetConstraintSpace(); const bool base_inherits_block_stretch_size_constraint = - ConstraintSpace().TargetStretchBlockSizes().has_value(); + constraint_space.TargetStretchBlockSizes().has_value(); const bool base_inherits_inline_stretch_size_constraint = !base_inherits_block_stretch_size_constraint && - ConstraintSpace().HasTargetStretchInlineSize(); + constraint_space.HasTargetStretchInlineSize(); UnderOverVerticalParameters parameters = GetUnderOverVerticalParameters( Style(), is_base_large_operator, is_base_stretchy_in_inline_axis); @@ -217,7 +218,7 @@ LayoutUnit inline_stretch_size; auto UpdateInlineStretchSize = [&](const NGLayoutResult* result) { LogicalFragment fragment( - ConstraintSpace().GetWritingDirection(), + constraint_space.GetWritingDirection(), To<NGPhysicalBoxFragment>(result->PhysicalFragment())); inline_stretch_size = std::max(inline_stretch_size, fragment.InlineSize()); }; @@ -225,15 +226,16 @@ // "Perform layout without any stretch size constraint on all the items of // LNotToStretch" bool layout_remaining_items_with_zero_inline_stretch_size = true; - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned() || - IsInlineAxisStretchyOperator(To<NGBlockNode>(child))) + IsInlineAxisStretchyOperator(To<BlockNode>(child))) { continue; + } const auto child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kMeasure); - const auto* child_layout_result = To<NGBlockNode>(child).Layout( + const auto* child_layout_result = To<BlockNode>(child).Layout( child_constraint_space, nullptr /* break_token */); UpdateInlineStretchSize(child_layout_result); layout_remaining_items_with_zero_inline_stretch_size = false; @@ -242,47 +244,47 @@ if (UNLIKELY(layout_remaining_items_with_zero_inline_stretch_size)) { // "If LNotToStretch is empty, perform layout with stretch size constraint 0 // on all the items of LToStretch. - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) continue; - DCHECK(IsInlineAxisStretchyOperator(To<NGBlockNode>(child))); + DCHECK(IsInlineAxisStretchyOperator(To<BlockNode>(child))); if (child == base && (base_inherits_block_stretch_size_constraint || base_inherits_inline_stretch_size_constraint)) continue; LayoutUnit zero_stretch_size; const auto child_constraint_space = CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kMeasure, absl::nullopt, zero_stretch_size); - const auto* child_layout_result = To<NGBlockNode>(child).Layout( + const auto* child_layout_result = To<BlockNode>(child).Layout( child_constraint_space, nullptr /* break_token */); UpdateInlineStretchSize(child_layout_result); } } - auto CreateConstraintSpaceForUnderOverChild = [&](const NGBlockNode child) { + auto CreateConstraintSpaceForUnderOverChild = [&](const BlockNode child) { if (child == base && base_inherits_block_stretch_size_constraint && - IsBlockAxisStretchyOperator(To<NGBlockNode>(child))) { + IsBlockAxisStretchyOperator(To<BlockNode>(child))) { return CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, - NGCacheSlot::kLayout, *ConstraintSpace().TargetStretchBlockSizes()); + Node(), ChildAvailableSize(), constraint_space, child, + NGCacheSlot::kLayout, *constraint_space.TargetStretchBlockSizes()); } if (child == base && base_inherits_inline_stretch_size_constraint && - IsInlineAxisStretchyOperator(To<NGBlockNode>(child))) { + IsInlineAxisStretchyOperator(To<BlockNode>(child))) { return CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kLayout, absl::nullopt, - ConstraintSpace().TargetStretchInlineSize()); + constraint_space.TargetStretchInlineSize()); } if ((child != base || (!base_inherits_block_stretch_size_constraint && !base_inherits_inline_stretch_size_constraint)) && - IsInlineAxisStretchyOperator(To<NGBlockNode>(child))) { + IsInlineAxisStretchyOperator(To<BlockNode>(child))) { return CreateConstraintSpaceForMathChild( - Node(), ChildAvailableSize(), ConstraintSpace(), child, + Node(), ChildAvailableSize(), constraint_space, child, NGCacheSlot::kLayout, absl::nullopt, inline_stretch_size); } return CreateConstraintSpaceForMathChild(Node(), ChildAvailableSize(), - ConstraintSpace(), child, + constraint_space, child, NGCacheSlot::kLayout); }; @@ -292,10 +294,10 @@ const auto base_space = CreateConstraintSpaceForUnderOverChild(base); auto* base_layout_result = base.Layout(base_space); auto base_margins = - ComputeMarginsFor(base_space, base.Style(), ConstraintSpace()); + ComputeMarginsFor(base_space, base.Style(), constraint_space); LogicalBoxFragment base_fragment( - ConstraintSpace().GetWritingDirection(), + constraint_space.GetWritingDirection(), To<NGPhysicalBoxFragment>(base_layout_result->PhysicalFragment())); LayoutUnit base_ascent = base_fragment.FirstBaselineOrSynthesize(baseline_type); @@ -306,9 +308,9 @@ const auto over_space = CreateConstraintSpaceForUnderOverChild(over); const NGLayoutResult* over_layout_result = over.Layout(over_space); BoxStrut over_margins = - ComputeMarginsFor(over_space, over.Style(), ConstraintSpace()); + ComputeMarginsFor(over_space, over.Style(), constraint_space); LogicalBoxFragment over_fragment( - ConstraintSpace().GetWritingDirection(), + constraint_space.GetWritingDirection(), To<NGPhysicalBoxFragment>(over_layout_result->PhysicalFragment())); ascent += parameters.over_extra_ascender + over_margins.block_start; LogicalOffset over_offset = { @@ -353,9 +355,9 @@ const auto under_space = CreateConstraintSpaceForUnderOverChild(under); const NGLayoutResult* under_layout_result = under.Layout(under_space); BoxStrut under_margins = - ComputeMarginsFor(under_space, under.Style(), ConstraintSpace()); + ComputeMarginsFor(under_space, under.Style(), constraint_space); LogicalBoxFragment under_fragment( - ConstraintSpace().GetWritingDirection(), + constraint_space.GetWritingDirection(), To<NGPhysicalBoxFragment>(under_layout_result->PhysicalFragment())); descent += under_margins.block_start; if (parameters.use_under_over_bar_fallback) { @@ -386,13 +388,13 @@ LayoutUnit intrinsic_block_size = ascent + descent; LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), intrinsic_block_size, + constraint_space, Style(), BorderPadding(), intrinsic_block_size, border_box_size.inline_size); container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), constraint_space, &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -408,13 +410,13 @@ MinMaxSizes sizes; bool depends_on_block_constraints = false; - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (child.IsOutOfFlowPositioned()) continue; // TODO(crbug.com/1125136): take into account italic correction. const auto child_result = ComputeMinAndMaxContentContributionForMathChild( - Style(), ConstraintSpace(), To<NGBlockNode>(child), + Style(), GetConstraintSpace(), To<BlockNode>(child), ChildAvailableSize().block_size); sizes.Encompass(child_result.sizes);
diff --git a/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.h b/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.h index 82a96932..085a9e1 100644 --- a/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/mathml/math_under_over_layout_algorithm.h
@@ -12,7 +12,7 @@ namespace blink { class CORE_EXPORT MathUnderOverLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -23,9 +23,7 @@ MinMaxSizesResult ComputeMinMaxSizes(const MinMaxSizesFloatInput&) override; private: - void GatherChildren(NGBlockNode* base, - NGBlockNode* second, - NGBlockNode* third); + void GatherChildren(BlockNode* base, BlockNode* second, BlockNode* third); }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/README.md b/third_party/blink/renderer/core/layout/ng/README.md index 9cc5a9f..48096acc9 100644 --- a/third_party/blink/renderer/core/layout/ng/README.md +++ b/third_party/blink/renderer/core/layout/ng/README.md
@@ -17,13 +17,13 @@ The input to an [NGLayoutAlgorithm](ng_layout_algorithm.h) is the same tuple for every kind of layout: - - The [NGBlockNode](ng_block_node.h) which we are currently performing layout for. The + - The [BlockNode](ng_block_node.h) which we are currently performing layout for. The following information is accessed: - The [ComputedStyle](../../style/ComputedStyle.h) for the node which we are currently performing laying for. - - The list of children [NGBlockNode](ng_block_node.h)es to perform layout upon, and their + - The list of children [BlockNode](ng_block_node.h)es to perform layout upon, and their respective style objects. - The [NGConstraintSpace](ng_constraint_space.h) which represents the "space" @@ -81,8 +81,8 @@ * We store the input constraint space and the resulting fragment on the [LayoutNGBlockFlow](layout_ng_block_flow.h). However, we only do that if we have no break token to simplify the initial implementation. We call - `LayoutNGBlockFlow::SetCachedLayoutResult` from `NGBlockNode::Layout`. -* Once cached, `NGBlockNode::Layout` checks at the beginning if we already + `LayoutNGBlockFlow::SetCachedLayoutResult` from `BlockNode::Layout`. +* Once cached, `BlockNode::Layout` checks at the beginning if we already have a cached result by calling `LayoutNGBlockFlow::CachedLayoutResult`. If that returns a layout result, we return it and are done. * `CachedLayoutResult` will always clone the fragment (but without the offset) @@ -132,7 +132,7 @@ may be dumped, for debugging, logging and testing purposes. #### For layout input node subtree #### -Call NGLayoutInputNode::ShowNodeTree() to dump the tree to stderr. +Call LayoutInputNode::ShowNodeTree() to dump the tree to stderr. #### For physical fragment subtree #### Call NGPhysicalFragment::ShowFragmentTree() to dump the tree to
diff --git a/third_party/blink/renderer/core/layout/ng/block-fragmentation-tutorial.md b/third_party/blink/renderer/core/layout/ng/block-fragmentation-tutorial.md index 69075350..0cbfa288 100644 --- a/third_party/blink/renderer/core/layout/ng/block-fragmentation-tutorial.md +++ b/third_party/blink/renderer/core/layout/ng/block-fragmentation-tutorial.md
@@ -11,7 +11,7 @@ ## Overview ## -Any layout algorithm for block nodes takes NGConstraintSpace, NGBlockNode and +Any layout algorithm for block nodes takes NGConstraintSpace, BlockNode and NGBlockBreakToken as input, and writes output to NGBoxFragmentBuilder, which will eventually generate an NGPhysicalBoxFragment wrapped inside an NGLayoutResult. This will serve as input to the parent algorithm, which will @@ -22,7 +22,7 @@ [ng_fragmentation_utils.cc](ng_fragmentation_utils.cc). This way each layout algorithm can easily hook up with the various stages or aspects of block fragmentation of a node. The utility functions will perform the relevant -operations on these core NG structures (NGConstraintSpace, NGBlockNode, +operations on these core NG structures (NGConstraintSpace, BlockNode, NGBlockBreakToken, NGLayoutResult, and so on). The purpose of the fragmentation machinery is to find the ideal (most appealing) @@ -69,9 +69,9 @@ content is taller than the fragmentainer, there's really nothing we can do about it. -[ConstraintSpace().HasBlockFragmentation()](ng_constraint_space.h) returns true -for anything that *participates* in block fragmentation. A multicol container -*establishes* a [fragmentation +[GetConstraintSpace().HasBlockFragmentation()](ng_constraint_space.h) returns +true for anything that *participates* in block fragmentation. A multicol +container *establishes* a [fragmentation context](https://www.w3.org/TR/css-break-3/#fragmentation-context). It is a fragmentation context root. Printing also establishes a fragmentation context, for the entire document. All descendants of a fragmentation context root @@ -113,7 +113,7 @@ how much space we can use before we need to insert a break. See [FragmentainerSpaceLeft()](ng_fragmentation_utils.h). If content is [monolithic](https://www.w3.org/TR/css-break-3/#monolithic) (i.e. truly -unbreakable), [NGLayoutInputNode::IsMonolithic()](ng_layout_input_node.h) will +unbreakable), [LayoutInputNode::IsMonolithic()](ng_layout_input_node.h) will return true. Being monolithic means that we cannot break inside the element (but we may break before or after it). @@ -158,7 +158,7 @@ each unfinished child. Block break tokens form a tree. Children are found in [NGBlockBreakToken::ChildBreakTokens()](ng_block_break_token.h). These will need to be resumed and laid out by passing the corresponding child break token - to [NGLayoutInputNode::Layout()](ng_layout_input_node.h). When done with all + to [LayoutInputNode::Layout()](ng_layout_input_node.h). When done with all the incoming child break tokens, and as long as we didn't break again, proceed with the consecutive siblings of the node associated with the last incoming child break token. @@ -230,12 +230,12 @@ As mentioned earlier, normally the right thing to do before performing block fragmentation steps is to check if -[ConstraintSpace().HasBlockFragmentation()](ng_constraint_space.h) returns true, -but there are situations where we may already have generated fragments from a -node, but need to stop it from fragmenting any further. This happens when +[GetConstraintSpace().HasBlockFragmentation()](ng_constraint_space.h) returns +true, but there are situations where we may already have generated fragments +from a node, but need to stop it from fragmenting any further. This happens when overflow is clipped [(overflow:clip)](https://www.w3.org/TR/css-overflow-3/#valdef-overflow-clip). In -such situations, ConstraintSpace().HasBlockFragmentation() will return false, +such situations, GetConstraintSpace().HasBlockFragmentation() will return false, but we still need to pick up any previous break token to resume layout correctly. In cases where this distinction matters (like here - since the previous break token is necessary in order to calculate the final block-size, if
diff --git a/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h b/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h index 8ce8a00..59f8fea0d 100644 --- a/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h +++ b/third_party/blink/renderer/core/layout/ng/legacy_layout_tree_walking.h
@@ -15,7 +15,7 @@ namespace blink { -// Return the layout object that should be the first child NGLayoutInputNode of +// Return the layout object that should be the first child LayoutInputNode of // |parent|. Normally this will just be the first layout object child, but there // are certain layout objects that should be skipped for NG. inline LayoutObject* GetLayoutObjectForFirstChildNode(LayoutBlock* parent) { @@ -27,7 +27,7 @@ return child; } -// Return the layout object that should be the parent NGLayoutInputNode of +// Return the layout object that should be the parent LayoutInputNode of // |object|. Normally this will just be the parent layout object, but there // are certain layout objects that should be skipped for NG. // @@ -50,7 +50,7 @@ return parent; } -// Return true if the NGLayoutInputNode children of the NGLayoutInputNode +// Return true if the LayoutInputNode children of the LayoutInputNode // established by |block| will be inline; see LayoutObject::ChildrenInline(). inline bool AreNGBlockFlowChildrenInline(const LayoutBlock* block) { if (block->ChildrenInline())
diff --git a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc index 259278c..9f7aeac4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.cc
@@ -247,7 +247,7 @@ *inset_end_out = imcb_end + margin_end; } -bool CanComputeBlockSizeWithoutLayout(const NGBlockNode& node) { +bool CanComputeBlockSizeWithoutLayout(const BlockNode& node) { // Tables (even with an explicit size) apply a min-content constraint. if (node.IsTable()) { return false; @@ -325,7 +325,7 @@ } InsetModifiedContainingBlock ComputeInsetModifiedContainingBlock( - const NGBlockNode& node, + const BlockNode& node, const LogicalSize& available_size, const LogicalOofInsets& insets, const LogicalStaticPosition& static_position, @@ -371,7 +371,7 @@ } bool ComputeOofInlineDimensions( - const NGBlockNode& node, + const BlockNode& node, const ComputedStyle& style, const NGConstraintSpace& space, const InsetModifiedContainingBlock& imcb, @@ -497,7 +497,7 @@ } const NGLayoutResult* ComputeOofBlockDimensions( - const NGBlockNode& node, + const BlockNode& node, const ComputedStyle& style, const NGConstraintSpace& space, const InsetModifiedContainingBlock& imcb, @@ -624,7 +624,7 @@ return result; } -void AdjustOffsetForSplitInline(const NGBlockNode& node, +void AdjustOffsetForSplitInline(const BlockNode& node, const NGBoxFragmentBuilder* container_builder, LogicalOffset& offset) { DCHECK(!RuntimeEnabledFeatures::LayoutNewContainingBlockEnabled());
diff --git a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h index 560deba..abafb1b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils.h
@@ -15,8 +15,8 @@ namespace blink { +class BlockNode; class NGBoxFragmentBuilder; -class NGBlockNode; class NGConstraintSpace; class NGLayoutResult; struct LogicalStaticPosition; @@ -89,7 +89,7 @@ // final position of the out-of-flow node. // https://www.w3.org/TR/css-position-3/#inset-modified-containing-block CORE_EXPORT InsetModifiedContainingBlock ComputeInsetModifiedContainingBlock( - const NGBlockNode& node, + const BlockNode& node, const LogicalSize& available_size, const LogicalOofInsets&, const LogicalStaticPosition&, @@ -119,9 +119,9 @@ // its required to correctly determine the min/max content sizes. // |replaced_size| should be set if and only if element is replaced element. -// Will return true if |NGBlockNode::ComputeMinMaxSizes| was called. +// Will return true if |BlockNode::ComputeMinMaxSizes| was called. CORE_EXPORT bool ComputeOofInlineDimensions( - const NGBlockNode&, + const BlockNode&, const ComputedStyle& style, const NGConstraintSpace&, const InsetModifiedContainingBlock&, @@ -134,7 +134,7 @@ // If layout was performed to determine the position, this will be returned // otherwise it will return nullptr. CORE_EXPORT const NGLayoutResult* ComputeOofBlockDimensions( - const NGBlockNode&, + const BlockNode&, const ComputedStyle& style, const NGConstraintSpace&, const InsetModifiedContainingBlock&, @@ -145,7 +145,7 @@ LogicalOofDimensions* dimensions); CORE_EXPORT void AdjustOffsetForSplitInline( - const NGBlockNode& node, + const BlockNode& node, const NGBoxFragmentBuilder* container_builder, LogicalOffset& offset);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc index 25b1beb5..b0fdbf9f 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_absolute_utils_test.cc
@@ -93,7 +93,7 @@ } void ComputeOutOfFlowInlineDimensions( - const NGBlockNode& node, + const BlockNode& node, const NGConstraintSpace& space, const BoxStrut& border_padding, const LogicalStaticPosition& static_position, @@ -129,7 +129,7 @@ } void ComputeOutOfFlowBlockDimensions( - const NGBlockNode& node, + const BlockNode& node, const NGConstraintSpace& space, const BoxStrut& border_padding, const LogicalStaticPosition& static_position, @@ -172,7 +172,7 @@ }; TEST_F(NGAbsoluteUtilsTest, Horizontal) { - NGBlockNode node(element_->GetLayoutBox()); + BlockNode node(element_->GetLayoutBox()); element_->SetInlineStyleProperty(CSSPropertyID::kContain, "size"); element_->SetInlineStyleProperty(CSSPropertyID::kContainIntrinsicSize, "60px 4px"); @@ -336,7 +336,7 @@ element_->SetInlineStyleProperty(CSSPropertyID::kContainIntrinsicSize, "60px 4px"); - NGBlockNode node(element_->GetLayoutBox()); + BlockNode node(element_->GetLayoutBox()); BoxStrut ltr_border_padding = ComputeBorders(ltr_space_, node) + ComputePadding(ltr_space_, node.Style()); @@ -450,7 +450,7 @@ } TEST_F(NGAbsoluteUtilsTest, CenterStaticPosition) { - NGBlockNode node(element_->GetLayoutBox()); + BlockNode node(element_->GetLayoutBox()); LogicalStaticPosition static_position = {{LayoutUnit(150), LayoutUnit(200)}, LogicalStaticPosition::kInlineCenter, LogicalStaticPosition::kBlockCenter}; @@ -490,7 +490,7 @@ element_->SetInlineStyleProperty(CSSPropertyID::kMaxHeight, "150px"); element_->SetInlineStyleProperty(CSSPropertyID::kContain, "size"); - NGBlockNode node(element_->GetLayoutBox()); + BlockNode node(element_->GetLayoutBox()); BoxStrut ltr_border_padding = ComputeBorders(ltr_space_, node) + ComputePadding(ltr_space_, node.Style());
diff --git a/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc index ce95af6..8b79aac 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.cc
@@ -31,7 +31,7 @@ } const NGPhysicalBoxFragment* BaseLayoutAlgorithmTest::RunBlockLayoutAlgorithm( - NGBlockNode node, + BlockNode node, const NGConstraintSpace& space, const NGBreakToken* break_token) { AdvanceToLayoutPhase(); @@ -49,7 +49,7 @@ const NGPhysicalBoxFragment* BaseLayoutAlgorithmTest::RunFieldsetLayoutAlgorithm( - NGBlockNode node, + BlockNode node, const NGConstraintSpace& space, const NGBreakToken* break_token) { AdvanceToLayoutPhase();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h b/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h index 9b5aeee..95a7bd6 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h +++ b/third_party/blink/renderer/core/layout/ng/ng_base_layout_algorithm_test.h
@@ -15,8 +15,8 @@ namespace blink { +class BlockNode; class LayoutNGBlockFlow; -class NGBlockNode; class NGBreakToken; class NGPhysicalBoxFragment; @@ -31,12 +31,12 @@ void AdvanceToLayoutPhase(); const NGPhysicalBoxFragment* RunBlockLayoutAlgorithm( - NGBlockNode node, + BlockNode node, const NGConstraintSpace& space, const NGBreakToken* break_token = nullptr); const NGPhysicalBoxFragment* RunFieldsetLayoutAlgorithm( - NGBlockNode node, + BlockNode node, const NGConstraintSpace& space, const NGBreakToken* break_token = nullptr);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc b/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc index 6a442b2..961cf9a 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_break_token.cc
@@ -34,7 +34,7 @@ PassKey(), builder); } -NGBlockBreakToken* NGBlockBreakToken::CreateRepeated(const NGBlockNode& node, +NGBlockBreakToken* NGBlockBreakToken::CreateRepeated(const BlockNode& node, unsigned sequence_number) { auto* token = MakeGarbageCollected<NGBlockBreakToken>(PassKey(), node); token->data_ = MakeGarbageCollected<NGBlockBreakTokenData>(); @@ -44,7 +44,7 @@ } NGBlockBreakToken* NGBlockBreakToken::CreateForBreakInRepeatedFragment( - const NGBlockNode& node, + const BlockNode& node, unsigned sequence_number, LayoutUnit consumed_block_size, bool is_at_block_end) { @@ -74,13 +74,13 @@ child_break_tokens_[i] = builder->child_break_tokens_[i]; } -NGBlockBreakToken::NGBlockBreakToken(PassKey key, NGLayoutInputNode node) +NGBlockBreakToken::NGBlockBreakToken(PassKey key, LayoutInputNode node) : NGBreakToken(kBlockBreakToken, node), data_(MakeGarbageCollected<NGBlockBreakTokenData>()), const_num_children_(0) {} const InlineBreakToken* NGBlockBreakToken::InlineBreakTokenFor( - const NGLayoutInputNode& node) const { + const LayoutInputNode& node) const { DCHECK(node.GetLayoutBox()); return InlineBreakTokenFor(*node.GetLayoutBox()); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h b/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h index 68bbaf2..6e4304d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h +++ b/third_party/blink/renderer/core/layout/ng/ng_block_break_token.h
@@ -25,14 +25,14 @@ // Creates a break token for a node which did fragment, and can potentially // produce more fragments. // - // The node is NGBlockNode, or any other NGLayoutInputNode that produces + // The node is BlockNode, or any other LayoutInputNode that produces // anonymous box. static NGBlockBreakToken* Create(NGBoxFragmentBuilder*); // Creates a break token for a node that needs to produce its first fragment // in the next fragmentainer. In this case we create a break token for a node // that hasn't yet produced any fragments. - static NGBlockBreakToken* CreateBreakBefore(NGLayoutInputNode node, + static NGBlockBreakToken* CreateBreakBefore(LayoutInputNode node, bool is_forced_break) { auto* token = MakeGarbageCollected<NGBlockBreakToken>(PassKey(), node); token->is_break_before_ = true; @@ -44,7 +44,7 @@ // Create a "repeat" break token. This is created at each fragment (that // didn't otherwise break) generated by repeated content, unless it's the very // last fragment. This is needed in order to get the sequence numbers right. - static NGBlockBreakToken* CreateRepeated(const NGBlockNode&, + static NGBlockBreakToken* CreateRepeated(const BlockNode&, unsigned sequence_number); // Create a break token for a "regular" break in a repeated fragment. @@ -62,7 +62,7 @@ // sequence numbers and consumed block-size). Any other use of this break // token is undefined (and likely to fail DCHECKs). static NGBlockBreakToken* CreateForBreakInRepeatedFragment( - const NGBlockNode&, + const BlockNode&, unsigned sequence_number, LayoutUnit consumed_block_size, bool is_at_block_end); @@ -212,7 +212,7 @@ } // Find the child InlineBreakToken for the specified node. - const InlineBreakToken* InlineBreakTokenFor(const NGLayoutInputNode&) const; + const InlineBreakToken* InlineBreakTokenFor(const LayoutInputNode&) const; const InlineBreakToken* InlineBreakTokenFor(const LayoutBox&) const; #if DCHECK_IS_ON() @@ -225,7 +225,7 @@ // has been allocated in the flexible array to store the children. NGBlockBreakToken(PassKey, NGBoxFragmentBuilder*); - explicit NGBlockBreakToken(PassKey, NGLayoutInputNode node); + explicit NGBlockBreakToken(PassKey, LayoutInputNode node); void TraceAfterDispatch(Visitor*) const;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc b/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc index 2ddf9064..3ccacde8 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.cc
@@ -11,7 +11,7 @@ namespace blink { -NGBlockChildIterator::NGBlockChildIterator(NGLayoutInputNode first_child, +NGBlockChildIterator::NGBlockChildIterator(LayoutInputNode first_child, const NGBlockBreakToken* break_token, bool calculate_child_idx) : next_unstarted_child_(first_child), @@ -66,7 +66,7 @@ const NGBreakToken* current_child_break_token = nullptr; absl::optional<wtf_size_t> current_child_idx; - NGLayoutInputNode current_child = next_unstarted_child_; + LayoutInputNode current_child = next_unstarted_child_; if (break_token_) { // If we're resuming layout after a fragmentainer break, we'll first resume // the children that fragmented earlier (represented by one break token @@ -101,7 +101,7 @@ return Entry(current_child, current_child_break_token, current_child_idx); } -void NGBlockChildIterator::AdvanceToNextChild(const NGLayoutInputNode& child) { +void NGBlockChildIterator::AdvanceToNextChild(const LayoutInputNode& child) { next_unstarted_child_ = child.NextSibling(); if (child_idx_) (*child_idx_)++;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h b/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h index 05a1b444..c341cc1 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h +++ b/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator.h
@@ -32,7 +32,7 @@ STACK_ALLOCATED(); public: - NGBlockChildIterator(NGLayoutInputNode first_child, + NGBlockChildIterator(LayoutInputNode first_child, const NGBlockBreakToken* break_token, bool calculate_child_idx = false); @@ -46,10 +46,10 @@ const InlineBreakToken* previous_inline_break_token = nullptr); private: - void AdvanceToNextChild(const NGLayoutInputNode&); + void AdvanceToNextChild(const LayoutInputNode&); - NGLayoutInputNode next_unstarted_child_; - NGLayoutInputNode tracked_child_ = nullptr; + LayoutInputNode next_unstarted_child_; + LayoutInputNode tracked_child_ = nullptr; const NGBlockBreakToken* break_token_; // An index into break_token_'s ChildBreakTokens() vector. Used for keeping @@ -66,12 +66,12 @@ public: Entry() : node(nullptr), token(nullptr) {} - Entry(NGLayoutInputNode node, + Entry(LayoutInputNode node, const NGBreakToken* token, absl::optional<wtf_size_t> index = absl::nullopt) : node(node), token(token), index(index) {} - NGLayoutInputNode node; + LayoutInputNode node; const NGBreakToken* token; absl::optional<wtf_size_t> index;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc b/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc index 9815829..558850d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_child_iterator_test.cc
@@ -16,7 +16,7 @@ namespace blink { const NGBlockBreakToken* CreateBreakToken( - NGLayoutInputNode node, + LayoutInputNode node, const NGBreakTokenVector* child_break_tokens = nullptr, bool has_seen_all_children = false) { NGBoxFragmentBuilder builder( @@ -47,9 +47,9 @@ <div id='child2'></div> <div id='child3'></div> )HTML"); - NGLayoutInputNode node1 = NGBlockNode(GetLayoutBoxByElementId("child1")); - NGLayoutInputNode node2 = node1.NextSibling(); - NGLayoutInputNode node3 = node2.NextSibling(); + LayoutInputNode node1 = BlockNode(GetLayoutBoxByElementId("child1")); + LayoutInputNode node2 = node1.NextSibling(); + LayoutInputNode node3 = node2.NextSibling(); // The iterator should loop through three children. NGBlockChildIterator iterator(node1, nullptr); @@ -69,11 +69,11 @@ <div id='child4'></div> </div> )HTML"); - NGBlockNode container = NGBlockNode(GetLayoutBoxByElementId("container")); - NGLayoutInputNode node1 = container.FirstChild(); - NGLayoutInputNode node2 = node1.NextSibling(); - NGLayoutInputNode node3 = node2.NextSibling(); - NGLayoutInputNode node4 = node3.NextSibling(); + BlockNode container = BlockNode(GetLayoutBoxByElementId("container")); + LayoutInputNode node1 = container.FirstChild(); + LayoutInputNode node2 = node1.NextSibling(); + LayoutInputNode node3 = node2.NextSibling(); + LayoutInputNode node4 = node3.NextSibling(); NGBreakTokenVector empty_tokens_list; const NGBreakToken* child_token1 = CreateBreakToken(node1); @@ -145,8 +145,8 @@ <div id='child2'></div> </div> )HTML"); - NGBlockNode container = NGBlockNode(GetLayoutBoxByElementId("container")); - NGLayoutInputNode node1 = container.FirstChild(); + BlockNode container = BlockNode(GetLayoutBoxByElementId("container")); + LayoutInputNode node1 = container.FirstChild(); const NGBlockBreakToken* child_token1 = CreateBreakToken(node1); @@ -183,9 +183,9 @@ <div id='child2'></div> <div id='child3'></div> )HTML"); - NGLayoutInputNode node1 = NGBlockNode(GetLayoutBoxByElementId("child1")); - NGLayoutInputNode node2 = node1.NextSibling(); - NGLayoutInputNode node3 = node2.NextSibling(); + LayoutInputNode node1 = BlockNode(GetLayoutBoxByElementId("child1")); + LayoutInputNode node2 = node1.NextSibling(); + LayoutInputNode node3 = node2.NextSibling(); using Entry = NGBlockChildIterator::Entry; NGBlockChildIterator iterator(node1, nullptr);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc index 972e459..fd2ba375 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.cc
@@ -93,7 +93,7 @@ const NGBreakToken* break_token, const NGEarlyBreak* early_break, const NGColumnSpannerPath* column_spanner_path, - NGBlockNode* node) { + BlockNode* node) { const NGEarlyBreak* early_break_in_child = nullptr; if (UNLIKELY(early_break)) early_break_in_child = EnterEarlyBreakInChild(*node, *early_break); @@ -107,14 +107,14 @@ const NGBreakToken* break_token, const NGEarlyBreak* early_break, const NGColumnSpannerPath* column_spanner_path, - NGLayoutInputNode* node, + LayoutInputNode* node, InlineChildLayoutContext* context) { if (auto* inline_node = DynamicTo<InlineNode>(node)) { return inline_node->Layout(space, break_token, column_spanner_path, context); } return LayoutBlockChild(space, break_token, early_break, column_spanner_path, - To<NGBlockNode>(node)); + To<BlockNode>(node)); } NGAdjoiningObjectTypes ToAdjoiningObjectTypes(EClear clear) { @@ -258,14 +258,14 @@ container_builder_.SetShouldForceSameFragmentationFlow(); child_percentage_size_ = CalculateChildPercentageSize( - ConstraintSpace(), Node(), ChildAvailableSize()); + GetConstraintSpace(), Node(), ChildAvailableSize()); replaced_child_percentage_size_ = CalculateReplacedChildPercentageSize( - ConstraintSpace(), Node(), ChildAvailableSize(), BorderScrollbarPadding(), - BorderPadding()); + GetConstraintSpace(), Node(), ChildAvailableSize(), + BorderScrollbarPadding(), BorderPadding()); // If |this| is a list item, keep track of the unpositioned list marker in // |container_builder_|. - if (const NGBlockNode marker_node = Node().ListMarkerBlockNodeIfListItem()) { + if (const BlockNode marker_node = Node().ListMarkerBlockNodeIfListItem()) { if (ShouldPlaceUnpositionedListMarker() && !marker_node.ListMarkerOccupiesWholeLine() && (!BreakToken() || BreakToken()->HasUnpositionedListMarker())) { @@ -296,12 +296,12 @@ LayoutUnit float_left_inline_size = float_input.float_left_inline_size; LayoutUnit float_right_inline_size = float_input.float_right_inline_size; - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { // We don't check IsRubyText() here intentionally. RubyText width should // affect this width. if (child.IsOutOfFlowPositioned() || - (child.IsColumnSpanAll() && ConstraintSpace().IsInColumnBfc())) { + (child.IsColumnSpanAll() && GetConstraintSpace().IsInColumnBfc())) { continue; } @@ -341,7 +341,7 @@ child_float_input.float_right_inline_size = float_right_inline_size; } - NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), child, + NGMinMaxConstraintSpaceBuilder builder(GetConstraintSpace(), Style(), child, child_is_new_fc); builder.SetAvailableBlockSize(ChildAvailableSize().block_size); builder.SetPercentageResolutionBlockSize(child_percentage_size_.block_size); @@ -352,7 +352,7 @@ MinMaxSizesResult child_result; if (child.IsInline()) { // From |BlockLayoutAlgorithm| perspective, we can handle |InlineNode| - // almost the same as |NGBlockNode|, because an |InlineNode| includes + // almost the same as |BlockNode|, because an |InlineNode| includes // all inline nodes following |child| and their descendants, and produces // an anonymous box that contains all line boxes. // |NextSibling| returns the next block sibling, or nullptr, skipping all @@ -361,15 +361,16 @@ Style().GetWritingMode(), space, child_float_input); } else { child_result = ComputeMinAndMaxContentContribution( - Style(), To<NGBlockNode>(child), space, child_float_input); + Style(), To<BlockNode>(child), space, child_float_input); } DCHECK_LE(child_result.sizes.min_size, child_result.sizes.max_size) << child.ToString(); // Determine the max inline contribution of the child. - BoxStrut margins = child.IsInline() ? BoxStrut() - : ComputeMarginsFor(space, child_style, - ConstraintSpace()); + BoxStrut margins = + child.IsInline() + ? BoxStrut() + : ComputeMarginsFor(space, child_style, GetConstraintSpace()); LayoutUnit max_inline_contribution; if (child.IsFloating()) { @@ -451,7 +452,7 @@ LayoutUnit child_bfc_line_offset, const absl::optional<LayoutUnit>& child_bfc_block_offset) { LayoutUnit inline_size = container_builder_.InlineSize(); - TextDirection direction = ConstraintSpace().Direction(); + TextDirection direction = GetConstraintSpace().Direction(); if (child_bfc_block_offset && container_builder_.BfcBlockOffset()) { return LogicalFromBfcOffsets( @@ -502,7 +503,7 @@ LayoutAlgorithmParams params( Node(), container_builder_.InitialFragmentGeometry(), - ConstraintSpace(), BreakToken(), result->GetEarlyBreak()); + GetConstraintSpace(), BreakToken(), result->GetEarlyBreak()); params.column_spanner_path = column_spanner_path_; BlockLayoutAlgorithm algorithm_with_break(params); return RelayoutAndBreakEarlier(&algorithm_with_break); @@ -511,7 +512,7 @@ DCHECK(!ignore_line_clamp_); return RelayoutIgnoringLineClamp(); case NGLayoutResult::kDisableFragmentation: - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(GetConstraintSpace().HasBlockFragmentation()); return RelayoutWithoutFragmentation<BlockLayoutAlgorithm>(); default: return result; @@ -560,7 +561,7 @@ BlockLayoutAlgorithm::RelayoutIgnoringLineClamp() { LayoutAlgorithmParams params(Node(), container_builder_.InitialFragmentGeometry(), - ConstraintSpace(), BreakToken(), nullptr); + GetConstraintSpace(), BreakToken(), nullptr); BlockLayoutAlgorithm algorithm_ignoring_line_clamp(params); algorithm_ignoring_line_clamp.ignore_line_clamp_ = true; NGBoxFragmentBuilder& new_builder = @@ -575,12 +576,13 @@ Node().IsInlineFormattingContextRoot()); container_builder_.SetIsInlineFormattingContext(inline_child_layout_context); + const auto& constraint_space = GetConstraintSpace(); container_builder_.SetBfcLineOffset( - ConstraintSpace().GetBfcOffset().line_offset); + constraint_space.GetBfcOffset().line_offset); if (NGAdjoiningObjectTypes adjoining_object_types = - ConstraintSpace().AdjoiningObjectTypes()) { - DCHECK(!ConstraintSpace().IsNewFormattingContext()); + constraint_space.AdjoiningObjectTypes()) { + DCHECK(!constraint_space.IsNewFormattingContext()); DCHECK(!container_builder_.BfcBlockOffset()); // If there were preceding adjoining objects, they will be affected when the @@ -590,7 +592,7 @@ abort_when_bfc_block_offset_updated_ = true; container_builder_.SetAdjoiningObjectTypes(adjoining_object_types); - } else if (ConstraintSpace().HasBlockFragmentation()) { + } else if (constraint_space.HasBlockFragmentation()) { // The offset from the block-start of the fragmentainer is part of the // constraint space, so if this offset changes, we need to abort. abort_when_bfc_block_offset_updated_ = true; @@ -608,7 +610,7 @@ LayoutUnit content_edge = BorderScrollbarPadding().block_start; PreviousInflowPosition previous_inflow_position = { - LayoutUnit(), ConstraintSpace().GetMarginStrut(), + LayoutUnit(), constraint_space.GetMarginStrut(), is_resuming_ ? LayoutUnit() : container_builder_.Padding().block_start, /* self_collapsing_child_had_clearance */ false}; @@ -642,14 +644,14 @@ // // In all those cases we can and must resolve the BFC block offset now. if (content_edge || is_resuming_ || - ConstraintSpace().IsNewFormattingContext()) { + constraint_space.IsNewFormattingContext()) { bool discard_subsequent_margins = previous_inflow_position.margin_strut.discard_margins && !content_edge; if (!ResolveBfcBlockOffset(&previous_inflow_position)) { // There should be no preceding content that depends on the BFC block // offset of a new formatting context block, and likewise when resuming // from a break token. - DCHECK(!ConstraintSpace().IsNewFormattingContext()); + DCHECK(!constraint_space.IsNewFormattingContext()); DCHECK(!is_resuming_); return container_builder_.Abort(NGLayoutResult::kBfcBlockOffsetResolved); } @@ -669,18 +671,20 @@ // here. If we're resuming from a break token (for a block that doesn't // establish a new formatting context), that may not be the case, // though. There may e.g. be clearance involved, or inline-start margins. - if (ConstraintSpace().IsNewFormattingContext()) + if (constraint_space.IsNewFormattingContext()) { DCHECK_EQ(*container_builder_.BfcBlockOffset(), LayoutUnit()); + } // If this is a new formatting context, or if we're resuming from a break // token, no margin strut must be lingering around at this point. - if (ConstraintSpace().IsNewFormattingContext() || is_resuming_) - DCHECK(ConstraintSpace().GetMarginStrut().IsEmpty()); + if (constraint_space.IsNewFormattingContext() || is_resuming_) { + DCHECK(constraint_space.GetMarginStrut().IsEmpty()); + } if (!container_builder_.BfcBlockOffset()) { // New formatting-contexts, and when we have a self-collapsing child // affected by clearance must already have their BFC block-offset resolved. DCHECK(!previous_inflow_position.self_collapsing_child_had_clearance); - DCHECK(!ConstraintSpace().IsNewFormattingContext()); + DCHECK(!constraint_space.IsNewFormattingContext()); } #endif @@ -708,12 +712,12 @@ // no children and that there are no break tokens. Due to this, we skip layout // on these children. if (Node().ChildLayoutBlockedByDisplayLock()) - child_iterator = NGBlockChildIterator(NGBlockNode(nullptr), nullptr); + child_iterator = NGBlockChildIterator(BlockNode(nullptr), nullptr); - NGBlockNode ruby_text_child(nullptr); - NGBlockNode placeholder_child(nullptr); + BlockNode ruby_text_child(nullptr); + BlockNode placeholder_child(nullptr); NGBlockChildIterator::Entry entry; - for (entry = child_iterator.NextChild(); NGLayoutInputNode child = entry.node; + for (entry = child_iterator.NextChild(); LayoutInputNode child = entry.node; entry = child_iterator.NextChild(previous_inline_break_token)) { const NGBreakToken* child_break_token = entry.token; @@ -725,17 +729,16 @@ DCHECK(!child_break_token || (child_break_token->IsBlockType() && To<NGBlockBreakToken>(child_break_token)->IsBreakBefore())); - HandleOutOfFlowPositioned(previous_inflow_position, - To<NGBlockNode>(child)); + HandleOutOfFlowPositioned(previous_inflow_position, To<BlockNode>(child)); } else if (child.IsFloating()) { - HandleFloat(previous_inflow_position, To<NGBlockNode>(child), + HandleFloat(previous_inflow_position, To<BlockNode>(child), To<NGBlockBreakToken>(child_break_token)); } else if (child.IsListMarker() && !child.ListMarkerOccupiesWholeLine()) { // Ignore outside list markers because they are already set to // |container_builder_.UnpositionedListMarker| in the constructor, unless // |ListMarkerOccupiesWholeLine|, which is handled like a regular child. - } else if (child.IsColumnSpanAll() && ConstraintSpace().IsInColumnBfc() && - ConstraintSpace().HasBlockFragmentation()) { + } else if (child.IsColumnSpanAll() && constraint_space.IsInColumnBfc() && + constraint_space.HasBlockFragmentation()) { // The child is a column spanner. If we have no breaks inside (in parallel // flows), we now need to finish this fragmentainer, then abort and let // the column layout algorithm handle the spanner as a child. The @@ -747,7 +750,7 @@ DCHECK(!container_builder_.FoundColumnSpanner()); DCHECK(!IsBreakInside(To<NGBlockBreakToken>(child_break_token))); - if (ConstraintSpace().IsPastBreak() || + if (constraint_space.IsPastBreak() || container_builder_.HasInsertedChildBreak()) { // Something broke inside (typically in a parallel flow, or we wouldn't // be here). Before we can handle the spanner, we need to finish what @@ -766,7 +769,7 @@ // Establish a column spanner path. The innermost node will be the spanner // itself, wrapped inside the container handled by this layout algorithm. const auto* child_spanner_path = - MakeGarbageCollected<NGColumnSpannerPath>(To<NGBlockNode>(child)); + MakeGarbageCollected<NGColumnSpannerPath>(To<BlockNode>(child)); const auto* container_spanner_path = MakeGarbageCollected<NGColumnSpannerPath>(Node(), child_spanner_path); container_builder_.SetColumnSpannerPath(container_spanner_path); @@ -782,7 +785,7 @@ // in front of that one. Otherwise we'll just resume after all the // children. for (entry = child_iterator.NextChild(); - NGLayoutInputNode sibling = entry.node; + LayoutInputNode sibling = entry.node; entry = child_iterator.NextChild()) { DCHECK(!entry.token); if (sibling.IsColumnSpanAll()) @@ -793,9 +796,9 @@ } break; } else if (IsRubyText(child)) { - ruby_text_child = To<NGBlockNode>(child); + ruby_text_child = To<BlockNode>(child); } else if (child.IsTextControlPlaceholder()) { - placeholder_child = To<NGBlockNode>(child); + placeholder_child = To<BlockNode>(child); } else { // If this is the child we had previously determined to break before, do // so now and finish layout. @@ -832,7 +835,7 @@ // We need to abort the layout. No fragment will be generated. return container_builder_.Abort(status); } - if (ConstraintSpace().HasBlockFragmentation()) { + if (constraint_space.HasBlockFragmentation()) { // A child break in a parallel flow doesn't affect whether we should // break here or not. if (container_builder_.HasInflowChildBreakInside()) { @@ -870,7 +873,7 @@ previous_inflow_position); } - if (UNLIKELY(ConstraintSpace().IsNewFormattingContext() && + if (UNLIKELY(constraint_space.IsNewFormattingContext() && !ignore_line_clamp_ && lines_until_clamp_ == 0 && intrinsic_block_size_when_clamped_)) { // Truncation of the last line was forced, but there are no lines after the @@ -908,6 +911,7 @@ const NGLayoutResult* BlockLayoutAlgorithm::FinishLayout( PreviousInflowPosition* previous_inflow_position, InlineChildLayoutContext* inline_child_layout_context) { + const auto& constraint_space = GetConstraintSpace(); LogicalSize border_box_size = container_builder_.InitialBorderBoxSize(); MarginStrut end_margin_strut = previous_inflow_position->margin_strut; @@ -946,7 +950,7 @@ // If the current layout is a new formatting context, we need to encapsulate // all of our floats. - if (ConstraintSpace().IsNewFormattingContext()) { + if (constraint_space.IsNewFormattingContext()) { intrinsic_block_size_ = std::max(intrinsic_block_size_, GetExclusionSpace().ClearanceOffsetIncludingInitialLetter( @@ -964,7 +968,7 @@ end_margin_strut = MarginStrut(); } else if (block_end_border_padding || previous_inflow_position->self_collapsing_child_had_clearance || - ConstraintSpace().IsNewFormattingContext()) { + constraint_space.IsNewFormattingContext()) { // The end margin strut of an in-flow fragment contributes to the size of // the current fragment if: // - There is block-end border/scrollbar/padding. @@ -979,7 +983,7 @@ // border, for instance). If we're a new formatting context, though, we // shouldn't be here, because then the offset should already have been // determined. - DCHECK(!ConstraintSpace().IsNewFormattingContext()); + DCHECK(!constraint_space.IsNewFormattingContext()); if (!ResolveBfcBlockOffset(previous_inflow_position)) { return container_builder_.Abort( NGLayoutResult::kBfcBlockOffsetResolved); @@ -994,9 +998,9 @@ ? end_margin_strut.QuirkyContainerSum() : end_margin_strut.Sum(); - if (ConstraintSpace().HasKnownFragmentainerBlockSize()) { + if (constraint_space.HasKnownFragmentainerBlockSize()) { LayoutUnit new_margin_strut_sum = AdjustedMarginAfterFinalChildFragment( - ConstraintSpace(), previous_inflow_position->logical_block_offset, + constraint_space, previous_inflow_position->logical_block_offset, margin_strut_sum); if (new_margin_strut_sum != margin_strut_sum) { container_builder_.SetIsTruncatedByFragmentationLine(); @@ -1035,7 +1039,7 @@ LayoutUnit unconstrained_intrinsic_block_size = intrinsic_block_size_; intrinsic_block_size_ = ClampIntrinsicBlockSize( - ConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), + constraint_space, Node(), BreakToken(), BorderScrollbarPadding(), intrinsic_block_size_, CalculateQuirkyBodyMarginBlockSum(end_margin_strut)); @@ -1058,7 +1062,7 @@ // Recompute the block-axis size now that we know our content size. border_box_size.block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), + constraint_space, Style(), BorderPadding(), previously_consumed_block_size + intrinsic_block_size_, border_box_size.inline_size); container_builder_.SetFragmentsTotalBlockSize(border_box_size.block_size); @@ -1082,7 +1086,7 @@ // - The block-size differs from the intrinsic size. // - The parent has computed block-size != auto. if (border_box_size.block_size != intrinsic_block_size_ || - !BlockLengthUnresolvable(ConstraintSpace(), Style().LogicalHeight())) { + !BlockLengthUnresolvable(constraint_space, Style().LogicalHeight())) { end_margin_strut = MarginStrut(); } } @@ -1114,14 +1118,15 @@ // If we've been forced at a particular BFC block-offset, (either from // clearance past adjoining floats, or a re-layout), we can safely set our // BFC block-offset now. - if (ConstraintSpace().ForcedBfcBlockOffset()) { + if (constraint_space.ForcedBfcBlockOffset()) { container_builder_.SetBfcBlockOffset( - *ConstraintSpace().ForcedBfcBlockOffset()); + *constraint_space.ForcedBfcBlockOffset()); // Also make sure that this is treated as a valid class C breakpoint (if // it is one). - if (ConstraintSpace().IsPushedByFloats()) + if (constraint_space.IsPushedByFloats()) { container_builder_.SetIsPushedByFloats(); + } } } @@ -1146,7 +1151,7 @@ } // At this point, perform any final table-cell adjustments needed. - if (ConstraintSpace().IsTableCell()) { + if (constraint_space.IsTableCell()) { FinalizeTableCellLayout(intrinsic_block_size_, &container_builder_); } @@ -1158,21 +1163,23 @@ 2); } - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), constraint_space, &container_builder_).Run(); - if (ConstraintSpace().BaselineAlgorithmType() == + if (constraint_space.BaselineAlgorithmType() == NGBaselineAlgorithmType::kInlineBlock) { container_builder_.SetUseLastBaselineForInlineBaseline(); } // An exclusion space is confined to nodes within the same formatting context. - if (ConstraintSpace().IsNewFormattingContext()) + if (constraint_space.IsNewFormattingContext()) { container_builder_.SetExclusionSpace(ExclusionSpace()); - else + } else { container_builder_.SetLinesUntilClamp(lines_until_clamp_); + } - if (ConstraintSpace().UseFirstLineStyle()) + if (constraint_space.UseFirstLineStyle()) { container_builder_.SetStyleVariant(StyleVariant::kFirstLine); + } return container_builder_.ToBoxFragment(); } @@ -1215,7 +1222,7 @@ const auto& children = container_builder_.Children(); const wtf_size_t children_before = children.size(); FragmentItemsBuilder* items_builder = container_builder_.ItemsBuilder(); - const NGConstraintSpace& space = ConstraintSpace(); + const auto& space = GetConstraintSpace(); DCHECK_EQ(items_builder->GetWritingDirection(), space.GetWritingDirection()); const auto result = items_builder->AddPreviousItems(previous_fragment, *previous_items, @@ -1255,15 +1262,15 @@ void BlockLayoutAlgorithm::HandleOutOfFlowPositioned( const PreviousInflowPosition& previous_inflow_position, - NGBlockNode child) { - if (ConstraintSpace().HasBlockFragmentation()) { + BlockNode child) { + if (GetConstraintSpace().HasBlockFragmentation()) { // Forced breaks cannot be specified directly on out-of-flow positioned // elements, but if the preceding block has a forced break after, we need to // break before it. Note that we really only need to do this if block-start // offset is auto (but it's harmless to do it also when it's non-auto). EBreakBetween break_between = container_builder_.JoinedBreakBetweenValue(EBreakBetween::kAuto); - if (IsForcedBreakValue(ConstraintSpace(), break_between)) { + if (IsForcedBreakValue(GetConstraintSpace(), break_between)) { container_builder_.AddBreakBeforeChild(child, kBreakAppealPerfect, /* is_forced_break*/ true); return; @@ -1292,11 +1299,11 @@ LayoutUnit origin_bfc_block_offset = container_builder_.BfcBlockOffset().value_or( - ConstraintSpace().ExpectedBfcBlockOffset()) + + GetConstraintSpace().ExpectedBfcBlockOffset()) + static_offset.block_offset; BfcOffset origin_bfc_offset = { - ConstraintSpace().GetBfcOffset().line_offset + + GetConstraintSpace().GetBfcOffset().line_offset + BorderScrollbarPadding().LineLeft(Style().Direction()), origin_bfc_block_offset}; @@ -1310,20 +1317,21 @@ void BlockLayoutAlgorithm::HandleFloat( const PreviousInflowPosition& previous_inflow_position, - NGBlockNode child, + BlockNode child, const NGBlockBreakToken* child_break_token) { // If we're resuming layout, we must always know our position in the BFC. DCHECK(!IsBreakInside(child_break_token) || container_builder_.BfcBlockOffset()); + const auto& constraint_space = GetConstraintSpace(); // If we don't have a BFC block-offset yet, the "expected" BFC block-offset // is used to optimistically place floats. BfcOffset origin_bfc_offset = { - ConstraintSpace().GetBfcOffset().line_offset + - BorderScrollbarPadding().LineLeft(ConstraintSpace().Direction()), + constraint_space.GetBfcOffset().line_offset + + BorderScrollbarPadding().LineLeft(constraint_space.Direction()), container_builder_.BfcBlockOffset() ? NextBorderEdge(previous_inflow_position) - : ConstraintSpace().ExpectedBfcBlockOffset()}; + : constraint_space.ExpectedBfcBlockOffset()}; if (child_break_token) { // If there's monolithic content inside the float from a previous page @@ -1333,13 +1341,13 @@ BreakToken()->MonolithicOverflow(); } - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { // Forced breaks cannot be specified directly on floats, but if the // preceding block has a forced break after, we need to break before this // float. EBreakBetween break_between = container_builder_.JoinedBreakBetweenValue(EBreakBetween::kAuto); - if (IsForcedBreakValue(ConstraintSpace(), break_between)) { + if (IsForcedBreakValue(constraint_space, break_between)) { container_builder_.AddBreakBeforeChild(child, kBreakAppealPerfect, /* is_forced_break*/ true); return; @@ -1348,19 +1356,20 @@ UnpositionedFloat unpositioned_float( child, child_break_token, ChildAvailableSize(), child_percentage_size_, - replaced_child_percentage_size_, origin_bfc_offset, ConstraintSpace(), + replaced_child_percentage_size_, origin_bfc_offset, constraint_space, Style()); if (!container_builder_.BfcBlockOffset()) { container_builder_.AddAdjoiningObjectTypes( - unpositioned_float.IsLineLeft(ConstraintSpace().Direction()) + unpositioned_float.IsLineLeft(constraint_space.Direction()) ? kAdjoiningFloatLeft : kAdjoiningFloatRight); // If we don't have a forced BFC block-offset yet, we'll optimistically // place floats at the "expected" BFC block-offset. If this differs from // our final BFC block-offset we'll need to re-layout. - if (!ConstraintSpace().ForcedBfcBlockOffset()) + if (!constraint_space.ForcedBfcBlockOffset()) { abort_when_bfc_block_offset_updated_ = true; + } } PositionedFloat positioned_float = @@ -1372,7 +1381,7 @@ } if (positioned_float.break_before_token) { - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(constraint_space.HasBlockFragmentation()); container_builder_.AddBreakToken(positioned_float.break_before_token, /* is_in_parallel_flow */ true); // After breaking before the float, carry on with layout of this @@ -1389,23 +1398,22 @@ const NGPhysicalFragment& physical_fragment = positioned_float.layout_result->PhysicalFragment(); LayoutUnit float_inline_size = - LogicalFragment(ConstraintSpace().GetWritingDirection(), - physical_fragment) + LogicalFragment(constraint_space.GetWritingDirection(), physical_fragment) .InlineSize(); - BfcOffset bfc_offset = {ConstraintSpace().GetBfcOffset().line_offset, + BfcOffset bfc_offset = {constraint_space.GetBfcOffset().line_offset, container_builder_.BfcBlockOffset().value_or( - ConstraintSpace().ExpectedBfcBlockOffset())}; + constraint_space.ExpectedBfcBlockOffset())}; LogicalOffset logical_offset = LogicalFromBfcOffsets( positioned_float.bfc_offset, bfc_offset, float_inline_size, - container_builder_.InlineSize(), ConstraintSpace().Direction()); + container_builder_.InlineSize(), constraint_space.Direction()); container_builder_.AddResult(*positioned_float.layout_result, logical_offset); } NGLayoutResult::EStatus BlockLayoutAlgorithm::HandleNewFormattingContext( - NGLayoutInputNode child, + LayoutInputNode child, const NGBlockBreakToken* child_break_token, PreviousInflowPosition* previous_inflow_position) { DCHECK(child); @@ -1414,14 +1422,15 @@ DCHECK(child.CreatesNewFormattingContext()); DCHECK(child.IsBlock()); + const auto& constraint_space = GetConstraintSpace(); const ComputedStyle& child_style = child.Style(); - const TextDirection direction = ConstraintSpace().Direction(); + const TextDirection direction = constraint_space.Direction(); InflowChildData child_data = ComputeChildData(*previous_inflow_position, child, child_break_token, /* is_new_fc */ true); LayoutUnit child_origin_line_offset = - ConstraintSpace().GetBfcOffset().line_offset + + constraint_space.GetBfcOffset().line_offset + BorderScrollbarPadding().LineLeft(direction); // If the child has a block-start margin, and the BFC block offset is still @@ -1456,24 +1465,24 @@ // floats, we consider the margin "separated". We should *never* attempt to // re-resolve the BFC block-offset in this case. bool has_clearance_past_adjoining_floats = - ConstraintSpace().AncestorHasClearancePastAdjoiningFloats() || + constraint_space.AncestorHasClearancePastAdjoiningFloats() || HasClearancePastAdjoiningFloats( container_builder_.AdjoiningObjectTypes(), child_style, Style()); if (has_clearance_past_adjoining_floats) { child_bfc_offset_estimate = NextBorderEdge(*previous_inflow_position); child_margin_got_separated = true; - } else if (ConstraintSpace().ForcedBfcBlockOffset()) { + } else if (constraint_space.ForcedBfcBlockOffset()) { // This is not the first time we're here. We already have a suggested BFC // block offset. bfc_offset_already_resolved = true; - child_bfc_offset_estimate = *ConstraintSpace().ForcedBfcBlockOffset(); + child_bfc_offset_estimate = *constraint_space.ForcedBfcBlockOffset(); // We require that the BFC block offset be the one we'd get with margins // adjoining, margins separated, or if clearance was applied to either of // these. Anything else is a bug. DCHECK(child_bfc_offset_estimate == adjoining_bfc_offset_estimate || child_bfc_offset_estimate == non_adjoining_bfc_offset_estimate || - child_bfc_offset_estimate == ConstraintSpace().ClearanceOffset()); + child_bfc_offset_estimate == constraint_space.ClearanceOffset()); // Figure out if the child margin has already got separated from the // margin strut or not. // @@ -1546,7 +1555,7 @@ // Re-resolving the BFC block-offset with a different "forced" BFC // block-offset is only safe if an ancestor *never* had clearance past // adjoining floats. - DCHECK(!ConstraintSpace().AncestorHasClearancePastAdjoiningFloats()); + DCHECK(!constraint_space.AncestorHasClearancePastAdjoiningFloats()); ResolveBfcBlockOffset(previous_inflow_position, non_adjoining_bfc_offset_estimate, /* forced_bfc_block_offset */ absl::nullopt); @@ -1574,7 +1583,7 @@ /* abort_if_cleared */ false, &child_bfc_offset, &resolved_margins); } - if (ConstraintSpace().HasBlockFragmentation()) { + if (constraint_space.HasBlockFragmentation()) { bool has_container_separation = has_break_opportunity_before_next_child_ || child_bfc_offset.block_offset > child_bfc_offset_estimate || @@ -1592,12 +1601,12 @@ } const auto& physical_fragment = layout_result->PhysicalFragment(); - LogicalFragment fragment(ConstraintSpace().GetWritingDirection(), + LogicalFragment fragment(constraint_space.GetWritingDirection(), physical_fragment); LogicalOffset logical_offset = LogicalFromBfcOffsets( child_bfc_offset, ContainerBfcOffset(), fragment.InlineSize(), - container_builder_.InlineSize(), ConstraintSpace().Direction()); + container_builder_.InlineSize(), constraint_space.Direction()); if (!PositionOrPropagateListMarker(*layout_result, &logical_offset, previous_inflow_position)) @@ -1616,7 +1625,7 @@ /* self_collapsing_child_had_clearance */ false); } - if (ConstraintSpace().HasBlockFragmentation() && + if (constraint_space.HasBlockFragmentation() && !has_break_opportunity_before_next_child_) { has_break_opportunity_before_next_child_ = HasBreakOpportunityBeforeNextChild(physical_fragment, @@ -1627,7 +1636,7 @@ } const NGLayoutResult* BlockLayoutAlgorithm::LayoutNewFormattingContext( - NGLayoutInputNode child, + LayoutInputNode child, const NGBlockBreakToken* child_break_token, const InflowChildData& child_data, BfcOffset origin_offset, @@ -1636,8 +1645,8 @@ BoxStrut* out_resolved_margins) { const auto& style = Style(); const auto& child_style = child.Style(); - const TextDirection direction = ConstraintSpace().Direction(); - const auto writing_direction = ConstraintSpace().GetWritingDirection(); + const TextDirection direction = GetConstraintSpace().Direction(); + const auto writing_direction = GetConstraintSpace().GetWritingDirection(); if (!IsBreakInside(child_break_token)) { // The origin offset is where we should start looking for layout @@ -1731,7 +1740,7 @@ const NGLayoutResult* layout_result = LayoutBlockChild( child_space, child_break_token, early_break_, - /* column_spanner_path */ nullptr, &To<NGBlockNode>(child)); + /* column_spanner_path */ nullptr, &To<BlockNode>(child)); // Since this child establishes a new formatting context, no exclusion space // should be returned. @@ -1764,7 +1773,7 @@ *marker_fragment.Children().front()) .InlineSize(); } - auto_margins.inline_start = UnpositionedListMarker(To<NGBlockNode>(child)) + auto_margins.inline_start = UnpositionedListMarker(To<BlockNode>(child)) .InlineOffset(marker_inline_size); auto_margins.inline_end = opportunity.rect.InlineSize() - fragment.InlineSize() - @@ -1849,7 +1858,7 @@ } NGLayoutResult::EStatus BlockLayoutAlgorithm::HandleInflow( - NGLayoutInputNode child, + LayoutInputNode child, const NGBreakToken* child_break_token, PreviousInflowPosition* previous_inflow_position, InlineChildLayoutContext* inline_child_layout_context, @@ -1918,7 +1927,7 @@ LayoutInflow(child_space, child_break_token, early_break_, column_spanner_path_, &child, inline_child_layout_context); - // To save space of the stack when we recurse into |NGBlockNode::Layout| + // To save space of the stack when we recurse into |BlockNode::Layout| // above, the rest of this function is continued within |FinishInflow|. // However it should be read as one function. return FinishInflow(child, child_break_token, child_space, @@ -1929,7 +1938,7 @@ } NGLayoutResult::EStatus BlockLayoutAlgorithm::FinishInflow( - NGLayoutInputNode child, + LayoutInputNode child, const NGBreakToken* child_break_token, const NGConstraintSpace& child_space, bool has_clearance_past_adjoining_floats, @@ -1968,17 +1977,19 @@ // If the child has the same clearance-offset as ourselves it means that // we should *also* resolve ourselves at that offset, (and we also have // been pushed by floats). - if (ConstraintSpace().ClearanceOffset() == child_space.ClearanceOffset()) + if (GetConstraintSpace().ClearanceOffset() == + child_space.ClearanceOffset()) { container_builder_.SetIsPushedByFloats(); - else + } else { bfc_block_offset = NextBorderEdge(*previous_inflow_position); + } } // A new formatting-context may have previously tried to resolve the BFC // block-offset. In this case we'll have a "forced" BFC block-offset // present, but we shouldn't apply it (instead preferring the child's new // BFC block-offset). - DCHECK(!ConstraintSpace().AncestorHasClearancePastAdjoiningFloats()); + DCHECK(!GetConstraintSpace().AncestorHasClearancePastAdjoiningFloats()); if (!ResolveBfcBlockOffset(previous_inflow_position, bfc_block_offset, /* forced_bfc_block_offset */ absl::nullopt)) @@ -2137,7 +2148,7 @@ const absl::optional<LayoutUnit> line_box_bfc_block_offset = layout_result->LineBoxBfcBlockOffset(); - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { if (container_builder_.BfcBlockOffset() && child_bfc_block_offset) { bool is_line_box_pushed_by_floats = line_box_bfc_block_offset && @@ -2210,7 +2221,7 @@ } const auto& physical_fragment = layout_result->PhysicalFragment(); - LogicalFragment fragment(ConstraintSpace().GetWritingDirection(), + LogicalFragment fragment(GetConstraintSpace().GetWritingDirection(), physical_fragment); if (line_box_bfc_block_offset) @@ -2233,7 +2244,7 @@ logical_offset.block_offset); } - if (IsA<NGBlockNode>(child)) { + if (IsA<BlockNode>(child)) { container_builder_.AddResult(*layout_result, logical_offset, child_data->margins); } else { @@ -2267,7 +2278,7 @@ } } - if (ConstraintSpace().HasBlockFragmentation() && + if (GetConstraintSpace().HasBlockFragmentation() && !has_break_opportunity_before_next_child_) { has_break_opportunity_before_next_child_ = HasBreakOpportunityBeforeNextChild(physical_fragment, @@ -2279,7 +2290,7 @@ InflowChildData BlockLayoutAlgorithm::ComputeChildData( const PreviousInflowPosition& previous_inflow_position, - NGLayoutInputNode child, + LayoutInputNode child, const NGBreakToken* child_break_token, bool is_new_fc) { DCHECK(child); @@ -2325,11 +2336,11 @@ if (child.IsBlock()) SetSubtreeModifiedMarginStrutIfNeeded(&child.Style().MarginBlockStart()); + TextDirection direction = GetConstraintSpace().Direction(); BfcOffset child_bfc_offset = { - ConstraintSpace().GetBfcOffset().line_offset + - BorderScrollbarPadding().LineLeft(ConstraintSpace().Direction()) + - additional_line_offset + - margins.LineLeft(ConstraintSpace().Direction()), + GetConstraintSpace().GetBfcOffset().line_offset + + BorderScrollbarPadding().LineLeft(direction) + + additional_line_offset + margins.LineLeft(direction), BfcBlockOffset() + logical_block_offset}; return InflowChildData(child_bfc_offset, margin_strut, margins); @@ -2337,7 +2348,7 @@ PreviousInflowPosition BlockLayoutAlgorithm::ComputeInflowPosition( const PreviousInflowPosition& previous_inflow_position, - const NGLayoutInputNode child, + const LayoutInputNode child, const InflowChildData& child_data, const absl::optional<LayoutUnit>& child_bfc_block_offset, const LogicalOffset& logical_offset, @@ -2431,7 +2442,7 @@ if (child.IsBlock()) SetSubtreeModifiedMarginStrutIfNeeded(&child.Style().MarginBlockEnd()); - if (UNLIKELY(ConstraintSpace().HasBlockFragmentation())) { + if (UNLIKELY(GetConstraintSpace().HasBlockFragmentation())) { // If the child broke inside, don't apply any trailing margin, since it's // only to be applied to the last fragment that's not in a parallel flow // (due to overflow). While trailing margins are normally truncated at @@ -2481,7 +2492,7 @@ } LayoutUnit BlockLayoutAlgorithm::PositionSelfCollapsingChildWithParentBfc( - const NGLayoutInputNode& child, + const LayoutInputNode& child, const NGConstraintSpace& child_space, const InflowChildData& child_data, const NGLayoutResult& layout_result) const { @@ -2500,21 +2511,21 @@ void BlockLayoutAlgorithm::ConsumeRemainingFragmentainerSpace( PreviousInflowPosition* previous_inflow_position) { - if (ConstraintSpace().HasKnownFragmentainerBlockSize()) { + if (GetConstraintSpace().HasKnownFragmentainerBlockSize()) { // The remaining part of the fragmentainer (the unusable space for child // content, due to the break) should still be occupied by this // container. Also encompass fragmentainer overflow (may be caused by // monolithic content). previous_inflow_position->logical_block_offset = std::max(previous_inflow_position->logical_block_offset, - FragmentainerSpaceLeft(ConstraintSpace())); + FragmentainerSpaceLeft(GetConstraintSpace())); } } NGBreakStatus BlockLayoutAlgorithm::FinalizeForFragmentation( LayoutUnit block_end_border_padding_added) { if (Node().IsInlineFormattingContextRoot() && !early_break_ && - ConstraintSpace().HasBlockFragmentation()) { + GetConstraintSpace().HasBlockFragmentation()) { if (container_builder_.HasInflowChildBreakInside() || first_overflowing_line_) { if (first_overflowing_line_ && @@ -2545,40 +2556,41 @@ } if (container_builder_.IsFragmentainerBoxType()) { - return FinishFragmentationForFragmentainer(ConstraintSpace(), + return FinishFragmentationForFragmentainer(GetConstraintSpace(), &container_builder_); } LayoutUnit space_left = kIndefiniteSize; - if (ConstraintSpace().HasKnownFragmentainerBlockSize()) - space_left = FragmentainerSpaceLeft(ConstraintSpace()); + if (GetConstraintSpace().HasKnownFragmentainerBlockSize()) { + space_left = FragmentainerSpaceLeft(GetConstraintSpace()); + } - return FinishFragmentation(Node(), ConstraintSpace(), + return FinishFragmentation(Node(), GetConstraintSpace(), block_end_border_padding_added, space_left, &container_builder_); } NGBreakStatus BlockLayoutAlgorithm::BreakBeforeChildIfNeeded( - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult& layout_result, PreviousInflowPosition* previous_inflow_position, LayoutUnit bfc_block_offset, bool has_container_separation) { - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(GetConstraintSpace().HasBlockFragmentation()); // If the BFC offset is unknown, there's nowhere to break, since there's no // non-empty child content yet (as that would have resolved the BFC offset). DCHECK(container_builder_.BfcBlockOffset()); LayoutUnit fragmentainer_block_offset = - FragmentainerOffsetAtBfc(ConstraintSpace()) + bfc_block_offset - + FragmentainerOffsetAtBfc(GetConstraintSpace()) + bfc_block_offset - layout_result.AnnotationBlockOffsetAdjustment(); if (has_container_separation) { EBreakBetween break_between = CalculateBreakBetweenValue(child, layout_result, container_builder_); - if (IsForcedBreakValue(ConstraintSpace(), break_between)) { - BreakBeforeChild(ConstraintSpace(), child, &layout_result, + if (IsForcedBreakValue(GetConstraintSpace(), break_between)) { + BreakBeforeChild(GetConstraintSpace(), child, &layout_result, fragmentainer_block_offset, kBreakAppealPerfect, /* is_forced_break */ true, &container_builder_); ConsumeRemainingFragmentainerSpace(previous_inflow_position); @@ -2587,15 +2599,16 @@ } NGBreakAppeal appeal_before = - CalculateBreakAppealBefore(ConstraintSpace(), child, layout_result, + CalculateBreakAppealBefore(GetConstraintSpace(), child, layout_result, container_builder_, has_container_separation); // Attempt to move past the break point, and if we can do that, also assess // the appeal of breaking there, even if we didn't. - if (MovePastBreakpoint(ConstraintSpace(), child, layout_result, + if (MovePastBreakpoint(GetConstraintSpace(), child, layout_result, fragmentainer_block_offset, appeal_before, - &container_builder_)) + &container_builder_)) { return NGBreakStatus::kContinue; + } // Figure out where to insert a soft break. It will either be before this // child, or before an earlier sibling, if there's a more appealing breakpoint @@ -2629,7 +2642,7 @@ // require an additional piece of machinery. This case should be rare // enough (to worry about performance), so let's focus on code // simplicity instead. - PropagateSpaceShortage(ConstraintSpace(), &layout_result, + PropagateSpaceShortage(GetConstraintSpace(), &layout_result, fragmentainer_block_offset, &container_builder_); } // Attempt to honor orphans and widows requests. @@ -2679,10 +2692,11 @@ } } - if (!AttemptSoftBreak(ConstraintSpace(), child, &layout_result, + if (!AttemptSoftBreak(GetConstraintSpace(), child, &layout_result, fragmentainer_block_offset, appeal_before, - &container_builder_)) + &container_builder_)) { return NGBreakStatus::kNeedsEarlierBreak; + } ConsumeRemainingFragmentainerSpace(previous_inflow_position); return NGBreakStatus::kBrokeBefore; @@ -2723,7 +2737,7 @@ } BoxStrut BlockLayoutAlgorithm::CalculateMargins( - NGLayoutInputNode child, + LayoutInputNode child, bool is_new_fc, LayoutUnit* additional_line_offset) { DCHECK(child); @@ -2733,7 +2747,7 @@ const ComputedStyle& child_style = child.Style(); BoxStrut margins = ComputeMarginsFor(child_style, child_percentage_size_.inline_size, - ConstraintSpace().GetWritingDirection()); + GetConstraintSpace().GetWritingDirection()); if (is_new_fc) { return margins; } @@ -2741,7 +2755,7 @@ absl::optional<LayoutUnit> child_inline_size; auto ChildInlineSize = [&]() -> LayoutUnit { if (!child_inline_size) { - NGConstraintSpaceBuilder builder(ConstraintSpace(), + NGConstraintSpaceBuilder builder(GetConstraintSpace(), child_style.GetWritingDirection(), /* is_new_fc */ false); builder.SetAvailableSize(ChildAvailableSize()); @@ -2749,7 +2763,7 @@ builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit); NGConstraintSpace space = builder.ToConstraintSpace(); - const auto block_child = To<NGBlockNode>(child); + const auto block_child = To<BlockNode>(child); BoxStrut child_border_padding = ComputeBorders(space, block_child) + ComputePadding(space, child_style); child_inline_size = ComputeInlineSizeForFragment(space, block_child, @@ -2786,7 +2800,7 @@ } NGConstraintSpace BlockLayoutAlgorithm::CreateConstraintSpaceForChild( - const NGLayoutInputNode child, + const LayoutInputNode child, const NGBreakToken* child_break_token, const InflowChildData& child_data, const LogicalSize child_available_size, @@ -2796,22 +2810,23 @@ LayoutUnit block_start_annotation_space) { const ComputedStyle& child_style = child.Style(); const auto child_writing_direction = child_style.GetWritingDirection(); - - NGConstraintSpaceBuilder builder(ConstraintSpace(), child_writing_direction, + const auto& constraint_space = GetConstraintSpace(); + NGConstraintSpaceBuilder builder(constraint_space, child_writing_direction, is_new_fc); if (UNLIKELY( - !IsParallelWritingMode(ConstraintSpace().GetWritingMode(), - child_writing_direction.GetWritingMode()))) + !IsParallelWritingMode(constraint_space.GetWritingMode(), + child_writing_direction.GetWritingMode()))) { SetOrthogonalFallbackInlineSize(Style(), child, &builder); - else if (ShouldBlockContainerChildStretchAutoInlineSize(child)) + } else if (ShouldBlockContainerChildStretchAutoInlineSize(child)) { builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit); + } builder.SetAvailableSize(child_available_size); builder.SetPercentageResolutionSize(child_percentage_size_); builder.SetReplacedPercentageResolutionSize(replaced_child_percentage_size_); - if (ConstraintSpace().IsTableCell()) { + if (constraint_space.IsTableCell()) { builder.SetIsTableCellChild(true); // Always shrink-to-fit children within a <mtd> element. @@ -2827,21 +2842,23 @@ // is considered to be "restricted". Otherwise, especially if this is the // only child of the cell, and that is the only cell in the row, we'd end // up with zero block size. - if (ConstraintSpace().IsRestrictedBlockSizeTableCell() && + if (constraint_space.IsRestrictedBlockSizeTableCell() && child_percentage_size_.block_size == kIndefiniteSize && !child.ShouldBeConsideredAsReplaced() && child_style.LogicalHeight().IsPercentOrCalc() && (child_style.OverflowBlockDirection() == EOverflow::kAuto || - child_style.OverflowBlockDirection() == EOverflow::kScroll)) + child_style.OverflowBlockDirection() == EOverflow::kScroll)) { builder.SetIsRestrictedBlockSizeTableCellChild(); + } } bool has_bfc_block_offset = container_builder_.BfcBlockOffset().has_value(); // Propagate the |NGConstraintSpace::ForcedBfcBlockOffset| down to our // children. - if (!has_bfc_block_offset && ConstraintSpace().ForcedBfcBlockOffset()) - builder.SetForcedBfcBlockOffset(*ConstraintSpace().ForcedBfcBlockOffset()); + if (!has_bfc_block_offset && constraint_space.ForcedBfcBlockOffset()) { + builder.SetForcedBfcBlockOffset(*constraint_space.ForcedBfcBlockOffset()); + } if (child_bfc_block_offset && !is_new_fc) builder.SetForcedBfcBlockOffset(*child_bfc_block_offset); @@ -2872,25 +2889,27 @@ } } } - } else if (ConstraintSpace().OptimisticBfcBlockOffset()) { + } else if (constraint_space.OptimisticBfcBlockOffset()) { // Propagate the |NGConstraintSpace::OptimisticBfcBlockOffset| down to our // children. builder.SetOptimisticBfcBlockOffset( - *ConstraintSpace().OptimisticBfcBlockOffset()); + *constraint_space.OptimisticBfcBlockOffset()); } // Propagate the |NGConstraintSpace::AncestorHasClearancePastAdjoiningFloats| // flag down to our children. if (!has_bfc_block_offset && - ConstraintSpace().AncestorHasClearancePastAdjoiningFloats()) + constraint_space.AncestorHasClearancePastAdjoiningFloats()) { builder.SetAncestorHasClearancePastAdjoiningFloats(); + } if (has_clearance_past_adjoining_floats) builder.SetAncestorHasClearancePastAdjoiningFloats(); LayoutUnit clearance_offset = LayoutUnit::Min(); if (!IsBreakInside(DynamicTo<NGBlockBreakToken>(child_break_token))) { - if (!ConstraintSpace().IsNewFormattingContext()) - clearance_offset = ConstraintSpace().ClearanceOffset(); + if (!constraint_space.IsNewFormattingContext()) { + clearance_offset = constraint_space.ClearanceOffset(); + } if (child.IsBlock()) { LayoutUnit child_clearance_offset = GetExclusionSpace().ClearanceOffset(child_style.Clear(Style())); @@ -2898,7 +2917,7 @@ } } builder.SetClearanceOffset(clearance_offset); - builder.SetBaselineAlgorithmType(ConstraintSpace().BaselineAlgorithmType()); + builder.SetBaselineAlgorithmType(constraint_space.BaselineAlgorithmType()); if (child_data.is_pushed_by_floats) { // Clearance has been applied, but it won't be automatically detected when @@ -2920,20 +2939,20 @@ } builder.SetBlockStartAnnotationSpace(block_start_annotation_space); - if (ConstraintSpace().HasBlockFragmentation()) { + if (constraint_space.HasBlockFragmentation()) { LayoutUnit fragmentainer_offset_delta; // We need to keep track of our block-offset within the fragmentation // context, to be able to tell where the fragmentation line is (i.e. where // to break). if (is_new_fc) { fragmentainer_offset_delta = - *child_bfc_block_offset - ConstraintSpace().ExpectedBfcBlockOffset(); + *child_bfc_block_offset - constraint_space.ExpectedBfcBlockOffset(); } else { fragmentainer_offset_delta = builder.ExpectedBfcBlockOffset() - - ConstraintSpace().ExpectedBfcBlockOffset(); + constraint_space.ExpectedBfcBlockOffset(); } SetupSpaceBuilderForFragmentation( - ConstraintSpace(), child, fragmentainer_offset_delta, &builder, + constraint_space, child, fragmentainer_offset_delta, &builder, is_new_fc, container_builder_.RequiresContentBeforeBreaking()); // If there's a child break inside (typically in a parallel flow, or we @@ -2941,9 +2960,10 @@ // fragmentainers, before we can insert any column spanners, so that // everything that is supposed to come before the spanner actually ends up // there. - if (ConstraintSpace().IsPastBreak() || - container_builder_.HasInsertedChildBreak()) + if (constraint_space.IsPastBreak() || + container_builder_.HasInsertedChildBreak()) { builder.SetIsPastBreak(); + } } return builder.ToConstraintSpace(); @@ -2991,7 +3011,7 @@ const BoxStrut& margins, LayoutUnit block_offset) { DCHECK(child.IsBox()); - const auto baseline_algorithm = ConstraintSpace().BaselineAlgorithmType(); + const auto baseline_algorithm = GetConstraintSpace().BaselineAlgorithmType(); // When computing baselines for an inline-block, table's don't contribute any // baselines. @@ -3005,7 +3025,7 @@ return; const auto& physical_fragment = To<NGPhysicalBoxFragment>(child); - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), physical_fragment); if (!container_builder_.FirstBaseline()) { @@ -3042,16 +3062,18 @@ // previous layout pass, so check the constraint space for pre-applied // clearance. This is important in order to identify possible class C break // points. - if (ConstraintSpace().IsPushedByFloats()) + if (GetConstraintSpace().IsPushedByFloats()) { container_builder_.SetIsPushedByFloats(); + } if (container_builder_.BfcBlockOffset()) return true; bfc_block_offset = forced_bfc_block_offset.value_or(bfc_block_offset); - if (ApplyClearance(ConstraintSpace(), &bfc_block_offset)) + if (ApplyClearance(GetConstraintSpace(), &bfc_block_offset)) { container_builder_.SetIsPushedByFloats(); + } container_builder_.SetBfcBlockOffset(bfc_block_offset); @@ -3059,7 +3081,7 @@ // A formatting context root should always be able to resolve its // whereabouts before layout, so there should never be any incorrect // estimates that we need to go back and fix. - DCHECK(!ConstraintSpace().IsNewFormattingContext()); + DCHECK(!GetConstraintSpace().IsNewFormattingContext()); return false; } @@ -3096,7 +3118,7 @@ // If our position differs from our (potentially optimistic) estimate, abort. return *container_builder_.BfcBlockOffset() != - ConstraintSpace().ExpectedBfcBlockOffset(); + GetConstraintSpace().ExpectedBfcBlockOffset(); } absl::optional<LayoutUnit> @@ -3108,12 +3130,13 @@ if (!Style().LogicalHeight().IsAuto()) return absl::nullopt; - if (ConstraintSpace().IsNewFormattingContext()) + if (GetConstraintSpace().IsNewFormattingContext()) { return absl::nullopt; + } DCHECK(Node().IsBody()); LayoutUnit block_end_margin = - ComputeMarginsForSelf(ConstraintSpace(), Style()).block_end; + ComputeMarginsForSelf(GetConstraintSpace(), Style()).block_end; // The |end_margin_strut| is the block-start margin if the body doesn't have // a resolved BFC block-offset. @@ -3123,7 +3146,7 @@ MarginStrut body_strut = end_margin_strut; body_strut.Append(block_end_margin, Style().HasMarginBlockEndQuirk()); return *container_builder_.BfcBlockOffset() - - ConstraintSpace().GetBfcOffset().block_offset + body_strut.Sum(); + GetConstraintSpace().GetBfcOffset().block_offset + body_strut.Sum(); } bool BlockLayoutAlgorithm::PositionOrPropagateListMarker( @@ -3142,7 +3165,7 @@ return true; container_builder_.ClearUnpositionedListMarker(); - const NGConstraintSpace& space = ConstraintSpace(); + const NGConstraintSpace& space = GetConstraintSpace(); const NGPhysicalFragment& content = layout_result.PhysicalFragment(); FontBaseline baseline_type = Style().GetFontBaseline(); if (auto content_baseline = @@ -3186,7 +3209,7 @@ DCHECK(container_builder_.GetUnpositionedListMarker()); auto list_marker = container_builder_.GetUnpositionedListMarker(); - const NGConstraintSpace& space = ConstraintSpace(); + const NGConstraintSpace& space = GetConstraintSpace(); FontBaseline baseline_type = Style().GetFontBaseline(); // Layout the list marker. const NGLayoutResult* marker_layout_result = @@ -3212,11 +3235,11 @@ return true; } -bool BlockLayoutAlgorithm::IsRubyText(const NGLayoutInputNode& child) const { +bool BlockLayoutAlgorithm::IsRubyText(const LayoutInputNode& child) const { return Node().IsRubyColumn() && child.IsRubyText(); } -void BlockLayoutAlgorithm::HandleRubyText(NGBlockNode ruby_text_child) { +void BlockLayoutAlgorithm::HandleRubyText(BlockNode ruby_text_child) { DCHECK(Node().IsRubyColumn()); const NGBlockBreakToken* break_token = nullptr; @@ -3230,13 +3253,14 @@ } const ComputedStyle& rt_style = ruby_text_child.Style(); - NGConstraintSpaceBuilder builder(ConstraintSpace(), + NGConstraintSpaceBuilder builder(GetConstraintSpace(), rt_style.GetWritingDirection(), true); SetOrthogonalFallbackInlineSizeIfNeeded(Style(), ruby_text_child, &builder); builder.SetAvailableSize(ChildAvailableSize()); - if (IsParallelWritingMode(ConstraintSpace().GetWritingMode(), - rt_style.GetWritingMode())) + if (IsParallelWritingMode(GetConstraintSpace().GetWritingMode(), + rt_style.GetWritingMode())) { builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit); + } const NGLayoutResult* result = ruby_text_child.Layout(builder.ToConstraintSpace(), break_token); @@ -3310,7 +3334,7 @@ } LayoutUnit BlockLayoutAlgorithm::HandleTextControlPlaceholder( - NGBlockNode placeholder, + BlockNode placeholder, const PreviousInflowPosition& previous_inflow_position) { DCHECK(Node().IsTextControl()) << Node().GetLayoutBox(); @@ -3327,7 +3351,7 @@ const auto begin = grand_children.begin(); if (begin != grand_children.end()) { LogicalFragment grand_child_fragment( - ConstraintSpace().GetWritingDirection(), *begin->fragment); + GetConstraintSpace().GetWritingDirection(), *begin->fragment); available_size.inline_size = grand_child_fragment.InlineSize(); } } @@ -3354,7 +3378,7 @@ previous_inflow_position); } LogicalBoxFragment fragment( - ConstraintSpace().GetWritingDirection(), + GetConstraintSpace().GetWritingDirection(), To<NGPhysicalBoxFragment>(result->PhysicalFragment())); // We should apply FirstBaseline() of the placeholder fragment because the // placeholder might have the 'overflow' property, and its LastBaseline() @@ -3396,7 +3420,7 @@ return block_offset; } LogicalBoxFragment fragment( - ConstraintSpace().GetWritingDirection(), + GetConstraintSpace().GetWritingDirection(), To<NGPhysicalBoxFragment>(result->PhysicalFragment())); return std::max(block_offset, offset.block_offset + fragment.BlockSize()); } @@ -3414,7 +3438,7 @@ // position the thumb's offset on the opposite side of the element (similar to // RTL direction). WritingDirectionMode writing_direction = - ConstraintSpace().GetWritingDirection(); + GetConstraintSpace().GetWritingDirection(); if (!writing_direction.IsHorizontal() && writing_direction.IsLtr() && !RuntimeEnabledFeatures:: FormControlsVerticalWritingModeDirectionSupportEnabled()) {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h index 48563c1..7ad897f4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm.h
@@ -60,7 +60,7 @@ // A class for general block layout (e.g. a <div> with no special style). // Lays out the children in sequence. class CORE_EXPORT BlockLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -100,7 +100,7 @@ return *container_builder_.BfcBlockOffset(); // Otherwise fall back to the BFC block offset assigned by the parent // algorithm. - return ConstraintSpace().GetBfcOffset().block_offset; + return GetConstraintSpace().GetBfcOffset().block_offset; } // Return the BFC block offset of the next block-start border edge (for some @@ -111,13 +111,13 @@ previous_inflow_position.margin_strut.Sum(); } - BoxStrut CalculateMargins(NGLayoutInputNode child, + BoxStrut CalculateMargins(LayoutInputNode child, bool is_new_fc, LayoutUnit* additional_line_offset); // Creates a new constraint space for the current child. NGConstraintSpace CreateConstraintSpaceForChild( - const NGLayoutInputNode child, + const LayoutInputNode child, const NGBreakToken* child_break_token, const InflowChildData& child_data, const LogicalSize child_available_size, @@ -128,13 +128,13 @@ // @return Estimated BFC block offset for the "to be layout" child. InflowChildData ComputeChildData(const PreviousInflowPosition&, - NGLayoutInputNode, + LayoutInputNode, const NGBreakToken* child_break_token, bool is_new_fc); PreviousInflowPosition ComputeInflowPosition( const PreviousInflowPosition&, - const NGLayoutInputNode child, + const LayoutInputNode child, const InflowChildData&, const absl::optional<LayoutUnit>& child_bfc_block_offset, const LogicalOffset&, @@ -150,7 +150,7 @@ // <div style="padding: 1px"> // <div id="zero" style="margin: 1px"></div> LayoutUnit PositionSelfCollapsingChildWithParentBfc( - const NGLayoutInputNode& child, + const LayoutInputNode& child, const NGConstraintSpace& child_space, const InflowChildData& child_data, const NGLayoutResult&) const; @@ -164,9 +164,9 @@ PreviousInflowPosition*, const InlineBreakToken** inline_break_token_out); - void HandleOutOfFlowPositioned(const PreviousInflowPosition&, NGBlockNode); + void HandleOutOfFlowPositioned(const PreviousInflowPosition&, BlockNode); void HandleFloat(const PreviousInflowPosition&, - NGBlockNode, + BlockNode, const NGBlockBreakToken*); // This uses the NGLayoutOpporunityIterator to position the fragment. @@ -187,14 +187,14 @@ // Returns false if we need to abort layout, because a previously unknown BFC // block offset has now been resolved. NGLayoutResult::EStatus HandleNewFormattingContext( - NGLayoutInputNode child, + LayoutInputNode child, const NGBlockBreakToken* child_break_token, PreviousInflowPosition*); // Performs the actual layout of a new formatting context. This may be called // multiple times from HandleNewFormattingContext. const NGLayoutResult* LayoutNewFormattingContext( - NGLayoutInputNode child, + LayoutInputNode child, const NGBlockBreakToken* child_break_token, const InflowChildData&, BfcOffset origin_offset, @@ -206,14 +206,14 @@ // Returns false if we need to abort layout, because a previously unknown BFC // block offset has now been resolved. (Same as HandleNewFormattingContext). NGLayoutResult::EStatus HandleInflow( - NGLayoutInputNode child, + LayoutInputNode child, const NGBreakToken* child_break_token, PreviousInflowPosition*, InlineChildLayoutContext*, const InlineBreakToken** previous_inline_break_token); NGLayoutResult::EStatus FinishInflow( - NGLayoutInputNode child, + LayoutInputNode child, const NGBreakToken* child_break_token, const NGConstraintSpace&, bool has_clearance_past_adjoining_floats, @@ -242,7 +242,7 @@ // Insert a fragmentainer break before the child if necessary. // See |::blink::BreakBeforeChildIfNeeded()| for more documentation. - NGBreakStatus BreakBeforeChildIfNeeded(NGLayoutInputNode child, + NGBreakStatus BreakBeforeChildIfNeeded(LayoutInputNode child, const NGLayoutResult&, PreviousInflowPosition*, LayoutUnit bfc_block_offset, @@ -288,7 +288,7 @@ bool ResolveBfcBlockOffset(PreviousInflowPosition* previous_inflow_position, LayoutUnit bfc_block_offset) { return ResolveBfcBlockOffset(previous_inflow_position, bfc_block_offset, - ConstraintSpace().ForcedBfcBlockOffset()); + GetConstraintSpace().ForcedBfcBlockOffset()); } // A very common way to resolve the BFC block offset is to simply commit the @@ -351,8 +351,9 @@ // Also need to check if the constraint space is anonymous, which is the // case for columns (the list item marker should be placed by the multicol // container then, not the individual columns). - if (!ConstraintSpace().IsAnonymous()) + if (!GetConstraintSpace().IsAnonymous()) { return true; + } // Ensure we're really a column box. We can't use |BoxType| to call this // from the constructor. DCHECK(node_.GetLayoutBox()->SlowFirstChild()->IsLayoutFlowThread()); @@ -361,18 +362,18 @@ // Returns true if |this| is a ruby segment (LayoutRubyColumn) and the // specified |child| is a ruby annotation box (LayoutNGRubyText). - bool IsRubyText(const NGLayoutInputNode& child) const; + bool IsRubyText(const LayoutInputNode& child) const; // Layout |ruby_text_child| content, and decide the location of // |ruby_text_child|. This is called only if IsRubyText() returns true. - void HandleRubyText(NGBlockNode ruby_text_child); + void HandleRubyText(BlockNode ruby_text_child); // Layout |placeholder| content, and decide the location of |placeholder|. // This is called only if |this| is a text control. // This function returns a new value for `PreviousInflowPosition:: // logical_block_offset`. LayoutUnit HandleTextControlPlaceholder( - NGBlockNode placeholder, + BlockNode placeholder, const PreviousInflowPosition& previous_inflow_position); // A helper for HandleTextControlPlaceholder(). // This function returns a new value for `PreviousInflowPosition::
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc index e175c815..90ab813 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_layout_algorithm_test.cc
@@ -42,7 +42,7 @@ &layout_box->GetSingleCachedLayoutResult()->PhysicalFragment()); } - MinMaxSizes RunComputeMinMaxSizes(NGBlockNode node) { + MinMaxSizes RunComputeMinMaxSizes(BlockNode node) { // The constraint space is not used for min/max computation, but we need // it to create the algorithm. NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( @@ -56,7 +56,7 @@ } const NGLayoutResult* RunCachedLayoutResult(const NGConstraintSpace& space, - const NGBlockNode& node) { + const BlockNode& node) { NGLayoutCacheStatus cache_status; absl::optional<FragmentGeometry> initial_fragment_geometry; return To<LayoutBlockFlow>(node.GetLayoutBox()) @@ -94,7 +94,7 @@ {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(100), kIndefiniteSize)); - NGBlockNode box(GetLayoutBoxByElementId("box")); + BlockNode box(GetLayoutBoxByElementId("box")); const NGPhysicalBoxFragment* fragment = RunBlockLayoutAlgorithm(box, space); @@ -115,7 +115,7 @@ LogicalSize(LayoutUnit(100), LayoutUnit(100))); auto* block_flow = To<LayoutBlockFlow>(GetLayoutObjectByElementId("box")); - NGBlockNode node(block_flow); + BlockNode node(block_flow); const NGLayoutResult* result = node.Layout(space, nullptr); EXPECT_EQ(PhysicalSize(30, 40), result->PhysicalFragment().Size()); @@ -162,7 +162,7 @@ LogicalSize(LayoutUnit(100), LayoutUnit(100))); auto* block_flow = To<LayoutBlockFlow>(GetLayoutObjectByElementId("box")); - NGBlockNode node(block_flow); + BlockNode node(block_flow); const NGLayoutResult* result = node.Layout(space, nullptr); EXPECT_EQ(PhysicalSize(30, 40), result->PhysicalFragment().Size()); @@ -248,7 +248,7 @@ auto run_test = [&](auto id) -> const NGLayoutResult* { // Grab the box under test. auto* box = To<LayoutBlockFlow>(GetLayoutObjectByElementId(id)); - NGBlockNode node(box); + BlockNode node(box); // Check that we have a cache hit with space100. const NGLayoutResult* result = RunCachedLayoutResult(space100, node); @@ -314,7 +314,7 @@ auto* box1 = To<LayoutBlockFlow>(GetLayoutObjectByElementId("box1")); // Ensure we get a cached layout result, even if our BFC line-offset changed. - result = RunCachedLayoutResult(space200, NGBlockNode(box1)); + result = RunCachedLayoutResult(space200, BlockNode(box1)); EXPECT_NE(result, nullptr); } @@ -333,7 +333,7 @@ const int kHeight2 = 30; const int kMarginTop = 5; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(100), kIndefiniteSize)); @@ -378,7 +378,7 @@ const int kHeight = 50; const int kMarginLeft = 100; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(500), LayoutUnit(500))); @@ -779,7 +779,7 @@ const int kMarginBottom = 10; const int kMarginTop = 40; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(500), LayoutUnit(500))); @@ -1075,7 +1075,7 @@ const int kPaddingBottom = 7; const int kPaddingLeft = 8; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -1112,7 +1112,7 @@ const int kPaddingLeft = 10; const int kWidth = 30; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -1144,7 +1144,7 @@ const int kWidth = 30; const int kChildWidth = 10; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -1516,7 +1516,7 @@ const int kSecondChildWidth = 30; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); MinMaxSizes sizes = RunComputeMinMaxSizes(container); EXPECT_EQ(kSecondChildWidth, sizes.min_size); @@ -1537,7 +1537,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); MinMaxSizes sizes = RunComputeMinMaxSizes(container); EXPECT_EQ(LayoutUnit(40), sizes.min_size); @@ -1558,7 +1558,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); MinMaxSizes sizes = RunComputeMinMaxSizes(container); EXPECT_EQ(LayoutUnit(40), sizes.min_size); @@ -1579,7 +1579,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); MinMaxSizes sizes = RunComputeMinMaxSizes(container); EXPECT_EQ(LayoutUnit(100), sizes.min_size); @@ -1601,7 +1601,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); MinMaxSizes sizes = RunComputeMinMaxSizes(container); EXPECT_EQ(LayoutUnit(30), sizes.min_size); @@ -1619,7 +1619,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); MinMaxSizes sizes = RunComputeMinMaxSizes(container); EXPECT_EQ(LayoutUnit(), sizes.min_size); @@ -1636,7 +1636,7 @@ )HTML"); const int kWidthChild2 = 30; - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, @@ -1783,7 +1783,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1811,7 +1811,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1854,7 +1854,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1918,7 +1918,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1981,7 +1981,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -2046,8 +2046,7 @@ LayoutUnit kFragmentainerSpaceAvailable(150); - NGBlockNode node( - To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); + BlockNode node(To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -2125,8 +2124,7 @@ LayoutUnit kFragmentainerSpaceAvailable(150); - NGBlockNode node( - To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); + BlockNode node(To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -2173,8 +2171,7 @@ LayoutUnit kFragmentainerSpaceAvailable(150); - NGBlockNode node( - To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); + BlockNode node(To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -2295,8 +2292,7 @@ </div> )HTML"); - NGBlockNode node( - To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); + BlockNode node(To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); @@ -2330,8 +2326,7 @@ </div> )HTML"); - NGBlockNode node( - To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); + BlockNode node(To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -2369,8 +2364,7 @@ </div> )HTML"); - NGBlockNode node( - To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); + BlockNode node(To<LayoutBlockFlow>(GetLayoutObjectByElementId("container"))); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize),
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc index c4bdf967..0aab7ee 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.cc
@@ -224,7 +224,7 @@ bool CanUseCachedIntrinsicInlineSizes(const NGConstraintSpace& constraint_space, const MinMaxSizesFloatInput& float_input, - const NGBlockNode& node) { + const BlockNode& node) { // Obviously can't use the cache if our intrinsic logical widths are dirty. if (node.GetLayoutBox()->IntrinsicLogicalWidthsDirty()) return false; @@ -268,7 +268,7 @@ } absl::optional<LayoutUnit> ContentMinimumInlineSize( - const NGBlockNode& block_node, + const BlockNode& block_node, const BoxStrut& border_padding) { // Table layout is never allowed to go below the min-intrinsic size. if (block_node.IsTable()) @@ -315,7 +315,7 @@ } // namespace -const NGLayoutResult* NGBlockNode::Layout( +const NGLayoutResult* BlockNode::Layout( const NGConstraintSpace& constraint_space, const NGBlockBreakToken* break_token, const NGEarlyBreak* early_break, @@ -569,7 +569,7 @@ return layout_result; } -const NGLayoutResult* NGBlockNode::SimplifiedLayout( +const NGLayoutResult* BlockNode::SimplifiedLayout( const NGPhysicalFragment& previous_fragment) const { const NGLayoutResult* previous_result = box_->GetSingleCachedLayoutResult(); DCHECK(previous_result); @@ -622,7 +622,7 @@ return result; } -const NGLayoutResult* NGBlockNode::LayoutRepeatableRoot( +const NGLayoutResult* BlockNode::LayoutRepeatableRoot( const NGConstraintSpace& constraint_space, const NGBlockBreakToken* break_token) const { // We read and write the physical fragments vector in LayoutBox here, which @@ -677,7 +677,7 @@ return result; } -void NGBlockNode::FinishRepeatableRoot() const { +void BlockNode::FinishRepeatableRoot() const { DCHECK(!NGDisableSideEffectsScope::IsDisabled()); // This is the last fragment. It won't be repeated again. We have already @@ -707,7 +707,7 @@ } } -const NGLayoutResult* NGBlockNode::CachedLayoutResultForOutOfFlowPositioned( +const NGLayoutResult* BlockNode::CachedLayoutResultForOutOfFlowPositioned( LogicalSize container_content_size) const { DCHECK(IsOutOfFlowPositioned()); @@ -754,7 +754,7 @@ return cached_layout_result; } -void NGBlockNode::PrepareForLayout() const { +void BlockNode::PrepareForLayout() const { auto* block = DynamicTo<LayoutBlock>(box_.Get()); if (block && block->IsScrollContainer()) { DCHECK(block->GetScrollableArea()); @@ -768,7 +768,7 @@ To<LayoutListItem>(box_.Get())->UpdateMarkerTextIfNeeded(); } -void NGBlockNode::FinishLayout( +void BlockNode::FinishLayout( LayoutBlockFlow* block_flow, const NGConstraintSpace& constraint_space, const NGBlockBreakToken* break_token, @@ -860,9 +860,9 @@ CopyFragmentDataToLayoutBox(constraint_space, *layout_result, break_token); } -void NGBlockNode::StoreResultInLayoutBox(const NGLayoutResult* result, - const NGBlockBreakToken* break_token, - bool clear_trailing_results) const { +void BlockNode::StoreResultInLayoutBox(const NGLayoutResult* result, + const NGBlockBreakToken* break_token, + bool clear_trailing_results) const { const auto& fragment = To<NGPhysicalBoxFragment>(result->PhysicalFragment()); wtf_size_t fragment_idx = 0; @@ -883,7 +883,7 @@ box_->ShrinkLayoutResults(fragment_idx + 1); } -MinMaxSizesResult NGBlockNode::ComputeMinMaxSizes( +MinMaxSizesResult BlockNode::ComputeMinMaxSizes( WritingMode container_writing_mode, const MinMaxSizesType type, const NGConstraintSpace& constraint_space, @@ -1052,7 +1052,7 @@ return result; } -NGLayoutInputNode NGBlockNode::NextSibling() const { +LayoutInputNode BlockNode::NextSibling() const { LayoutObject* next_sibling = box_->NextSibling(); // We may have some LayoutInline(s) still within the tree (due to treating @@ -1070,10 +1070,10 @@ if (!next_sibling) return nullptr; - return NGBlockNode(To<LayoutBox>(next_sibling)); + return BlockNode(To<LayoutBox>(next_sibling)); } -NGLayoutInputNode NGBlockNode::FirstChild() const { +LayoutInputNode BlockNode::FirstChild() const { // If this layout is blocked by a display-lock, then we pretend this node has // no children. if (ChildLayoutBlockedByDisplayLock()) { @@ -1081,12 +1081,12 @@ } auto* block = DynamicTo<LayoutBlock>(box_.Get()); if (UNLIKELY(!block)) - return NGBlockNode(box_->FirstChildBox()); + return BlockNode(box_->FirstChildBox()); auto* child = GetLayoutObjectForFirstChildNode(block); if (!child) return nullptr; if (!AreNGBlockFlowChildrenInline(block)) - return NGBlockNode(To<LayoutBox>(child)); + return BlockNode(To<LayoutBox>(child)); InlineNode inline_node(To<LayoutBlockFlow>(block)); if (!inline_node.IsBlockLevel()) @@ -1112,24 +1112,24 @@ return nullptr; DCHECK(child->IsFloatingOrOutOfFlowPositioned()); - return NGBlockNode(To<LayoutBox>(child)); + return BlockNode(To<LayoutBox>(child)); } -NGBlockNode NGBlockNode::GetRenderedLegend() const { +BlockNode BlockNode::GetRenderedLegend() const { if (!IsFieldsetContainer()) return nullptr; - return NGBlockNode( + return BlockNode( LayoutFieldset::FindInFlowLegend(*To<LayoutBlock>(box_.Get()))); } -NGBlockNode NGBlockNode::GetFieldsetContent() const { +BlockNode BlockNode::GetFieldsetContent() const { if (!IsFieldsetContainer()) return nullptr; - return NGBlockNode( + return BlockNode( To<LayoutFieldset>(box_.Get())->FindAnonymousFieldsetContentBox()); } -LayoutUnit NGBlockNode::EmptyLineBlockSize( +LayoutUnit BlockNode::EmptyLineBlockSize( const NGBlockBreakToken* incoming_break_token) const { // Only return a line-height for the first fragment. if (IsBreakInside(incoming_break_token)) @@ -1137,12 +1137,12 @@ return box_->LogicalHeightForEmptyLine(); } -String NGBlockNode::ToString() const { - return String::Format("NGBlockNode: %s", +String BlockNode::ToString() const { + return String::Format("BlockNode: %s", GetLayoutBox()->ToString().Ascii().c_str()); } -void NGBlockNode::CopyFragmentDataToLayoutBox( +void BlockNode::CopyFragmentDataToLayoutBox( const NGConstraintSpace& constraint_space, const NGLayoutResult& layout_result, const NGBlockBreakToken* previous_break_token) const { @@ -1216,7 +1216,7 @@ } } -void NGBlockNode::PlaceChildrenInLayoutBox( +void BlockNode::PlaceChildrenInLayoutBox( const NGPhysicalBoxFragment& physical_fragment, const NGBlockBreakToken* previous_break_token, bool needs_invalidation_check) const { @@ -1243,7 +1243,7 @@ } } -void NGBlockNode::PlaceChildrenInFlowThread( +void BlockNode::PlaceChildrenInFlowThread( LayoutMultiColumnFlowThread* flow_thread, const NGConstraintSpace& space, const NGPhysicalBoxFragment& physical_fragment, @@ -1331,7 +1331,7 @@ } // Copies data back to the legacy layout tree for a given child fragment. -void NGBlockNode::CopyChildFragmentPosition( +void BlockNode::CopyChildFragmentPosition( const NGPhysicalBoxFragment& child_fragment, PhysicalOffset offset, const NGPhysicalBoxFragment& container_fragment, @@ -1352,7 +1352,7 @@ layout_box->SetShouldCheckForPaintInvalidation(); } -void NGBlockNode::MakeRoomForExtraColumns(LayoutUnit block_size) const { +void BlockNode::MakeRoomForExtraColumns(LayoutUnit block_size) const { auto* block_flow = DynamicTo<LayoutBlockFlow>(GetLayoutBox()); DCHECK(block_flow && block_flow->MultiColumnFlowThread()); MultiColumnFragmentainerGroup& last_group = @@ -1362,7 +1362,7 @@ last_group.ExtendLogicalBottomInFlowThread(block_size); } -void NGBlockNode::CopyFragmentItemsToLayoutBox( +void BlockNode::CopyFragmentItemsToLayoutBox( const NGPhysicalBoxFragment& container, const FragmentItems& items, const NGBlockBreakToken* previous_break_token) const { @@ -1416,12 +1416,12 @@ } } -bool NGBlockNode::IsInlineFormattingContextRoot( +bool BlockNode::IsInlineFormattingContextRoot( InlineNode* first_child_out) const { if (const auto* block = DynamicTo<LayoutBlockFlow>(box_.Get())) { if (!AreNGBlockFlowChildrenInline(block)) return false; - NGLayoutInputNode first_child = FirstChild(); + LayoutInputNode first_child = FirstChild(); if (first_child.IsInline()) { if (first_child_out) *first_child_out = To<InlineNode>(first_child); @@ -1431,21 +1431,21 @@ return false; } -bool NGBlockNode::IsInlineLevel() const { +bool BlockNode::IsInlineLevel() const { return GetLayoutBox()->IsInline(); } -bool NGBlockNode::IsAtomicInlineLevel() const { +bool BlockNode::IsAtomicInlineLevel() const { // LayoutObject::IsAtomicInlineLevel() returns true for e.g., <img // style="display: block">. Check IsInline() as well. return GetLayoutBox()->IsAtomicInlineLevel() && GetLayoutBox()->IsInline(); } -bool NGBlockNode::IsInTopOrViewTransitionLayer() const { +bool BlockNode::IsInTopOrViewTransitionLayer() const { return GetLayoutBox()->IsInTopOrViewTransitionLayer(); } -bool NGBlockNode::HasAspectRatio() const { +bool BlockNode::HasAspectRatio() const { if (!Style().AspectRatio().IsAuto()) { DCHECK(!GetAspectRatio().IsEmpty()); return true; @@ -1461,7 +1461,7 @@ return !GetAspectRatio().IsEmpty(); } -LogicalSize NGBlockNode::GetAspectRatio() const { +LogicalSize BlockNode::GetAspectRatio() const { // The CSS parser will ensure that this will only be set if the feature // is enabled. const EAspectRatioType ar_type = Style().AspectRatio().GetType(); @@ -1487,7 +1487,7 @@ return LogicalSize(); } -absl::optional<gfx::Transform> NGBlockNode::GetTransformForChildFragment( +absl::optional<gfx::Transform> BlockNode::GetTransformForChildFragment( const NGPhysicalBoxFragment& child_fragment, PhysicalSize size) const { const auto* child_layout_object = child_fragment.GetLayoutObject(); @@ -1519,28 +1519,28 @@ return transform; } -bool NGBlockNode::HasNonVisibleBlockOverflow() const { +bool BlockNode::HasNonVisibleBlockOverflow() const { OverflowClipAxes clip_axes = GetOverflowClipAxes(); if (Style().IsHorizontalWritingMode()) return clip_axes & kOverflowClipY; return clip_axes & kOverflowClipX; } -bool NGBlockNode::IsCustomLayoutLoaded() const { +bool BlockNode::IsCustomLayoutLoaded() const { return To<LayoutCustom>(box_.Get())->IsLoaded(); } -MathScriptType NGBlockNode::ScriptType() const { +MathScriptType BlockNode::ScriptType() const { DCHECK(IsA<MathMLScriptsElement>(GetDOMNode())); return To<MathMLScriptsElement>(GetDOMNode())->GetScriptType(); } -bool NGBlockNode::HasIndex() const { +bool BlockNode::HasIndex() const { DCHECK(IsA<MathMLRadicalElement>(GetDOMNode())); return To<MathMLRadicalElement>(GetDOMNode())->HasIndex(); } -const NGLayoutResult* NGBlockNode::LayoutAtomicInline( +const NGLayoutResult* BlockNode::LayoutAtomicInline( const NGConstraintSpace& parent_constraint_space, const ComputedStyle& parent_style, bool use_first_line_style, @@ -1570,7 +1570,7 @@ return result; } -const NGLayoutResult* NGBlockNode::RunSimplifiedLayout( +const NGLayoutResult* BlockNode::RunSimplifiedLayout( const LayoutAlgorithmParams& params, const NGLayoutResult& previous_result) const { SimplifiedLayoutAlgorithm algorithm(params, previous_result); @@ -1582,7 +1582,7 @@ return algorithm.Layout(); } -void NGBlockNode::UpdateMarginPaddingInfoIfNeeded( +void BlockNode::UpdateMarginPaddingInfoIfNeeded( const NGConstraintSpace& space, const NGPhysicalFragment& fragment) const { // Table-cells don't have margins, and aren't grid-items. @@ -1615,7 +1615,7 @@ // Floats can optionally have a shape area, specified by "shape-outside". The // current shape machinery requires setting the size of the float after layout // in the parents writing mode. -void NGBlockNode::UpdateShapeOutsideInfoIfNeeded( +void BlockNode::UpdateShapeOutsideInfoIfNeeded( const NGLayoutResult& layout_result, const NGConstraintSpace& constraint_space) const { if (!box_->IsFloating() || !box_->GetShapeOutsideInfo()) @@ -1642,7 +1642,7 @@ constraint_space.PercentageResolutionInlineSize()); } -void NGBlockNode::StoreColumnSizeAndCount(LayoutUnit inline_size, int count) { +void BlockNode::StoreColumnSizeAndCount(LayoutUnit inline_size, int count) { LayoutMultiColumnFlowThread* flow_thread = To<LayoutBlockFlow>(box_.Get())->MultiColumnFlowThread(); // We have no chance to unregister the inline size for the
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node.h b/third_party/blink/renderer/core/layout/ng/ng_block_node.h index 4846b1c..34aeb1be 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node.h +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node.h
@@ -29,12 +29,13 @@ enum class MathScriptType; // Represents a node to be laid out. -class CORE_EXPORT NGBlockNode : public NGLayoutInputNode { - friend NGLayoutInputNode; - public: - explicit NGBlockNode(LayoutBox* box) : NGLayoutInputNode(box, kBlock) {} +class CORE_EXPORT BlockNode : public LayoutInputNode { + friend LayoutInputNode; - NGBlockNode(std::nullptr_t) : NGLayoutInputNode(nullptr) {} + public: + explicit BlockNode(LayoutBox* box) : LayoutInputNode(box, kBlock) {} + + BlockNode(std::nullptr_t) : LayoutInputNode(nullptr) {} const NGLayoutResult* Layout(const NGConstraintSpace& constraint_space, const NGBlockBreakToken* break_token = nullptr, @@ -99,7 +100,7 @@ const NGLayoutResult* CachedLayoutResultForOutOfFlowPositioned( LogicalSize container_content_size) const; - NGLayoutInputNode NextSibling() const; + LayoutInputNode NextSibling() const; // Computes the value of min-content and max-content for this node's border // box. @@ -125,10 +126,10 @@ const NGConstraintSpace&, const MinMaxSizesFloatInput float_input = MinMaxSizesFloatInput()) const; - NGLayoutInputNode FirstChild() const; + LayoutInputNode FirstChild() const; - NGBlockNode GetRenderedLegend() const; - NGBlockNode GetFieldsetContent() const; + BlockNode GetRenderedLegend() const; + BlockNode GetFieldsetContent() const; bool IsTableCell() const { return box_->IsTableCell(); } @@ -238,8 +239,8 @@ // legacy flow thread to encompass those extra columns. void MakeRoomForExtraColumns(LayoutUnit block_size) const; - bool operator==(const NGBlockNode& other) const { return box_ == other.box_; } - bool operator==(const NGLayoutInputNode& other) const { + bool operator==(const BlockNode& other) const { return box_ == other.box_; } + bool operator==(const LayoutInputNode& other) const { return other.Type() == kBlock && GetLayoutBox() == other.GetLayoutBox(); } @@ -293,10 +294,8 @@ }; template <> -struct DowncastTraits<NGBlockNode> { - static bool AllowFrom(const NGLayoutInputNode& node) { - return node.IsBlock(); - } +struct DowncastTraits<BlockNode> { + static bool AllowFrom(const LayoutInputNode& node) { return node.IsBlock(); } }; // Devtools can trigger layout to collect devtools-specific data. We don't want @@ -314,6 +313,6 @@ } // namespace blink -WTF_ALLOW_CLEAR_UNUSED_SLOTS_WITH_MEM_FUNCTIONS(blink::NGBlockNode) +WTF_ALLOW_CLEAR_UNUSED_SLOTS_WITH_MEM_FUNCTIONS(blink::BlockNode) #endif // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_NG_NG_BLOCK_NODE_H_
diff --git a/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc b/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc index 69edd0d..b6a7dcf 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_block_node_test.cc
@@ -11,9 +11,9 @@ namespace blink { namespace { -using NGBlockNodeForTest = RenderingTest; +using BlockNodeForTest = RenderingTest; -TEST_F(NGBlockNodeForTest, IsFloatingForOutOfFlowFloating) { +TEST_F(BlockNodeForTest, IsFloatingForOutOfFlowFloating) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -24,39 +24,39 @@ </style> <div id=container></div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); EXPECT_FALSE(container.IsFloating()); } -TEST_F(NGBlockNodeForTest, ChildInlineAndBlock) { +TEST_F(BlockNodeForTest, ChildInlineAndBlock) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <div id=container>Hello!<div></div></div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsBlock()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_TRUE(child2 && child2.IsBlock()); - NGLayoutInputNode child3 = child2.NextSibling(); + LayoutInputNode child3 = child2.NextSibling(); EXPECT_EQ(child3, nullptr); } -TEST_F(NGBlockNodeForTest, ChildBlockAndInline) { +TEST_F(BlockNodeForTest, ChildBlockAndInline) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <div id=container><div></div>Hello!</div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsBlock()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_TRUE(child2 && child2.IsBlock()); - NGLayoutInputNode child3 = child2.NextSibling(); + LayoutInputNode child3 = child2.NextSibling(); EXPECT_EQ(child3, nullptr); } -TEST_F(NGBlockNodeForTest, ChildFloatBeforeBlock) { +TEST_F(BlockNodeForTest, ChildFloatBeforeBlock) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -64,16 +64,16 @@ </style> <div id=container><float></float><div></div></div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsBlock()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_TRUE(child2 && child2.IsBlock()); - NGLayoutInputNode child3 = child2.NextSibling(); + LayoutInputNode child3 = child2.NextSibling(); EXPECT_EQ(child3, nullptr); } -TEST_F(NGBlockNodeForTest, ChildFloatBeforeInline) { +TEST_F(BlockNodeForTest, ChildFloatBeforeInline) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -81,14 +81,14 @@ </style> <div id=container><float></float>Hello!</div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsInline()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_EQ(child2, nullptr); } -TEST_F(NGBlockNodeForTest, ChildFloatAfterInline) { +TEST_F(BlockNodeForTest, ChildFloatAfterInline) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -96,14 +96,14 @@ </style> <div id=container>Hello<float></float></div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsInline()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_EQ(child2, nullptr); } -TEST_F(NGBlockNodeForTest, ChildFloatOnly) { +TEST_F(BlockNodeForTest, ChildFloatOnly) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -111,14 +111,14 @@ </style> <div id=container><float></float></div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsBlock()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_EQ(child2, nullptr); } -TEST_F(NGBlockNodeForTest, ChildFloatWithSpaces) { +TEST_F(BlockNodeForTest, ChildFloatWithSpaces) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -128,14 +128,14 @@ <float></float> </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsBlock()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_EQ(child2, nullptr); } -TEST_F(NGBlockNodeForTest, ChildOofBeforeInline) { +TEST_F(BlockNodeForTest, ChildOofBeforeInline) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -143,14 +143,14 @@ </style> <div id=container><oof></oof>Hello!</div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsInline()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_EQ(child2, nullptr); } -TEST_F(NGBlockNodeForTest, ChildOofAfterInline) { +TEST_F(BlockNodeForTest, ChildOofAfterInline) { SetBodyInnerHTML(R"HTML( <!DOCTYPE html> <style> @@ -158,15 +158,15 @@ </style> <div id=container>Hello!<oof></oof></div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); - NGLayoutInputNode child1 = container.FirstChild(); + BlockNode container(GetLayoutBoxByElementId("container")); + LayoutInputNode child1 = container.FirstChild(); EXPECT_TRUE(child1 && child1.IsInline()); - NGLayoutInputNode child2 = child1.NextSibling(); + LayoutInputNode child2 = child1.NextSibling(); EXPECT_EQ(child2, nullptr); } // crbug.com/1107291 -TEST_F(NGBlockNodeForTest, MinContentForControls) { +TEST_F(BlockNodeForTest, MinContentForControls) { SetBodyInnerHTML(R"HTML( <div style="display: flex;"> <select id="box1" style="border: solid 2px blue; flex: 0; width: 10%;"> @@ -186,7 +186,7 @@ .ToConstraintSpace(); for (const auto* id : ids) { - NGBlockNode box(GetLayoutBoxByElementId(id)); + BlockNode box(GetLayoutBoxByElementId(id)); MinMaxSizes sizes = box.ComputeMinMaxSizes(WritingMode::kHorizontalTb, MinMaxSizesType::kContent, space) .sizes;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc index 46ed963..5fba012c 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.cc
@@ -44,7 +44,7 @@ } void NGBoxFragmentBuilder::AddBreakBeforeChild( - NGLayoutInputNode child, + LayoutInputNode child, absl::optional<NGBreakAppeal> appeal, bool is_forced_break) { // If there's a pre-set break token, we shouldn't be here. @@ -149,8 +149,9 @@ if (UNLIKELY(has_block_fragmentation_)) PropagateBreakInfo(*result_for_propagation, offset); - if (UNLIKELY(ConstraintSpace().ShouldPropagateChildBreakValues())) + if (UNLIKELY(GetConstraintSpace().ShouldPropagateChildBreakValues())) { PropagateChildBreakValues(*result_for_propagation); + } PropagateFromLayoutResult(*result_for_propagation); } @@ -362,7 +363,7 @@ block_size_for_fragmentation_ = std::max(block_size_for_fragmentation_, block_end_in_container); - if (ConstraintSpace().RequiresContentBeforeBreaking()) { + if (GetConstraintSpace().RequiresContentBeforeBreaking()) { if (child_layout_result.IsBlockSizeForFragmentationClamped()) is_block_size_for_fragmentation_clamped_ = true; } @@ -382,10 +383,10 @@ !child_fragment.IsFloatingOrOutOfFlowPositioned()) || child_layout_result.ShouldForceSameFragmentationFlow(); - if (ConstraintSpace().IsPaginated() && + if (GetConstraintSpace().IsPaginated() && ((child_is_in_same_flow && !IsFragmentainerBoxType()) || Node().IsPaginatedRoot())) { - DCHECK(ConstraintSpace().HasKnownFragmentainerBlockSize()); + DCHECK(GetConstraintSpace().HasKnownFragmentainerBlockSize()); // Include overflow inside monolithic content if this is for a page // fragment. Otherwise just use the fragment size. LayoutUnit block_size; @@ -405,7 +406,7 @@ } LayoutUnit fragment_block_end = offset.block_offset + block_size; LayoutUnit fragmentainer_overflow = - fragment_block_end - FragmentainerSpaceLeft(ConstraintSpace()); + fragment_block_end - FragmentainerSpaceLeft(GetConstraintSpace()); if (fragmentainer_overflow > LayoutUnit()) { // This child overflows the page, because there's something monolithic // inside. We need to be aware of this when laying out subsequent pages, @@ -425,7 +426,7 @@ // Downgrade the appeal of breaking inside this container, if the break // inside the child is less appealing than what we've found so far. NGBreakAppeal appeal_inside = - CalculateBreakAppealInside(ConstraintSpace(), child_layout_result); + CalculateBreakAppealInside(GetConstraintSpace(), child_layout_result); ClampBreakAppeal(appeal_inside); } @@ -445,7 +446,7 @@ // If a spanner was found inside the child, we need to finish up and propagate // the spanner to the column layout algorithm, so that it can take care of it. - if (UNLIKELY(ConstraintSpace().IsInColumnBfc())) { + if (UNLIKELY(GetConstraintSpace().IsInColumnBfc())) { if (const NGColumnSpannerPath* child_spanner_path = child_layout_result.ColumnSpannerPath()) { DCHECK(HasInflowChildBreakInside() || @@ -498,7 +499,7 @@ child_layout_result.FinalBreakAfter(), child_style.BreakAfter()); SetPreviousBreakAfter(break_after); - if (ConstraintSpace().IsPaginated()) { + if (GetConstraintSpace().IsPaginated()) { SetPageNameIfNeeded(To<NGPhysicalBoxFragment>(fragment).PageName()); } } @@ -545,7 +546,7 @@ OverflowClipAxes block_axis = GetWritingDirection().IsHorizontal() ? kOverflowClipY : kOverflowClipX; - if ((To<NGBlockNode>(node_).GetOverflowClipAxes() & block_axis) || + if ((To<BlockNode>(node_).GetOverflowClipAxes() & block_axis) || is_block_size_for_fragmentation_clamped_) { // If block-axis overflow is clipped, ignore child overflow and just use // the border-box size of the fragment itself. Also do this if the node @@ -681,9 +682,9 @@ DCHECK(!HasInflowChildBreakInside()); DCHECK(!DidBreakSelf()); DCHECK(!has_forced_break_); - DCHECK(ConstraintSpace().ShouldRepeat() || !HasBreakTokenData()); + DCHECK(GetConstraintSpace().ShouldRepeat() || !HasBreakTokenData()); DCHECK_EQ(minimal_space_shortage_, kIndefiniteSize); - if (!ConstraintSpace().ShouldPropagateChildBreakValues()) { + if (!GetConstraintSpace().ShouldPropagateChildBreakValues()) { DCHECK(!initial_break_before_); DCHECK_EQ(previous_break_after_, EBreakBetween::kAuto); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h index 2640f35..9469d70 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h +++ b/third_party/blink/renderer/core/layout/ng/ng_box_fragment_builder.h
@@ -38,15 +38,15 @@ STACK_ALLOCATED(); public: - NGBoxFragmentBuilder(NGLayoutInputNode node, + NGBoxFragmentBuilder(LayoutInputNode node, const ComputedStyle* style, const NGConstraintSpace& space, WritingDirectionMode writing_direction) : NGFragmentBuilder(node, style, space, writing_direction), is_inline_formatting_context_(node.IsInline()) {} - // Build a fragment for LayoutObject without NGLayoutInputNode. LayoutInline - // has InlineItem but does not have corresponding NGLayoutInputNode. + // Build a fragment for LayoutObject without LayoutInputNode. LayoutInline + // has InlineItem but does not have corresponding LayoutInputNode. NGBoxFragmentBuilder(LayoutObject* layout_object, const ComputedStyle* style, const NGConstraintSpace& space, @@ -73,7 +73,7 @@ border_scrollbar_padding_.block_start; if (node_) { child_available_size_ = CalculateChildAvailableSize( - space_, To<NGBlockNode>(node_), size_, border_scrollbar_padding_); + space_, To<BlockNode>(node_), size_, border_scrollbar_padding_); } } @@ -179,9 +179,9 @@ DCHECK(initial_fragment_geometry_); return child_available_size_; } - const NGBlockNode& Node() { + const BlockNode& Node() { DCHECK(node_); - return To<NGBlockNode>(node_); + return To<BlockNode>(node_); } // Be sure to use the layout result that's relevant for propagation and block @@ -197,7 +197,7 @@ // always be provided for regular in-flow children. For other types of // children it may be omitted, if the break shouldn't affect the appeal of // breaking inside this container. - void AddBreakBeforeChild(NGLayoutInputNode child, + void AddBreakBeforeChild(LayoutInputNode child, absl::optional<NGBreakAppeal> appeal, bool is_forced_break); @@ -284,7 +284,7 @@ } void ReserveSpaceForMonolithicOverflow(LayoutUnit monolithic_overflow) { - DCHECK(ConstraintSpace().IsPaginated()); + DCHECK(GetConstraintSpace().IsPaginated()); auto* data = EnsureBreakTokenData(); data->monolithic_overflow = std::max(data->monolithic_overflow, monolithic_overflow);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_break_token.h b/third_party/blink/renderer/core/layout/ng/ng_break_token.h index 96a71195..62dcb04 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_break_token.h +++ b/third_party/blink/renderer/core/layout/ng/ng_break_token.h
@@ -24,7 +24,7 @@ // Each layout algorithm which can fragment, e.g. block-flow can optionally // accept a break token. For example: // -// NGLayoutInputNode* node = ...; +// LayoutInputNode* node = ...; // NGPhysicalFragment* fragment = node->Layout(space); // NGPhysicalFragment* fragment2 = node->Layout(space, fragment->BreakToken()); // @@ -32,8 +32,8 @@ class CORE_EXPORT NGBreakToken : public GarbageCollected<NGBreakToken> { public: enum NGBreakTokenType { - kBlockBreakToken = NGLayoutInputNode::kBlock, - kInlineBreakToken = NGLayoutInputNode::kInline + kBlockBreakToken = LayoutInputNode::kBlock, + kInlineBreakToken = LayoutInputNode::kInline }; NGBreakTokenType Type() const { return static_cast<NGBreakTokenType>(type_); } @@ -42,10 +42,9 @@ // Returns the node associated with this break token. A break token cannot be // used with any other node. - NGLayoutInputNode InputNode() const { - return NGLayoutInputNode::Create( - box_.Get(), - static_cast<NGLayoutInputNode::NGLayoutInputNodeType>(type_)); + LayoutInputNode InputNode() const { + return LayoutInputNode::Create( + box_.Get(), static_cast<LayoutInputNode::LayoutInputNodeType>(type_)); } // Return true if this break token is for a node that's being resumed in a @@ -61,9 +60,7 @@ void TraceAfterDispatch(Visitor*) const; protected: - NGBreakToken(NGBreakTokenType type, - NGLayoutInputNode node, - unsigned flags = 0) + NGBreakToken(NGBreakTokenType type, LayoutInputNode node, unsigned flags = 0) : box_(node.GetLayoutBox()), type_(type), #if DCHECK_IS_ON() @@ -80,7 +77,7 @@ } private: - // Because |NGLayoutInputNode| has a pointer and 1 bit flag, and it's fast to + // Because |LayoutInputNode| has a pointer and 1 bit flag, and it's fast to // re-construct, keep |LayoutBox| to save the memory consumed by alignment. Member<LayoutBox> box_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc index b4b17d33..53c74ca4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.cc
@@ -38,7 +38,7 @@ public: Entry() = default; - Entry(const NGBlockBreakToken* token, NGBlockNode spanner) + Entry(const NGBlockBreakToken* token, BlockNode spanner) : break_token(token), spanner(spanner) {} // The incoming break token for the content to process, or null if we're at @@ -47,10 +47,10 @@ // The column spanner node to process, or null if we're dealing with regular // column content. - NGBlockNode spanner = nullptr; + BlockNode spanner = nullptr; }; - MulticolPartWalker(NGBlockNode multicol_container, + MulticolPartWalker(BlockNode multicol_container, const NGBlockBreakToken* break_token) : multicol_container_(multicol_container), parent_break_token_(break_token), @@ -76,7 +76,7 @@ void Next(); // Move over to the specified spanner, and take it from there. - void MoveToSpanner(NGBlockNode spanner, + void MoveToSpanner(BlockNode spanner, const NGBlockBreakToken* next_column_token); // Push a break token for the column content to resume at. @@ -92,8 +92,8 @@ void UpdateCurrent(); Entry current_; - NGBlockNode spanner_ = nullptr; - NGBlockNode multicol_container_; + BlockNode spanner_ = nullptr; + BlockNode multicol_container_; const NGBlockBreakToken* parent_break_token_; const NGBlockBreakToken* next_column_token_ = nullptr; @@ -113,7 +113,7 @@ } void MulticolPartWalker::MoveToSpanner( - NGBlockNode spanner, + BlockNode spanner, const NGBlockBreakToken* next_column_token) { *this = MulticolPartWalker(multicol_container_, nullptr); DCHECK(spanner.IsColumnSpanAll()); @@ -153,7 +153,7 @@ if (child_break_token->InputNode() == multicol_container_) { current_.spanner = nullptr; } else { - current_.spanner = To<NGBlockNode>(child_break_token->InputNode()); + current_.spanner = To<BlockNode>(child_break_token->InputNode()); DCHECK(current_.spanner.IsColumnSpanAll()); } current_.break_token = child_break_token; @@ -191,10 +191,10 @@ } if (spanner_) { - NGLayoutInputNode next = spanner_.NextSibling(); + LayoutInputNode next = spanner_.NextSibling(); // Otherwise, if there's a next spanner, we'll use that. if (next && next.IsColumnSpanAll()) { - spanner_ = To<NGBlockNode>(next); + spanner_ = To<BlockNode>(next); return; } spanner_ = nullptr; @@ -208,11 +208,11 @@ is_finished_ = true; } -NGBlockNode GetSpannerFromPath(const NGColumnSpannerPath* path) { +BlockNode GetSpannerFromPath(const NGColumnSpannerPath* path) { while (path->Child()) path = path->Child(); - DCHECK(path->BlockNode().IsColumnSpanAll()); - return path->BlockNode(); + DCHECK(path->GetBlockNode().IsColumnSpanAll()); + return path->GetBlockNode(); } } // namespace @@ -223,7 +223,7 @@ // When a list item has multicol, |ColumnLayoutAlgorithm| needs to keep // track of the list marker instead of the child layout algorithm. See // |NGBlockLayoutAlgorithm|. - if (const NGBlockNode marker_node = Node().ListMarkerBlockNodeIfListItem()) { + if (const BlockNode marker_node = Node().ListMarkerBlockNodeIfListItem()) { if (!marker_node.ListMarkerOccupiesWholeLine() && (!BreakToken() || BreakToken()->HasUnpositionedListMarker())) { container_builder_.SetUnpositionedListMarker( @@ -266,7 +266,7 @@ // fragmentainers. This would be in the first layout pass of an outer multicol // container, before any tentative column block-size has been calculated. is_constrained_by_outer_fragmentation_context_ = - ConstraintSpace().HasKnownFragmentainerBlockSize(); + GetConstraintSpace().HasKnownFragmentainerBlockSize(); container_builder_.SetIsBlockFragmentationContextRoot(); @@ -293,11 +293,11 @@ previously_consumed_block_size = token->ConsumedBlockSize(); intrinsic_block_size_ = - ClampIntrinsicBlockSize(ConstraintSpace(), Node(), BreakToken(), + ClampIntrinsicBlockSize(GetConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), intrinsic_block_size_); LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), + GetConstraintSpace(), Style(), BorderPadding(), previously_consumed_block_size + intrinsic_block_size_, border_box_size.inline_size); @@ -311,8 +311,8 @@ if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) { // In addition to establishing one, we're nested inside another // fragmentation context. - FinishFragmentation(Node(), ConstraintSpace(), BorderPadding().block_end, - FragmentainerSpaceLeft(ConstraintSpace()), + FinishFragmentation(Node(), GetConstraintSpace(), BorderPadding().block_end, + FragmentainerSpaceLeft(GetConstraintSpace()), &container_builder_); // OOF positioned elements inside a nested fragmentation context are laid @@ -333,11 +333,11 @@ #endif } - if (ConstraintSpace().IsTableCell()) { + if (GetConstraintSpace().IsTableCell()) { FinalizeTableCellLayout(intrinsic_block_size_, &container_builder_); } - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -410,11 +410,11 @@ } MinMaxSizesResult ColumnLayoutAlgorithm::ComputeSpannersMinMaxSizes( - const NGBlockNode& search_parent) const { + const BlockNode& search_parent) const { MinMaxSizesResult result; - for (NGLayoutInputNode child = search_parent.FirstChild(); child; + for (LayoutInputNode child = search_parent.FirstChild(); child; child = child.NextSibling()) { - const NGBlockNode* child_block = DynamicTo<NGBlockNode>(&child); + const BlockNode* child_block = DynamicTo<BlockNode>(&child); if (!child_block) continue; MinMaxSizesResult child_result; @@ -426,7 +426,7 @@ child_result = ComputeSpannersMinMaxSizes(*child_block); } else { NGMinMaxConstraintSpaceBuilder builder( - ConstraintSpace(), Style(), *child_block, /* is_new_fc */ true); + GetConstraintSpace(), Style(), *child_block, /* is_new_fc */ true); builder.SetAvailableBlockSize(ChildAvailableSize().block_size); const NGConstraintSpace child_space = builder.ToConstraintSpace(); child_result = ComputeMinAndMaxContentContribution(Style(), *child_block, @@ -457,7 +457,7 @@ if (!result) { // An outer fragmentainer break was inserted before this row. - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(GetConstraintSpace().HasBlockFragmentation()); break; } @@ -471,7 +471,7 @@ // it, |next_column_token| will be set. Move the walker to the // spanner. We'll now walk that spanner and any sibling spanners, before // resuming at |next_column_token|. - NGBlockNode spanner_node = GetSpannerFromPath(path); + BlockNode spanner_node = GetSpannerFromPath(path); walker.MoveToSpanner(spanner_node, next_column_token); continue; } @@ -487,7 +487,7 @@ // Attempt to lay out one column spanner. - NGBlockNode spanner_node = entry.spanner; + BlockNode spanner_node = entry.spanner; // If this is the child we had previously determined to break before, do so // now and finish layout. @@ -497,7 +497,7 @@ // Handle any OOF fragmentainer descendants that were found before the // spanner. - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_) + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_) .HandleFragmentation(); walker.UpdateNextColumnBreakToken(container_builder_.Children()); @@ -517,8 +517,8 @@ if (!walker.IsFinished() || container_builder_.HasInflowChildBreakInside()) { // We broke in the main flow. Let this multicol container take up any // remaining space. - intrinsic_block_size_ = std::max(intrinsic_block_size_, - FragmentainerSpaceLeft(ConstraintSpace())); + intrinsic_block_size_ = std::max( + intrinsic_block_size_, FragmentainerSpaceLeft(GetConstraintSpace())); // Go through any remaining parts that we didn't get to, and push them as // break tokens for the next (outer) fragmentainer to handle. @@ -604,7 +604,7 @@ if (is_constrained_by_outer_fragmentation_context_) { available_outer_space = std::max( minimum_column_block_size, - UnclampedFragmentainerSpaceLeft(ConstraintSpace()) - row_offset); + UnclampedFragmentainerSpaceLeft(GetConstraintSpace()) - row_offset); if (available_outer_space <= LayoutUnit()) { if (available_outer_space < LayoutUnit()) { @@ -614,9 +614,10 @@ // retry in the next outer fragmentainer. Otherwise, we need to continue // (once we have started laying out, we cannot skip any fragmentainers) // with no available size. - if (ConstraintSpace().IsInsideBalancedColumns() && - !container_builder_.IsInitialColumnBalancingPass()) + if (GetConstraintSpace().IsInsideBalancedColumns() && + !container_builder_.IsInitialColumnBalancingPass()) { container_builder_.PropagateSpaceShortage(-available_outer_space); + } available_outer_space = LayoutUnit(); } @@ -643,9 +644,10 @@ // performing its initial column balancing pass. Otherwise we might report a // taller block-size that we eventually end up with, resulting in the outer // columns to be overstretched. - bool balance_columns = Style().GetColumnFill() == EColumnFill::kBalance || - (ConstraintSpace().HasBlockFragmentation() && - !ConstraintSpace().HasKnownFragmentainerBlockSize()); + bool balance_columns = + Style().GetColumnFill() == EColumnFill::kBalance || + (GetConstraintSpace().HasBlockFragmentation() && + !GetConstraintSpace().HasKnownFragmentainerBlockSize()); // If columns are to be balanced, we need to examine the contents of the // multicol container to figure out a good initial (minimal) column @@ -697,10 +699,11 @@ // retry there. bool may_have_more_space_in_next_outer_fragmentainer = false; if (may_resume_in_next_outer_fragmentainer && !IsBreakInside(BreakToken())) { - if (intrinsic_block_size_) + if (intrinsic_block_size_) { may_have_more_space_in_next_outer_fragmentainer = true; - else if (!ConstraintSpace().IsAtFragmentainerStart()) + } else if (!GetConstraintSpace().IsAtFragmentainerStart()) { may_have_more_space_in_next_outer_fragmentainer = true; + } } const NGLayoutResult* result = nullptr; @@ -728,7 +731,7 @@ do { // Lay out one column. Each column will become a fragment. NGConstraintSpace child_space = CreateConstraintSpaceForFragmentainer( - ConstraintSpace(), kFragmentColumn, column_size, + GetConstraintSpace(), kFragmentColumn, column_size, ColumnPercentageResolutionSize(), balance_columns, min_break_appeal.value_or(kBreakAppealLastResort)); @@ -824,13 +827,15 @@ result->BreakAppeal()); LayoutUnit block_end_overflow = - LogicalBoxFragment(ConstraintSpace().GetWritingDirection(), column) + LogicalBoxFragment(GetConstraintSpace().GetWritingDirection(), + column) .BlockEndLayoutOverflow(); if (row_offset + block_end_overflow > - FragmentainerSpaceLeft(ConstraintSpace())) { - if (ConstraintSpace().IsInsideBalancedColumns() && - !container_builder_.IsInitialColumnBalancingPass()) + FragmentainerSpaceLeft(GetConstraintSpace())) { + if (GetConstraintSpace().IsInsideBalancedColumns() && + !container_builder_.IsInitialColumnBalancingPass()) { container_builder_.PropagateSpaceShortage(minimal_space_shortage); + } if (!minimum_column_block_size && block_end_overflow > column_size.block_size) { // We're inside nested block fragmentation, and the column was @@ -900,7 +905,7 @@ } DCHECK(column_balancing_info.HasOutOfFlowFragmentainerDescendants()); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_) + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_) .HandleFragmentation(&column_balancing_info); actual_column_count += column_balancing_info.num_new_columns; if (column_balancing_info.minimal_space_shortage > LayoutUnit()) { @@ -955,7 +960,7 @@ // a specified block-size preventing taller columns, for instance. DCHECK_GE(new_column_block_size, column_size.block_size); if (new_column_block_size <= column_size.block_size) { - if (ConstraintSpace().IsInsideBalancedColumns()) { + if (GetConstraintSpace().IsInsideBalancedColumns()) { // If we're doing nested column balancing, propagate any space shortage // to the outer multicol container, so that the outer multicol container // can attempt to stretch, so that this inner one may fit as well. @@ -970,14 +975,15 @@ column_size.block_size = new_column_block_size; } while (true); - if (ConstraintSpace().HasBlockFragmentation() && row_offset > LayoutUnit()) { + if (GetConstraintSpace().HasBlockFragmentation() && + row_offset > LayoutUnit()) { // If we have container separation, breaking before this row is fine. LayoutUnit fragmentainer_block_offset = - ConstraintSpace().FragmentainerOffset() + row_offset; + GetConstraintSpace().FragmentainerOffset() + row_offset; // TODO(layout-dev): Consider adjusting break appeal based on the preceding // column spanner (if any), e.g. if it has break-after:avoid, so that we can // support early-breaks. - if (!MovePastBreakpoint(ConstraintSpace(), *result, + if (!MovePastBreakpoint(GetConstraintSpace(), *result, fragmentainer_block_offset, kBreakAppealPerfect, &container_builder_)) { // This row didn't fit nicely in the outer fragmentation context. Breaking @@ -1042,14 +1048,14 @@ } NGBreakStatus ColumnLayoutAlgorithm::LayoutSpanner( - NGBlockNode spanner_node, + BlockNode spanner_node, const NGBlockBreakToken* break_token, MarginStrut* margin_strut) { spanner_path_ = nullptr; const ComputedStyle& spanner_style = spanner_node.Style(); BoxStrut margins = ComputeMarginsFor(spanner_style, ChildAvailableSize().inline_size, - ConstraintSpace().GetWritingDirection()); + GetConstraintSpace().GetWritingDirection()); AdjustMarginsForFragmentation(break_token, &margins); // Collapse the block-start margin of this spanner with the block-end margin @@ -1067,15 +1073,15 @@ auto* result = spanner_node.Layout(spanner_space, break_token, early_break_in_child); - if (ConstraintSpace().HasBlockFragmentation() && !early_break_) { + if (GetConstraintSpace().HasBlockFragmentation() && !early_break_) { // We're nested inside another fragmentation context. Examine this break // point, and determine whether we should break. LayoutUnit fragmentainer_block_offset = - ConstraintSpace().FragmentainerOffset() + block_offset; + GetConstraintSpace().FragmentainerOffset() + block_offset; NGBreakStatus break_status = BreakBeforeChildIfNeeded( - ConstraintSpace(), spanner_node, *result, fragmentainer_block_offset, + GetConstraintSpace(), spanner_node, *result, fragmentainer_block_offset, has_processed_first_child_, &container_builder_); if (break_status != NGBreakStatus::kContinue) { @@ -1086,7 +1092,7 @@ const auto& spanner_fragment = To<NGPhysicalBoxFragment>(result->PhysicalFragment()); - LogicalFragment logical_fragment(ConstraintSpace().GetWritingDirection(), + LogicalFragment logical_fragment(GetConstraintSpace().GetWritingDirection(), spanner_fragment); ResolveInlineAutoMargins(spanner_style, Style(), @@ -1124,18 +1130,18 @@ FontBaseline baseline_type = Style().GetFontBaseline(); auto baseline = marker.ContentAlignmentBaseline( - ConstraintSpace(), baseline_type, child_fragment); + GetConstraintSpace(), baseline_type, child_fragment); if (!baseline) return; const NGLayoutResult* layout_result = marker.Layout( - ConstraintSpace(), container_builder_.Style(), baseline_type); + GetConstraintSpace(), container_builder_.Style(), baseline_type); DCHECK(layout_result); // TODO(layout-dev): AddToBox() may increase the specified block-offset, which // is bad, since it means that we may need to refragment. For now we'll just // ignore the adjustment (which is also bad, of course). - marker.AddToBox(ConstraintSpace(), baseline_type, child_fragment, + marker.AddToBox(GetConstraintSpace(), baseline_type, child_fragment, BorderScrollbarPadding(), *layout_result, *baseline, &block_offset, &container_builder_); @@ -1152,10 +1158,10 @@ // Lay out the list marker. FontBaseline baseline_type = Style().GetFontBaseline(); const NGLayoutResult* layout_result = - marker.Layout(ConstraintSpace(), Style(), baseline_type); + marker.Layout(GetConstraintSpace(), Style(), baseline_type); DCHECK(layout_result); // Position the list marker without aligning with line boxes. - marker.AddToBoxWithoutLineBoxes(ConstraintSpace(), baseline_type, + marker.AddToBoxWithoutLineBoxes(GetConstraintSpace(), baseline_type, *layout_result, &container_builder_, &intrinsic_block_size_); container_builder_.ClearUnpositionedListMarker(); @@ -1164,7 +1170,8 @@ void ColumnLayoutAlgorithm::PropagateBaselineFromChild( const NGPhysicalBoxFragment& child, LayoutUnit block_offset) { - LogicalBoxFragment fragment(ConstraintSpace().GetWritingDirection(), child); + LogicalBoxFragment fragment(GetConstraintSpace().GetWritingDirection(), + child); // The first-baseline is the highest first-baseline of all fragments. if (auto first_baseline = fragment.FirstBaseline()) { @@ -1310,7 +1317,7 @@ // many forced breaks). if (forced_break_count < used_column_count_) { LayoutUnit column_block_size = BlockSizeForFragmentation( - *result, ConstraintSpace().GetWritingDirection()); + *result, GetConstraintSpace().GetWritingDirection()); // Encompass the block-size of the (single-strip column) fragment, to // account for any trailing margins. We let them affect the column @@ -1327,8 +1334,8 @@ // getting truncated. After all, they don't really require any space, so // what we're doing currently might be seen as unnecessary (and slightly // unpredictable) column over-stretching. - LogicalFragment logical_fragment(ConstraintSpace().GetWritingDirection(), - fragment); + LogicalFragment logical_fragment( + GetConstraintSpace().GetWritingDirection(), fragment); column_block_size = std::max(column_block_size, logical_fragment.BlockSize()); content_runs.AddRun(column_block_size); @@ -1359,7 +1366,7 @@ break_token = fragment.BreakToken(); } while (break_token); - if (ConstraintSpace().IsInitialColumnBalancingPass()) { + if (GetConstraintSpace().IsInitialColumnBalancingPass()) { // Nested column balancing. Our outer fragmentation context is in its // initial balancing pass, so it also wants to know the largest unbreakable // block-size. @@ -1409,8 +1416,9 @@ // in the table layout algorithm. A constraint space with fixed block-size // will be passed from the table layout algorithm if necessary. Leave it // alone. - if (ConstraintSpace().IsTableCell()) + if (GetConstraintSpace().IsTableCell()) { return size; + } // The {,min-,max-}block-size properties are specified on the multicol // container, but here we're calculating the column block sizes inside the @@ -1428,11 +1436,12 @@ const ComputedStyle& style = Style(); LayoutUnit max = ResolveMaxBlockLength( - ConstraintSpace(), style, BorderPadding(), style.LogicalMaxHeight()); + GetConstraintSpace(), style, BorderPadding(), style.LogicalMaxHeight()); LayoutUnit extent = kIndefiniteSize; if (!style.LogicalHeight().IsAuto()) { - extent = ResolveMainBlockLength(ConstraintSpace(), style, BorderPadding(), - style.LogicalHeight(), kIndefiniteSize); + extent = + ResolveMainBlockLength(GetConstraintSpace(), style, BorderPadding(), + style.LogicalHeight(), kIndefiniteSize); // A specified block-size will just constrain the maximum length. if (extent != kIndefiniteSize) max = std::min(max, extent); @@ -1440,7 +1449,7 @@ // A specified min-block-size may increase the maximum length. LayoutUnit min = ResolveMinBlockLength( - ConstraintSpace(), style, BorderPadding(), style.LogicalMinHeight()); + GetConstraintSpace(), style, BorderPadding(), style.LogicalMinHeight()); max = std::max(max, min); if (max != LayoutUnit::Max()) { @@ -1461,8 +1470,9 @@ NGConstraintSpace ColumnLayoutAlgorithm::CreateConstraintSpaceForBalancing( const LogicalSize& column_size) const { - NGConstraintSpaceBuilder space_builder( - ConstraintSpace(), Style().GetWritingDirection(), /* is_new_fc */ true); + NGConstraintSpaceBuilder space_builder(GetConstraintSpace(), + Style().GetWritingDirection(), + /* is_new_fc */ true); space_builder.SetFragmentationType(kFragmentColumn); space_builder.SetShouldPropagateChildBreakValues(); space_builder.SetAvailableSize({column_size.inline_size, kIndefiniteSize}); @@ -1476,25 +1486,26 @@ } NGConstraintSpace ColumnLayoutAlgorithm::CreateConstraintSpaceForSpanner( - const NGBlockNode& spanner, + const BlockNode& spanner, LayoutUnit block_offset) const { auto child_writing_direction = spanner.Style().GetWritingDirection(); NGConstraintSpaceBuilder space_builder( - ConstraintSpace(), child_writing_direction, /* is_new_fc */ true); - if (!IsParallelWritingMode(ConstraintSpace().GetWritingMode(), - child_writing_direction.GetWritingMode())) + GetConstraintSpace(), child_writing_direction, /* is_new_fc */ true); + if (!IsParallelWritingMode(GetConstraintSpace().GetWritingMode(), + child_writing_direction.GetWritingMode())) { SetOrthogonalFallbackInlineSizeIfNeeded(Style(), spanner, &space_builder); - else if (ShouldBlockContainerChildStretchAutoInlineSize(spanner)) + } else if (ShouldBlockContainerChildStretchAutoInlineSize(spanner)) { space_builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit); + } space_builder.SetAvailableSize(ChildAvailableSize()); space_builder.SetPercentageResolutionSize(ChildAvailableSize()); space_builder.SetBaselineAlgorithmType( - ConstraintSpace().BaselineAlgorithmType()); + GetConstraintSpace().BaselineAlgorithmType()); - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { SetupSpaceBuilderForFragmentation( - ConstraintSpace(), spanner, block_offset, &space_builder, + GetConstraintSpace(), spanner, block_offset, &space_builder, /* is_new_fc */ true, container_builder_.RequiresContentBeforeBreaking()); } @@ -1504,8 +1515,9 @@ NGConstraintSpace ColumnLayoutAlgorithm::CreateConstraintSpaceForMinMax() const { - NGConstraintSpaceBuilder space_builder( - ConstraintSpace(), Style().GetWritingDirection(), /* is_new_fc */ true); + NGConstraintSpaceBuilder space_builder(GetConstraintSpace(), + Style().GetWritingDirection(), + /* is_new_fc */ true); space_builder.SetIsAnonymous(true); space_builder.SetIsInColumnBfc();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h index 1000beb..3662de5 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm.h
@@ -11,16 +11,16 @@ namespace blink { -enum class NGBreakStatus; -class NGBlockNode; +class BlockNode; class NGBlockBreakToken; class NGColumnSpannerPath; class NGConstraintSpace; +enum class NGBreakStatus; struct LogicalSize; struct MarginStrut; class CORE_EXPORT ColumnLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -32,7 +32,7 @@ private: MinMaxSizesResult ComputeSpannersMinMaxSizes( - const NGBlockNode& search_parent) const; + const BlockNode& search_parent) const; // Lay out as many children as we can. If |kNeedsEarlierBreak| is returned, it // means that we ran out of space at an unappealing location, and need to @@ -53,7 +53,7 @@ // before the spanner or not. If |NGBreakStatus::kContinue| is returned, and // no break token was set, it means that we can proceed to the next row of // columns. - NGBreakStatus LayoutSpanner(NGBlockNode spanner_node, + NGBreakStatus LayoutSpanner(BlockNode spanner_node, const NGBlockBreakToken* break_token, MarginStrut*); @@ -115,7 +115,7 @@ NGConstraintSpace CreateConstraintSpaceForBalancing( const LogicalSize& column_size) const; NGConstraintSpace CreateConstraintSpaceForSpanner( - const NGBlockNode& spanner, + const BlockNode& spanner, LayoutUnit block_offset) const; NGConstraintSpace CreateConstraintSpaceForMinMax() const;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc index 3eb4382..d6216703 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_column_layout_algorithm_test.cc
@@ -17,7 +17,7 @@ class ColumnLayoutAlgorithmTest : public BaseLayoutAlgorithmTest { protected: const NGPhysicalBoxFragment* RunBlockLayoutAlgorithm(Element* element) { - NGBlockNode container(element->GetLayoutBox()); + BlockNode container(element->GetLayoutBox()); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); @@ -87,7 +87,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); @@ -127,7 +127,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); @@ -176,7 +176,7 @@ </div> )HTML"); - NGBlockNode container(GetLayoutBoxByElementId("container")); + BlockNode container(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); @@ -2748,7 +2748,7 @@ LayoutObject* layout_object = GetLayoutObjectByElementId("multicol"); ASSERT_TRUE(layout_object); - NGBlockNode node = NGBlockNode(To<LayoutBox>(layout_object)); + BlockNode node = BlockNode(To<LayoutBox>(layout_object)); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_column_spanner_path.h b/third_party/blink/renderer/core/layout/ng/ng_column_spanner_path.h index 5d7128fa..60e90ac 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_column_spanner_path.h +++ b/third_party/blink/renderer/core/layout/ng/ng_column_spanner_path.h
@@ -17,11 +17,11 @@ // a node is on the path between the multicol container and the spanner. class NGColumnSpannerPath : public GarbageCollected<NGColumnSpannerPath> { public: - explicit NGColumnSpannerPath(NGBlockNode block, + explicit NGColumnSpannerPath(BlockNode block, const NGColumnSpannerPath* child = nullptr) : box_(block.GetLayoutBox()), child_(child) {} - NGBlockNode BlockNode() const { return NGBlockNode(box_); } + BlockNode GetBlockNode() const { return BlockNode(box_); } const NGColumnSpannerPath* Child() const { return child_.Get(); } void Trace(Visitor* visitor) const {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h b/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h index 90bbf1a..73772a5 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h +++ b/third_party/blink/renderer/core/layout/ng/ng_constraint_space_builder.h
@@ -592,7 +592,7 @@ public: NGMinMaxConstraintSpaceBuilder(const NGConstraintSpace& parent_space, const ComputedStyle& parent_style, - const NGLayoutInputNode& child, + const LayoutInputNode& child, bool is_new_fc) : delegate_(parent_space, child.Style().GetWritingDirection(),
diff --git a/third_party/blink/renderer/core/layout/ng/ng_early_break.h b/third_party/blink/renderer/core/layout/ng/ng_early_break.h index 5d80879..6bf1b3d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_early_break.h +++ b/third_party/blink/renderer/core/layout/ng/ng_early_break.h
@@ -23,7 +23,7 @@ kBlock // Break before or inside a specified child block. }; - explicit NGEarlyBreak(NGBlockNode block, + explicit NGEarlyBreak(BlockNode block, NGBreakAppeal break_appeal, const NGEarlyBreak* break_inside_child = nullptr) : box_(block.GetLayoutBox()), @@ -37,9 +37,9 @@ BreakType Type() const { return static_cast<BreakType>(const_type_); } bool IsBreakBefore() const { return !break_inside_child_; } - NGBlockNode BlockNode() const { + BlockNode GetBlockNode() const { CHECK_EQ(const_type_, kBlock); - return NGBlockNode(box_); + return BlockNode(box_); } int LineNumber() const { DCHECK_EQ(const_type_, kLine);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc index 2a957d0..c3ac055 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.cc
@@ -60,7 +60,7 @@ FieldsetLayoutAlgorithm::FieldsetLayoutAlgorithm( const LayoutAlgorithmParams& params) : LayoutAlgorithm(params), - writing_direction_(ConstraintSpace().GetWritingDirection()), + writing_direction_(GetConstraintSpace().GetWritingDirection()), consumed_block_size_(BreakToken() ? BreakToken()->ConsumedBlockSize() : LayoutUnit()) { DCHECK(params.fragment_geometry.scrollbar.IsEmpty()); @@ -95,14 +95,14 @@ } intrinsic_block_size_ = ClampIntrinsicBlockSize( - ConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), + GetConstraintSpace(), Node(), BreakToken(), BorderScrollbarPadding(), intrinsic_block_size_ + Borders().block_end); // Recompute the block-axis size now that we know our content size. - border_box_size_.block_size = - ComputeBlockSizeForFragment(ConstraintSpace(), Style(), BorderPadding(), - intrinsic_block_size_ + consumed_block_size_, - border_box_size_.inline_size); + border_box_size_.block_size = ComputeBlockSizeForFragment( + GetConstraintSpace(), Style(), BorderPadding(), + intrinsic_block_size_ + consumed_block_size_, + border_box_size_.inline_size); // The above computation utility knows nothing about fieldset weirdness. The // legend may eat from the available content box block size. Make room for @@ -125,8 +125,8 @@ if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) { NGBreakStatus status = FinishFragmentation( - Node(), ConstraintSpace(), Borders().block_end, - FragmentainerSpaceLeft(ConstraintSpace()), &container_builder_); + Node(), GetConstraintSpace(), Borders().block_end, + FragmentainerSpaceLeft(GetConstraintSpace()), &container_builder_); if (status == NGBreakStatus::kNeedsEarlierBreak) { // If we found a good break somewhere inside this block, re-layout and // break at that location. @@ -144,7 +144,7 @@ #endif } - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); const auto& style = Style(); if (style.LogicalHeight().IsPercentOrCalc() || @@ -183,7 +183,7 @@ LogicalSize adjusted_padding_box_size = ShrinkLogicalSize(border_box_size_, Borders()); - NGBlockNode legend = Node().GetRenderedLegend(); + BlockNode legend = Node().GetRenderedLegend(); if (legend) { if (!IsBreakInside(BreakToken())) LayoutLegend(legend); @@ -223,7 +223,7 @@ // Proceed with normal fieldset children (excluding the rendered legend). They // all live inside an anonymous child box of the fieldset container. if (content_break_token || !has_seen_all_children) { - NGBlockNode fieldset_content = Node().GetFieldsetContent(); + BlockNode fieldset_content = Node().GetFieldsetContent(); DCHECK(fieldset_content); NGBreakStatus break_status = LayoutFieldsetContent(fieldset_content, content_break_token, @@ -235,15 +235,15 @@ return NGBreakStatus::kContinue; } -void FieldsetLayoutAlgorithm::LayoutLegend(NGBlockNode& legend) { +void FieldsetLayoutAlgorithm::LayoutLegend(BlockNode& legend) { // Lay out the legend. While the fieldset container normally ignores its // padding, the legend is laid out within what would have been the content // box had the fieldset been a regular block with no weirdness. LogicalSize percentage_size = CalculateChildPercentageSize( - ConstraintSpace(), Node(), ChildAvailableSize()); + GetConstraintSpace(), Node(), ChildAvailableSize()); BoxStrut legend_margins = ComputeMarginsFor(legend.Style(), percentage_size.inline_size, - ConstraintSpace().GetWritingDirection()); + GetConstraintSpace().GetWritingDirection()); auto legend_space = CreateConstraintSpaceForLegend( legend, ChildAvailableSize(), percentage_size); @@ -318,7 +318,7 @@ } NGBreakStatus FieldsetLayoutAlgorithm::LayoutFieldsetContent( - NGBlockNode& fieldset_content, + BlockNode& fieldset_content, const NGBlockBreakToken* content_break_token, LogicalSize adjusted_padding_box_size, bool has_legend) { @@ -343,7 +343,7 @@ LayoutUnit max_content_block_size = LayoutUnit::Max(); if (adjusted_padding_box_size.block_size == kIndefiniteSize) { max_content_block_size = - ResolveMaxBlockLength(ConstraintSpace(), Style(), BorderPadding(), + ResolveMaxBlockLength(GetConstraintSpace(), Style(), BorderPadding(), Style().LogicalMaxHeight()); } @@ -398,10 +398,10 @@ DCHECK(result); NGBreakStatus break_status = NGBreakStatus::kContinue; - if (ConstraintSpace().HasBlockFragmentation() && !early_break_) { + if (GetConstraintSpace().HasBlockFragmentation() && !early_break_) { break_status = BreakBeforeChildIfNeeded( - ConstraintSpace(), fieldset_content, *result, - ConstraintSpace().FragmentainerOffset() + intrinsic_block_size_, + GetConstraintSpace(), fieldset_content, *result, + GetConstraintSpace().FragmentainerOffset() + intrinsic_block_size_, /* has_container_separation */ false, &container_builder_); } @@ -434,12 +434,12 @@ LayoutUnit FieldsetLayoutAlgorithm::FragmentainerSpaceAvailable() const { // The legend may have extended past the end of the fragmentainer. Clamp to // zero if this is the case. - return std::max(LayoutUnit(), FragmentainerSpaceLeft(ConstraintSpace()) - + return std::max(LayoutUnit(), FragmentainerSpaceLeft(GetConstraintSpace()) - intrinsic_block_size_); } void FieldsetLayoutAlgorithm::ConsumeRemainingFragmentainerSpace() { - if (ConstraintSpace().HasKnownFragmentainerBlockSize()) { + if (GetConstraintSpace().HasKnownFragmentainerBlockSize()) { // The remaining part of the fragmentainer (the unusable space for child // content, due to the break) should still be occupied by this container. intrinsic_block_size_ += FragmentainerSpaceAvailable(); @@ -458,15 +458,16 @@ if (result_without_children) return *result_without_children; } else { - if (NGBlockNode legend = Node().GetRenderedLegend()) { - NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), legend, + if (BlockNode legend = Node().GetRenderedLegend()) { + NGMinMaxConstraintSpaceBuilder builder(GetConstraintSpace(), Style(), + legend, /* is_new_fc */ true); builder.SetAvailableBlockSize(kIndefiniteSize); const auto space = builder.ToConstraintSpace(); result = ComputeMinAndMaxContentContribution(Style(), legend, space); result.sizes += - ComputeMarginsFor(space, legend.Style(), ConstraintSpace()) + ComputeMarginsFor(space, legend.Style(), GetConstraintSpace()) .InlineSum(); } } @@ -474,13 +475,14 @@ // The fieldset content includes the fieldset padding (and any scrollbars), // while the legend is a regular child and doesn't. We may have a fieldset // without any content or legend, so add the padding here, on the outside. - result.sizes += ComputePadding(ConstraintSpace(), Style()).InlineSum(); + result.sizes += ComputePadding(GetConstraintSpace(), Style()).InlineSum(); // Size containment does not consider the content for sizing. if (!has_inline_size_containment) { - NGBlockNode content = Node().GetFieldsetContent(); + BlockNode content = Node().GetFieldsetContent(); DCHECK(content); - NGMinMaxConstraintSpaceBuilder builder(ConstraintSpace(), Style(), content, + NGMinMaxConstraintSpaceBuilder builder(GetConstraintSpace(), Style(), + content, /* is_new_fc */ true); builder.SetAvailableBlockSize(kIndefiniteSize); const auto space = builder.ToConstraintSpace(); @@ -488,22 +490,22 @@ MinMaxSizesResult content_result = ComputeMinAndMaxContentContribution(Style(), content, space); content_result.sizes += - ComputeMarginsFor(space, content.Style(), ConstraintSpace()) + ComputeMarginsFor(space, content.Style(), GetConstraintSpace()) .InlineSum(); result.sizes.Encompass(content_result.sizes); result.depends_on_block_constraints |= content_result.depends_on_block_constraints; } - result.sizes += ComputeBorders(ConstraintSpace(), Node()).InlineSum(); + result.sizes += ComputeBorders(GetConstraintSpace(), Node()).InlineSum(); return result; } const NGConstraintSpace FieldsetLayoutAlgorithm::CreateConstraintSpaceForLegend( - NGBlockNode legend, + BlockNode legend, LogicalSize available_size, LogicalSize percentage_size) { - NGConstraintSpaceBuilder builder(ConstraintSpace(), + NGConstraintSpaceBuilder builder(GetConstraintSpace(), legend.Style().GetWritingDirection(), /* is_new_fc */ true); SetOrthogonalFallbackInlineSizeIfNeeded(Style(), legend, &builder); @@ -515,12 +517,12 @@ const NGConstraintSpace FieldsetLayoutAlgorithm::CreateConstraintSpaceForFieldsetContent( - NGBlockNode fieldset_content, + BlockNode fieldset_content, LogicalSize padding_box_size, LayoutUnit block_offset) { DCHECK(fieldset_content.CreatesNewFormattingContext()); NGConstraintSpaceBuilder builder( - ConstraintSpace(), fieldset_content.Style().GetWritingDirection(), + GetConstraintSpace(), fieldset_content.Style().GetWritingDirection(), /* is_new_fc */ true); builder.SetAvailableSize(padding_box_size); builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit); @@ -532,13 +534,14 @@ // > * For the purpose of calculating percentage padding, act as if the // > padding was calculated for the fieldset element. builder.SetPercentageResolutionSize( - ConstraintSpace().PercentageResolutionSize()); + GetConstraintSpace().PercentageResolutionSize()); builder.SetIsFixedBlockSize(padding_box_size.block_size != kIndefiniteSize); - builder.SetBaselineAlgorithmType(ConstraintSpace().BaselineAlgorithmType()); + builder.SetBaselineAlgorithmType( + GetConstraintSpace().BaselineAlgorithmType()); - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { SetupSpaceBuilderForFragmentation( - ConstraintSpace(), fieldset_content, block_offset, &builder, + GetConstraintSpace(), fieldset_content, block_offset, &builder, /* is_new_fc */ true, container_builder_.RequiresContentBeforeBreaking()); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h index 4efbb76..1dc4343 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm.h
@@ -17,7 +17,7 @@ class NGConstraintSpace; class CORE_EXPORT FieldsetLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -37,19 +37,19 @@ private: NGBreakStatus LayoutChildren(); - void LayoutLegend(NGBlockNode& legend); + void LayoutLegend(BlockNode& legend); NGBreakStatus LayoutFieldsetContent( - NGBlockNode& fieldset_content, + BlockNode& fieldset_content, const NGBlockBreakToken* content_break_token, LogicalSize adjusted_padding_box_size, bool has_legend); const NGConstraintSpace CreateConstraintSpaceForLegend( - NGBlockNode legend, + BlockNode legend, LogicalSize available_size, LogicalSize percentage_size); const NGConstraintSpace CreateConstraintSpaceForFieldsetContent( - NGBlockNode fieldset_content, + BlockNode fieldset_content, LogicalSize padding_box_size, LayoutUnit block_offset);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc index 8303aef..92a97ae4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fieldset_layout_algorithm_test.cc
@@ -16,14 +16,14 @@ class NGFieldsetLayoutAlgorithmTest : public BaseLayoutAlgorithmTest { protected: const NGPhysicalBoxFragment* RunBlockLayoutAlgorithm(Element* element) { - NGBlockNode container(element->GetLayoutBox()); + BlockNode container(element->GetLayoutBox()); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize)); return BaseLayoutAlgorithmTest::RunBlockLayoutAlgorithm(container, space); } - MinMaxSizes RunComputeMinMaxSizes(NGBlockNode node) { + MinMaxSizes RunComputeMinMaxSizes(BlockNode node) { NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(), LayoutUnit()), @@ -37,7 +37,7 @@ } MinMaxSizes RunComputeMinMaxSizes(const char* element_id) { - NGBlockNode node(GetLayoutBoxByElementId(element_id)); + BlockNode node(GetLayoutBoxByElementId(element_id)); return RunComputeMinMaxSizes(node); } @@ -449,7 +449,7 @@ </fieldset> )HTML"); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -549,7 +549,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -576,7 +576,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -611,7 +611,7 @@ LayoutUnit kFragmentainerSpaceAvailable(10); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -659,7 +659,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -722,7 +722,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -785,7 +785,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -835,7 +835,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -889,7 +889,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -955,7 +955,7 @@ LayoutUnit kFragmentainerSpaceAvailable(200); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1013,7 +1013,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1071,7 +1071,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1125,7 +1125,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1171,7 +1171,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1236,7 +1236,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1287,7 +1287,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1352,7 +1352,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1403,7 +1403,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1459,7 +1459,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1558,7 +1558,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1613,7 +1613,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1661,7 +1661,7 @@ LayoutUnit kFragmentainerSpaceAvailable(40); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1718,7 +1718,7 @@ LayoutUnit kFragmentainerSpaceAvailable(40); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1780,7 +1780,7 @@ LayoutUnit kFragmentainerSpaceAvailable(100); - NGBlockNode node(GetLayoutBoxByElementId("container")); + BlockNode node(GetLayoutBoxByElementId("container")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize), @@ -1829,7 +1829,7 @@ LayoutUnit kFragmentainerSpaceAvailable(40); - NGBlockNode node(GetLayoutBoxByElementId("fieldset")); + BlockNode node(GetLayoutBoxByElementId("fieldset")); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize),
diff --git a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc index 8cc0816e6..46452b7 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_floats_utils.cc
@@ -209,7 +209,7 @@ ExclusionSpace* exclusion_space) { DCHECK(unpositioned_float); const NGConstraintSpace& parent_space = unpositioned_float->parent_space; - NGBlockNode node = unpositioned_float->node; + BlockNode node = unpositioned_float->node; bool is_same_writing_mode = node.Style().GetWritingMode() == parent_space.GetWritingMode();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc b/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc index 9408456..bd05ae9 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.cc
@@ -15,7 +15,7 @@ namespace { -bool IsInlineContainerForNode(const NGBlockNode& node, +bool IsInlineContainerForNode(const BlockNode& node, const LayoutObject* inline_container) { return inline_container && inline_container->IsLayoutInline() && inline_container->CanContainOutOfFlowPositionedElement( @@ -24,7 +24,7 @@ NGLogicalAnchorQuery::SetOptions AnchorQuerySetOptions( const NGPhysicalFragment& fragment, - const NGLayoutInputNode& container, + const LayoutInputNode& container, bool maybe_out_of_order_if_oof) { // If the |fragment| is not absolutely positioned, it's an in-flow anchor. // https://drafts.csswg.org/css-anchor-1/#determining @@ -370,7 +370,7 @@ } void NGFragmentBuilder::AddOutOfFlowChildCandidate( - NGBlockNode child, + BlockNode child, const LogicalOffset& child_offset, LogicalStaticPosition::InlineEdge inline_edge, LogicalStaticPosition::BlockEdge block_edge) { @@ -386,7 +386,7 @@ } void NGFragmentBuilder::AddOutOfFlowInlineChildCandidate( - NGBlockNode child, + BlockNode child, const LogicalOffset& child_offset, TextDirection inline_container_direction) { DCHECK(node_.IsInline() || layout_object_->IsLayoutInline()); @@ -425,7 +425,7 @@ } void NGFragmentBuilder::AddMulticolWithPendingOOFs( - const NGBlockNode& multicol, + const BlockNode& multicol, MulticolWithPendingOofs<LogicalOffset>* multicol_info) { DCHECK(To<LayoutBlockFlow>(multicol.GetLayoutBox())->MultiColumnFlowThread()); auto it = multicols_with_pending_oofs_.find(multicol.GetLayoutBox()); @@ -451,7 +451,7 @@ LogicalOffset additional_offset, const MulticolWithPendingOofs<LogicalOffset>* multicol) { for (auto& candidate : oof_positioned_candidates_) { - NGBlockNode node = candidate.Node(); + BlockNode node = candidate.Node(); candidate.static_position.offset += additional_offset; if (multicol && multicol->fixedpos_containing_block.Fragment() && node.Style().GetPosition() == EPosition::kFixed) { @@ -524,7 +524,7 @@ // Collect the child's out of flow descendants. const WritingModeConverter converter(GetWritingDirection(), fragment.Size()); for (const auto& descendant : fragment.OutOfFlowPositionedDescendants()) { - NGBlockNode node = descendant.Node(); + BlockNode node = descendant.Node(); LogicalStaticPosition static_position = descendant.StaticPosition().ConvertToLogical(converter); @@ -663,7 +663,7 @@ absl::optional<LayoutUnit> fixedpos_clipped_container_block_offset; AddMulticolWithPendingOOFs( - NGBlockNode(multicol.key), + BlockNode(multicol.key), MakeGarbageCollected<MulticolWithPendingOofs<LogicalOffset>>( multicol_offset, OofContainingBlock<LogicalOffset>(
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h b/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h index a778b27..62ef5a92 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h +++ b/third_party/blink/renderer/core/layout/ng/ng_fragment_builder.h
@@ -57,7 +57,7 @@ style_variant_ = style_variant; } - const NGConstraintSpace& ConstraintSpace() const { return space_; } + const NGConstraintSpace& GetConstraintSpace() const { return space_; } WritingDirectionMode GetWritingDirection() const { return writing_direction_; @@ -203,7 +203,7 @@ // // See layout part for builder interaction. void AddOutOfFlowChildCandidate( - NGBlockNode, + BlockNode, const LogicalOffset& child_offset, LogicalStaticPosition::InlineEdge = LogicalStaticPosition::kInlineStart, LogicalStaticPosition::BlockEdge = LogicalStaticPosition::kBlockStart); @@ -214,7 +214,7 @@ // |inline_container_direction| is the current text direction for determining // the correct static-position. void AddOutOfFlowInlineChildCandidate( - NGBlockNode, + BlockNode, const LogicalOffset& child_offset, TextDirection inline_container_direction); @@ -234,7 +234,7 @@ // inner multicol in which their containing block resides. Thus, we need to // store such inner multicols for later use. void AddMulticolWithPendingOOFs( - const NGBlockNode& multicol, + const BlockNode& multicol, MulticolWithPendingOofs<LogicalOffset>* multicol_info = MakeGarbageCollected<MulticolWithPendingOofs<LogicalOffset>>()); @@ -505,7 +505,7 @@ #endif protected: - NGFragmentBuilder(const NGLayoutInputNode& node, + NGFragmentBuilder(const LayoutInputNode& node, const ComputedStyle* style, const NGConstraintSpace& space, WritingDirectionMode writing_direction) @@ -550,7 +550,7 @@ const OofInlineContainer<LogicalOffset>* current_inline_container = nullptr) const; - NGLayoutInputNode node_; + LayoutInputNode node_; const NGConstraintSpace& space_; const ComputedStyle* style_; WritingDirectionMode writing_direction_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragment_repeater.cc b/third_party/blink/renderer/core/layout/ng/ng_fragment_repeater.cc index e2046bf..5784a8eb 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragment_repeater.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fragment_repeater.cc
@@ -30,7 +30,7 @@ } void UpdateBreakTokens(LayoutBox& layout_box) { - NGBlockNode node(&layout_box); + BlockNode node(&layout_box); wtf_size_t sequence_number = 0; wtf_size_t fragment_count = layout_box.PhysicalFragmentCount();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_test.cc b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_test.cc index eea2ead4..f9412a49 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_test.cc
@@ -14,7 +14,7 @@ class FragmentationTest : public BaseLayoutAlgorithmTest { protected: const NGPhysicalBoxFragment* RunBlockLayoutAlgorithm(Element* element) { - NGBlockNode container(element->GetLayoutBox()); + BlockNode container(element->GetLayoutBox()); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc index 31fb62ef..8eb8541 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.cc
@@ -108,7 +108,7 @@ template bool CORE_TEMPLATE_EXPORT IsAvoidBreakValue(const NGConstraintSpace&, EBreakInside); -EBreakBetween CalculateBreakBetweenValue(NGLayoutInputNode child, +EBreakBetween CalculateBreakBetweenValue(LayoutInputNode child, const NGLayoutResult& layout_result, const NGBoxFragmentBuilder& builder) { if (child.IsInline()) @@ -134,9 +134,9 @@ EBreakBetween break_before = JoinFragmentainerBreakValues( child.Style().BreakBefore(), layout_result.InitialBreakBefore()); break_before = builder.JoinedBreakBetweenValue(break_before); - const NGConstraintSpace& space = builder.ConstraintSpace(); + const auto& space = builder.GetConstraintSpace(); if (space.IsPaginated() && box_fragment && - !IsForcedBreakValue(builder.ConstraintSpace(), break_before)) { + !IsForcedBreakValue(builder.GetConstraintSpace(), break_before)) { AtomicString current_name = builder.PageName(); if (current_name == g_null_atom) { current_name = space.PageName(); @@ -172,7 +172,7 @@ } NGBreakAppeal CalculateBreakAppealBefore(const NGConstraintSpace& space, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult& layout_result, const NGBoxFragmentBuilder& builder, bool has_container_separation) { @@ -292,7 +292,7 @@ } void SetupSpaceBuilderForFragmentation(const NGConstraintSpace& parent_space, - const NGLayoutInputNode& child, + const LayoutInputNode& child, LayoutUnit fragmentainer_offset_delta, NGConstraintSpaceBuilder* builder, bool is_new_fc, @@ -354,7 +354,7 @@ void SetupFragmentBuilderForFragmentation( const NGConstraintSpace& space, - const NGLayoutInputNode& node, + const LayoutInputNode& node, const NGBlockBreakToken* previous_break_token, NGBoxFragmentBuilder* builder) { // When resuming layout after a break, we may not be allowed to break again @@ -457,7 +457,7 @@ } // We're going to break inside. - if (builder.ConstraintSpace().IsNewFormattingContext()) { + if (builder.GetConstraintSpace().IsNewFormattingContext()) { return false; } // Not being a formatting context root, only in-flow child breaks will have an @@ -465,7 +465,7 @@ return !builder.HasInflowChildBreakInside(); } -NGBreakStatus FinishFragmentation(NGBlockNode node, +NGBreakStatus FinishFragmentation(BlockNode node, const NGConstraintSpace& space, LayoutUnit trailing_border_padding, LayoutUnit space_left, @@ -815,7 +815,7 @@ NGBreakStatus BreakBeforeChildIfNeeded( const NGConstraintSpace& space, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult& layout_result, LayoutUnit fragmentainer_block_offset, bool has_container_separation, @@ -859,7 +859,7 @@ } void BreakBeforeChild(const NGConstraintSpace& space, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult* layout_result, LayoutUnit fragmentainer_block_offset, absl::optional<NGBreakAppeal> appeal, @@ -960,7 +960,7 @@ } bool MovePastBreakpoint(const NGConstraintSpace& space, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult& layout_result, LayoutUnit fragmentainer_block_offset, NGBreakAppeal appeal_before, @@ -1027,7 +1027,7 @@ // that we know what do to in order to honor orphans and widows, if at all // possible. We also only do this for non-row items since items in a row // will be parallel to one another.) - UpdateEarlyBreakAtBlockChild(space, To<NGBlockNode>(child), layout_result, + UpdateEarlyBreakAtBlockChild(space, To<BlockNode>(child), layout_result, appeal_before, builder, flex_column_break_info); } @@ -1142,7 +1142,7 @@ void UpdateEarlyBreakAtBlockChild( const NGConstraintSpace& space, - NGBlockNode child, + BlockNode child, const NGLayoutResult& layout_result, NGBreakAppeal appeal_before, NGBoxFragmentBuilder* builder, @@ -1207,7 +1207,7 @@ } bool AttemptSoftBreak(const NGConstraintSpace& space, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult* layout_result, LayoutUnit fragmentainer_block_offset, NGBreakAppeal appeal_before, @@ -1243,11 +1243,12 @@ return true; } -const NGEarlyBreak* EnterEarlyBreakInChild(const NGBlockNode& child, +const NGEarlyBreak* EnterEarlyBreakInChild(const BlockNode& child, const NGEarlyBreak& early_break) { if (early_break.Type() != NGEarlyBreak::kBlock || - early_break.BlockNode() != child) + early_break.GetBlockNode() != child) { return nullptr; + } // If there's no break inside, we should already have broken before the child. DCHECK(early_break.BreakInside()); @@ -1256,12 +1257,12 @@ bool IsEarlyBreakTarget(const NGEarlyBreak& early_break, const NGBoxFragmentBuilder& builder, - const NGLayoutInputNode& child) { + const LayoutInputNode& child) { if (early_break.Type() == NGEarlyBreak::kLine) { DCHECK(child.IsInline() || child.IsFlexItem()); return early_break.LineNumber() == builder.LineCount(); } - return early_break.IsBreakBefore() && early_break.BlockNode() == child; + return early_break.IsBreakBefore() && early_break.GetBlockNode() == child; } NGConstraintSpace CreateConstraintSpaceForFragmentainer( @@ -1294,7 +1295,7 @@ } NGBoxFragmentBuilder CreateContainerBuilderForMulticol( - const NGBlockNode& multicol, + const BlockNode& multicol, const NGConstraintSpace& space, const FragmentGeometry& fragment_geometry) { const ComputedStyle* style = &multicol.Style(); @@ -1307,8 +1308,7 @@ return multicol_container_builder; } -NGConstraintSpace CreateConstraintSpaceForMulticol( - const NGBlockNode& multicol) { +NGConstraintSpace CreateConstraintSpaceForMulticol(const BlockNode& multicol) { WritingDirectionMode writing_direction_mode = multicol.Style().GetWritingDirection(); NGConstraintSpaceBuilder space_builder(
diff --git a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h index bf6bcc6..1761a93 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_fragmentation_utils.h
@@ -72,7 +72,7 @@ // currently performing block fragmentation; we also need to know if it has // already been fragmented (to resume layout correctly, but not break again). inline bool InvolvedInBlockFragmentation(const NGBoxFragmentBuilder& builder) { - return builder.ConstraintSpace().HasBlockFragmentation() || + return builder.GetConstraintSpace().HasBlockFragmentation() || IsBreakInside(builder.PreviousBreakToken()); } @@ -87,7 +87,7 @@ // Calculate the final "break-between" value at a class A or C breakpoint. This // is the combination of all break-before and break-after values that met at the // breakpoint. -EBreakBetween CalculateBreakBetweenValue(NGLayoutInputNode child, +EBreakBetween CalculateBreakBetweenValue(LayoutInputNode child, const NGLayoutResult&, const NGBoxFragmentBuilder&); @@ -112,7 +112,7 @@ // Calculate the appeal of breaking before this child. NGBreakAppeal CalculateBreakAppealBefore(const NGConstraintSpace&, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult&, const NGBoxFragmentBuilder&, bool has_container_separation); @@ -227,7 +227,7 @@ // when inside node that we know will fit (and stay) in the current // fragmentainer. See MustStayInCurrentFragmentainer() in NGBoxFragmentBuilder. void SetupSpaceBuilderForFragmentation(const NGConstraintSpace& parent_space, - const NGLayoutInputNode& child, + const LayoutInputNode& child, LayoutUnit fragmentainer_offset_delta, NGConstraintSpaceBuilder*, bool is_new_fc, @@ -237,7 +237,7 @@ // beginning of layout. void SetupFragmentBuilderForFragmentation( const NGConstraintSpace&, - const NGLayoutInputNode&, + const LayoutInputNode&, const NGBlockBreakToken* previous_break_token, NGBoxFragmentBuilder*); @@ -290,7 +290,7 @@ // fragmentation (kDisableFragmentation). kBrokeBefore is never returned here // (if we need a break before the node, that's something that will be determined // by the parent algorithm). -NGBreakStatus FinishFragmentation(NGBlockNode node, +NGBreakStatus FinishFragmentation(BlockNode node, const NGConstraintSpace&, LayoutUnit trailing_border_padding, LayoutUnit space_left, @@ -331,7 +331,7 @@ // the column level. NGBreakStatus BreakBeforeChildIfNeeded( const NGConstraintSpace&, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult&, LayoutUnit fragmentainer_block_offset, bool has_container_separation, @@ -344,7 +344,7 @@ // different block-size than that of the provided layout result. void BreakBeforeChild( const NGConstraintSpace&, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult*, LayoutUnit fragmentainer_block_offset, absl::optional<NGBreakAppeal> appeal, @@ -400,7 +400,7 @@ // details on |flex_column_break_info|. bool MovePastBreakpoint( const NGConstraintSpace& space, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult& layout_result, LayoutUnit fragmentainer_block_offset, NGBreakAppeal appeal_before, @@ -408,7 +408,7 @@ bool is_row_item = false, NGFlexColumnBreakInfo* flex_column_break_info = nullptr); -// Same as above, but without the parts that require an NGLayoutInputNode. +// Same as above, but without the parts that require an LayoutInputNode. bool MovePastBreakpoint( const NGConstraintSpace& space, const NGLayoutResult& layout_result, @@ -424,7 +424,7 @@ // details on |flex_column_break_info|. void UpdateEarlyBreakAtBlockChild( const NGConstraintSpace&, - NGBlockNode child, + BlockNode child, const NGLayoutResult&, NGBreakAppeal appeal_before, NGBoxFragmentBuilder*, @@ -438,7 +438,7 @@ // BreakBeforeChildIfNeeded() for details on |flex_column_break_info|. bool AttemptSoftBreak( const NGConstraintSpace&, - NGLayoutInputNode child, + LayoutInputNode child, const NGLayoutResult*, LayoutUnit fragmentainer_block_offset, NGBreakAppeal appeal_before, @@ -450,25 +450,26 @@ // the node we're going to break before, return the early break inside. This can // then be passed to child layout, so that child layout eventually can tell // where to insert the break. -const NGEarlyBreak* EnterEarlyBreakInChild(const NGBlockNode& child, +const NGEarlyBreak* EnterEarlyBreakInChild(const BlockNode& child, const NGEarlyBreak&); // Return true if this is the child that we had previously determined to break // before. bool IsEarlyBreakTarget(const NGEarlyBreak&, const NGBoxFragmentBuilder&, - const NGLayoutInputNode& child); + const LayoutInputNode& child); // Find out if |child| is the next step on the column spanner path (if any), and // return the remaining path if that's the case, nullptr otherwise. inline const NGColumnSpannerPath* FollowColumnSpannerPath( const NGColumnSpannerPath* path, - const NGBlockNode& child) { + const BlockNode& child) { if (!path) return nullptr; const NGColumnSpannerPath* next_step = path->Child(); - if (next_step && next_step->BlockNode() == child) + if (next_step && next_step->GetBlockNode() == child) { return next_step; + } return nullptr; } @@ -484,10 +485,10 @@ // Calculate the container builder and constraint space for a multicol. NGBoxFragmentBuilder CreateContainerBuilderForMulticol( - const NGBlockNode& multicol, + const BlockNode& multicol, const NGConstraintSpace& space, const FragmentGeometry& fragment_geometry); -NGConstraintSpace CreateConstraintSpaceForMulticol(const NGBlockNode& multicol); +NGConstraintSpace CreateConstraintSpaceForMulticol(const BlockNode& multicol); // Return the adjusted child margin to be applied at the end of a fragment. // Margins should collapse with the fragmentainer boundary. |block_offset| is
diff --git a/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.cc index bb04585b..6bd0875 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.cc
@@ -39,7 +39,7 @@ FrameSetLayoutAlgorithm::FrameSetLayoutAlgorithm( const LayoutAlgorithmParams& params) - : LayoutAlgorithm<NGBlockNode, NGBoxFragmentBuilder, NGBlockBreakToken>( + : LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken>( params) {} const NGLayoutResult* FrameSetLayoutAlgorithm::Layout() { @@ -51,7 +51,7 @@ layout_data->col_allow_border = frame_set.AllowBorderColumns(); PhysicalSize size = ToPhysicalSize(container_builder_.Size(), - ConstraintSpace().GetWritingMode()); + GetConstraintSpace().GetWritingMode()); const wtf_size_t row_count = frame_set.TotalRows(); layout_data->row_sizes = LayoutAxis(row_count, frame_set.RowLengths(), frame_set.RowDeltas(), @@ -70,7 +70,7 @@ MinMaxSizesResult FrameSetLayoutAlgorithm::ComputeMinMaxSizes( const MinMaxSizesFloatInput&) { MinMaxSizes sizes; - const auto& space = ConstraintSpace(); + const auto& space = GetConstraintSpace(); // This function needs to return a value which is >= border+padding in order // to pass a DCHECK in NGFlexLayoutAlgorithm::ConstructAndAppendFlexItems() // though <frameset> ignores border and padding. @@ -272,7 +272,7 @@ void FrameSetLayoutAlgorithm::LayoutChildren( const FrameSetLayoutData& layout_data) { PhysicalOffset position; - NGLayoutInputNode child = Node().FirstChild(); + LayoutInputNode child = Node().FirstChild(); if (!child) return; for (wtf_size_t row = 0; row < layout_data.row_sizes.size(); ++row) { @@ -305,12 +305,12 @@ } } -void FrameSetLayoutAlgorithm::LayoutChild(const NGLayoutInputNode& child, +void FrameSetLayoutAlgorithm::LayoutChild(const LayoutInputNode& child, LogicalSize available_size, PhysicalOffset position, PhysicalSize child_size) { const PhysicalSize frameset_size = ToPhysicalSize( - container_builder_.Size(), ConstraintSpace().GetWritingMode()); + container_builder_.Size(), GetConstraintSpace().GetWritingMode()); const auto container_direction = Style().GetWritingDirection(); const bool kNewFormattingContext = true; NGConstraintSpaceBuilder space_builder(container_direction.GetWritingMode(), @@ -320,7 +320,7 @@ space_builder.SetIsFixedInlineSize(true); space_builder.SetIsFixedBlockSize(true); const NGLayoutResult* result = - To<NGBlockNode>(child).Layout(space_builder.ToConstraintSpace()); + To<BlockNode>(child).Layout(space_builder.ToConstraintSpace()); container_builder_.AddResult( *result, position.ConvertToLogical(container_direction, frameset_size, child_size));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.h index 7bbc451..b2222888 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_frame_set_layout_algorithm.h
@@ -14,7 +14,7 @@ class NGBlockBreakToken; class CORE_EXPORT FrameSetLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public: @@ -29,7 +29,7 @@ const Vector<int>& deltas, LayoutUnit available_length); void LayoutChildren(const FrameSetLayoutData& layout_data); - void LayoutChild(const NGLayoutInputNode&, + void LayoutChild(const LayoutInputNode&, LogicalSize available_size, PhysicalOffset position, PhysicalSize child_size);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc b/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc index d1b4062f..7e9d0d4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_inline_layout_test.cc
@@ -43,7 +43,7 @@ Element* target = GetDocument().getElementById(AtomicString("target")); auto* block_flow = To<LayoutBlockFlow>(target->GetLayoutObject()); NGConstraintSpace constraint_space = ConstraintSpaceForElement(block_flow); - NGBlockNode node(block_flow); + BlockNode node(block_flow); FragmentGeometry fragment_geometry = CalculateInitialFragmentGeometry( constraint_space, node, /* break_token */ nullptr); @@ -69,7 +69,7 @@ Element* target = GetDocument().getElementById(AtomicString("target")); auto* block_flow = To<LayoutBlockFlow>(target->GetLayoutObject()); NGConstraintSpace constraint_space = ConstraintSpaceForElement(block_flow); - NGBlockNode node(block_flow); + BlockNode node(block_flow); FragmentGeometry fragment_geometry = CalculateInitialFragmentGeometry(constraint_space, node,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h index e71269b..8070613b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_algorithm.h
@@ -42,7 +42,7 @@ public: LayoutAlgorithmParams( - NGBlockNode node, + BlockNode node, const FragmentGeometry& fragment_geometry, const NGConstraintSpace& space, const NGBlockBreakToken* break_token = nullptr, @@ -55,7 +55,7 @@ early_break(early_break), additional_early_breaks(additional_early_breaks) {} - NGBlockNode node; + BlockNode node; const FragmentGeometry& fragment_geometry; const NGConstraintSpace& space; const NGBlockBreakToken* break_token; @@ -109,8 +109,8 @@ virtual ~LayoutAlgorithm() = default; protected: - const NGConstraintSpace& ConstraintSpace() const { - return container_builder_.ConstraintSpace(); + const NGConstraintSpace& GetConstraintSpace() const { + return container_builder_.GetConstraintSpace(); } const ComputedStyle& Style() const { return node_.Style(); } @@ -157,9 +157,10 @@ DCHECK(!early_break_); DCHECK(!additional_early_breaks_ || additional_early_breaks_->empty()); - LayoutAlgorithmParams params( - Node(), container_builder_.InitialFragmentGeometry(), ConstraintSpace(), - BreakToken(), &breakpoint, additional_early_breaks); + LayoutAlgorithmParams params(Node(), + container_builder_.InitialFragmentGeometry(), + GetConstraintSpace(), BreakToken(), + &breakpoint, additional_early_breaks); Algorithm algorithm_with_break(params); return RelayoutAndBreakEarlier(&algorithm_with_break); } @@ -183,7 +184,7 @@ // contribute to superfluous fragmentainers. template <typename Algorithm> const NGLayoutResult* RelayoutWithoutFragmentation() { - DCHECK(ConstraintSpace().HasBlockFragmentation()); + DCHECK(GetConstraintSpace().HasBlockFragmentation()); // We'll relayout with a special cloned constraint space that disables // further fragmentation (but rather lets clipped child content "overflow" // past the fragmentation line). This means that the cached constraint space @@ -191,7 +192,8 @@ // right thing, since, as far as input is concerned, this node is meant to // perform block fragmentation (and it may already have produced multiple // fragment, but this one will be the last). - NGConstraintSpace new_space = ConstraintSpace().CloneWithoutFragmentation(); + NGConstraintSpace new_space = + GetConstraintSpace().CloneWithoutFragmentation(); LayoutAlgorithmParams params(Node(), container_builder_.InitialFragmentGeometry(),
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc index 7b1831b..584cf2d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.cc
@@ -29,13 +29,13 @@ namespace { #if DCHECK_IS_ON() -void AppendSubtreeToString(const NGBlockNode&, - const NGLayoutInputNode* target, +void AppendSubtreeToString(const BlockNode&, + const LayoutInputNode* target, StringBuilder*, unsigned indent); -void IndentForDump(const NGLayoutInputNode& node, - const NGLayoutInputNode* target, +void IndentForDump(const LayoutInputNode& node, + const LayoutInputNode* target, StringBuilder* string_builder, unsigned indent) { unsigned start_col = 0; @@ -48,8 +48,8 @@ } } -void AppendNodeToString(const NGLayoutInputNode& node, - const NGLayoutInputNode* target, +void AppendNodeToString(const LayoutInputNode& node, + const LayoutInputNode* target, StringBuilder* string_builder, unsigned indent = 2) { if (!node) @@ -60,15 +60,15 @@ string_builder->Append(node.ToString()); string_builder->Append("\n"); - if (auto* block_node = DynamicTo<NGBlockNode>(node)) { + if (auto* block_node = DynamicTo<BlockNode>(node)) { AppendSubtreeToString(*block_node, target, string_builder, indent + 2); } else if (auto* inline_node = DynamicTo<InlineNode>(node)) { const auto& items = inline_node->ItemsData(false).items; indent += 2; for (const InlineItem& inline_item : items) { - NGBlockNode child_node(nullptr); + BlockNode child_node(nullptr); if (auto* box = DynamicTo<LayoutBox>(inline_item.GetLayoutObject())) { - child_node = NGBlockNode(box); + child_node = BlockNode(box); } IndentForDump(child_node, target, string_builder, indent); string_builder->Append(inline_item.ToString()); @@ -82,12 +82,12 @@ } } -void AppendSubtreeToString(const NGBlockNode& node, - const NGLayoutInputNode* target, +void AppendSubtreeToString(const BlockNode& node, + const LayoutInputNode* target, StringBuilder* string_builder, unsigned indent) { - NGLayoutInputNode first_child = node.FirstChild(); - for (NGLayoutInputNode node_runner = first_child; node_runner; + LayoutInputNode first_child = node.FirstChild(); + for (LayoutInputNode node_runner = first_child; node_runner; node_runner = node_runner.NextSibling()) { AppendNodeToString(node_runner, target, string_builder, indent); } @@ -96,59 +96,59 @@ } // namespace -bool NGLayoutInputNode::IsSlider() const { +bool LayoutInputNode::IsSlider() const { if (const auto* input = DynamicTo<HTMLInputElement>(box_->GetNode())) return input->FormControlType() == FormControlType::kInputRange; return false; } -bool NGLayoutInputNode::IsSliderThumb() const { +bool LayoutInputNode::IsSliderThumb() const { return IsBlock() && blink::IsSliderThumb(GetDOMNode()); } -bool NGLayoutInputNode::IsSvgText() const { +bool LayoutInputNode::IsSvgText() const { return box_ && box_->IsSVGText(); } -bool NGLayoutInputNode::IsEmptyTableSection() const { +bool LayoutInputNode::IsEmptyTableSection() const { return box_->IsTableSection() && To<LayoutTableSection>(box_.Get())->IsEmpty(); } -wtf_size_t NGLayoutInputNode::TableColumnSpan() const { +wtf_size_t LayoutInputNode::TableColumnSpan() const { DCHECK(IsTableCol() || IsTableColgroup()); return To<LayoutTableColumn>(box_.Get())->Span(); } -wtf_size_t NGLayoutInputNode::TableCellColspan() const { +wtf_size_t LayoutInputNode::TableCellColspan() const { DCHECK(box_->IsTableCell()); return To<LayoutTableCell>(box_.Get())->ColSpan(); } -wtf_size_t NGLayoutInputNode::TableCellRowspan() const { +wtf_size_t LayoutInputNode::TableCellRowspan() const { DCHECK(box_->IsTableCell()); return To<LayoutTableCell>(box_.Get())->ComputedRowSpan(); } -bool NGLayoutInputNode::IsTextControlPlaceholder() const { +bool LayoutInputNode::IsTextControlPlaceholder() const { return IsBlock() && blink::IsTextControlPlaceholder(GetDOMNode()); } -bool NGLayoutInputNode::IsPaginatedRoot() const { +bool LayoutInputNode::IsPaginatedRoot() const { if (!IsBlock()) return false; const auto* view = DynamicTo<LayoutView>(box_.Get()); return view && view->IsFragmentationContextRoot(); } -NGBlockNode NGLayoutInputNode::ListMarkerBlockNodeIfListItem() const { +BlockNode LayoutInputNode::ListMarkerBlockNodeIfListItem() const { if (auto* list_item = DynamicTo<LayoutListItem>(box_.Get())) { - return NGBlockNode(DynamicTo<LayoutBox>(list_item->Marker())); + return BlockNode(DynamicTo<LayoutBox>(list_item->Marker())); } - return NGBlockNode(nullptr); + return BlockNode(nullptr); } -void NGLayoutInputNode::IntrinsicSize( +void LayoutInputNode::IntrinsicSize( absl::optional<LayoutUnit>* computed_inline_size, absl::optional<LayoutUnit>* computed_block_size) const { DCHECK(IsReplaced()); @@ -183,36 +183,36 @@ } } -NGLayoutInputNode NGLayoutInputNode::NextSibling() const { +LayoutInputNode LayoutInputNode::NextSibling() const { auto* inline_node = DynamicTo<InlineNode>(this); - return inline_node ? nullptr : To<NGBlockNode>(*this).NextSibling(); + return inline_node ? nullptr : To<BlockNode>(*this).NextSibling(); } -PhysicalSize NGLayoutInputNode::InitialContainingBlockSize() const { +PhysicalSize LayoutInputNode::InitialContainingBlockSize() const { gfx::Size icb_size = GetDocument().GetLayoutView()->GetLayoutSize(kIncludeScrollbars); return PhysicalSize(icb_size); } -String NGLayoutInputNode::ToString() const { +String LayoutInputNode::ToString() const { auto* inline_node = DynamicTo<InlineNode>(this); return inline_node ? inline_node->ToString() - : To<NGBlockNode>(*this).ToString(); + : To<BlockNode>(*this).ToString(); } #if DCHECK_IS_ON() -String NGLayoutInputNode::DumpNodeTree(const NGLayoutInputNode* target) const { +String LayoutInputNode::DumpNodeTree(const LayoutInputNode* target) const { StringBuilder string_builder; string_builder.Append(".:: Layout input node tree ::.\n"); AppendNodeToString(*this, target, &string_builder); return string_builder.ToString(); } -String NGLayoutInputNode::DumpNodeTreeFromRoot() const { - return NGBlockNode(box_->View()).DumpNodeTree(this); +String LayoutInputNode::DumpNodeTreeFromRoot() const { + return BlockNode(box_->View()).DumpNodeTree(this); } -void NGLayoutInputNode::ShowNodeTree(const NGLayoutInputNode* target) const { +void LayoutInputNode::ShowNodeTree(const LayoutInputNode* target) const { if (getenv("RUNNING_UNDER_RR")) { // Printing timestamps requires an IPC to get the local time, which // does not work in an rr replay session. Just disable timestamp printing @@ -226,12 +226,12 @@ DLOG(INFO) << "\n" << DumpNodeTree(target).Utf8(); } -void NGLayoutInputNode::ShowNodeTreeFromRoot() const { - NGBlockNode(box_->View()).ShowNodeTree(this); +void LayoutInputNode::ShowNodeTreeFromRoot() const { + BlockNode(box_->View()).ShowNodeTree(this); } #endif -void NGLayoutInputNode::GetOverrideIntrinsicSize( +void LayoutInputNode::GetOverrideIntrinsicSize( absl::optional<LayoutUnit>* computed_inline_size, absl::optional<LayoutUnit>* computed_block_size) const { DCHECK(IsReplaced()); @@ -264,7 +264,7 @@ #if DCHECK_IS_ON() -CORE_EXPORT void ShowLayoutTree(const blink::NGLayoutInputNode& node) { +CORE_EXPORT void ShowLayoutTree(const blink::LayoutInputNode& node) { ShowLayoutTree(node.GetLayoutBox()); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h index fdc1dc4..4c37059d 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node.h
@@ -52,26 +52,26 @@ // Represents the input to a layout algorithm for a given node. The layout // engine should use the style, node type to determine which type of layout // algorithm to use to produce fragments for this node. -class CORE_EXPORT NGLayoutInputNode { +class CORE_EXPORT LayoutInputNode { DISALLOW_NEW(); public: - enum NGLayoutInputNodeType { + enum LayoutInputNodeType { kBlock, kInline // When adding new values, ensure type_ below has enough bits. }; - static NGLayoutInputNode Create(LayoutBox* box, NGLayoutInputNodeType type) { + static LayoutInputNode Create(LayoutBox* box, LayoutInputNodeType type) { // This function should create an instance of the subclass. This works // because subclasses are not virtual and do not add fields. - return NGLayoutInputNode(box, type); + return LayoutInputNode(box, type); } - NGLayoutInputNode(std::nullptr_t) : box_(nullptr), type_(kBlock) {} + LayoutInputNode(std::nullptr_t) : box_(nullptr), type_(kBlock) {} - NGLayoutInputNodeType Type() const { - return static_cast<NGLayoutInputNodeType>(type_); + LayoutInputNodeType Type() const { + return static_cast<LayoutInputNodeType>(type_); } bool IsInline() const { return type_ == kInline; } bool IsBlock() const { return type_ == kBlock; } @@ -106,7 +106,7 @@ bool IsListItem() const { return IsBlock() && box_->IsLayoutListItem(); } // Returns the list marker if |this.IsListItem()| with an outside list marker. // Otherwise |nullptr|. - NGBlockNode ListMarkerBlockNodeIfListItem() const; + BlockNode ListMarkerBlockNodeIfListItem() const; bool IsListMarker() const { return IsBlock() && box_->IsLayoutOutsideListMarker(); } @@ -213,12 +213,12 @@ // Returns intrinsic sizing information for replaced elements. // ComputeReplacedSize can use it to compute actual replaced size. // Corresponds to Legacy's LayoutReplaced::IntrinsicSizingInfo. - // Use NGBlockNode::GetAspectRatio to get the aspect ratio. + // Use BlockNode::GetAspectRatio to get the aspect ratio. void IntrinsicSize(absl::optional<LayoutUnit>* computed_inline_size, absl::optional<LayoutUnit>* computed_block_size) const; // Returns the next sibling. - NGLayoutInputNode NextSibling() const; + LayoutInputNode NextSibling() const; Document& GetDocument() const { return box_->GetDocument(); } @@ -301,29 +301,29 @@ explicit operator bool() const { return box_ != nullptr; } - bool operator==(const NGLayoutInputNode& other) const { + bool operator==(const LayoutInputNode& other) const { return box_ == other.box_ && type_ == other.type_; } - bool operator!=(const NGLayoutInputNode& other) const { + bool operator!=(const LayoutInputNode& other) const { return !(*this == other); } #if DCHECK_IS_ON() - String DumpNodeTree(const NGLayoutInputNode* target = nullptr) const; + String DumpNodeTree(const LayoutInputNode* target = nullptr) const; // Dump the node tree for the entire document, and mark `this` with an // asterisk. String DumpNodeTreeFromRoot() const; - void ShowNodeTree(const NGLayoutInputNode* target = nullptr) const; + void ShowNodeTree(const LayoutInputNode* target = nullptr) const; void ShowNodeTreeFromRoot() const; #endif void Trace(Visitor* visitor) const { visitor->Trace(box_); } protected: - NGLayoutInputNode(LayoutBox* box, NGLayoutInputNodeType type) + LayoutInputNode(LayoutBox* box, LayoutInputNodeType type) : box_(box), type_(type) {} void GetOverrideIntrinsicSize( @@ -332,7 +332,7 @@ Member<LayoutBox> box_; - unsigned type_ : 1; // NGLayoutInputNodeType + unsigned type_ : 1; // LayoutInputNodeType }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node_test.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node_test.cc index ef6512f1..ddbeb01e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_input_node_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_input_node_test.cc
@@ -14,28 +14,28 @@ #if DCHECK_IS_ON() -class NGLayoutInputNodeTest : public RenderingTest { +class LayoutInputNodeTest : public RenderingTest { public: - String DumpAll(const NGLayoutInputNode* target = nullptr) const { - NGBlockNode root_node(GetDocument().GetLayoutView()); + String DumpAll(const LayoutInputNode* target = nullptr) const { + BlockNode root_node(GetDocument().GetLayoutView()); return root_node.DumpNodeTree(target); } - NGBlockNode BlockNodeFromId(const char* id) { + BlockNode BlockNodeFromId(const char* id) { auto* box = DynamicTo<LayoutBox>(GetLayoutObjectByElementId(id)); - return NGBlockNode(box); + return BlockNode(box); } }; -TEST_F(NGLayoutInputNodeTest, DumpBasic) { +TEST_F(LayoutInputNodeTest, DumpBasic) { SetBodyInnerHTML(R"HTML( <div id="block"><span>Hello world!</span></div> )HTML"); String dump = DumpAll(); String expectation = R"DUMP(.:: Layout input node tree ::. - NGBlockNode: LayoutView #document - NGBlockNode: LayoutNGBlockFlow HTML - NGBlockNode: LayoutNGBlockFlow BODY - NGBlockNode: LayoutNGBlockFlow DIV id="block" + BlockNode: LayoutView #document + BlockNode: LayoutNGBlockFlow HTML + BlockNode: LayoutNGBlockFlow BODY + BlockNode: LayoutNGBlockFlow DIV id="block" InlineNode InlineItem OpenTag. LayoutInline SPAN InlineItem Text. "Hello world!" @@ -44,7 +44,7 @@ EXPECT_EQ(expectation, dump); } -TEST_F(NGLayoutInputNodeTest, DumpBlockInInline) { +TEST_F(LayoutInputNodeTest, DumpBlockInInline) { SetBodyInnerHTML(R"HTML( <div id="block"> <span> @@ -55,19 +55,19 @@ </span> </div> )HTML"); - NGBlockNode inner = BlockNodeFromId("inner"); + BlockNode inner = BlockNodeFromId("inner"); String dump = inner.DumpNodeTreeFromRoot(); String expectation = R"DUMP(.:: Layout input node tree ::. - NGBlockNode: LayoutView #document - NGBlockNode: LayoutNGBlockFlow HTML - NGBlockNode: LayoutNGBlockFlow BODY - NGBlockNode: LayoutNGBlockFlow DIV id="block" + BlockNode: LayoutView #document + BlockNode: LayoutNGBlockFlow HTML + BlockNode: LayoutNGBlockFlow BODY + BlockNode: LayoutNGBlockFlow DIV id="block" InlineNode InlineItem OpenTag. LayoutInline SPAN InlineItem Text. "\n Hello world!\n " InlineItem BlockInInline. LayoutNGBlockFlow (anonymous) - NGBlockNode: LayoutNGBlockFlow DIV id="blockininline" -* NGBlockNode: LayoutNGBlockFlow DIV id="inner" + BlockNode: LayoutNGBlockFlow DIV id="blockininline" +* BlockNode: LayoutNGBlockFlow DIV id="inner" InlineNode InlineItem Text. "Hello trouble!" InlineItem CloseTag. LayoutInline SPAN @@ -76,7 +76,7 @@ EXPECT_EQ(expectation, dump); } -TEST_F(NGLayoutInputNodeTest, DumpInlineBlockInInline) { +TEST_F(LayoutInputNodeTest, DumpInlineBlockInInline) { SetBodyInnerHTML(R"HTML( <div id="block"> <span> @@ -87,18 +87,18 @@ </span> </div> )HTML"); - NGBlockNode inner = BlockNodeFromId("inner"); + BlockNode inner = BlockNodeFromId("inner"); String dump = inner.DumpNodeTreeFromRoot(); String expectation = R"DUMP(.:: Layout input node tree ::. - NGBlockNode: LayoutView #document - NGBlockNode: LayoutNGBlockFlow HTML - NGBlockNode: LayoutNGBlockFlow BODY - NGBlockNode: LayoutNGBlockFlow DIV id="block" + BlockNode: LayoutView #document + BlockNode: LayoutNGBlockFlow HTML + BlockNode: LayoutNGBlockFlow BODY + BlockNode: LayoutNGBlockFlow DIV id="block" InlineNode InlineItem OpenTag. LayoutInline SPAN InlineItem Text. "\n Hello world!\n " InlineItem AtomicInline. LayoutNGBlockFlow DIV id="inlineblock" style="display:inline-block;" -* NGBlockNode: LayoutNGBlockFlow DIV id="inner" +* BlockNode: LayoutNGBlockFlow DIV id="inner" InlineNode InlineItem Text. "Hello Janus!" InlineItem Text. "\n " @@ -108,7 +108,7 @@ EXPECT_EQ(expectation, dump); } -TEST_F(NGLayoutInputNodeTest, DumpFloatInInline) { +TEST_F(LayoutInputNodeTest, DumpFloatInInline) { SetBodyInnerHTML(R"HTML( <div id="block"> <span> @@ -119,18 +119,18 @@ </span> </div> )HTML"); - NGBlockNode inner = BlockNodeFromId("inner"); + BlockNode inner = BlockNodeFromId("inner"); String dump = inner.DumpNodeTreeFromRoot(); String expectation = R"DUMP(.:: Layout input node tree ::. - NGBlockNode: LayoutView #document - NGBlockNode: LayoutNGBlockFlow HTML - NGBlockNode: LayoutNGBlockFlow BODY - NGBlockNode: LayoutNGBlockFlow DIV id="block" + BlockNode: LayoutView #document + BlockNode: LayoutNGBlockFlow HTML + BlockNode: LayoutNGBlockFlow BODY + BlockNode: LayoutNGBlockFlow DIV id="block" InlineNode InlineItem OpenTag. LayoutInline SPAN InlineItem Text. "\n Hello world!\n " InlineItem Floating. LayoutNGBlockFlow (floating) DIV id="float" style="float:left;" -* NGBlockNode: LayoutNGBlockFlow DIV id="inner" +* BlockNode: LayoutNGBlockFlow DIV id="inner" InlineNode InlineItem Text. "Hello Hermes!" InlineItem CloseTag. LayoutInline SPAN @@ -139,7 +139,7 @@ EXPECT_EQ(expectation, dump); } -TEST_F(NGLayoutInputNodeTest, DumpAbsposInInline) { +TEST_F(LayoutInputNodeTest, DumpAbsposInInline) { SetBodyInnerHTML(R"HTML( <div id="block"> <span> @@ -150,18 +150,18 @@ </span> </div> )HTML"); - NGBlockNode inner = BlockNodeFromId("inner"); + BlockNode inner = BlockNodeFromId("inner"); String dump = inner.DumpNodeTreeFromRoot(); String expectation = R"DUMP(.:: Layout input node tree ::. - NGBlockNode: LayoutView #document - NGBlockNode: LayoutNGBlockFlow HTML - NGBlockNode: LayoutNGBlockFlow BODY - NGBlockNode: LayoutNGBlockFlow DIV id="block" + BlockNode: LayoutView #document + BlockNode: LayoutNGBlockFlow HTML + BlockNode: LayoutNGBlockFlow BODY + BlockNode: LayoutNGBlockFlow DIV id="block" InlineNode InlineItem OpenTag. LayoutInline SPAN InlineItem Text. "\n Hello world!\n " InlineItem OutOfFlowPositioned. LayoutNGBlockFlow (positioned) DIV id="abspos" style="position:absolute;" -* NGBlockNode: LayoutNGBlockFlow DIV id="inner" +* BlockNode: LayoutNGBlockFlow DIV id="inner" InlineNode InlineItem Text. "Hello Thor!" InlineItem CloseTag. LayoutInline SPAN @@ -170,15 +170,15 @@ EXPECT_EQ(expectation, dump); } -TEST_F(NGLayoutInputNodeTest, DumpRelposInline) { +TEST_F(LayoutInputNodeTest, DumpRelposInline) { SetBodyInnerHTML(R"HTML( <span style="position:relative;">Hello world!</span> )HTML"); String dump = DumpAll(); String expectation = R"DUMP(.:: Layout input node tree ::. - NGBlockNode: LayoutView #document - NGBlockNode: LayoutNGBlockFlow HTML - NGBlockNode: LayoutNGBlockFlow BODY + BlockNode: LayoutView #document + BlockNode: LayoutNGBlockFlow HTML + BlockNode: LayoutNGBlockFlow BODY InlineNode InlineItem OpenTag. LayoutInline (relative positioned) SPAN style="position:relative;" InlineItem Text. "Hello world!"
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.cc index 35e4d82c1..a5ce9ce 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.cc
@@ -24,7 +24,7 @@ PhysicalRect NGLayoutOverflowCalculator::RecalculateLayoutOverflowForFragment( const NGPhysicalBoxFragment& fragment, bool has_block_fragmentation) { - const NGBlockNode node(const_cast<LayoutBox*>( + const BlockNode node(const_cast<LayoutBox*>( To<LayoutBox>(fragment.GetSelfOrContainerLayoutObject()))); DCHECK(!node.IsReplaced() || node.IsMedia()); @@ -73,7 +73,7 @@ } NGLayoutOverflowCalculator::NGLayoutOverflowCalculator( - const NGBlockNode& node, + const BlockNode& node, bool is_css_box, bool has_block_fragmentation, const PhysicalBoxStrut& borders,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.h b/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.h index 0664f37..dc240cd0 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_overflow_calculator.h
@@ -26,7 +26,7 @@ const NGPhysicalBoxFragment&, bool has_block_fragmentation); - NGLayoutOverflowCalculator(const NGBlockNode&, + NGLayoutOverflowCalculator(const BlockNode&, bool is_css_box, bool has_block_fragmentation, const PhysicalBoxStrut& borders, @@ -78,7 +78,7 @@ layout_overflow_.UniteEvenIfEmpty(child_overflow); } - const NGBlockNode node_; + const BlockNode node_; const WritingDirectionMode writing_direction_; const bool is_scroll_container_; const bool is_view_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc index 2c7665dc..c9e8196e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_result.cc
@@ -85,7 +85,7 @@ bitfields_.is_truncated_by_fragmentation_line = builder->is_truncated_by_fragmentation_line; - if (builder->ConstraintSpace().ShouldPropagateChildBreakValues() && + if (builder->GetConstraintSpace().ShouldPropagateChildBreakValues() && !builder->layout_object_->ShouldApplyLayoutContainment()) { bitfields_.initial_break_before = static_cast<unsigned>( builder->initial_break_before_.value_or(EBreakBetween::kAuto));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc index 6eb7ac0..7dfb72a8 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_utils.cc
@@ -72,7 +72,7 @@ return false; } -bool BlockSizeMayChange(const NGBlockNode& node, +bool BlockSizeMayChange(const BlockNode& node, const NGConstraintSpace& new_space, const NGConstraintSpace& old_space, const NGLayoutResult& layout_result) { @@ -115,7 +115,7 @@ // Return true if it's possible (but not necessarily guaranteed) that the new // constraint space will give a different size compared to the old one, when // computed style and child content remain unchanged. -bool SizeMayChange(const NGBlockNode& node, +bool SizeMayChange(const BlockNode& node, const NGConstraintSpace& new_space, const NGConstraintSpace& old_space, const NGLayoutResult& layout_result) { @@ -176,7 +176,7 @@ // have %-block-sizes). // - |NGLayoutCacheStatus::kHit| otherwise. NGLayoutCacheStatus CalculateSizeBasedLayoutCacheStatusWithGeometry( - const NGBlockNode& node, + const BlockNode& node, const FragmentGeometry& fragment_geometry, const NGLayoutResult& layout_result, const NGConstraintSpace& new_space, @@ -418,7 +418,7 @@ } bool IntrinsicSizeWillChange( - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const NGLayoutResult& cached_layout_result, const NGConstraintSpace& new_space, @@ -446,7 +446,7 @@ } // namespace NGLayoutCacheStatus CalculateSizeBasedLayoutCacheStatus( - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const NGLayoutResult& cached_layout_result, const NGConstraintSpace& new_space,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_layout_utils.h b/third_party/blink/renderer/core/layout/ng/ng_layout_utils.h index 7094aad..f9438b5 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_layout_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_layout_utils.h
@@ -36,7 +36,7 @@ // // May pre-compute the |fragment_geometry| while calculating this status. NGLayoutCacheStatus CalculateSizeBasedLayoutCacheStatus( - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const NGLayoutResult& cached_layout_result, const NGConstraintSpace& new_space,
diff --git a/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc index b6d54a5..987b567 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_length_utils.cc
@@ -232,7 +232,7 @@ template <typename MinMaxSizesFunc> MinMaxSizesResult ComputeMinAndMaxContentContributionInternal( WritingMode parent_writing_mode, - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space, const MinMaxSizesFunc& min_max_sizes_func) { const ComputedStyle& style = child.Style(); @@ -307,7 +307,7 @@ // Currently this simply sets the correct override sizes for the replaced // element, and lets legacy layout do the result. MinMaxSizesResult ComputeMinAndMaxContentContributionForReplaced( - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space) { const auto& child_style = child.Style(); const BoxStrut border_padding = @@ -348,7 +348,7 @@ MinMaxSizesResult ComputeMinAndMaxContentContribution( const ComputedStyle& parent_style, - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space, const MinMaxSizesFloatInput float_input) { const auto& child_style = child.Style(); @@ -370,7 +370,7 @@ } MinMaxSizesResult ComputeMinAndMaxContentContributionForSelf( - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space) { DCHECK(child.CreatesNewFormattingContext()); @@ -390,7 +390,7 @@ MinMaxSizes ComputeMinAndMaxContentContributionForTest( WritingMode parent_writing_mode, - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space, const MinMaxSizes& min_max_sizes) { auto MinMaxSizesFunc = [&](MinMaxSizesType) -> MinMaxSizesResult { @@ -427,7 +427,7 @@ LayoutUnit ComputeUsedInlineSizeForTableFragment( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const MinMaxSizes& table_grid_min_max_sizes) { DCHECK(!space.IsFixedInlineSize()); @@ -654,7 +654,7 @@ namespace { // Returns the default natural size. -LogicalSize ComputeDefaultNaturalSize(const NGBlockNode& node) { +LogicalSize ComputeDefaultNaturalSize(const BlockNode& node) { const auto& style = node.Style(); PhysicalSize natural_size(LayoutUnit(300), LayoutUnit(150)); natural_size.Scale(style.EffectiveZoom()); @@ -673,7 +673,7 @@ // use the default replaced size of 300x150 as a last resort). // https://www.w3.org/TR/CSS22/visudet.html#inline-replaced-width absl::optional<LogicalSize> ComputeNormalizedNaturalSize( - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const EBoxSizing box_sizing, const LogicalSize& aspect_ratio) { @@ -719,7 +719,7 @@ // The main part of ComputeReplacedSize(). This function doesn't handle a // case of <svg> as the documentElement. LogicalSize ComputeReplacedSizeInternal( - const NGBlockNode& node, + const BlockNode& node, const NGConstraintSpace& space, const BoxStrut& border_padding, absl::optional<LogicalSize> override_available_size, @@ -995,7 +995,7 @@ // Computes size for a replaced element. LogicalSize ComputeReplacedSize( - const NGBlockNode& node, + const BlockNode& node, const NGConstraintSpace& space, const BoxStrut& border_padding, absl::optional<LogicalSize> override_available_size, @@ -1159,7 +1159,7 @@ } // namespace BoxStrut ComputeBorders(const NGConstraintSpace& constraint_space, - const NGBlockNode& node) { + const BlockNode& node) { // If we are producing an anonymous fragment (e.g. a column), it has no // borders, padding or scrollbars. Using the ones from the container can only // cause trouble. @@ -1219,7 +1219,7 @@ percentage_resolution_size)}; } -BoxStrut ComputeScrollbarsForNonAnonymous(const NGBlockNode& node) { +BoxStrut ComputeScrollbarsForNonAnonymous(const BlockNode& node) { const ComputedStyle& style = node.Style(); if (!style.IsScrollContainer() && style.IsScrollbarGutterAuto()) return BoxStrut(); @@ -1298,7 +1298,7 @@ // Calculates default content size for html and body elements in quirks mode. // Returns |kIndefiniteSize| in all other cases. LayoutUnit CalculateDefaultBlockSize(const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const BoxStrut& border_scrollbar_padding) { // In quirks mode, html and body elements will completely fill the ICB, block @@ -1314,7 +1314,7 @@ FragmentGeometry CalculateInitialFragmentGeometry( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, bool is_intrinsic) { auto MinMaxSizesFunc = [&](MinMaxSizesType type) -> MinMaxSizesResult { @@ -1340,7 +1340,7 @@ LogicalSize CalculateChildAvailableSize( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const LogicalSize border_box_size, const BoxStrut& border_scrollbar_padding) { LogicalSize child_available_size = @@ -1357,7 +1357,7 @@ // Implements the common part of the child percentage size calculation. Deals // with how percentages are propagated from parent to child in quirks mode. LogicalSize AdjustChildPercentageSize(const NGConstraintSpace& space, - const NGBlockNode node, + const BlockNode node, LogicalSize child_percentage_size, LayoutUnit parent_percentage_block_size) { // In quirks mode the percentage resolution height is passed from parent to @@ -1374,7 +1374,7 @@ LogicalSize CalculateChildPercentageSize( const NGConstraintSpace& space, - const NGBlockNode node, + const BlockNode node, const LogicalSize child_available_size) { // Anonymous block or spaces should use the parent percent block-size. if (space.IsAnonymous() || node.IsAnonymousBlock()) { @@ -1394,7 +1394,7 @@ LogicalSize CalculateReplacedChildPercentageSize( const NGConstraintSpace& space, - const NGBlockNode node, + const BlockNode node, const LogicalSize child_available_size, const BoxStrut& border_scrollbar_padding, const BoxStrut& border_padding) { @@ -1434,7 +1434,7 @@ LayoutUnit ClampIntrinsicBlockSize( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const BoxStrut& border_scrollbar_padding, LayoutUnit current_intrinsic_block_size, @@ -1482,7 +1482,7 @@ } absl::optional<MinMaxSizesResult> CalculateMinMaxSizesIgnoringChildren( - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_scrollbar_padding) { MinMaxSizes sizes; sizes += border_scrollbar_padding.InlineSum();
diff --git a/third_party/blink/renderer/core/layout/ng/ng_length_utils.h b/third_party/blink/renderer/core/layout/ng/ng_length_utils.h index dfdafd4..9c10700b 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_length_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_length_utils.h
@@ -272,7 +272,7 @@ // size of the child). MinMaxSizesResult ComputeMinAndMaxContentContribution( const ComputedStyle& parent_style, - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space, const MinMaxSizesFloatInput float_input = MinMaxSizesFloatInput()); @@ -280,13 +280,13 @@ // writing-mode, and instead computes the contribution relative to |child|'s // own writing-mode. MinMaxSizesResult ComputeMinAndMaxContentContributionForSelf( - const NGBlockNode& child, + const BlockNode& child, const NGConstraintSpace& space); // Used for unit-tests. CORE_EXPORT MinMaxSizes ComputeMinAndMaxContentContributionForTest(WritingMode writing_mode, - const NGBlockNode&, + const BlockNode&, const NGConstraintSpace&, const MinMaxSizes&); @@ -321,7 +321,7 @@ template <typename MinMaxSizesFunc> MinMaxSizes ComputeMinMaxInlineSizes( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const MinMaxSizesFunc& min_max_sizes_func, const Length* opt_min_length = nullptr, @@ -385,7 +385,7 @@ template <typename MinMaxSizesFunc> LayoutUnit ComputeInlineSizeForFragmentInternal( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const MinMaxSizesFunc& min_max_sizes_func) { const auto& style = node.Style(); @@ -433,7 +433,7 @@ template <typename MinMaxSizesFunc> LayoutUnit ComputeInlineSizeForFragment( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const MinMaxSizesFunc& min_max_sizes_func) { if (space.IsFixedInlineSize() || space.IsAnonymous()) { @@ -456,7 +456,7 @@ // `override_min_max_sizes_for_test` is provided *solely* for use by unit tests. inline LayoutUnit ComputeInlineSizeForFragment( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const MinMaxSizes* override_min_max_sizes_for_test = nullptr) { auto MinMaxSizesFunc = [&](MinMaxSizesType type) -> MinMaxSizesResult { @@ -476,7 +476,7 @@ // https://drafts.csswg.org/css-tables-3/#used-width-of-table CORE_EXPORT LayoutUnit ComputeUsedInlineSizeForTableFragment( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const BoxStrut& border_padding, const MinMaxSizes& table_grid_min_max_sizes); @@ -492,7 +492,7 @@ // Returns |kIndefiniteSize| in all other cases. CORE_EXPORT LayoutUnit CalculateDefaultBlockSize(const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const BoxStrut& border_scrollbar_padding); @@ -514,7 +514,7 @@ // space provided. (E.g. if the available inline-size is indefinite it will // return the intrinsic size). CORE_EXPORT LogicalSize ComputeReplacedSize( - const NGBlockNode&, + const BlockNode&, const NGConstraintSpace&, const BoxStrut& border_padding, absl::optional<LogicalSize> override_available_size = absl::nullopt, @@ -619,8 +619,7 @@ {constraint_space.GetWritingMode(), TextDirection::kLtr}); } -CORE_EXPORT BoxStrut ComputeBorders(const NGConstraintSpace&, - const NGBlockNode&); +CORE_EXPORT BoxStrut ComputeBorders(const NGConstraintSpace&, const BlockNode&); CORE_EXPORT BoxStrut ComputeBordersForInline(const ComputedStyle&); @@ -644,10 +643,10 @@ } // Compute the scrollbars and scrollbar gutters. -CORE_EXPORT BoxStrut ComputeScrollbarsForNonAnonymous(const NGBlockNode&); +CORE_EXPORT BoxStrut ComputeScrollbarsForNonAnonymous(const BlockNode&); inline BoxStrut ComputeScrollbars(const NGConstraintSpace& space, - const NGBlockNode& node) { + const BlockNode& node) { if (space.IsAnonymous()) return BoxStrut(); @@ -678,7 +677,7 @@ template <typename MinMaxSizesFunc> FragmentGeometry CalculateInitialFragmentGeometry( const NGConstraintSpace& space, - const NGBlockNode& node, + const BlockNode& node, const NGBlockBreakToken* break_token, const MinMaxSizesFunc& min_max_sizes_func, bool is_intrinsic = false) { @@ -755,12 +754,12 @@ // The "pre-layout" block-size may be indefinite, as we'll only have enough // information to determine this post-layout. // Setting |is_intrinsic| to true will avoid calculating the inline-size, and -// is typically used within the |NGBlockNode::ComputeMinMaxSizes| pass (as to +// is typically used within the |BlockNode::ComputeMinMaxSizes| pass (as to // determine the inline-size, we'd need to compute the min/max sizes, which in // turn would call this function). CORE_EXPORT FragmentGeometry CalculateInitialFragmentGeometry(const NGConstraintSpace&, - const NGBlockNode&, + const BlockNode&, const NGBlockBreakToken*, bool is_intrinsic = false); @@ -770,7 +769,7 @@ // Calculates the available size that children of the node should use. LogicalSize CalculateChildAvailableSize( const NGConstraintSpace&, - const NGBlockNode& node, + const BlockNode& node, const LogicalSize border_box_size, const BoxStrut& border_scrollbar_padding); @@ -778,14 +777,14 @@ // use. LogicalSize CalculateChildPercentageSize( const NGConstraintSpace&, - const NGBlockNode node, + const BlockNode node, const LogicalSize child_available_size); // Calculates the percentage resolution size that replaced children of the node // should use. LogicalSize CalculateReplacedChildPercentageSize( const NGConstraintSpace&, - const NGBlockNode node, + const BlockNode node, const LogicalSize child_available_size, const BoxStrut& border_scrollbar_padding, const BoxStrut& border_padding); @@ -795,7 +794,7 @@ // and display locking status. LayoutUnit ClampIntrinsicBlockSize( const NGConstraintSpace&, - const NGBlockNode&, + const BlockNode&, const NGBlockBreakToken* break_token, const BoxStrut& border_scrollbar_padding, LayoutUnit current_intrinsic_block_size, @@ -806,7 +805,7 @@ // Otherwise, it returns absl::nullopt and the caller has to compute the size // itself. absl::optional<MinMaxSizesResult> CalculateMinMaxSizesIgnoringChildren( - const NGBlockNode&, + const BlockNode&, const BoxStrut& border_scrollbar_padding); // Determine which scrollbars to freeze in the next layout pass. Scrollbars that
diff --git a/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc b/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc index 87adf72..8505618e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_length_utils_test.cc
@@ -93,7 +93,7 @@ class NGLengthUtilsTestWithNode : public RenderingTest { public: LayoutUnit ComputeInlineSizeForFragment( - const NGBlockNode& node, + const BlockNode& node, NGConstraintSpace constraint_space = ConstructConstraintSpace(200, 300), const MinMaxSizes& sizes = MinMaxSizes()) { BoxStrut border_padding = ComputeBorders(constraint_space, node) + @@ -103,7 +103,7 @@ } LayoutUnit ComputeBlockSizeForFragment( - const NGBlockNode& node, + const BlockNode& node, NGConstraintSpace constraint_space = ConstructConstraintSpace(200, 300), LayoutUnit content_size = LayoutUnit(), absl::optional<LayoutUnit> inline_size = absl::nullopt) { @@ -182,26 +182,26 @@ .ToConstraintSpace(); MinMaxSizes expected = sizes; - NGBlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test1"))); + BlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test1"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test2"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test2"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); expected = MinMaxSizes{LayoutUnit(150), LayoutUnit(150)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test3"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test3"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); expected = sizes; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test4"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test4"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); expected = MinMaxSizes{LayoutUnit(430), LayoutUnit(440)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test5"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test5"))); auto sizes_padding400 = sizes; sizes_padding400 += LayoutUnit(400); EXPECT_EQ(expected, @@ -209,30 +209,30 @@ WritingMode::kHorizontalTb, node, space, sizes_padding400)); expected = MinMaxSizes{LayoutUnit(30), LayoutUnit(40)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test6"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test6"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); expected = MinMaxSizes{LayoutUnit(30), LayoutUnit(35)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test7"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test7"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); expected = MinMaxSizes{LayoutUnit(80), LayoutUnit(80)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test8"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test8"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); expected = MinMaxSizes{LayoutUnit(150), LayoutUnit(150)}; auto sizes_padding50 = sizes; sizes_padding50 += LayoutUnit(50); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test9"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test9"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes_padding50)); expected = MinMaxSizes{LayoutUnit(100), LayoutUnit(100)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test10"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test10"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes_padding50)); @@ -240,13 +240,13 @@ // Content size should never be below zero, even with box-sizing: border-box // and a large padding... expected = MinMaxSizes{LayoutUnit(400), LayoutUnit(400)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test11"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test11"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes_padding400)); expected.min_size = expected.max_size = sizes.min_size + LayoutUnit(400); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test12"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test12"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes_padding400)); @@ -254,13 +254,13 @@ // Due to padding and box-sizing, width computes to 400px and max-width to // 440px, so the result is 400. expected = MinMaxSizes{LayoutUnit(400), LayoutUnit(400)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test13"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test13"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes_padding400)); expected = MinMaxSizes{LayoutUnit(40), LayoutUnit(40)}; - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test14"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test14"))); EXPECT_EQ(expected, ComputeMinAndMaxContentContributionForTest( WritingMode::kHorizontalTb, node, space, sizes)); } @@ -287,65 +287,65 @@ MinMaxSizes sizes = {LayoutUnit(30), LayoutUnit(40)}; - NGBlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test1"))); + BlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test1"))); EXPECT_EQ(LayoutUnit(60), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test2"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test2"))); EXPECT_EQ(LayoutUnit(200), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test3"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test3"))); EXPECT_EQ(LayoutUnit(150), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test4"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test4"))); EXPECT_EQ(LayoutUnit(200), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test5"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test5"))); EXPECT_EQ(LayoutUnit(80), ComputeInlineSizeForFragment(node)); NGConstraintSpace constraint_space = ConstructConstraintSpace(120, 120, true, true); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test6"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test6"))); EXPECT_EQ(LayoutUnit(120), ComputeInlineSizeForFragment(node, constraint_space)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test7"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test7"))); EXPECT_EQ(LayoutUnit(160), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test8"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test8"))); EXPECT_EQ(LayoutUnit(160), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test9"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test9"))); EXPECT_EQ(LayoutUnit(180), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test10"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test10"))); EXPECT_EQ(LayoutUnit(150), ComputeInlineSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test11"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test11"))); EXPECT_EQ(LayoutUnit(100), ComputeInlineSizeForFragment(node)); // Content size should never be below zero, even with box-sizing: border-box // and a large padding... - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test12"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test12"))); EXPECT_EQ(LayoutUnit(400), ComputeInlineSizeForFragment(node)); auto sizes_padding400 = sizes; sizes_padding400 += LayoutUnit(400); // ...and the same goes for fill-available with a large padding. - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test13"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test13"))); EXPECT_EQ(LayoutUnit(400), ComputeInlineSizeForFragment(node)); constraint_space = ConstructConstraintSpace(120, 140); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test14"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test14"))); EXPECT_EQ(LayoutUnit(430), ComputeInlineSizeForFragment( node, constraint_space, sizes_padding400)); // Due to padding and box-sizing, width computes to 400px and max-width to // 440px, so the result is 400. - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test15"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test15"))); EXPECT_EQ(LayoutUnit(400), ComputeInlineSizeForFragment( node, constraint_space, sizes_padding400)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test16"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test16"))); EXPECT_EQ(LayoutUnit(40), ComputeInlineSizeForFragment(node, constraint_space, sizes)); } @@ -370,69 +370,69 @@ <div id="test16" style="width:100px; aspect-ratio:2/1; padding-right:10px; padding-bottom:20px; box-sizing:border-box;"></div> )HTML"); - NGBlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test1"))); + BlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test1"))); EXPECT_EQ(LayoutUnit(90), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test2"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test2"))); EXPECT_EQ(LayoutUnit(300), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test3"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test3"))); EXPECT_EQ(LayoutUnit(150), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test4"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test4"))); EXPECT_EQ(LayoutUnit(0), ComputeBlockSizeForFragment(node)); NGConstraintSpace constraint_space = ConstructConstraintSpace(200, 300); EXPECT_EQ(LayoutUnit(120), ComputeBlockSizeForFragment(node, constraint_space, LayoutUnit(120))); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test5"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test5"))); EXPECT_EQ(LayoutUnit(70), ComputeBlockSizeForFragment(node)); constraint_space = ConstructConstraintSpace(200, 200, true, true); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test6"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test6"))); EXPECT_EQ(LayoutUnit(200), ComputeBlockSizeForFragment(node, constraint_space)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test7"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test7"))); EXPECT_EQ(LayoutUnit(240), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test8"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test8"))); EXPECT_EQ(LayoutUnit(240), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test9"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test9"))); EXPECT_EQ(LayoutUnit(280), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test10"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test10"))); EXPECT_EQ(LayoutUnit(150), ComputeBlockSizeForFragment(node)); - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test11"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test11"))); EXPECT_EQ(LayoutUnit(100), ComputeBlockSizeForFragment(node)); // Content size should never be below zero, even with box-sizing: border-box // and a large padding... - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test12"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test12"))); EXPECT_EQ(LayoutUnit(400), ComputeBlockSizeForFragment(node)); // ...and the same goes for fill-available with a large padding. - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test13"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test13"))); EXPECT_EQ(LayoutUnit(400), ComputeBlockSizeForFragment(node)); // Now check aspect-ratio. - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test14"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test14"))); EXPECT_EQ(LayoutUnit(50), ComputeBlockSizeForFragment( node, ConstructConstraintSpace(200, 300), LayoutUnit(), LayoutUnit(100))); // Default box-sizing // Should be (100 - 10) / 2 + 20 = 65. - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test15"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test15"))); EXPECT_EQ(LayoutUnit(65), ComputeBlockSizeForFragment( node, ConstructConstraintSpace(200, 300), LayoutUnit(20), LayoutUnit(100))); // With box-sizing: border-box, should be 50. - node = NGBlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test16"))); + node = BlockNode(To<LayoutBox>(GetLayoutObjectByElementId("test16"))); EXPECT_EQ(LayoutUnit(50), ComputeBlockSizeForFragment( node, ConstructConstraintSpace(200, 300), LayoutUnit(20), LayoutUnit(100))); @@ -443,7 +443,7 @@ <div id="test" style="min-height:20px; height:20%;"></div> )HTML"); - NGBlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test"))); + BlockNode node(To<LayoutBox>(GetLayoutObjectByElementId("test"))); EXPECT_EQ(kIndefiniteSize, ComputeBlockSizeForFragment(node, ConstructConstraintSpace(200, -1), LayoutUnit(-1))); @@ -467,7 +467,7 @@ } </style> <span><svg></svg></span>)HTML"); - // Pass if no DCHECK failures in NGBlockNode::FinishLayout(). + // Pass if no DCHECK failures in BlockNode::FinishLayout(). } TEST_F(NGLengthUtilsTest, TestMargins) {
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc index 747cbf84..168cef8 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.cc
@@ -325,7 +325,7 @@ // static absl::optional<LogicalSize> -OutOfFlowLayoutPart::InitialContainingBlockFixedSize(NGBlockNode container) { +OutOfFlowLayoutPart::InitialContainingBlockFixedSize(BlockNode container) { if (!container.GetLayoutBox()->IsLayoutView() || container.GetDocument().Printing()) return absl::nullopt; @@ -337,7 +337,7 @@ } OutOfFlowLayoutPart::OutOfFlowLayoutPart( - const NGBlockNode& container_node, + const BlockNode& container_node, const NGConstraintSpace& container_space, NGBoxFragmentBuilder* container_builder) : container_builder_(container_builder), @@ -362,9 +362,9 @@ !container_node.IsGrid() && !has_block_fragmentation_; default_containing_block_info_for_absolute_.writing_direction = - ConstraintSpace().GetWritingDirection(); + GetConstraintSpace().GetWritingDirection(); default_containing_block_info_for_fixed_.writing_direction = - ConstraintSpace().GetWritingDirection(); + GetConstraintSpace().GetWritingDirection(); if (container_builder_->HasBlockSize()) { default_containing_block_info_for_absolute_.rect.size = ShrinkLogicalSize(container_builder_->Size(), border_scrollbar); @@ -616,7 +616,7 @@ LogicalSize container_builder_size = container_builder_->Size(); PhysicalSize container_builder_physical_size = ToPhysicalSize( - container_builder_size, ConstraintSpace().GetWritingMode()); + container_builder_size, GetConstraintSpace().GetWritingMode()); AddInlineContainingBlockInfo( inline_container_fragments, default_containing_block_info_for_absolute_.writing_direction, @@ -811,12 +811,12 @@ // current builder. Thus, we need to adjust the start offset to take the // writing mode of the builder into account. PhysicalSize physical_size = - ToPhysicalSize(inline_cb_size, ConstraintSpace().GetWritingMode()); + ToPhysicalSize(inline_cb_size, GetConstraintSpace().GetWritingMode()); start_offset = start_offset .ConvertToPhysical(container_writing_direction, container_builder_size, physical_size) - .ConvertToLogical(ConstraintSpace().GetWritingDirection(), + .ConvertToLogical(GetConstraintSpace().GetWritingDirection(), container_builder_size, physical_size); } @@ -945,7 +945,7 @@ while (!multicols_with_pending_oofs.empty()) { for (auto& multicol : multicols_with_pending_oofs) - LayoutOOFsInMulticol(NGBlockNode(multicol.key), multicol.value); + LayoutOOFsInMulticol(BlockNode(multicol.key), multicol.value); multicols_with_pending_oofs.clear(); container_builder->SwapMulticolsWithPendingOOFs( &multicols_with_pending_oofs); @@ -953,7 +953,7 @@ } void OutOfFlowLayoutPart::LayoutOOFsInMulticol( - const NGBlockNode& multicol, + const BlockNode& multicol, const MulticolWithPendingOofs<LogicalOffset>* multicol_info) { HeapVector<LogicalOofNodeForFragmentation> oof_nodes_to_layout; ClearCollectionScope<HeapVector<LogicalOofNodeForFragmentation>> @@ -1517,7 +1517,7 @@ if (container_builder_->Node().IsPaginatedRoot()) { // Finish repeated fixed-positioned elements. for (const NodeToLayout& node_to_layout : repeated_fixedpos_descendants) { - const NGBlockNode& node = node_to_layout.node_info.node; + const BlockNode& node = node_to_layout.node_info.node; DCHECK_EQ(node.Style().GetPosition(), EPosition::kFixed); node.FinishRepeatableRoot(); } @@ -1528,7 +1528,7 @@ OutOfFlowLayoutPart::NodeInfo OutOfFlowLayoutPart::SetupNodeInfo( const LogicalOofPositionedNode& oof_node) { - NGBlockNode node = oof_node.Node(); + BlockNode node = oof_node.Node(); const NGPhysicalFragment* containing_block_fragment = oof_node.is_for_fragmentation ? To<LogicalOofNodeForFragmentation>(oof_node) @@ -1563,7 +1563,7 @@ LogicalSize container_content_size = container_info.rect.size; PhysicalSize container_physical_content_size = ToPhysicalSize( - container_content_size, ConstraintSpace().GetWritingMode()); + container_content_size, GetConstraintSpace().GetWritingMode()); // Adjust the |static_position| (which is currently relative to the default // container's border-box). ng_absolute_utils expects the static position to @@ -1580,13 +1580,13 @@ LogicalStaticPosition oof_static_position = static_position - .ConvertToPhysical({ConstraintSpace().GetWritingDirection(), + .ConvertToPhysical({GetConstraintSpace().GetWritingDirection(), container_physical_content_size}) .ConvertToLogical( {oof_writing_direction, container_physical_content_size}); // Need a constraint space to resolve offsets. - NGConstraintSpaceBuilder builder(ConstraintSpace(), oof_writing_direction, + NGConstraintSpaceBuilder builder(GetConstraintSpace(), oof_writing_direction, /* is_new_fc */ true); builder.SetAvailableSize(container_content_size); builder.SetPercentageResolutionSize(container_content_size); @@ -1595,7 +1595,7 @@ // The |fragmentainer_offset_delta| will not make a difference in the // initial column balancing pass. SetupSpaceBuilderForFragmentation( - ConstraintSpace(), node, + GetConstraintSpace(), node, /* fragmentainer_offset_delta */ LayoutUnit(), &builder, /* is_new_fc */ true, /* requires_content_before_breaking */ false); @@ -1615,7 +1615,7 @@ return NodeInfo(node, builder.ToConstraintSpace(), oof_static_position, container_physical_content_size, container_info, - ConstraintSpace().GetWritingDirection(), + GetConstraintSpace().GetWritingDirection(), /* is_fragmentainer_descendant */ containing_block_fragment, containing_block, fixedpos_containing_block, fixedpos_inline_container, @@ -1640,7 +1640,7 @@ is_last_fragmentainer_so_far); // Since out-of-flow positioning sets up a constraint space with fixed - // inline-size, the regular layout code (|NGBlockNode::Layout()|) cannot + // inline-size, the regular layout code (|BlockNode::Layout()|) cannot // re-layout if it discovers that a scrollbar was added or removed. Handle // that situation here. The assumption is that if intrinsic logical widths are // dirty after layout, AND its inline-size depends on the intrinsic logical @@ -1656,7 +1656,7 @@ scrollbars_after.InlineSum() && scrollbars_after.BlockSum(); // If we're in a measure pass, freeze both scrollbars right away, to avoid // quadratic time complexity for deeply nested flexboxes. - if (ConstraintSpace().CacheSlot() == NGCacheSlot::kMeasure) { + if (GetConstraintSpace().CacheSlot() == NGCacheSlot::kMeasure) { freeze_horizontal = freeze_vertical = true; ignore_first_inline_freeze = false; } @@ -2055,7 +2055,7 @@ // layout pass, if needed. Also do this if we're inside repeatable content, as // the pre-computed layout result is unusable then. if (fragmentainer_constraint_space || - ConstraintSpace().IsInsideRepeatableContent()) { + GetConstraintSpace().IsInsideRepeatableContent()) { layout_result = nullptr; } @@ -2120,7 +2120,7 @@ const NodeInfo& node_info = oof_node_to_layout.node_info; const OffsetInfo& offset_info = oof_node_to_layout.offset_info; const NGBlockBreakToken* break_token = oof_node_to_layout.break_token; - const NGBlockNode& node = node_info.node; + const BlockNode& node = node_info.node; const auto& style = node.Style(); const LayoutUnit block_offset = offset_info.offset.block_offset; LogicalSize container_content_size_in_candidate_writing_mode = @@ -2137,10 +2137,10 @@ PhysicalSize physical_size = ToPhysicalSize(logical_size, style.GetWritingMode()); LogicalSize available_size = - physical_size.ConvertToLogical(ConstraintSpace().GetWritingMode()); + physical_size.ConvertToLogical(GetConstraintSpace().GetWritingMode()); bool is_repeatable = false; - NGConstraintSpaceBuilder builder(ConstraintSpace(), + NGConstraintSpaceBuilder builder(GetConstraintSpace(), style.GetWritingDirection(), /* is_new_fc */ true); builder.SetAvailableSize(available_size); @@ -2195,7 +2195,8 @@ } } else if (container_builder_->IsInitialColumnBalancingPass()) { SetupSpaceBuilderForFragmentation( - ConstraintSpace(), node, block_offset, &builder, /* is_new_fc */ true, + GetConstraintSpace(), node, block_offset, &builder, + /* is_new_fc */ true, /* requires_content_before_breaking */ false); } NGConstraintSpace space = builder.ToConstraintSpace(); @@ -2242,7 +2243,7 @@ const auto& fragmentainer = children[index]; DCHECK(fragmentainer.fragment->IsFragmentainerBox()); - const NGBlockNode& node = container_builder_->Node(); + const BlockNode& node = container_builder_->Node(); const auto* fragment = To<NGPhysicalBoxFragment>(fragmentainer.fragment.Get()); FragmentGeometry fragment_geometry = @@ -2542,7 +2543,7 @@ NGBreakAppeal min_break_appeal = kBreakAppealLastResort; return CreateConstraintSpaceForFragmentainer( - ConstraintSpace(), GetFragmentainerType(), column_size, + GetConstraintSpace(), GetFragmentainerType(), column_size, percentage_resolution_size, /* balance_columns */ false, min_break_appeal); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h index 458efb01..c79098dc 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part.h
@@ -42,7 +42,7 @@ STACK_ALLOCATED(); public: - OutOfFlowLayoutPart(const NGBlockNode& container_node, + OutOfFlowLayoutPart(const BlockNode& container_node, const NGConstraintSpace& container_space, NGBoxFragmentBuilder* container_builder); void Run(); @@ -149,7 +149,7 @@ DISALLOW_NEW(); public: - NGBlockNode node; + BlockNode node; const NGConstraintSpace constraint_space; const LogicalStaticPosition static_position; PhysicalSize container_physical_content_size; @@ -161,7 +161,7 @@ bool inline_container = false; bool requires_content_before_breaking = false; - NodeInfo(NGBlockNode node, + NodeInfo(BlockNode node, const NGConstraintSpace constraint_space, const LogicalStaticPosition static_position, PhysicalSize container_physical_content_size, @@ -255,7 +255,7 @@ }; static absl::optional<LogicalSize> InitialContainingBlockFixedSize( - NGBlockNode container); + BlockNode container); private: const ContainingBlockInfo GetContainingBlockInfo( @@ -266,8 +266,8 @@ return kFragmentPage; return kFragmentColumn; } - const NGConstraintSpace& ConstraintSpace() const { - return container_builder_->ConstraintSpace(); + const NGConstraintSpace& GetConstraintSpace() const { + return container_builder_->GetConstraintSpace(); } void ComputeInlineContainingBlocks( @@ -291,7 +291,7 @@ void HandleMulticolsWithPendingOOFs(NGBoxFragmentBuilder* container_builder); void LayoutOOFsInMulticol( - const NGBlockNode& multicol, + const BlockNode& multicol, const MulticolWithPendingOofs<LogicalOffset>* multicol_info); // Layout the OOF nodes that are descendants of a fragmentation context root.
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc index d48a283..f5846f1 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_layout_part_test.cc
@@ -18,7 +18,7 @@ class OutOfFlowLayoutPartTest : public BaseLayoutAlgorithmTest { protected: const NGPhysicalBoxFragment* RunBlockLayoutAlgorithm(Element* element) { - NGBlockNode container(element->GetLayoutBox()); + BlockNode container(element->GetLayoutBox()); NGConstraintSpace space = ConstructBlockLayoutTestConstraintSpace( {WritingMode::kHorizontalTb, TextDirection::kLtr}, LogicalSize(LayoutUnit(1000), kIndefiniteSize));
diff --git a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h index 3ede3db6e1..80440ffb 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h +++ b/third_party/blink/renderer/core/layout/ng/ng_out_of_flow_positioned_node.h
@@ -164,7 +164,7 @@ OofInlineContainer<PhysicalOffset> inline_container; PhysicalOofPositionedNode( - NGBlockNode node, + BlockNode node, PhysicalStaticPosition static_position, bool requires_content_before_breaking, OofInlineContainer<PhysicalOffset> inline_container = {}) @@ -178,7 +178,7 @@ DCHECK(node.IsBlock()); } - NGBlockNode Node() const { return NGBlockNode(box); } + BlockNode Node() const { return BlockNode(box); } HorizontalEdge GetStaticPositionHorizontalEdge() const { return static_cast<HorizontalEdge>(static_position_horizontal_edge); } @@ -213,7 +213,7 @@ unsigned requires_content_before_breaking : 1; LogicalOofPositionedNode( - NGBlockNode node, + BlockNode node, LogicalStaticPosition static_position, bool requires_content_before_breaking, OofInlineContainer<LogicalOffset> inline_container = {}) @@ -225,7 +225,7 @@ DCHECK(node.IsBlock()); } - NGBlockNode Node() const { return NGBlockNode(box); } + BlockNode Node() const { return BlockNode(box); } void Trace(Visitor* visitor) const; void TraceAfterDispatch(Visitor*) const; @@ -258,7 +258,7 @@ OofInlineContainer<PhysicalOffset> fixedpos_inline_container; PhysicalOofNodeForFragmentation( - NGBlockNode node, + BlockNode node, PhysicalStaticPosition static_position, bool requires_content_before_breaking, OofInlineContainer<PhysicalOffset> inline_container = {}, @@ -294,7 +294,7 @@ OofInlineContainer<LogicalOffset> fixedpos_inline_container; LogicalOofNodeForFragmentation( - NGBlockNode node, + BlockNode node, LogicalStaticPosition static_position, bool requires_content_before_breaking, OofInlineContainer<LogicalOffset> inline_container = {},
diff --git a/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc index 0be6548..a701b59 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.cc
@@ -21,8 +21,7 @@ const NGLayoutResult* PageLayoutAlgorithm::Layout() { DCHECK(!BreakToken()); - WritingDirectionMode writing_direction = - ConstraintSpace().GetWritingDirection(); + auto writing_direction = GetConstraintSpace().GetWritingDirection(); const NGBlockBreakToken* break_token = nullptr; LayoutUnit intrinsic_block_size; LogicalOffset page_offset; @@ -68,11 +67,11 @@ // Compute the block-axis size now that we know our content size. LayoutUnit block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), /* border_padding */ BoxStrut(), + GetConstraintSpace(), Style(), /* border_padding */ BoxStrut(), intrinsic_block_size, absl::nullopt); container_builder_.SetFragmentsTotalBlockSize(block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); } @@ -88,7 +87,7 @@ const AtomicString& page_name, const NGBlockBreakToken* break_token) const { const LayoutView* view = Node().GetDocument().GetLayoutView(); - WritingMode writing_mode = ConstraintSpace().GetWritingMode(); + WritingMode writing_mode = GetConstraintSpace().GetWritingMode(); LogicalSize page_size = view->PageAreaSize(page_index, page_name).ConvertToLogical(writing_mode); @@ -106,8 +105,9 @@ NGConstraintSpace PageLayoutAlgorithm::CreateConstraintSpaceForPages( const LogicalSize& page_size) const { - NGConstraintSpaceBuilder space_builder( - ConstraintSpace(), Style().GetWritingDirection(), /* is_new_fc */ true); + NGConstraintSpaceBuilder space_builder(GetConstraintSpace(), + Style().GetWritingDirection(), + /* is_new_fc */ true); space_builder.SetAvailableSize(page_size); space_builder.SetPercentageResolutionSize(page_size); space_builder.SetInlineAutoBehavior(NGAutoBehavior::kStretchImplicit);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h index 07bfbde..48cb00b7 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_page_layout_algorithm.h
@@ -12,13 +12,13 @@ namespace blink { -class NGBlockNode; +class BlockNode; class NGBlockBreakToken; class NGConstraintSpace; struct LogicalSize; class CORE_EXPORT PageLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc index c6dc6b1f..4436234f 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_box_fragment.cc
@@ -156,10 +156,10 @@ builder->initial_fragment_geometry_->scrollbar.ConvertToPhysical( writing_direction); NGLayoutOverflowCalculator calculator( - To<NGBlockNode>(builder->node_), + To<BlockNode>(builder->node_), /* is_css_box */ !builder->IsFragmentainerBoxType(), - builder->ConstraintSpace().HasBlockFragmentation(), borders, scrollbar, - padding, physical_size, writing_direction); + builder->GetConstraintSpace().HasBlockFragmentation(), borders, + scrollbar, padding, physical_size, writing_direction); if (FragmentItemsBuilder* items_builder = builder->ItemsBuilder()) { calculator.AddItems(builder->GetLayoutObject(),
diff --git a/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc b/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc index 0c8b600..3921810 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_physical_fragment.cc
@@ -1024,7 +1024,7 @@ bool NGPhysicalFragment::DependsOnPercentageBlockSize( const NGFragmentBuilder& builder) { - NGLayoutInputNode node = builder.node_; + LayoutInputNode node = builder.node_; if (!node || node.IsInline()) return builder.has_descendant_that_depends_on_percentage_block_size_;
diff --git a/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.cc index 66660c4..df32cb1f 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.cc
@@ -24,7 +24,7 @@ // the intrinsic block size for NON-replaced elements. This is inconsistent // and could lead to subtle bugs. const LayoutUnit intrinsic_block_size = - ComputeReplacedSize(Node(), ConstraintSpace(), BorderPadding(), + ComputeReplacedSize(Node(), GetConstraintSpace(), BorderPadding(), /* override_available_size */ absl::nullopt, ReplacedSizeMode::kIgnoreBlockLengths) .block_size; @@ -44,7 +44,7 @@ // This is only used by flex, which expects inline-lengths to be ignored for // the min/max content size. MinMaxSizes sizes; - sizes = ComputeReplacedSize(Node(), ConstraintSpace(), BorderPadding(), + sizes = ComputeReplacedSize(Node(), GetConstraintSpace(), BorderPadding(), /* override_available_size */ absl::nullopt, ReplacedSizeMode::kIgnoreInlineLengths) .inline_size; @@ -54,19 +54,19 @@ Style().LogicalMinHeight().IsPercentOrCalc() || Style().LogicalMaxHeight().IsPercentOrCalc() || (Style().LogicalHeight().IsAuto() && - ConstraintSpace().IsBlockAutoBehaviorStretch()); + GetConstraintSpace().IsBlockAutoBehaviorStretch()); return {sizes, depends_on_block_constraints}; } void ReplacedLayoutAlgorithm::LayoutMediaChildren() { - WritingModeConverter converter(ConstraintSpace().GetWritingDirection(), + WritingModeConverter converter(GetConstraintSpace().GetWritingDirection(), container_builder_.Size()); LogicalRect logical_new_rect( BorderPadding().StartOffset(), ShrinkLogicalSize(container_builder_.Size(), BorderPadding())); PhysicalRect new_rect = converter.ToPhysical(logical_new_rect); - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { LayoutUnit width = new_rect.Width(); if (child.GetDOMNode()->IsMediaControls()) { @@ -74,16 +74,17 @@ To<LayoutMedia>(Node().GetLayoutBox())->ComputePanelWidth(new_rect); } - NGConstraintSpaceBuilder space_builder(ConstraintSpace().GetWritingMode(), - child.Style().GetWritingDirection(), - /* is_new_fc */ true); + NGConstraintSpaceBuilder space_builder( + GetConstraintSpace().GetWritingMode(), + child.Style().GetWritingDirection(), + /* is_new_fc */ true); LogicalSize child_size = converter.ToLogical({width, new_rect.Height()}); space_builder.SetAvailableSize(child_size); space_builder.SetIsFixedInlineSize(true); space_builder.SetIsFixedBlockSize(true); const NGLayoutResult* result = - To<NGBlockNode>(child).Layout(space_builder.ToConstraintSpace()); + To<BlockNode>(child).Layout(space_builder.ToConstraintSpace()); LogicalOffset offset = converter.ToLogical(new_rect.offset, result->PhysicalFragment().Size()); container_builder_.AddResult(*result, offset);
diff --git a/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.h index b3d763b..1783507 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_replaced_layout_algorithm.h
@@ -12,11 +12,11 @@ namespace blink { -class NGBlockNode; +class BlockNode; class NGBlockBreakToken; class CORE_EXPORT ReplacedLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc index 3b53ba5..1b633b4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.cc
@@ -58,7 +58,7 @@ container_builder_.SetEndMarginStrut(result.EndMarginStrut()); // Ensure that the parent layout hasn't asked us to move our BFC position. - DCHECK_EQ(ConstraintSpace().GetBfcOffset(), + DCHECK_EQ(GetConstraintSpace().GetBfcOffset(), previous_result_.GetConstraintSpaceForCaching().GetBfcOffset()); container_builder_.SetBfcLineOffset(result.BfcLineOffset()); if (result.BfcBlockOffset()) @@ -75,7 +75,7 @@ container_builder_.SetIsPushedByFloats(); container_builder_.SetAdjoiningObjectTypes(result.AdjoiningObjectTypes()); - if (ConstraintSpace().IsTableCell()) { + if (GetConstraintSpace().IsTableCell()) { container_builder_.SetHasCollapsedBorders( physical_fragment.HasCollapsedBorders()); container_builder_.SetTableCellColumnIndex( @@ -92,7 +92,7 @@ DCHECK(!result.SubtreeModifiedMarginStrut()); DCHECK(result.EndMarginStrut().IsEmpty()); - DCHECK_EQ(ConstraintSpace().GetBfcOffset(), BfcOffset()); + DCHECK_EQ(GetConstraintSpace().GetBfcOffset(), BfcOffset()); DCHECK_EQ(result.BfcLineOffset(), LayoutUnit()); DCHECK_EQ(result.BfcBlockOffset().value_or(LayoutUnit()), LayoutUnit()); @@ -175,7 +175,7 @@ auto ComputeNewBlockSize = [&]() -> LayoutUnit { return ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), BorderPadding(), + GetConstraintSpace(), Style(), BorderPadding(), result.IntrinsicBlockSize(), container_builder_.InitialBorderBoxSize().inline_size); }; @@ -251,7 +251,7 @@ // Add the (potentially updated) layout result. const NGLayoutResult* result = - NGBlockNode(To<LayoutBox>(child_fragment.GetMutableLayoutObject())) + BlockNode(To<LayoutBox>(child_fragment.GetMutableLayoutObject())) .SimplifiedLayout(child_fragment); // The child may have failed "simplified" layout! (Due to adding/removing @@ -270,7 +270,7 @@ } // Iterate through all our OOF-positioned children and add them as candidates. - for (NGLayoutInputNode child = Node().FirstChild(); child; + for (LayoutInputNode child = Node().FirstChild(); child; child = child.NextSibling()) { if (!child.IsOutOfFlowPositioned()) continue; @@ -281,7 +281,7 @@ const auto* layer = child.GetLayoutBox()->Layer(); LogicalStaticPosition position = layer->GetStaticPosition(); container_builder_.AddOutOfFlowChildCandidate( - To<NGBlockNode>(child), position.offset, position.inline_edge, + To<BlockNode>(child), position.offset, position.inline_edge, position.block_edge); } @@ -317,7 +317,7 @@ previous_result_.InitialBreakBefore()); container_builder_.SetPreviousBreakAfter(previous_result_.FinalBreakAfter()); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.h index 3ecaed551..b4018b4 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_simplified_layout_algorithm.h
@@ -37,7 +37,7 @@ // "simplified" layout on its children). // 3. Run the |OutOfFlowLayoutPart|. class CORE_EXPORT SimplifiedLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.cc b/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.cc index 89bd77b..f2c0e4e 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.cc
@@ -76,7 +76,8 @@ } const NGLayoutResult* SimplifiedOofLayoutAlgorithm::Layout() { - FinishFragmentationForFragmentainer(ConstraintSpace(), &container_builder_); + FinishFragmentationForFragmentainer(GetConstraintSpace(), + &container_builder_); return container_builder_.ToBoxFragment(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.h b/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.h index bc724c3e..79ddf84 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/ng/ng_simplified_oof_layout_algorithm.h
@@ -22,7 +22,7 @@ // previous |NGPhysicalFragment| and appends the OOF-positioned elements to the // |container_builder_|. class CORE_EXPORT SimplifiedOofLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc b/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc index d5ad7d2..6c926be 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc +++ b/third_party/blink/renderer/core/layout/ng/ng_space_utils.cc
@@ -25,7 +25,7 @@ } void SetOrthogonalFallbackInlineSize(const ComputedStyle& parent_style, - const NGLayoutInputNode child, + const LayoutInputNode child, NGConstraintSpaceBuilder* builder) { DCHECK(!IsParallelWritingMode(parent_style.GetWritingMode(), child.Style().GetWritingMode())); @@ -78,7 +78,7 @@ } bool ShouldBlockContainerChildStretchAutoInlineSize( - const NGLayoutInputNode& child) { + const LayoutInputNode& child) { return !child.GetLayoutBox()->AutoWidthShouldFitContent() && !child.IsReplaced() && !child.IsTable(); }
diff --git a/third_party/blink/renderer/core/layout/ng/ng_space_utils.h b/third_party/blink/renderer/core/layout/ng/ng_space_utils.h index 06b66f4..1438205 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_space_utils.h +++ b/third_party/blink/renderer/core/layout/ng/ng_space_utils.h
@@ -30,12 +30,12 @@ // // [1] https://www.w3.org/TR/css-writing-modes-3/#orthogonal-auto void SetOrthogonalFallbackInlineSize(const ComputedStyle& parent_style, - const NGLayoutInputNode child, + const LayoutInputNode child, NGConstraintSpaceBuilder* builder); inline void SetOrthogonalFallbackInlineSizeIfNeeded( const ComputedStyle& parent_style, - const NGLayoutInputNode child, + const LayoutInputNode child, NGConstraintSpaceBuilder* builder) { if (LIKELY(IsParallelWritingMode(parent_style.GetWritingMode(), child.Style().GetWritingMode()))) @@ -46,7 +46,7 @@ // Only to be called if the child is in a writing-mode parallel with its // container. Return true if an auto inline-size means that the child should be // stretched (rather than being shrink-to-fit). -bool ShouldBlockContainerChildStretchAutoInlineSize(const NGLayoutInputNode&); +bool ShouldBlockContainerChildStretchAutoInlineSize(const LayoutInputNode&); } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h b/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h index a8f77fc..8921049 100644 --- a/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h +++ b/third_party/blink/renderer/core/layout/ng/ng_unpositioned_float.h
@@ -26,7 +26,7 @@ STACK_ALLOCATED(); public: - UnpositionedFloat(NGBlockNode node, + UnpositionedFloat(BlockNode node, const NGBlockBreakToken* token, const LogicalSize available_size, const LogicalSize percentage_size, @@ -43,7 +43,7 @@ parent_space(parent_space), parent_style(parent_style) {} - NGBlockNode node; + BlockNode node; const NGBlockBreakToken* token = nullptr; const LogicalSize available_size;
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc index f217a18..58e35fb 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_foreign_object.cc
@@ -146,7 +146,7 @@ builder.SetAvailableSize(zoomed_size); builder.SetIsFixedInlineSize(true); builder.SetIsFixedBlockSize(true); - const auto* result = NGBlockNode(this).Layout(builder.ToConstraintSpace()); + const auto* result = BlockNode(this).Layout(builder.ToConstraintSpace()); // Any propagated sticky-descendants may have invalid sticky-constraints. // Clear them now.
diff --git a/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc b/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc index 7d99831f..0c9a6c0 100644 --- a/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc +++ b/third_party/blink/renderer/core/layout/svg/layout_svg_text.cc
@@ -245,7 +245,7 @@ style.GetWritingMode(), style.GetWritingDirection(), /* is_new_fc */ true, /* adjust_inline_size_if_needed */ false); builder.SetAvailableSize(LogicalSize()); - NGBlockNode(this).Layout(builder.ToConstraintSpace()); + BlockNode(this).Layout(builder.ToConstraintSpace()); needs_update_bounding_box_ = true;
diff --git a/third_party/blink/renderer/core/layout/table/layout_table.cc b/third_party/blink/renderer/core/layout/table/layout_table.cc index f78a5291..a1f2aa0 100644 --- a/third_party/blink/renderer/core/layout/table/layout_table.cc +++ b/third_party/blink/renderer/core/layout/table/layout_table.cc
@@ -76,7 +76,7 @@ return false; } TableGroupedChildren grouped_children( - NGBlockNode(const_cast<LayoutTable*>(this))); + BlockNode(const_cast<LayoutTable*>(this))); auto first_section = grouped_children.begin(); return first_section != grouped_children.end() && (*first_section).GetLayoutBox() == section; @@ -85,7 +85,7 @@ LayoutTableSection* LayoutTable::FirstSection() const { NOT_DESTROYED(); TableGroupedChildren grouped_children( - NGBlockNode(const_cast<LayoutTable*>(this))); + BlockNode(const_cast<LayoutTable*>(this))); auto first_section = grouped_children.begin(); if (first_section != grouped_children.end()) { return To<LayoutTableSection>((*first_section).GetLayoutBox()); @@ -96,7 +96,7 @@ LayoutTableSection* LayoutTable::FirstNonEmptySection() const { NOT_DESTROYED(); TableGroupedChildren grouped_children( - NGBlockNode(const_cast<LayoutTable*>(this))); + BlockNode(const_cast<LayoutTable*>(this))); auto first_section = grouped_children.begin(); if (first_section != grouped_children.end()) { auto* section_object = @@ -112,7 +112,7 @@ LayoutTableSection* LayoutTable::LastNonEmptySection() const { NOT_DESTROYED(); TableGroupedChildren grouped_children( - NGBlockNode(const_cast<LayoutTable*>(this))); + BlockNode(const_cast<LayoutTable*>(this))); auto last_section = --grouped_children.end(); if (last_section != grouped_children.end()) { auto* section_object = @@ -130,9 +130,9 @@ SkipEmptySectionsValue skip) const { NOT_DESTROYED(); TableGroupedChildren grouped_children( - NGBlockNode(const_cast<LayoutTable*>(this))); + BlockNode(const_cast<LayoutTable*>(this))); bool found = false; - for (NGBlockNode section : grouped_children) { + for (BlockNode section : grouped_children) { if (found && (skip == kDoNotSkipEmptySections || !section.IsEmptyTableSection())) { return To<LayoutTableSection>(section.GetLayoutBox()); @@ -149,11 +149,11 @@ SkipEmptySectionsValue skip) const { NOT_DESTROYED(); TableGroupedChildren grouped_children( - NGBlockNode(const_cast<LayoutTable*>(this))); + BlockNode(const_cast<LayoutTable*>(this))); auto stop = --grouped_children.begin(); bool found = false; for (auto it = --grouped_children.end(); it != stop; --it) { - NGBlockNode section = *it; + BlockNode section = *it; if (found && (skip == kDoNotSkipEmptySections || !section.IsEmptyTableSection())) { return To<LayoutTableSection>(section.GetLayoutBox());
diff --git a/third_party/blink/renderer/core/layout/table/layout_table_column.cc b/third_party/blink/renderer/core/layout/table/layout_table_column.cc index 0e97495..5c2783a 100644 --- a/third_party/blink/renderer/core/layout/table/layout_table_column.cc +++ b/third_party/blink/renderer/core/layout/table/layout_table_column.cc
@@ -19,7 +19,7 @@ // `LayoutTable::HasBackgroundForPaint`). Used to know whether the table // background should be invalidated when some column span changes. bool TableHasColumnsWithBackground(LayoutTable* table) { - TableGroupedChildren grouped_children(NGBlockNode(To<LayoutBox>(table))); + TableGroupedChildren grouped_children(BlockNode(To<LayoutBox>(table))); for (const auto& column : grouped_children.columns) { if (column.Style().HasBackground()) { return true; @@ -27,7 +27,7 @@ // Iterate through a colgroup's children. if (column.IsTableColgroup()) { - NGLayoutInputNode node = column.FirstChild(); + LayoutInputNode node = column.FirstChild(); while (node) { DCHECK(node.IsTableCol()); if (node.Style().HasBackground()) {
diff --git a/third_party/blink/renderer/core/layout/table/layout_table_column_visitor.h b/third_party/blink/renderer/core/layout/table/layout_table_column_visitor.h index bb2250fd..d97133e 100644 --- a/third_party/blink/renderer/core/layout/table/layout_table_column_visitor.h +++ b/third_party/blink/renderer/core/layout/table/layout_table_column_visitor.h
@@ -20,23 +20,23 @@ // traversal, and computes correct spans. // // class Visitor { -// void VisitCol(const NGBlockNode& column, +// void VisitCol(const BlockNode& column, // wtf_size_t start_column_index, // wtf_size_t span); -// void EnterColgroup(const NGBlockNode& colgroup, +// void EnterColgroup(const BlockNode& colgroup, // wtf_size_t start_column_index); -// void LeaveColgroup(const NGBlockNode& colgroup, +// void LeaveColgroup(const BlockNode& colgroup, // wtf_size_t start_column_index, // wtf_size_t span, // bool has_children); // } template <typename Visitor> -void VisitLayoutTableColumn(const HeapVector<NGBlockNode>& columns, +void VisitLayoutTableColumn(const HeapVector<BlockNode>& columns, wtf_size_t table_column_count, Visitor* visitor) { wtf_size_t current_column_index = 0; - auto VisitCol = [&](const NGBlockNode& col) { + auto VisitCol = [&](const BlockNode& col) { wtf_size_t span = col.TableColumnSpan(); span = std::min(span, table_column_count - current_column_index); visitor->VisitCol(col, current_column_index, span); @@ -44,7 +44,7 @@ return span; }; - for (const NGBlockNode& table_column : columns) { + for (const BlockNode& table_column : columns) { // Col spans can cause columns to extend beyond table's edge. // These columns are ignored. if (current_column_index >= table_column_count) @@ -56,7 +56,7 @@ DCHECK(table_column.IsTableColgroup()); // Visit COLGROUP element. visitor->EnterColgroup(table_column, current_column_index); - NGBlockNode col_child = To<NGBlockNode>(table_column.FirstChild()); + BlockNode col_child = To<BlockNode>(table_column.FirstChild()); wtf_size_t colgroup_start_index = current_column_index; wtf_size_t colgroup_span = 0; bool has_children = bool(col_child); @@ -65,7 +65,7 @@ colgroup_span += VisitCol(col_child); if (current_column_index >= table_column_count) break; - col_child = To<NGBlockNode>(col_child.NextSibling()); + col_child = To<BlockNode>(col_child.NextSibling()); } } else { // If COLGROUP has no children, its span is defined by the COLGROUP.
diff --git a/third_party/blink/renderer/core/layout/table/table_borders.cc b/third_party/blink/renderer/core/layout/table/table_borders.cc index 751dbd2..6d15da8 100644 --- a/third_party/blink/renderer/core/layout/table/table_borders.cc +++ b/third_party/blink/renderer/core/layout/table/table_borders.cc
@@ -49,7 +49,7 @@ STACK_ALLOCATED(); public: - void VisitCol(const NGLayoutInputNode& column, + void VisitCol(const LayoutInputNode& column, wtf_size_t start_column_index, wtf_size_t span) { for (wtf_size_t i = 0; i < span; ++i) { @@ -59,9 +59,9 @@ box_order, table_writing_direction); } } - void EnterColgroup(const NGLayoutInputNode& colgroup, + void EnterColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index) {} - void LeaveColgroup(const NGLayoutInputNode& colgroup, + void LeaveColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index, wtf_size_t span, bool has_children) {} @@ -83,12 +83,12 @@ STACK_ALLOCATED(); public: - void VisitCol(const NGLayoutInputNode& column, + void VisitCol(const LayoutInputNode& column, wtf_size_t start_column_index, wtf_size_t span) {} - void EnterColgroup(const NGLayoutInputNode& colgroup, + void EnterColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index) {} - void LeaveColgroup(const NGLayoutInputNode& colgroup, + void LeaveColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index, wtf_size_t span, bool has_children) { @@ -112,8 +112,7 @@ } // namespace -const TableBorders* TableBorders::ComputeTableBorders( - const NGBlockNode& table) { +const TableBorders* TableBorders::ComputeTableBorders(const BlockNode& table) { const ComputedStyle& table_style = table.Style(); const bool is_collapsed = table_style.BorderCollapse() == EBorderCollapse::kCollapse; @@ -133,14 +132,14 @@ wtf_size_t table_row_index = 0; // Mark cell borders. bool found_multispan_cells = false; - for (const NGBlockNode section : grouped_children) { + for (const BlockNode section : grouped_children) { wtf_size_t section_start_row = table_row_index; ColspanCellTabulator tabulator; - for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row; - row = To<NGBlockNode>(row.NextSibling())) { + for (BlockNode row = To<BlockNode>(section.FirstChild()); row; + row = To<BlockNode>(row.NextSibling())) { tabulator.StartRow(); - for (NGBlockNode cell = To<NGBlockNode>(row.FirstChild()); cell; - cell = To<NGBlockNode>(cell.NextSibling())) { + for (BlockNode cell = To<BlockNode>(row.FirstChild()); cell; + cell = To<BlockNode>(cell.NextSibling())) { tabulator.FindNextFreeColumn(); wtf_size_t cell_colspan = cell.TableCellColspan(); found_multispan_cells |= @@ -176,13 +175,13 @@ // If any cells have rowspan, need to redistribute cell borders. if (found_multispan_cells) { wtf_size_t section_index = 0; - for (NGBlockNode section : grouped_children) { + for (BlockNode section : grouped_children) { ColspanCellTabulator tabulator; - for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row; - row = To<NGBlockNode>(row.NextSibling())) { + for (BlockNode row = To<BlockNode>(section.FirstChild()); row; + row = To<BlockNode>(row.NextSibling())) { tabulator.StartRow(); - for (NGBlockNode cell = To<NGBlockNode>(row.FirstChild()); cell; - cell = To<NGBlockNode>(cell.NextSibling())) { + for (BlockNode cell = To<BlockNode>(row.FirstChild()); cell; + cell = To<BlockNode>(cell.NextSibling())) { tabulator.FindNextFreeColumn(); table_borders->MergeBorders( table_row_index, tabulator.CurrentColumn(), @@ -200,9 +199,9 @@ // Mark row borders. table_row_index = 0; - for (NGBlockNode section : grouped_children) { - for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row; - row = To<NGBlockNode>(row.NextSibling())) { + for (BlockNode section : grouped_children) { + for (BlockNode row = To<BlockNode>(section.FirstChild()); row; + row = To<BlockNode>(row.NextSibling())) { table_borders->MergeBorders(table_row_index, 0, 1, table_column_count, row.Style(), TableBorders::EdgeSource::kRow, ++box_order, table_writing_direction); @@ -214,7 +213,7 @@ // It is tempting to traverse sections at the same time as rows, // but it would cause precedence errors. wtf_size_t section_index = 0; - for (NGBlockNode section : grouped_children) { + for (BlockNode section : grouped_children) { TableBorders::Section section_info = table_borders->GetSection(section_index); table_borders->MergeBorders( @@ -230,12 +229,12 @@ ColBordersMarker col_borders_marker(table_row_count, ++box_order, table_writing_direction, *table_borders); VisitLayoutTableColumn( - const_cast<HeapVector<NGBlockNode>&>(grouped_children.columns), + const_cast<HeapVector<BlockNode>&>(grouped_children.columns), table_column_count, &col_borders_marker); ColgroupBordersMarker colgroup_borders_marker( table_row_count, ++box_order, table_writing_direction, *table_borders); VisitLayoutTableColumn( - const_cast<HeapVector<NGBlockNode>&>(grouped_children.columns), + const_cast<HeapVector<BlockNode>&>(grouped_children.columns), table_column_count, &colgroup_borders_marker); // Mark table borders. @@ -400,7 +399,7 @@ } BoxStrut TableBorders::CellBorder( - const NGBlockNode& cell, + const BlockNode& cell, wtf_size_t row, wtf_size_t column, wtf_size_t section,
diff --git a/third_party/blink/renderer/core/layout/table/table_borders.h b/third_party/blink/renderer/core/layout/table/table_borders.h index ed40847e..111dcf6 100644 --- a/third_party/blink/renderer/core/layout/table/table_borders.h +++ b/third_party/blink/renderer/core/layout/table/table_borders.h
@@ -19,8 +19,8 @@ namespace blink { +class BlockNode; class ComputedStyle; -class NGBlockNode; struct BoxStrut; // When table has collapsed borders, computing borders for table parts is @@ -61,7 +61,7 @@ class TableBorders : public GarbageCollected<TableBorders> { public: - static const TableBorders* ComputeTableBorders(const NGBlockNode&); + static const TableBorders* ComputeTableBorders(const BlockNode&); TableBorders(const BoxStrut& table_border, const bool is_collapsed); @@ -182,7 +182,7 @@ const BoxStrut& TableBorder() const { return table_border_; } - BoxStrut CellBorder(const NGBlockNode& cell, + BoxStrut CellBorder(const BlockNode& cell, wtf_size_t row, wtf_size_t column, wtf_size_t section,
diff --git a/third_party/blink/renderer/core/layout/table/table_child_iterator.cc b/third_party/blink/renderer/core/layout/table/table_child_iterator.cc index 46a34936..4eb1efe3 100644 --- a/third_party/blink/renderer/core/layout/table/table_child_iterator.cc +++ b/third_party/blink/renderer/core/layout/table/table_child_iterator.cc
@@ -48,14 +48,14 @@ TableChildIterator::Entry TableChildIterator::NextChild() { const NGBlockBreakToken* current_child_break_token = nullptr; - NGBlockNode current_child(nullptr); + BlockNode current_child(nullptr); if (break_token_) { const auto& child_break_tokens = break_token_->ChildBreakTokens(); if (child_token_idx_ < child_break_tokens.size()) { current_child_break_token = To<NGBlockBreakToken>(child_break_tokens[child_token_idx_++].Get()); - current_child = To<NGBlockNode>(current_child_break_token->InputNode()); + current_child = To<BlockNode>(current_child_break_token->InputNode()); // Normally (for non-tables), when we're out of break tokens, we can // just proceed to the next sibling node, but we can't do this for @@ -86,9 +86,9 @@ return Entry(current_child, current_child_break_token, current_section_idx); } -NGBlockNode TableChildIterator::CurrentChild() const { +BlockNode TableChildIterator::CurrentChild() const { if (!grouped_children_) - return NGBlockNode(nullptr); // We have nothing. + return BlockNode(nullptr); // We have nothing. if (!section_iterator_) { // We're at a top caption, since we have no iterator yet. @@ -110,7 +110,7 @@ } // We're done. - return NGBlockNode(nullptr); + return BlockNode(nullptr); } void TableChildIterator::AdvanceChild() {
diff --git a/third_party/blink/renderer/core/layout/table/table_child_iterator.h b/third_party/blink/renderer/core/layout/table/table_child_iterator.h index 7f4e032f..8442212 100644 --- a/third_party/blink/renderer/core/layout/table/table_child_iterator.h +++ b/third_party/blink/renderer/core/layout/table/table_child_iterator.h
@@ -31,12 +31,12 @@ STACK_ALLOCATED(); public: - Entry(NGBlockNode node, + Entry(BlockNode node, const NGBlockBreakToken* token, wtf_size_t section_index) : node(node), token(token), section_index(section_index) {} - const NGBlockNode GetNode() const { return node; } + const BlockNode GetNode() const { return node; } const NGBlockBreakToken* GetBreakToken() const { return token; } wtf_size_t GetSectionIndex() const { DCHECK(!node.IsTableCaption()); @@ -45,7 +45,7 @@ explicit operator bool() const { return !!node; } private: - NGBlockNode node; + BlockNode node; const NGBlockBreakToken* token; wtf_size_t section_index; }; @@ -55,7 +55,7 @@ Entry NextChild(); private: - NGBlockNode CurrentChild() const; + BlockNode CurrentChild() const; void AdvanceChild(); const TableGroupedChildren* grouped_children_;
diff --git a/third_party/blink/renderer/core/layout/table/table_fragment_data.h b/third_party/blink/renderer/core/layout/table/table_fragment_data.h index 1e58368c..0edd7c78 100644 --- a/third_party/blink/renderer/core/layout/table/table_fragment_data.h +++ b/third_party/blink/renderer/core/layout/table/table_fragment_data.h
@@ -25,7 +25,7 @@ wtf_size_t span, LayoutUnit inline_offset, LayoutUnit inline_size, - NGLayoutInputNode node) + LayoutInputNode node) : start_column(start_column), span(span), inline_offset(inline_offset), @@ -36,7 +36,7 @@ wtf_size_t span; LayoutUnit inline_offset; LayoutUnit inline_size; - NGLayoutInputNode node; + LayoutInputNode node; }; using ColumnGeometries = HeapVector<ColumnGeometry>;
diff --git a/third_party/blink/renderer/core/layout/table/table_layout_algorithm.cc b/third_party/blink/renderer/core/layout/table/table_layout_algorithm.cc index 30be0225..a178aea 100644 --- a/third_party/blink/renderer/core/layout/table/table_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/table/table_layout_algorithm.cc
@@ -43,7 +43,7 @@ const TableGroupedChildren& grouped_children) { // Caption inline size constraints. TableTypes::Caption caption_min_max; - for (const NGBlockNode& caption : grouped_children.captions) { + for (const BlockNode& caption : grouped_children.captions) { // Caption %-block-sizes are treated as auto, as there isn't a reasonable // block-size to resolve against. NGMinMaxConstraintSpaceBuilder builder(table_space, table_style, caption, @@ -63,7 +63,7 @@ NGConstraintSpace CreateCaptionConstraintSpace( const NGConstraintSpace& table_constraint_space, const ComputedStyle& table_style, - const NGBlockNode& caption, + const BlockNode& caption, LogicalSize available_size, absl::optional<LayoutUnit> block_offset = absl::nullopt) { NGConstraintSpaceBuilder builder(table_constraint_space, @@ -94,7 +94,7 @@ const ComputedStyle& table_style, LayoutUnit table_inline_size, const NGConstraintSpace& caption_constraint_space, - const NGBlockNode& caption, + const BlockNode& caption, BoxStrut margins, const NGBlockBreakToken* break_token = nullptr, const NGEarlyBreak* early_break = nullptr) { @@ -117,7 +117,7 @@ // percentages. BoxStrut ComputeCaptionMargins( const NGConstraintSpace& table_constraint_space, - const NGBlockNode& caption, + const BlockNode& caption, LayoutUnit table_border_box_inline_size, const NGBlockBreakToken* caption_break_token = nullptr) { BoxStrut margins = @@ -134,10 +134,10 @@ HeapVector<TableLayoutAlgorithm::CaptionResult>* captions, LayoutUnit& captions_block_size) { const NGConstraintSpace& table_constraint_space = - table_builder.ConstraintSpace(); + table_builder.GetConstraintSpace(); const LayoutUnit table_inline_size = table_builder.InlineSize(); const LogicalSize available_size = {table_inline_size, kIndefiniteSize}; - for (NGBlockNode caption : grouped_children.captions) { + for (BlockNode caption : grouped_children.captions) { BoxStrut margins = ComputeCaptionMargins(table_constraint_space, caption, table_inline_size); NGConstraintSpace caption_constraint_space = CreateCaptionConstraintSpace( @@ -362,7 +362,7 @@ STACK_ALLOCATED(); public: - void VisitCol(const NGLayoutInputNode& col, + void VisitCol(const LayoutInputNode& col, wtf_size_t start_column_index, wtf_size_t span) { wtf_size_t end_column_index = start_column_index + span - 1; @@ -377,10 +377,10 @@ column_inline_size, col); } - void EnterColgroup(const NGLayoutInputNode& colgroup, + void EnterColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index) {} - void LeaveColgroup(const NGLayoutInputNode& colgroup, + void LeaveColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index, wtf_size_t span, bool has_children) { @@ -569,7 +569,7 @@ const scoped_refptr<const TableTypes::Columns> column_constraints = Node().GetColumnConstraints(grouped_children, border_padding); const TableTypes::Caption caption_constraint = - ComputeCaptionConstraint(ConstraintSpace(), Style(), grouped_children); + ComputeCaptionConstraint(GetConstraintSpace(), Style(), grouped_children); // Compute assignable table inline size. // Standard: https://www.w3.org/TR/css-tables-3/#width-distribution const LayoutUnit undistributable_space = ComputeUndistributableTableSpace( @@ -578,7 +578,7 @@ const LayoutUnit assignable_table_inline_size = ComputeAssignableTableInlineSize( - Node(), ConstraintSpace(), *column_constraints, caption_constraint, + Node(), GetConstraintSpace(), *column_constraints, caption_constraint, undistributable_space, border_padding, is_fixed_layout); // Distribute assignable table width. @@ -596,7 +596,7 @@ const bool is_grid_empty = column_locations.empty(); if (is_grid_empty) { table_inline_size_before_collapse = ComputeEmptyTableInlineSize( - ConstraintSpace(), Style(), assignable_table_inline_size, + GetConstraintSpace(), Style(), assignable_table_inline_size, undistributable_space, caption_constraint, border_padding, table_borders->IsCollapsed()); } else { @@ -638,7 +638,7 @@ (table_inline_size_before_collapse - container_builder_.InlineSize()) .Abs(), LayoutUnit(1)); - } else if (ConstraintSpace().IsFixedInlineSize()) { + } else if (GetConstraintSpace().IsFixedInlineSize()) { // Collapsed columns + fixed inline size: columns define table whose // inline size is less or equal InitialFragmentGeometry. LayoutUnit table_inline_size = @@ -691,7 +691,7 @@ const scoped_refptr<const TableTypes::Columns> column_constraints = Node().GetColumnConstraints(grouped_children, border_padding); const TableTypes::Caption caption_constraint = - ComputeCaptionConstraint(ConstraintSpace(), Style(), grouped_children); + ComputeCaptionConstraint(GetConstraintSpace(), Style(), grouped_children); const LayoutUnit undistributable_space = ComputeUndistributableTableSpace( *column_constraints, border_padding.InlineSum(), @@ -716,8 +716,8 @@ const NGLayoutResult* TableLayoutAlgorithm::RelayoutAsLastTableBox() { DCHECK(!is_known_to_be_last_table_box_); LayoutAlgorithmParams params( - Node(), container_builder_.InitialFragmentGeometry(), ConstraintSpace(), - BreakToken(), /* early_break */ nullptr); + Node(), container_builder_.InitialFragmentGeometry(), + GetConstraintSpace(), BreakToken(), /* early_break */ nullptr); TableLayoutAlgorithm algorithm(params); algorithm.is_known_to_be_last_table_box_ = true; @@ -773,8 +773,8 @@ } LayoutUnit css_table_block_size; - if (ConstraintSpace().IsInitialBlockSizeIndefinite() && - !ConstraintSpace().IsFixedBlockSize()) { + if (GetConstraintSpace().IsInitialBlockSizeIndefinite() && + !GetConstraintSpace().IsFixedBlockSize()) { // We get here when a flexbox wants to use the table's intrinsic height as // an input to the flex algorithm. css_table_block_size = kIndefiniteSize; @@ -783,20 +783,23 @@ // sections/rows into this space. Pass a definite intrinsic block-size into // |ComputeBlockSizeForFragment| to force it to resolve. LayoutUnit intrinsic_block_size = - BlockLengthUnresolvable(ConstraintSpace(), Style().LogicalMinHeight()) + BlockLengthUnresolvable(GetConstraintSpace(), + Style().LogicalMinHeight()) ? kIndefiniteSize : table_border_padding.BlockSum(); LayoutUnit override_available_block_size = kIndefiniteSize; - if (ConstraintSpace().AvailableSize().block_size != kIndefiniteSize) { + if (GetConstraintSpace().AvailableSize().block_size != kIndefiniteSize) { override_available_block_size = - (ConstraintSpace().AvailableSize().block_size - captions_block_size) + (GetConstraintSpace().AvailableSize().block_size - + captions_block_size) .ClampNegativeToZero(); } css_table_block_size = ComputeBlockSizeForFragment( - ConstraintSpace(), Style(), table_border_padding, intrinsic_block_size, - table_grid_inline_size, override_available_block_size); + GetConstraintSpace(), Style(), table_border_padding, + intrinsic_block_size, table_grid_inline_size, + override_available_block_size); } // In quirks mode, empty tables ignore any specified block-size. const bool is_empty_quirks_mode_table = @@ -898,8 +901,9 @@ const LogicalSize& border_spacing) { const TableBreakTokenData* incoming_table_break_data = nullptr; LogicalBoxSides border_padding_sides_to_include; + const auto& constraint_space = GetConstraintSpace(); const LayoutUnit fragmentainer_space_at_start = - FragmentainerSpaceLeft(ConstraintSpace()); + FragmentainerSpaceLeft(constraint_space); LayoutUnit previously_consumed_block_size; LayoutUnit previously_consumed_table_box_block_size; @@ -988,13 +992,13 @@ auto CreateSectionConstraintSpace = [&table_writing_direction, §ion_available_inline_size, &constraint_space_data, §ions, this]( - const NGBlockNode& section, + const BlockNode& section, LayoutUnit fragmentainer_block_offset, wtf_size_t section_index, LayoutUnit reserved_space, ESectionRepeatMode repeat_mode) { NGConstraintSpaceBuilder section_space_builder( - ConstraintSpace(), table_writing_direction, /* is_new_fc */ true); + GetConstraintSpace(), table_writing_direction, /* is_new_fc */ true); LogicalSize available_size = {section_available_inline_size, kIndefiniteSize}; @@ -1016,7 +1020,7 @@ section_space_builder.SetShouldRepeat(repeat_mode == kMayRepeatAgain); section_space_builder.SetIsInsideRepeatableContent(true); section_space_builder.SetShouldPropagateChildBreakValues(false); - } else if (ConstraintSpace().HasBlockFragmentation()) { + } else if (GetConstraintSpace().HasBlockFragmentation()) { // Note that, with fragmentainer_block_offset, we pretend that any // repeated table header isn't there (since it doesn't really participate // in block fragmentation anyway), so that the block-offset right after @@ -1025,13 +1029,14 @@ // having made some content progress (even if the first piece of content // doesn't fit). SetupSpaceBuilderForFragmentation( - ConstraintSpace(), section, fragmentainer_block_offset, + GetConstraintSpace(), section, fragmentainer_block_offset, §ion_space_builder, /* is_new_fc */ true, container_builder_.RequiresContentBeforeBreaking()); // Reserve space for any repeated header / footer. - if (ConstraintSpace().HasKnownFragmentainerBlockSize()) + if (GetConstraintSpace().HasKnownFragmentainerBlockSize()) { section_space_builder.ReserveSpaceInFragmentainer(reserved_space); + } } return section_space_builder.ToConstraintSpace(); @@ -1063,14 +1068,14 @@ // crbug.com/1352931 for more details. Furthermore, we cannot repeat content // if side-effects are disabled, as that machinery depends on updating and // reading the physical fragments vector of the LayoutBox. - if (!ConstraintSpace().IsInsideRepeatableContent() && + if (!GetConstraintSpace().IsInsideRepeatableContent() && !NGDisableSideEffectsScope::IsDisabled() && (grouped_children.header || grouped_children.footer)) { LayoutUnit max_section_block_size = - ConstraintSpace().FragmentainerBlockSize() / 4; + GetConstraintSpace().FragmentainerBlockSize() / 4; TableChildIterator child_iterator(grouped_children, BreakToken()); for (auto entry = child_iterator.NextChild(); - NGBlockNode child = entry.GetNode(); + BlockNode child = entry.GetNode(); entry = child_iterator.NextChild()) { if (child != grouped_children.header && child != grouped_children.footer) continue; @@ -1109,11 +1114,12 @@ // of the fragmentainer, so that would be impossible), but we will // continue repeating if we previously decided to do so in a previous // layout pass, for a previous fragment. - if (!ConstraintSpace().HasKnownFragmentainerBlockSize() || - block_size > max_section_block_size) + if (!GetConstraintSpace().HasKnownFragmentainerBlockSize() || + block_size > max_section_block_size) { continue; + } - if (!IsAvoidBreakValue(ConstraintSpace(), + if (!IsAvoidBreakValue(GetConstraintSpace(), child.Style().BreakInside())) { continue; } @@ -1151,8 +1157,7 @@ // Generate section fragments; and also caption fragments, if we need to // regenerate them (block fragmentation). for (auto entry = child_iterator.NextChild(); - NGBlockNode child = entry.GetNode(); - entry = child_iterator.NextChild()) { + BlockNode child = entry.GetNode(); entry = child_iterator.NextChild()) { DCHECK(child.IsTableCaption() || child.IsTableSection()); const NGEarlyBreak* early_break_in_child = nullptr; @@ -1207,23 +1212,23 @@ // We're done with the table box if it fits inside the fragmentainer. is_past_table_box = - !ConstraintSpace().HasKnownFragmentainerBlockSize() || + !constraint_space.HasKnownFragmentainerBlockSize() || table_box_extent->end <= fragmentainer_space_at_start; } LogicalSize available_size(container_builder_.InlineSize(), kIndefiniteSize); - BoxStrut margins = ComputeCaptionMargins(ConstraintSpace(), child, + BoxStrut margins = ComputeCaptionMargins(constraint_space, child, container_builder_.InlineSize(), child_break_token); child_block_start_margin = margins.block_start; child_block_end_margin = margins.block_end; NGConstraintSpace child_space = CreateCaptionConstraintSpace( - ConstraintSpace(), Style(), child, available_size, + constraint_space, Style(), child, available_size, child_block_offset + child_block_start_margin); CaptionResult caption = LayoutCaption( - ConstraintSpace(), Style(), container_builder_.InlineSize(), + constraint_space, Style(), container_builder_.InlineSize(), child_space, child, margins, child_break_token, early_break_in_child); DCHECK_EQ(caption.layout_result->Status(), NGLayoutResult::kSuccess); child_result = caption.layout_result; @@ -1346,13 +1351,13 @@ child_block_offset = offset_for_childless_section; } } - if (ConstraintSpace().HasBlockFragmentation() && + if (constraint_space.HasBlockFragmentation() && (!child_break_token || !is_repeated_section)) { LayoutUnit fragmentainer_block_offset = - ConstraintSpace().FragmentainerOffset() + child_block_start_margin + + constraint_space.FragmentainerOffset() + child_block_start_margin + child_block_offset - repeated_header_block_size; NGBreakStatus break_status = BreakBeforeChildIfNeeded( - ConstraintSpace(), child, *child_result, fragmentainer_block_offset, + constraint_space, child, *child_result, fragmentainer_block_offset, has_container_separation, &container_builder_); if (break_status == NGBreakStatus::kNeedsEarlierBreak) return container_builder_.Abort(NGLayoutResult::kNeedsEarlierBreak); @@ -1412,7 +1417,7 @@ is_past_table_box = true; } - if (ConstraintSpace().HasBlockFragmentation()) { + if (constraint_space.HasBlockFragmentation()) { if (!has_container_separation) has_container_separation = !is_repeated_section; if (container_builder_.HasInflowChildBreakInside()) { @@ -1446,7 +1451,7 @@ // next table fragment (inserting a break token for the repeated footer // alone would make the table child iterator skip any preceding sections). auto entry = child_iterator.NextChild(); - for (; NGBlockNode child = entry.GetNode(); + for (; BlockNode child = entry.GetNode(); entry = child_iterator.NextChild()) { if (child == grouped_children.footer) break; @@ -1471,7 +1476,7 @@ if (has_entered_non_repeated_section) { adjusted_child_block_offset = std::min(adjusted_child_block_offset, - UnclampedFragmentainerSpaceLeft(ConstraintSpace()) - + UnclampedFragmentainerSpaceLeft(constraint_space) - repeated_footer_block_size); } @@ -1490,9 +1495,9 @@ // out of space before a repeatable footer. So insert a break if // necessary. LayoutUnit fragmentainer_block_offset = - ConstraintSpace().FragmentainerOffset() + offset.block_offset; + constraint_space.FragmentainerOffset() + offset.block_offset; break_status = BreakBeforeChildIfNeeded( - ConstraintSpace(), grouped_children.footer, *result, + constraint_space, grouped_children.footer, *result, fragmentainer_block_offset, has_container_separation, &container_builder_); } @@ -1510,12 +1515,12 @@ // If we had (any) break inside, we don't need end border-spacing, and // should be at-least the fragmentainer size (if definite). if (broke_inside) { - if (ConstraintSpace().HasKnownFragmentainerBlockSize()) { + if (constraint_space.HasKnownFragmentainerBlockSize()) { table_box_extent->end = std::max(table_box_extent->end, fragmentainer_space_at_start); } border_spacing_after_last_section = LayoutUnit(); - } else if (ConstraintSpace().HasKnownFragmentainerBlockSize()) { + } else if (constraint_space.HasKnownFragmentainerBlockSize()) { // Truncate trailing border-spacing to fit within the fragmentainer. LayoutUnit new_border_spacing_after_last_section = std::min(border_spacing_after_last_section, @@ -1542,7 +1547,7 @@ if (!broke_inside) { // If the table box fits inside the fragmentainer, we're past it. is_past_table_box = - !ConstraintSpace().HasKnownFragmentainerBlockSize() || + !constraint_space.HasKnownFragmentainerBlockSize() || table_box_extent->end <= fragmentainer_space_at_start; } } @@ -1581,9 +1586,9 @@ container_builder_.SetIntrinsicBlockSize(intrinsic_block_size); block_size += previously_consumed_block_size; - if (ConstraintSpace().IsFixedBlockSize()) { - block_size = ConstraintSpace().AvailableSize().block_size; - if (ConstraintSpace().MinBlockSizeShouldEncompassIntrinsicSize()) { + if (constraint_space.IsFixedBlockSize()) { + block_size = constraint_space.AvailableSize().block_size; + if (constraint_space.MinBlockSizeShouldEncompassIntrinsicSize()) { block_size = std::max( block_size, previously_consumed_block_size + intrinsic_block_size); } @@ -1605,7 +1610,7 @@ if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) { NGBreakStatus status = - FinishFragmentation(Node(), ConstraintSpace(), border_padding.block_end, + FinishFragmentation(Node(), constraint_space, border_padding.block_end, fragmentainer_space_at_start, &container_builder_); if (status == NGBreakStatus::kNeedsEarlierBreak) return container_builder_.Abort(NGLayoutResult::kNeedsEarlierBreak); @@ -1670,7 +1675,7 @@ table_borders, table_grid_rect, column_block_size); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), constraint_space, &container_builder_).Run(); if (has_repeated_header && has_entered_table_box && !table_box_will_continue && !is_known_to_be_last_table_box_) {
diff --git a/third_party/blink/renderer/core/layout/table/table_layout_algorithm.h b/third_party/blink/renderer/core/layout/table/table_layout_algorithm.h index f537db6..06ce50d 100644 --- a/third_party/blink/renderer/core/layout/table/table_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/table/table_layout_algorithm.h
@@ -49,7 +49,7 @@ visitor->Trace(layout_result); } - NGBlockNode node; + BlockNode node; Member<const NGLayoutResult> layout_result; const BoxStrut margins; };
diff --git a/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.cc b/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.cc index a8da027..ea7d09c 100644 --- a/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.cc +++ b/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.cc
@@ -117,9 +117,9 @@ // Implements https://www.w3.org/TR/css-tables-3/#computing-cell-measures // "outer min-content and outer max-content widths for table cells" -// Note: this method calls NGBlockNode::ComputeMinMaxSizes. +// Note: this method calls BlockNode::ComputeMinMaxSizes. TableTypes::CellInlineConstraint TableTypes::CreateCellInlineConstraint( - const NGBlockNode& node, + const BlockNode& node, WritingDirectionMode table_writing_direction, bool is_fixed_layout, const BoxStrut& cell_border, @@ -212,7 +212,7 @@ css_percentage_inline_size, percent_border_padding, is_constrained}; } -TableTypes::Section TableTypes::CreateSection(const NGLayoutInputNode& section, +TableTypes::Section TableTypes::CreateSection(const LayoutInputNode& section, wtf_size_t start_row, wtf_size_t row_count, LayoutUnit block_size, @@ -295,11 +295,11 @@ is_constrained |= cell->is_constrained; } -TableGroupedChildren::TableGroupedChildren(const NGBlockNode& table) - : header(NGBlockNode(nullptr)), footer(NGBlockNode(nullptr)) { - for (NGLayoutInputNode child = table.FirstChild(); child; +TableGroupedChildren::TableGroupedChildren(const BlockNode& table) + : header(BlockNode(nullptr)), footer(BlockNode(nullptr)) { + for (LayoutInputNode child = table.FirstChild(); child; child = child.NextSibling()) { - NGBlockNode block_child = To<NGBlockNode>(child); + BlockNode block_child = To<BlockNode>(child); if (block_child.IsTableCaption()) { captions.push_back(block_child); } else { @@ -400,7 +400,7 @@ return *this; } -NGBlockNode TableGroupedChildrenIterator::operator*() const { +BlockNode TableGroupedChildrenIterator::operator*() const { switch (current_section_) { case kHead: return grouped_children_.header; @@ -411,7 +411,7 @@ case kEnd: case kNone: NOTREACHED(); - return NGBlockNode(nullptr); + return BlockNode(nullptr); } }
diff --git a/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.h b/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.h index 1eadca8e..eb5ff9ab 100644 --- a/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.h +++ b/third_party/blink/renderer/core/layout/table/table_layout_algorithm_types.h
@@ -18,9 +18,9 @@ namespace blink { +class BlockNode; class ComputedStyle; -class NGBlockNode; -class NGLayoutInputNode; +class LayoutInputNode; // Define constraint classes for TableLayoutAlgorithm. class CORE_EXPORT TableTypes { @@ -210,13 +210,13 @@ bool is_table_fixed); static CellInlineConstraint CreateCellInlineConstraint( - const NGBlockNode&, + const BlockNode&, WritingDirectionMode table_writing_direction, bool is_fixed_layout, const BoxStrut& cell_border, const BoxStrut& cell_padding); - static Section CreateSection(const NGLayoutInputNode&, + static Section CreateSection(const LayoutInputNode&, wtf_size_t start_row, wtf_size_t row_count, LayoutUnit block_size, @@ -243,7 +243,7 @@ DISALLOW_NEW(); public: - explicit TableGroupedChildren(const NGBlockNode& table); + explicit TableGroupedChildren(const BlockNode& table); ~TableGroupedChildren() { captions.clear(); columns.clear(); @@ -252,16 +252,16 @@ void Trace(Visitor*) const; - HeapVector<NGBlockNode> captions; // CAPTION - HeapVector<NGBlockNode> columns; // COLGROUP, COL + HeapVector<BlockNode> captions; // CAPTION + HeapVector<BlockNode> columns; // COLGROUP, COL - NGBlockNode header; // first THEAD + BlockNode header; // first THEAD // These cannot be modified except in ctor to ensure // TableGroupedChildrenIterator works correctly. - HeapVector<NGBlockNode> bodies; // TBODY/multiple THEAD/TFOOT + HeapVector<BlockNode> bodies; // TBODY/multiple THEAD/TFOOT - NGBlockNode footer; // first TFOOT + BlockNode footer; // first TFOOT // Default iterators iterate over tbody-like (THEAD/TBODY/TFOOT) elements. TableGroupedChildrenIterator begin() const; @@ -282,7 +282,7 @@ TableGroupedChildrenIterator& operator++(); TableGroupedChildrenIterator& operator--(); - NGBlockNode operator*() const; + BlockNode operator*() const; bool operator==(const TableGroupedChildrenIterator& rhs) const; bool operator!=(const TableGroupedChildrenIterator& rhs) const; // True if section should be treated as tbody @@ -296,7 +296,7 @@ // |body_vector_| can be modified only in ctor and // |AdvanceToNonEmptySection()|. - const HeapVector<NGBlockNode>* body_vector_ = nullptr; + const HeapVector<BlockNode>* body_vector_ = nullptr; wtf_size_t position_ = 0; };
diff --git a/third_party/blink/renderer/core/layout/table/table_layout_utils.cc b/third_party/blink/renderer/core/layout/table/table_layout_utils.cc index 83f05b33..a30a7e4 100644 --- a/third_party/blink/renderer/core/layout/table/table_layout_utils.cc +++ b/third_party/blink/renderer/core/layout/table/table_layout_utils.cc
@@ -170,7 +170,7 @@ template <typename RowCountFunc> TableTypes::Row ComputeMinimumRowBlockSize( const RowCountFunc& row_count_func, - const NGBlockNode& row, + const BlockNode& row, const LayoutUnit cell_percentage_inline_size, const bool is_table_block_size_specified, const Vector<TableColumnLocation>& column_locations, @@ -198,8 +198,8 @@ RowBaselineTabulator row_baseline_tabulator; // Gather block sizes of all cells. - for (NGBlockNode cell = To<NGBlockNode>(row.FirstChild()); cell; - cell = To<NGBlockNode>(cell.NextSibling())) { + for (BlockNode cell = To<BlockNode>(row.FirstChild()); cell; + cell = To<BlockNode>(cell.NextSibling())) { colspan_cell_tabulator->FindNextFreeColumn(); const ComputedStyle& cell_style = cell.Style(); const auto cell_writing_direction = cell_style.GetWritingDirection(); @@ -336,7 +336,7 @@ // Computes inline constraints for COLGROUP/COLs. class ColumnConstraintsBuilder { public: - void VisitCol(const NGLayoutInputNode& column, + void VisitCol(const LayoutInputNode& column, wtf_size_t start_column_index, wtf_size_t span) { // COL creates SPAN constraints. Its width is col css width, or enclosing @@ -352,13 +352,13 @@ column.GetLayoutBox()->ClearNeedsLayout(); } - void EnterColgroup(const NGLayoutInputNode& colgroup, + void EnterColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index) { colgroup_constraint_ = TableTypes::CreateColumn( colgroup.Style(), absl::nullopt, is_fixed_layout_); } - void LeaveColgroup(const NGLayoutInputNode& colgroup, + void LeaveColgroup(const LayoutInputNode& colgroup, wtf_size_t start_column_index, wtf_size_t span, bool has_children) { @@ -384,7 +384,7 @@ }; // Computes constraints specified on column elements. -void ComputeColumnElementConstraints(const HeapVector<NGBlockNode>& columns, +void ComputeColumnElementConstraints(const HeapVector<BlockNode>& columns, bool is_fixed_layout, TableTypes::Columns* column_constraints) { ColumnConstraintsBuilder constraints_builder(column_constraints, @@ -394,7 +394,7 @@ } void ComputeSectionInlineConstraints( - const NGBlockNode& section, + const BlockNode& section, bool is_fixed_layout, bool is_first_section, WritingDirectionMode table_writing_direction, @@ -405,14 +405,14 @@ TableTypes::ColspanCells* colspan_cell_inline_constraints) { ColspanCellTabulator colspan_cell_tabulator; bool is_first_row = true; - for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row; - row = To<NGBlockNode>(row.NextSibling())) { + for (BlockNode row = To<BlockNode>(section.FirstChild()); row; + row = To<BlockNode>(row.NextSibling())) { colspan_cell_tabulator.StartRow(); // Gather constraints for each cell, and merge them into // CellInlineConstraints. - for (NGBlockNode cell = To<NGBlockNode>(row.FirstChild()); cell; - cell = To<NGBlockNode>(cell.NextSibling())) { + for (BlockNode cell = To<BlockNode>(row.FirstChild()); cell; + cell = To<BlockNode>(cell.NextSibling())) { colspan_cell_tabulator.FindNextFreeColumn(); wtf_size_t colspan = cell.TableCellColspan(); @@ -1392,7 +1392,7 @@ void SetupTableCellConstraintSpaceBuilder( const WritingDirectionMode table_writing_direction, - const NGBlockNode cell, + const BlockNode cell, const BoxStrut& cell_borders, const Vector<TableColumnLocation>& column_locations, LayoutUnit cell_block_size, @@ -1456,7 +1456,7 @@ // Computes maximum possible number of non-mergeable columns. wtf_size_t ComputeMaximumNonMergeableColumnCount( - const HeapVector<NGBlockNode>& columns, + const HeapVector<BlockNode>& columns, bool is_fixed_layout) { // Build column constraints. scoped_refptr<TableTypes::Columns> column_constraints = @@ -1478,7 +1478,7 @@ } scoped_refptr<TableTypes::Columns> ComputeColumnConstraints( - const NGBlockNode& table, + const BlockNode& table, const TableGroupedChildren& grouped_children, const TableBorders& table_borders, const BoxStrut& border_padding) { @@ -1497,7 +1497,7 @@ bool is_first_section = true; wtf_size_t row_index = 0; wtf_size_t section_index = 0; - for (NGBlockNode section : grouped_children) { + for (BlockNode section : grouped_children) { if (!section.IsEmptyTableSection()) { ComputeSectionInlineConstraints( section, is_fixed_layout, is_first_section, @@ -1515,7 +1515,7 @@ } void ComputeSectionMinimumRowBlockSizes( - const NGBlockNode& section, + const BlockNode& section, const LayoutUnit cell_percentage_inline_size, const bool is_table_block_size_specified, const Vector<TableColumnLocation>& column_locations, @@ -1533,8 +1533,8 @@ auto RowCountFunc = [&]() -> wtf_size_t { if (!row_count) { row_count = 0; - for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row; - row = To<NGBlockNode>(row.NextSibling())) { + for (BlockNode row = To<BlockNode>(section.FirstChild()); row; + row = To<BlockNode>(row.NextSibling())) { (*row_count)++; } } @@ -1551,8 +1551,8 @@ // total_row_percent must be under 100% float total_row_percent = 0; // Get minimum block size of each row. - for (NGBlockNode row = To<NGBlockNode>(section.FirstChild()); row; - row = To<NGBlockNode>(row.NextSibling())) { + for (BlockNode row = To<BlockNode>(section.FirstChild()); row; + row = To<BlockNode>(row.NextSibling())) { colspan_cell_tabulator.StartRow(); TableTypes::Row row_constraint = ComputeMinimumRowBlockSize( RowCountFunc, row, cell_percentage_inline_size, @@ -1604,8 +1604,8 @@ void FinalizeTableCellLayout(LayoutUnit unconstrained_intrinsic_block_size, NGBoxFragmentBuilder* builder) { - const NGBlockNode& node = builder->Node(); - const NGConstraintSpace& space = builder->ConstraintSpace(); + const BlockNode& node = builder->Node(); + const auto& space = builder->GetConstraintSpace(); const bool has_inflow_children = !builder->Children().empty(); // Hide table-cells if: @@ -1695,7 +1695,7 @@ } } -void ColspanCellTabulator::ProcessCell(const NGBlockNode& cell) { +void ColspanCellTabulator::ProcessCell(const BlockNode& cell) { wtf_size_t colspan = cell.TableCellColspan(); wtf_size_t rowspan = cell.TableCellRowspan(); if (rowspan > 1)
diff --git a/third_party/blink/renderer/core/layout/table/table_layout_utils.h b/third_party/blink/renderer/core/layout/table/table_layout_utils.h index 7df0e691..d0700ce1 100644 --- a/third_party/blink/renderer/core/layout/table/table_layout_utils.h +++ b/third_party/blink/renderer/core/layout/table/table_layout_utils.h
@@ -12,8 +12,8 @@ namespace blink { +class BlockNode; class LogicalBoxFragment; -class NGBlockNode; class NGBoxFragmentBuilder; class NGConstraintSpaceBuilder; class TableBorders; @@ -42,7 +42,7 @@ // creating the constraint-space for table-cells as consistent as possible. void SetupTableCellConstraintSpaceBuilder( const WritingDirectionMode table_writing_direction, - const NGBlockNode cell, + const BlockNode cell, const BoxStrut& cell_borders, const Vector<TableColumnLocation>& column_locations, LayoutUnit cell_block_size, @@ -56,17 +56,17 @@ NGConstraintSpaceBuilder*); wtf_size_t ComputeMaximumNonMergeableColumnCount( - const HeapVector<NGBlockNode>& columns, + const HeapVector<BlockNode>& columns, bool is_fixed_layout); scoped_refptr<TableTypes::Columns> ComputeColumnConstraints( - const NGBlockNode& table, + const BlockNode& table, const TableGroupedChildren&, const TableBorders& table_borders, const BoxStrut& border_padding); void ComputeSectionMinimumRowBlockSizes( - const NGBlockNode& section, + const BlockNode& section, const LayoutUnit cell_percentage_resolution_inline_size, const bool is_table_block_size_specified, const Vector<TableColumnLocation>& column_locations, @@ -101,7 +101,7 @@ unsigned CurrentColumn() { return current_column_; } void StartRow(); void FindNextFreeColumn(); - void ProcessCell(const NGBlockNode& cell); + void ProcessCell(const BlockNode& cell); void EndRow(); struct Cell {
diff --git a/third_party/blink/renderer/core/layout/table/table_node.h b/third_party/blink/renderer/core/layout/table/table_node.h index 1aec9c6f..e7d13840 100644 --- a/third_party/blink/renderer/core/layout/table/table_node.h +++ b/third_party/blink/renderer/core/layout/table/table_node.h
@@ -13,10 +13,10 @@ namespace blink { -// Table specific extensions to NGBlockNode. -class CORE_EXPORT TableNode final : public NGBlockNode { +// Table specific extensions to BlockNode. +class CORE_EXPORT TableNode final : public BlockNode { public: - explicit TableNode(LayoutBox* box) : NGBlockNode(box) {} + explicit TableNode(LayoutBox* box) : BlockNode(box) {} const BoxStrut& GetTableBordersStrut() const; @@ -44,9 +44,7 @@ template <> struct DowncastTraits<TableNode> { - static bool AllowFrom(const NGLayoutInputNode& node) { - return node.IsTable(); - } + static bool AllowFrom(const LayoutInputNode& node) { return node.IsTable(); } }; } // namespace blink
diff --git a/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.cc b/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.cc index bda2fa37..0d7d621 100644 --- a/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.cc
@@ -35,12 +35,13 @@ : LayoutAlgorithm(params) {} const NGLayoutResult* TableRowLayoutAlgorithm::Layout() { - const TableConstraintSpaceData& table_data = *ConstraintSpace().TableData(); - const auto& row = table_data.rows[ConstraintSpace().TableRowIndex()]; + const TableConstraintSpaceData& table_data = + *GetConstraintSpace().TableData(); + const auto& row = table_data.rows[GetConstraintSpace().TableRowIndex()]; auto CreateCellConstraintSpace = [this, &table_data]( - NGBlockNode cell, const NGBlockBreakToken* cell_break_token, + BlockNode cell, const NGBlockBreakToken* cell_break_token, const TableConstraintSpaceData::Cell& cell_data, LayoutUnit row_block_size, absl::optional<LayoutUnit> row_baseline, bool min_block_size_should_encompass_intrinsic_size) { @@ -60,9 +61,9 @@ } DCHECK_EQ(table_data.table_writing_direction.GetWritingMode(), - ConstraintSpace().GetWritingMode()); + GetConstraintSpace().GetWritingMode()); - NGConstraintSpaceBuilder builder(ConstraintSpace(), + NGConstraintSpaceBuilder builder(GetConstraintSpace(), cell.Style().GetWritingDirection(), /* is_new_fc */ true); @@ -74,9 +75,9 @@ table_data.is_table_block_size_specified, table_data.has_collapsed_borders, NGCacheSlot::kLayout, &builder); - if (ConstraintSpace().HasBlockFragmentation()) { + if (GetConstraintSpace().HasBlockFragmentation()) { SetupSpaceBuilderForFragmentation( - ConstraintSpace(), cell, + GetConstraintSpace(), cell, /* fragmentainer_offset_delta */ LayoutUnit(), &builder, /* is_new_fc */ true, container_builder_.RequiresContentBeforeBreaking()); @@ -88,12 +89,12 @@ return builder.ToConstraintSpace(); }; - bool has_block_fragmentation = ConstraintSpace().HasBlockFragmentation(); + bool has_block_fragmentation = GetConstraintSpace().HasBlockFragmentation(); bool should_propagate_child_break_values = - ConstraintSpace().ShouldPropagateChildBreakValues(); + GetConstraintSpace().ShouldPropagateChildBreakValues(); auto MinBlockSizeShouldEncompassIntrinsicSize = - [&](const NGBlockNode& cell, + [&](const BlockNode& cell, const TableConstraintSpaceData::Cell& cell_data) -> bool { if (!has_block_fragmentation) return false; @@ -139,7 +140,7 @@ NGBlockChildIterator child_iterator(Node().FirstChild(), BreakToken(), /* calculate_child_idx */ true); for (auto entry = child_iterator.NextChild(); - NGBlockNode cell = To<NGBlockNode>(entry.node); + BlockNode cell = To<BlockNode>(entry.node); entry = child_iterator.NextChild()) { const auto* cell_break_token = To<NGBlockBreakToken>(entry.token); const auto& cell_style = cell.Style(); @@ -258,8 +259,9 @@ if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) { NGBreakStatus status = FinishFragmentation( - Node(), ConstraintSpace(), /* trailing_border_padding */ LayoutUnit(), - FragmentainerSpaceLeft(ConstraintSpace()), &container_builder_); + Node(), GetConstraintSpace(), + /* trailing_border_padding */ LayoutUnit(), + FragmentainerSpaceLeft(GetConstraintSpace()), &container_builder_); // TODO(mstensho): Deal with early-breaks. DCHECK_EQ(status, NGBreakStatus::kContinue); @@ -276,7 +278,7 @@ container_builder_.SetBaselines(row_baseline_tabulator.ComputeBaseline( container_builder_.FragmentBlockSize())); - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), GetConstraintSpace(), &container_builder_).Run(); return container_builder_.ToBoxFragment(); }
diff --git a/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.h b/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.h index edb29df..eaec23f 100644 --- a/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/table/table_row_layout_algorithm.h
@@ -13,11 +13,11 @@ namespace blink { -class NGBlockNode; +class BlockNode; class NGBlockBreakToken; class CORE_EXPORT TableRowLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.cc b/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.cc index d625dba..b74e0a6 100644 --- a/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.cc +++ b/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.cc
@@ -31,9 +31,10 @@ // | vspacing | // +--------------------------+ const NGLayoutResult* TableSectionLayoutAlgorithm::Layout() { - const TableConstraintSpaceData& table_data = *ConstraintSpace().TableData(); + const auto& constraint_space = GetConstraintSpace(); + const TableConstraintSpaceData& table_data = *constraint_space.TableData(); const auto& section = - table_data.sections[ConstraintSpace().TableSectionIndex()]; + table_data.sections[constraint_space.TableSectionIndex()]; const wtf_size_t start_row_index = section.start_row_index; const LogicalSize available_size = {container_builder_.InlineSize(), kIndefiniteSize}; @@ -50,7 +51,7 @@ NGBlockChildIterator child_iterator(Node().FirstChild(), BreakToken(), /* calculate_child_idx */ true); for (auto entry = child_iterator.NextChild(); - NGBlockNode row = To<NGBlockNode>(entry.node); + BlockNode row = To<BlockNode>(entry.node); entry = child_iterator.NextChild()) { const auto* row_break_token = To<NGBlockBreakToken>(entry.token); wtf_size_t row_index = start_row_index + *entry.index; @@ -68,19 +69,19 @@ offset.block_offset += table_data.table_border_spacing.block_size; DCHECK_EQ(table_data.table_writing_direction.GetWritingMode(), - ConstraintSpace().GetWritingMode()); + constraint_space.GetWritingMode()); NGConstraintSpaceBuilder row_space_builder( - ConstraintSpace(), table_data.table_writing_direction, + constraint_space, table_data.table_writing_direction, /* is_new_fc */ true); row_space_builder.SetAvailableSize(available_size); row_space_builder.SetPercentageResolutionSize(available_size); row_space_builder.SetIsFixedInlineSize(true); row_space_builder.SetTableRowData(&table_data, row_index); - if (ConstraintSpace().HasBlockFragmentation()) { + if (constraint_space.HasBlockFragmentation()) { SetupSpaceBuilderForFragmentation( - ConstraintSpace(), row, offset.block_offset, &row_space_builder, + constraint_space, row, offset.block_offset, &row_space_builder, /* is_new_fc */ true, container_builder_.RequiresContentBeforeBreaking()); } @@ -88,11 +89,11 @@ NGConstraintSpace row_space = row_space_builder.ToConstraintSpace(); const NGLayoutResult* row_result = row.Layout(row_space, row_break_token); - if (ConstraintSpace().HasBlockFragmentation()) { + if (constraint_space.HasBlockFragmentation()) { LayoutUnit fragmentainer_block_offset = - ConstraintSpace().FragmentainerOffset() + offset.block_offset; + constraint_space.FragmentainerOffset() + offset.block_offset; NGBreakStatus break_status = BreakBeforeChildIfNeeded( - ConstraintSpace(), row, *row_result, fragmentainer_block_offset, + constraint_space, row, *row_result, fragmentainer_block_offset, !is_first_non_collapsed_row, &container_builder_); if (break_status == NGBreakStatus::kNeedsEarlierBreak) { return RelayoutAndBreakEarlier<TableSectionLayoutAlgorithm>( @@ -135,10 +136,10 @@ container_builder_.SetHasSeenAllChildren(); LayoutUnit block_size; - if (ConstraintSpace().IsFixedBlockSize()) { + if (constraint_space.IsFixedBlockSize()) { // A fixed block-size should only occur for a section without children. DCHECK_EQ(section.row_count, 0u); - block_size = ConstraintSpace().AvailableSize().block_size; + block_size = constraint_space.AvailableSize().block_size; } else { block_size = offset.block_offset; if (BreakToken()) @@ -161,12 +162,12 @@ if (UNLIKELY(InvolvedInBlockFragmentation(container_builder_))) { NGBreakStatus status = FinishFragmentation( - Node(), ConstraintSpace(), /* trailing_border_padding */ LayoutUnit(), - FragmentainerSpaceLeft(ConstraintSpace()), &container_builder_); + Node(), constraint_space, /* trailing_border_padding */ LayoutUnit(), + FragmentainerSpaceLeft(constraint_space), &container_builder_); DCHECK_EQ(status, NGBreakStatus::kContinue); } - OutOfFlowLayoutPart(Node(), ConstraintSpace(), &container_builder_).Run(); + OutOfFlowLayoutPart(Node(), constraint_space, &container_builder_).Run(); return container_builder_.ToBoxFragment(); }
diff --git a/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.h b/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.h index 6db86467..efe8e17f 100644 --- a/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.h +++ b/third_party/blink/renderer/core/layout/table/table_section_layout_algorithm.h
@@ -13,11 +13,11 @@ namespace blink { -class NGBlockNode; +class BlockNode; class NGBlockBreakToken; class CORE_EXPORT TableSectionLayoutAlgorithm - : public LayoutAlgorithm<NGBlockNode, + : public LayoutAlgorithm<BlockNode, NGBoxFragmentBuilder, NGBlockBreakToken> { public:
diff --git a/third_party/blink/renderer/core/paint/timing/paint_timing_detector.cc b/third_party/blink/renderer/core/paint/timing/paint_timing_detector.cc index 8b0d0f6..edc87caf 100644 --- a/third_party/blink/renderer/core/paint/timing/paint_timing_detector.cc +++ b/third_party/blink/renderer/core/paint/timing/paint_timing_detector.cc
@@ -106,31 +106,33 @@ // Get the layout dimensions and screen DPR uint32_t layout_width = image_element->LayoutBoxWidth(); uint32_t layout_height = image_element->LayoutBoxHeight(); - float_t document_dpr = document.DevicePixelRatio(); + float document_dpr = document.DevicePixelRatio(); // Get the size attribute calculated width, if any absl::optional<float> sizes_width = image_element->GetResourceWidth(); // Report offset in pixels between intrinsic and layout dimensions - const float_t kDPRCap = 2.0; - float_t capped_dpr = std::min(document_dpr, kDPRCap); - uint64_t fetched_pixels = base::saturated_cast<uint64_t>( - intrinsic_dimensions.width() * intrinsic_dimensions.height()); + const float kDPRCap = 2.0; + float capped_dpr = std::min(document_dpr, kDPRCap); + uint64_t fetched_pixels = intrinsic_dimensions.Area64(); uint64_t needed_pixels = base::saturated_cast<uint64_t>( - layout_width * layout_height * document_dpr * document_dpr); + (layout_width * document_dpr) * (layout_height * document_dpr)); uint64_t capped_pixels = base::saturated_cast<uint64_t>( - layout_width * layout_height * capped_dpr * capped_dpr); - int64_t overfetched_pixels = fetched_pixels - needed_pixels; - int64_t overfetched_capped_pixels = fetched_pixels - capped_pixels; + (layout_width * capped_dpr) * (layout_height * capped_dpr)); + bool has_overfetched_pixels = fetched_pixels > needed_pixels; base::UmaHistogramBoolean("Renderer.Images.HasOverfetchedPixels", - (overfetched_pixels > 0)); - if (overfetched_pixels > 0) { + has_overfetched_pixels); + if (has_overfetched_pixels) { + uint64_t overfetched_pixels = fetched_pixels - needed_pixels; base::UmaHistogramCounts10M("Renderer.Images.OverfetchedPixels", base::saturated_cast<int>(overfetched_pixels)); } + + bool has_overfetched_capped_pixels = fetched_pixels > capped_pixels; base::UmaHistogramBoolean("Renderer.Images.HasOverfetchedCappedPixels", - (overfetched_capped_pixels > 0)); - if (overfetched_capped_pixels > 0) { + has_overfetched_capped_pixels); + if (has_overfetched_capped_pixels) { + uint64_t overfetched_capped_pixels = fetched_pixels - capped_pixels; base::UmaHistogramCounts10M( "Renderer.Images.OverfetchedCappedPixels", base::saturated_cast<int>(overfetched_capped_pixels));
diff --git a/third_party/blink/renderer/core/style/computed_style.cc b/third_party/blink/renderer/core/style/computed_style.cc index 7bbd0d9..d02a8d60 100644 --- a/third_party/blink/renderer/core/style/computed_style.cc +++ b/third_party/blink/renderer/core/style/computed_style.cc
@@ -2569,7 +2569,8 @@ bool ComputedStyle::IsInterleavingRoot(const ComputedStyle* style) { const ComputedStyle* unensured = ComputedStyle::NullifyEnsured(style); - return unensured && unensured->IsContainerForSizeContainerQueries(); + return unensured && (unensured->IsContainerForSizeContainerQueries() || + unensured->PositionFallback()); } bool ComputedStyle::CalculateIsStackingContextWithoutContainment() const {
diff --git a/third_party/blink/renderer/core/style/computed_style.h b/third_party/blink/renderer/core/style/computed_style.h index c25cb7f..b889f8e 100644 --- a/third_party/blink/renderer/core/style/computed_style.h +++ b/third_party/blink/renderer/core/style/computed_style.h
@@ -1613,7 +1613,7 @@ // Return true if an element can match size container queries. In addition to // checking if it has a size container-type, we check if we are never able to - // reach NGBlockNode::Layout() for legacy layout objects or SVG elements. + // reach BlockNode::Layout() for legacy layout objects or SVG elements. bool CanMatchSizeContainerQueries(const Element& element) const; bool IsContainerForSizeContainerQueries() const {
diff --git a/third_party/blink/renderer/modules/formatted_text/formatted_text.cc b/third_party/blink/renderer/modules/formatted_text/formatted_text.cc index b73bffa..244dfd34 100644 --- a/third_party/blink/renderer/modules/formatted_text/formatted_text.cc +++ b/third_party/blink/renderer/modules/formatted_text/formatted_text.cc
@@ -184,7 +184,7 @@ return PaintRecord(); UpdateComputedStylesIfNeeded(document, font); - NGBlockNode block_node(block_); + BlockNode block_node(block_); NGConstraintSpaceBuilder builder( WritingMode::kHorizontalTb,
diff --git a/third_party/blink/renderer/modules/managed_device/navigator_managed_data.cc b/third_party/blink/renderer/modules/managed_device/navigator_managed_data.cc index 3be2d4fb..bfebf74f 100644 --- a/third_party/blink/renderer/modules/managed_device/navigator_managed_data.cc +++ b/third_party/blink/renderer/modules/managed_device/navigator_managed_data.cc
@@ -12,6 +12,7 @@ #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/navigator.h" +#include "third_party/blink/renderer/core/inspector/console_message.h" #include "third_party/blink/renderer/modules/event_target_modules.h" namespace blink { @@ -21,6 +22,11 @@ const char kNotHighTrustedAppExceptionMessage[] = "This API is available only for managed apps."; +#if BUILDFLAG(IS_ANDROID) +const char kManagedConfigNotSupported[] = + "Managed Configuration API is not supported on this platform."; +#endif // BUILDFLAG(IS_ANDROID) + } // namespace const char NavigatorManagedData::kSupplementName[] = "NavigatorManagedData"; @@ -85,6 +91,7 @@ return device_api_service_.get(); } +#if !BUILDFLAG(IS_ANDROID) mojom::blink::ManagedConfigurationService* NavigatorManagedData::GetManagedConfigurationService() { if (!managed_configuration_service_.is_bound()) { @@ -100,6 +107,7 @@ return managed_configuration_service_.get(); } +#endif // !BUILDFLAG(IS_ANDROID) void NavigatorManagedData::OnServiceConnectionError() { device_api_service_.reset(); @@ -129,9 +137,15 @@ if (!GetExecutionContext()) { return promise; } +#if !BUILDFLAG(IS_ANDROID) GetManagedConfigurationService()->GetManagedConfiguration( keys, WTF::BindOnce(&NavigatorManagedData::OnConfigurationReceived, WrapWeakPersistent(this), WrapPersistent(resolver))); +#else + resolver->Reject(MakeGarbageCollected<DOMException>( + DOMExceptionCode::kNotSupportedError, kManagedConfigNotSupported)); +#endif // !BUILDFLAG(IS_ANDROID) + return promise; } @@ -262,6 +276,7 @@ } EventTarget::AddedEventListener(event_type, registered_listener); +#if !BUILDFLAG(IS_ANDROID) if (event_type == event_type_names::kManagedconfigurationchange) { if (!configuration_observer_.is_bound()) { GetManagedConfigurationService()->SubscribeToManagedConfiguration( @@ -270,6 +285,11 @@ TaskType::kMiscPlatformAPI))); } } +#else + GetExecutionContext()->AddConsoleMessage(MakeGarbageCollected<ConsoleMessage>( + mojom::blink::ConsoleMessageSource::kOther, + mojom::blink::ConsoleMessageLevel::kWarning, kManagedConfigNotSupported)); +#endif // !BUILDFLAG(IS_ANDROID) } void NavigatorManagedData::RemovedEventListener(
diff --git a/third_party/blink/renderer/modules/mediastream/input_device_info.cc b/third_party/blink/renderer/modules/mediastream/input_device_info.cc index 283c1e4..8a8f8dd 100644 --- a/third_party/blink/renderer/modules/mediastream/input_device_info.cc +++ b/third_party/blink/renderer/modules/mediastream/input_device_info.cc
@@ -8,11 +8,13 @@ #include "build/build_config.h" #include "media/base/sample_format.h" +#include "media/capture/mojom/video_capture_types.mojom-shared.h" #include "media/webrtc/constants.h" #include "third_party/blink/public/mojom/mediastream/media_devices.mojom-blink.h" #include "third_party/blink/public/platform/modules/mediastream/web_media_stream_track.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_double_range.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_long_range.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_media_settings_range.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_media_track_capabilities.h" #include "third_party/blink/renderer/modules/mediastream/media_stream_constraints_util_video_device.h" #include "third_party/blink/renderer/platform/mediastream/media_stream_audio_processor_options.h" @@ -51,6 +53,10 @@ static_cast<double>(max_width)}; platform_capabilities_.frame_rate = {min_frame_rate, max_frame_rate}; } + platform_capabilities_.is_available = + !video_input_capabilities->availability || + (*video_input_capabilities->availability == + media::mojom::CameraAvailability::kAvailable); } void InputDeviceInfo::SetAudioInputCapabilities( @@ -79,9 +85,11 @@ MediaTrackCapabilities* capabilities = MediaTrackCapabilities::Create(); // If label is null, permissions have not been given and no capabilities - // should be returned. - if (label().empty()) + // should be returned. Also, if the device is marked as not available, it + // does not expose any capabilities. + if (label().empty() || !platform_capabilities_.is_available) { return capabilities; + } capabilities->setDeviceId(deviceId()); capabilities->setGroupId(groupId());
diff --git a/third_party/blink/renderer/modules/mediastream/input_device_info.h b/third_party/blink/renderer/modules/mediastream/input_device_info.h index dc0fdd6..ca34c7b 100644 --- a/third_party/blink/renderer/modules/mediastream/input_device_info.h +++ b/third_party/blink/renderer/modules/mediastream/input_device_info.h
@@ -6,13 +6,14 @@ #define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIASTREAM_INPUT_DEVICE_INFO_H_ #include "third_party/blink/renderer/modules/mediastream/media_device_info.h" +#include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/platform/mediastream/media_stream_source.h" namespace blink { class MediaTrackCapabilities; -class InputDeviceInfo final : public MediaDeviceInfo { +class MODULES_EXPORT InputDeviceInfo final : public MediaDeviceInfo { DEFINE_WRAPPERTYPEINFO(); public:
diff --git a/third_party/blink/renderer/modules/mediastream/media_devices_test.cc b/third_party/blink/renderer/modules/mediastream/media_devices_test.cc index 749c33d..76c69e95 100644 --- a/third_party/blink/renderer/modules/mediastream/media_devices_test.cc +++ b/third_party/blink/renderer/modules/mediastream/media_devices_test.cc
@@ -9,12 +9,17 @@ #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" +#include "media/base/video_types.h" +#include "media/capture/mojom/video_capture_types.mojom.h" +#include "media/capture/video/video_capture_device_descriptor.h" +#include "media/capture/video_capture_types.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/mediastream/media_devices.h" #include "third_party/blink/public/mojom/media/capture_handle_config.mojom-blink.h" +#include "third_party/blink/public/mojom/mediastream/media_devices.mojom-blink-forward.h" #include "third_party/blink/public/mojom/mediastream/media_devices.mojom-blink.h" #include "third_party/blink/public/mojom/mediastream/media_devices.mojom-shared.h" #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" @@ -25,7 +30,10 @@ #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_testing.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_capture_handle_config.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_crop_target.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_double_range.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_long_range.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_media_device_info.h" +#include "third_party/blink/renderer/bindings/modules/v8/v8_media_track_capabilities.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_restriction_target.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_user_media_stream_constraints.h" #include "third_party/blink/renderer/core/dom/events/event.h" @@ -36,18 +44,21 @@ #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/testing/page_test_base.h" #include "third_party/blink/renderer/modules/mediastream/crop_target.h" +#include "third_party/blink/renderer/modules/mediastream/input_device_info.h" #include "third_party/blink/renderer/modules/mediastream/media_device_info.h" #include "third_party/blink/renderer/modules/mediastream/restriction_target.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/testing/testing_platform_support.h" #include "third_party/blink/renderer/platform/weborigin/security_origin.h" #include "third_party/blink/renderer/platform/wtf/functional.h" +#include "ui/gfx/geometry/mojom/geometry.mojom.h" namespace blink { using ::base::HistogramTester; using ::blink::mojom::blink::MediaDeviceInfoPtr; using ::testing::_; +using ::testing::ElementsAre; using ::testing::StrictMock; using MediaDeviceType = ::blink::mojom::MediaDeviceType; @@ -71,11 +82,22 @@ { {"fake_audio_input_1", "Fake Audio Input 1", "common_group_1"}, {"fake_audio_input_2", "Fake Audio Input 2", "common_group_2"}, - {"fake_audio_input_3", "Fake Audio Input 3", "audio_input_group"} + {"fake_audio_input_3", "Fake Audio Input 3", "audio_input_group"}, }, { - {"fake_video_input_1", "Fake Video Input 1", "common_group_1"}, - {"fake_video_input_2", "Fake Video Input 2", "video_input_group"} - }, { + {"fake_video_input_1", "Fake Video Input 1", "common_group_1", + media::VideoCaptureControlSupport(), + blink::mojom::FacingMode::kNone, + media::CameraAvailability::kAvailable}, + {"fake_video_input_2", "Fake Video Input 2", "video_input_group", + media::VideoCaptureControlSupport(), + blink::mojom::FacingMode::kUser, absl::nullopt}, + {"fake_video_input_3", "Fake Video Input 3", "video_input_group 2", + media::VideoCaptureControlSupport(), + blink::mojom::FacingMode::kUser, + media::CameraAvailability:: + kUnavailableExclusivelyUsedByOtherApplication}, + }, + { {"fake_audio_output_1", "Fake Audio Output 1", "common_group_1"}, {"fake_audio_putput_2", "Fake Audio Output 2", "common_group_2"}, } @@ -88,13 +110,34 @@ mojom::blink::VideoInputDeviceCapabilities::New(); capabilities->device_id = String(enumeration_[1][0].device_id); capabilities->group_id = String(enumeration_[1][0].group_id); - capabilities->facing_mode = mojom::blink::FacingMode::kNone; + capabilities->facing_mode = + enumeration_[1][0].video_facing; // mojom::blink::FacingMode::kNone; + capabilities->formats.push_back(media::VideoCaptureFormat( + gfx::Size(640, 480), 30.0, media::VideoPixelFormat::PIXEL_FORMAT_I420)); + capabilities->availability = static_cast<media::mojom::CameraAvailability>( + *enumeration_[1][0].availability); video_input_capabilities_.push_back(std::move(capabilities)); capabilities = mojom::blink::VideoInputDeviceCapabilities::New(); capabilities->device_id = String(enumeration_[1][1].device_id); capabilities->group_id = String(enumeration_[1][1].group_id); - capabilities->facing_mode = mojom::blink::FacingMode::kUser; + capabilities->formats.push_back(media::VideoCaptureFormat( + gfx::Size(640, 480), 30.0, media::VideoPixelFormat::PIXEL_FORMAT_I420)); + capabilities->facing_mode = enumeration_[1][1].video_facing; + media::VideoCaptureFormat format; + video_input_capabilities_.push_back(std::move(capabilities)); + + capabilities = mojom::blink::VideoInputDeviceCapabilities::New(); + capabilities->device_id = String(enumeration_[1][2].device_id); + capabilities->group_id = String(enumeration_[1][2].group_id); + capabilities->formats.push_back(media::VideoCaptureFormat( + gfx::Size(640, 480), 30.0, media::VideoPixelFormat::PIXEL_FORMAT_I420)); + capabilities->formats.push_back( + media::VideoCaptureFormat(gfx::Size(1920, 1080), 60.0, + media::VideoPixelFormat::PIXEL_FORMAT_I420)); + capabilities->facing_mode = enumeration_[1][2].video_facing; + capabilities->availability = static_cast<media::mojom::CameraAvailability>( + *enumeration_[1][2].availability); video_input_capabilities_.push_back(std::move(capabilities)); } @@ -281,6 +324,11 @@ MediaDeviceType::kMediaAudioOuput)]; } + const Vector<mojom::blink::VideoInputDeviceCapabilitiesPtr>& + VideoInputCapabilities() { + return video_input_capabilities_; + } + private: mojo::Remote<mojom::blink::MediaDevicesListener> listener_; mojo::Receiver<mojom::blink::MediaDevicesDispatcherHost> receiver_{this}; @@ -313,6 +361,27 @@ } } +void VerifyFacingMode(const Vector<String>& js_facing_mode, + blink::mojom::FacingMode cpp_facing_mode) { + switch (cpp_facing_mode) { + case blink::mojom::FacingMode::kNone: + EXPECT_TRUE(js_facing_mode.empty()); + break; + case blink::mojom::FacingMode::kUser: + EXPECT_THAT(js_facing_mode, ElementsAre("user")); + break; + case blink::mojom::FacingMode::kEnvironment: + EXPECT_THAT(js_facing_mode, ElementsAre("environment")); + break; + case blink::mojom::FacingMode::kLeft: + EXPECT_THAT(js_facing_mode, ElementsAre("left")); + break; + case blink::mojom::FacingMode::kRight: + EXPECT_THAT(js_facing_mode, ElementsAre("right")); + break; + } +} + void VerifyDeviceInfo(const MediaDeviceInfo* device, const WebMediaDeviceInfo& expected, MediaDeviceType type) { @@ -322,6 +391,50 @@ EXPECT_EQ(device->kind(), ToString(type)); } +void VerifyVideoInputCapabilities( + const MediaDeviceInfo* device, + const WebMediaDeviceInfo& expected_device_info, + const mojom::blink::VideoInputDeviceCapabilitiesPtr& + expected_capabilities) { + CHECK_EQ(device->kind(), "videoinput"); + const InputDeviceInfo* info = static_cast<const InputDeviceInfo*>(device); + MediaTrackCapabilities* capabilities = info->getCapabilities(); + EXPECT_EQ(capabilities->hasFacingMode(), expected_device_info.IsAvailable()); + if (capabilities->hasFacingMode()) { + VerifyFacingMode(capabilities->facingMode(), + expected_device_info.video_facing); + } + EXPECT_EQ(capabilities->hasDeviceId(), expected_device_info.IsAvailable()); + EXPECT_EQ(capabilities->hasGroupId(), expected_device_info.IsAvailable()); + EXPECT_EQ(capabilities->hasWidth(), expected_device_info.IsAvailable()); + EXPECT_EQ(capabilities->hasHeight(), expected_device_info.IsAvailable()); + EXPECT_EQ(capabilities->hasAspectRatio(), expected_device_info.IsAvailable()); + EXPECT_EQ(capabilities->hasFrameRate(), expected_device_info.IsAvailable()); + if (expected_device_info.IsAvailable()) { + int max_expected_width = 0; + int max_expected_height = 0; + float max_expected_frame_rate = 0.0; + for (const auto& format : expected_capabilities->formats) { + max_expected_width = + std::max(max_expected_width, format.frame_size.width()); + max_expected_height = + std::max(max_expected_height, format.frame_size.height()); + max_expected_frame_rate = + std::max(max_expected_frame_rate, format.frame_rate); + } + EXPECT_EQ(capabilities->deviceId().Utf8(), expected_device_info.device_id); + EXPECT_EQ(capabilities->groupId().Utf8(), expected_device_info.group_id); + EXPECT_EQ(capabilities->width()->min(), 1); + EXPECT_EQ(capabilities->width()->max(), max_expected_width); + EXPECT_EQ(capabilities->height()->min(), 1); + EXPECT_EQ(capabilities->height()->max(), max_expected_height); + EXPECT_EQ(capabilities->aspectRatio()->min(), 1.0 / max_expected_height); + EXPECT_EQ(capabilities->aspectRatio()->max(), max_expected_width); + EXPECT_EQ(capabilities->frameRate()->min(), 1.0); + EXPECT_EQ(capabilities->frameRate()->max(), max_expected_frame_rate); + } +} + #if !BUILDFLAG(IS_ANDROID) SubCaptureTarget* ToSubCaptureTarget(const blink::ScriptValue& value) { if (CropTarget* crop_target = @@ -439,15 +552,25 @@ ExpectEnumerateDevicesHistogramReport(EnumerateDevicesResult::kOk); - for (wtf_size_t i = 0, result_index = 0; + const auto& video_input_capabilities = + dispatcher_host().VideoInputCapabilities(); + for (wtf_size_t i = 0, result_index = 0, video_input_index = 0; i < static_cast<wtf_size_t>(MediaDeviceType::kNumMediaDeviceTypes); ++i) { - for (const auto& device_info : dispatcher_host().enumeration()[i]) { + for (const auto& expected_device_info : + dispatcher_host().enumeration()[i]) { testing::Message message; message << "Verifying result index " << result_index; SCOPED_TRACE(message); - VerifyDeviceInfo(device_infos[result_index++], device_info, + VerifyDeviceInfo(device_infos[result_index], expected_device_info, static_cast<MediaDeviceType>(i)); + if (i == static_cast<wtf_size_t>(MediaDeviceType::kMediaVideoInput)) { + VerifyVideoInputCapabilities( + device_infos[result_index], expected_device_info, + video_input_capabilities[video_input_index]); + video_input_index++; + } + result_index++; } } }
diff --git a/third_party/blink/renderer/modules/scheduler/dom_timer_test.cc b/third_party/blink/renderer/modules/scheduler/dom_timer_test.cc index 31b6a8e..26aba5e 100644 --- a/third_party/blink/renderer/modules/scheduler/dom_timer_test.cc +++ b/third_party/blink/renderer/modules/scheduler/dom_timer_test.cc
@@ -71,6 +71,7 @@ Vector<double> ToDoubleArray(v8::Local<v8::Value> value, v8::HandleScope& scope) { + ScriptState::Scope context_scope(ToScriptStateForMainWorld(&GetFrame())); NonThrowableExceptionState exception_state; return NativeValueTraits<IDLSequence<IDLDouble>>::NativeValue( scope.GetIsolate(), value, exception_state);
diff --git a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc index 11cdf54..de3528ff 100644 --- a/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc +++ b/third_party/blink/renderer/platform/fonts/shaping/shape_result.cc
@@ -633,7 +633,6 @@ unsigned absolute_offset, AdjustMidCluster adjust_mid_cluster) const { float x = 0; - float offset_x = 0; // The absolute_offset argument represents the offset for the entire // ShapeResult while offset is continuously updated to be relative to the @@ -643,10 +642,8 @@ if (IsRtl()) { // Convert logical offsets to visual offsets, because results are in // logical order while runs are in visual order. - x = width_; if (offset < NumCharacters()) offset = NumCharacters() - offset - 1; - x -= Width(); } for (unsigned i = 0; i < runs_.size(); i++) { @@ -655,10 +652,8 @@ DCHECK_EQ(IsRtl(), runs_[i]->IsRtl()); unsigned num_characters = runs_[i]->num_characters_; - if (!offset_x && offset < num_characters) { - offset_x = - runs_[i]->XPositionForVisualOffset(offset, adjust_mid_cluster) + x; - break; + if (offset < num_characters) { + return runs_[i]->XPositionForVisualOffset(offset, adjust_mid_cluster) + x; } offset -= num_characters; @@ -666,10 +661,11 @@ } // The position in question might be just after the text. - if (!offset_x && absolute_offset == NumCharacters()) + if (absolute_offset == NumCharacters()) { return IsRtl() ? 0 : width_; + } - return offset_x; + return 0; } float ShapeResult::CaretPositionForOffset(
diff --git a/third_party/blink/renderer/platform/mediastream/DEPS b/third_party/blink/renderer/platform/mediastream/DEPS index 3b27c412..46ff12d 100644 --- a/third_party/blink/renderer/platform/mediastream/DEPS +++ b/third_party/blink/renderer/platform/mediastream/DEPS
@@ -7,6 +7,7 @@ # Dependencies. "+media/base", + "+media/capture", "+media/webrtc/audio_processor_controls.h", "+media/webrtc/webrtc_features.h", "+third_party/blink/renderer/platform/audio",
diff --git a/third_party/blink/renderer/platform/mediastream/media_stream_source.h b/third_party/blink/renderer/platform/mediastream/media_stream_source.h index 3a917c0..8c88849 100644 --- a/third_party/blink/renderer/platform/mediastream/media_stream_source.h +++ b/third_party/blink/renderer/platform/mediastream/media_stream_source.h
@@ -145,6 +145,10 @@ MediaStreamTrackPlatform::FacingMode::kNone; String device_id; String group_id; + + // Indicates if the device is available for use. If not, capabilities are + // not exposed. + bool is_available = true; }; const Capabilities& GetCapabilities() { return capabilities_; }
diff --git a/third_party/blink/renderer/platform/runtime_enabled_features.json5 b/third_party/blink/renderer/platform/runtime_enabled_features.json5 index 988cd87..a4fa9be 100644 --- a/third_party/blink/renderer/platform/runtime_enabled_features.json5 +++ b/third_party/blink/renderer/platform/runtime_enabled_features.json5
@@ -957,6 +957,12 @@ status: "stable", }, { + // Tracked as an experiment to help Search quantify + // performance improvements. + name: "CSSMPCImprovements", + status: "stable", + }, + { // Support nested selectors that start with idents. name: "CSSNestingIdent", status: "stable",
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 4079c4d..b4b443b0 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -1536,8 +1536,6 @@ crbug.com/1488371 virtual/deprecate-unload/http/tests/navigation/image-load-in-unload-handler.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/navigation/navigate-to-about-blank-from-subframe-unload-handler-cross-origin.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/navigation/navigate-to-about-blank-from-subframe-unload-handler-same-origin.html [ Skip Failure Timeout ] -crbug.com/1488371 virtual/deprecate-unload/http/tests/navigation/redirect-on-back-updates-history-item.html [ Skip Failure Timeout ] -crbug.com/1488371 virtual/deprecate-unload/http/tests/navigation/redirect-on-reload-updates-history-item.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/navigation/targeted-navigation-in-unload-handler.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/notifications/close-on-document-unload.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/notifications/notification-creation-detached-context.html [ Skip Failure Timeout ] @@ -1546,13 +1544,11 @@ crbug.com/1488371 virtual/deprecate-unload/http/tests/security/window-events-clear-domain.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/security/window-events-clear-port.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/security/window-events-pass.html [ Skip Failure Timeout ] -crbug.com/1488371 virtual/deprecate-unload/http/tests/sendbeacon/beacon-detached-no-crash.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/xmlhttprequest/frame-load-cancelled-abort.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/xmlhttprequest/frame-unload-abort-crash.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/xmlhttprequest/xhr-onunload.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/xmlhttprequest/xmlhttprequest-unload-sync-handler-attached-from-parent.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/http/tests/xmlhttprequest/xmlhttprequest-unload-sync.html [ Skip Failure Timeout ] -crbug.com/1488371 virtual/deprecate-unload/external/wpt/battery-status/no-leak-on-detached-use.https.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/external/wpt/document-picture-in-picture/clears-session-on-close.https.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/external/wpt/html/browsers/browsing-the-web/back-forward-cache/events.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/external/wpt/html/browsers/browsing-the-web/navigating-across-documents/navigate-to-unparseable-url.html [ Skip Failure Timeout ] @@ -1592,7 +1588,6 @@ crbug.com/1488371 virtual/deprecate-unload/wpt_internal/geolocation-api/disconnected-frame-permission-denied.https.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/wpt_internal/geolocation-api/disconnected-frame.https.html [ Skip Failure Timeout ] crbug.com/1488371 virtual/deprecate-unload/wpt_internal/presentation/presentation-receiver-terminate-connection.https.html [ Skip Failure Timeout ] -crbug.com/1488371 virtual/deprecate-unload/wpt_internal/speech/scripted/speechrecognition-no-crash-detached.html [ Skip Failure Timeout ] # ========== End of Unload deprecation pending @@ -3385,9 +3380,6 @@ ### external/wpt/speculation-rules/prerender crbug.com/1126305 external/wpt/speculation-rules/prerender/restrictions.html [ Skip Timeout ] -# This test is failing on Mac due to the race condition between visibility -# change and prerender activation. -crbug.com/1431109 [ Mac ] virtual/speculation-rules-prerender-target-hint/http/tests/inspector-protocol/prerender/prerender-status-update-with-target-hint.js [ Failure Pass ] ### See crbug.com/891427 comment near the top of this file: crbug.com/367760 external/wpt/svg/pservers/reftests/meshgradient-basic-004.svg [ Failure ]
diff --git a/third_party/blink/web_tests/VirtualTestSuites b/third_party/blink/web_tests/VirtualTestSuites index b0f30cf..1dfe6a6 100644 --- a/third_party/blink/web_tests/VirtualTestSuites +++ b/third_party/blink/web_tests/VirtualTestSuites
@@ -2107,7 +2107,7 @@ ], "exclusive_tests": "ALL", "args": [ - "--enable-features=Prerender2InNewTab" + "--enable-features=Prerender2InNewTab,Prerender2AllowActivationInBackground" ], "owners": ["nhiroki@chromium.org"], "expires": "Jul 1, 2024"
diff --git a/third_party/blink/web_tests/external/wpt/battery-status/resources/window-postmessage-open-close.html b/third_party/blink/web_tests/external/wpt/battery-status/resources/window-postmessage-open-close.html index 3adb8ce..ae256c7 100644 --- a/third_party/blink/web_tests/external/wpt/battery-status/resources/window-postmessage-open-close.html +++ b/third_party/blink/web_tests/external/wpt/battery-status/resources/window-postmessage-open-close.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <!-- Used when testing access of a closed/detached window's properties --> <html> -<body onunload="opener.postMessage('closed', '*');"> +<body onpagehide="opener.postMessage('closed', '*');"> <script> opener.postMessage("opened", "*"); </script>
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/audio-setSinkId.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/audio-setSinkId.https.html index f53e2f9..31df3c5c 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/audio-setSinkId.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/audio-setSinkId.https.html
@@ -7,6 +7,8 @@ <script> const params = new URLSearchParams(location.search); +const target_hint = params.get('target_hint'); +const rule_extras = {target_hint}; // The main test page (restriction-audio-setSinkId.https.html) loads the // initiator page, then the initiator page will prerender itself with the @@ -14,7 +16,7 @@ const isPrerendering = params.has('prerendering'); if (!isPrerendering) { - loadInitiatorPage(); + loadInitiatorPage(rule_extras); } else { const prerenderEventCollector = new PrerenderEventCollector();
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-fetch.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-fetch.https.html index 3f1c072..ab5918d3 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-fetch.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-fetch.https.html
@@ -6,6 +6,8 @@ <script> const params = new URLSearchParams(location.search); +const target_hint = params.get('target_hint'); +const rule_extras = {target_hint}; // The main test page (restriction-background-fetch.https.html) loads the // initiator page, then the initiator page will prerender itself with the @@ -13,7 +15,7 @@ const isPrerendering = params.has('prerendering'); if (!isPrerendering) { - loadInitiatorPage(); + loadInitiatorPage(rule_extras); } else { async function loadPrerenderPage() { const prerenderEventCollector = new PrerenderEventCollector();
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-sync.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-sync.https.html index f11a951..322bcbe 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-sync.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/background-sync.https.html
@@ -6,6 +6,8 @@ <script> const params = new URLSearchParams(location.search); +const target_hint = params.get('target_hint'); +const rule_extras = {target_hint}; // The main test page (restriction-background-sync.tentative.https.html) // loads the initiator page, then the initiator page will prerender itself @@ -13,7 +15,7 @@ const isPrerendering = params.has('prerendering'); if (!isPrerendering) { - loadInitiatorPage(); + loadInitiatorPage(rule_extras); } else { async function loadPrerenderPage() { const prerenderEventCollector = new PrerenderEventCollector();
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/battery-status.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/battery-status.https.html index eb611175..0ddf620 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/battery-status.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/battery-status.https.html
@@ -7,12 +7,14 @@ <script> const params = new URLSearchParams(location.search); +const target_hint = params.get('target_hint'); +const rule_extras = {target_hint}; // The main test page (restriction-battery-status.html) loads the initiator // page, then the initiator page will prerender itself with the `prerendering` // parameter. if (!params.has('prerendering')) { - loadInitiatorPage(); + loadInitiatorPage(rule_extras); } else { const prerenderEventCollector = new PrerenderEventCollector(); prerenderEventCollector.start(navigator.getBattery(), 'navigator.getBattery');
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/utils.js b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/utils.js index 62b3b32..aca0381f 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/utils.js +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/utils.js
@@ -102,7 +102,10 @@ // Loads the initiator page, and navigates to the prerendered page after it // receives the 'readyToActivate' message. -function loadInitiatorPage() { +// +// `rule_extras` provides additional parameters for the speculation rule used +// to trigger prerendering. +function loadInitiatorPage(rule_extras = {}) { // Used to communicate with the prerendering page. const prerenderChannel = new PrerenderChannel('prerender-channel'); window.addEventListener('unload', () => { @@ -125,11 +128,15 @@ url.searchParams.append('prerendering', ''); // Prerender a page that notifies the initiator page of the page's ready to be // activated via the 'readyToActivate'. - startPrerendering(url.toString()); + startPrerendering(url.toString(), rule_extras); // Navigate to the prerendered page after being informed. readyToActivate.then(() => { - window.location = url.toString(); + if (rule_extras['target_hint'] === '_blank') { + window.open(url.toString(), '_blank', 'noopener'); + } else { + window.location = url.toString(); + } }).catch(e => { const testChannel = new PrerenderChannel('test-channel'); testChannel.postMessage(
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-immersive-vr-session.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-immersive-vr-session.https.html index d043c88..7b379f7 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-immersive-vr-session.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-immersive-vr-session.https.html
@@ -6,6 +6,8 @@ <script> const params = new URLSearchParams(location.search); +const target_hint = params.get('target_hint'); +const rule_extras = {target_hint}; // The main test page (restriction-web-xr-immersive-vr-session.https.html) loads // the initiator page, then the initiator page will prerender itself with the @@ -13,7 +15,7 @@ const isPrerendering = params.has('prerendering'); if (!isPrerendering) { - loadInitiatorPage(); + loadInitiatorPage(rule_extras); } else { const prerenderEventCollector = new PrerenderEventCollector(); prerenderEventCollector.start(
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-inline-session.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-inline-session.https.html index 8f3e011..091f5e196 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-inline-session.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/resources/web-xr-inline-session.https.html
@@ -6,6 +6,8 @@ <script> const params = new URLSearchParams(location.search); +const target_hint = params.get('target_hint'); +const rule_extras = {target_hint}; // The main test page (restriction-web-xr-inline-session.https.html) loads the // initiator page, then the initiator page will prerender itself with the @@ -13,7 +15,7 @@ const isPrerendering = params.has('prerendering'); if (!isPrerendering) { - loadInitiatorPage(); + loadInitiatorPage(rule_extras); } else { const prerenderEventCollector = new PrerenderEventCollector(); prerenderEventCollector.start(
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId-with-invalid-sinkId.https.tentative.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId-with-invalid-sinkId.https.tentative.html index 136c2c1c..adb41ca7 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId-with-invalid-sinkId.https.tentative.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId-with-invalid-sinkId.https.tentative.html
@@ -2,6 +2,8 @@ <title> Access to the setSinkId of the Audio API with an invalid value is deferred </title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -13,6 +15,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -26,7 +31,7 @@ }); }); - const url = `resources/audio-setSinkId.https.html?sinkId=invalid&uid=${uid}`; + const url = `resources/audio-setSinkId.https.html?sinkId=invalid&uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId.https.tentative.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId.https.tentative.html index ba5c0e8..ec486f8 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId.https.tentative.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-audio-setSinkId.https.tentative.html
@@ -1,5 +1,7 @@ <!DOCTYPE html> <title>Access to the setSinkId of the Audio API is deferred</title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -11,6 +13,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -24,7 +29,7 @@ }); }); - const url = `resources/audio-setSinkId.https.html?sinkId=default&uid=${uid}`; + const url = `resources/audio-setSinkId.https.html?sinkId=default&uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-fetch.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-fetch.https.html index 40b3aa2..40fa9d05 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-fetch.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-fetch.https.html
@@ -1,5 +1,7 @@ <!DOCTYPE html> <title>Access to the Background Fetch API is deferred</title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -14,6 +16,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -42,7 +47,7 @@ t.add_cleanup(() => registration.unregister()); await wait_for_state(t, registration.installing, 'activated'); - const url = `resources/background-fetch.https.html?uid=${uid}`; + const url = `resources/background-fetch.https.html?uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-sync.tentative.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-sync.tentative.https.html index a6dcde2..45b21f5 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-sync.tentative.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-background-sync.tentative.https.html
@@ -1,5 +1,7 @@ <!DOCTYPE html> <title>Access to the Background Sync API is deferred</title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -14,6 +16,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -42,7 +47,7 @@ t.add_cleanup(() => registration.unregister()); await wait_for_state(t, registration.installing, 'activated'); - const url = `resources/background-sync.https.html?uid=${uid}`; + const url = `resources/background-sync.https.html?uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-battery-status.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-battery-status.https.html index 920ff24..cafbd7d 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-battery-status.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-battery-status.https.html
@@ -1,5 +1,7 @@ <!DOCTYPE html> <title>Access to the Battery Status API is deferred</title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -11,6 +13,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -22,7 +27,7 @@ once: true }); }); - const url = `resources/battery-status.https.html?uid=${uid}`; + const url = `resources/battery-status.https.html?uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-immersive-vr-session.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-immersive-vr-session.https.html index 1db22e2..73219784 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-immersive-vr-session.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-immersive-vr-session.https.html
@@ -1,5 +1,7 @@ <!DOCTYPE html> <title>Access to the WebXR immersive-vr session API is deferred</title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -11,6 +13,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -24,7 +29,7 @@ }); }); - const url = `resources/web-xr-immersive-vr-session.https.html?uid=${uid}`; + const url = `resources/web-xr-immersive-vr-session.https.html?uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-inline-session.https.html b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-inline-session.https.html index d3dd5569..ef31846 100644 --- a/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-inline-session.https.html +++ b/third_party/blink/web_tests/external/wpt/speculation-rules/prerender/restriction-web-xr-inline-session.https.html
@@ -1,5 +1,7 @@ <!DOCTYPE html> <title>Access to the WebXR inline session API is deferred</title> +<meta name="variant" content="?target_hint=_self"> +<meta name="variant" content="?target_hint=_blank"> <meta name="timeout" content="long"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> @@ -11,6 +13,9 @@ <script> setup(() => assertSpeculationRulesIsSupported()); +const params = new URLSearchParams(window.location.search); +const target_hint = params.get('target_hint'); + promise_test(async t => { const uid = token(); const bc = new PrerenderChannel('test-channel', uid); @@ -24,7 +29,7 @@ }); }); - const url = `resources/web-xr-inline-session.https.html?uid=${uid}`; + const url = `resources/web-xr-inline-session.https.html?uid=${uid}&target_hint=${target_hint}`; window.open(url, '_blank', 'noopener'); const result = await gotMessage;
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-frameworks/frameworks-skip-break-program-expected.txt b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-frameworks/frameworks-skip-break-program-expected.txt deleted file mode 100644 index cc5ceb42..0000000 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-frameworks/frameworks-skip-break-program-expected.txt +++ /dev/null
@@ -1,6 +0,0 @@ -Tests that framework blackboxing skips instant pauses (e.g. breakpoints on console.assert(), setTimeout(), etc.) if they happen entirely inside the framework. - -Set timer for test function. -Call stack: - 0) stop (frameworks-skip-break-program.js:34) -
diff --git a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-frameworks/frameworks-skip-break-program.js b/third_party/blink/web_tests/http/tests/devtools/sources/debugger-frameworks/frameworks-skip-break-program.js deleted file mode 100644 index 845fbf3..0000000 --- a/third_party/blink/web_tests/http/tests/devtools/sources/debugger-frameworks/frameworks-skip-break-program.js +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2017 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {TestRunner} from 'test_runner'; -import {SourcesTestRunner} from 'sources_test_runner'; - -import * as Common from 'devtools/core/common/common.js'; -import * as SDK from 'devtools/core/sdk/sdk.js'; - -(async function() { - TestRunner.addResult( - `Tests that framework blackboxing skips instant pauses (e.g. breakpoints on console.assert(), setTimeout(), etc.) if they happen entirely inside the framework.\n`); - await TestRunner.showPanel('sources'); - await TestRunner.loadHTML(` - <input type="button" onclick="testFunction()" value="Test"> - `); - await TestRunner.addScriptTag('../debugger/resources/framework.js'); - await TestRunner.evaluateInPagePromise(` - function testFunction() - { - debugger; - Promise.resolve() - // Should not pause on console.assert() inside framework. - .then(Framework.bind(Framework.assert, null, false, "Assert from test")) - // Should not pause on setTimeout inside the framework. - .then(Framework.willSchedule(Framework.empty, 0)) - .then(stop) - .catch(function FAIL_should_not_pause(e) { debugger; throw e; }); - } - - function stop() - { - setTimeout(function() {}, 0); // Should pause here. - } - `); - - var frameworkRegexString = '/framework\\.js$'; - Common.Settings.settingForTest('skipStackFramesPattern').set(frameworkRegexString); - - SourcesTestRunner.startDebuggerTest(step1, true); - - function step1() { - SourcesTestRunner.runTestFunctionAndWaitUntilPaused(step2); - } - - function step2() { - TestRunner.DebuggerAgent.setPauseOnExceptions(SDK.DebuggerModel.PauseOnExceptionsState.PauseOnAllExceptions); - SourcesTestRunner.setEventListenerBreakpoint('instrumentation:setTimeout', true); - SourcesTestRunner.resumeExecution(SourcesTestRunner.waitUntilPaused.bind(SourcesTestRunner, didPause)); - } - - async function didPause(callFrames, reason, breakpointIds, asyncStackTrace) { - await SourcesTestRunner.captureStackTrace(callFrames); - completeTest(); - } - - function completeTest() { - TestRunner.DebuggerAgent.setPauseOnExceptions(SDK.DebuggerModel.PauseOnExceptionsState.DontPauseOnExceptions); - SourcesTestRunner.setEventListenerBreakpoint('instrumentation:setTimeout', false); - SourcesTestRunner.completeDebuggerTest(); - } -})();
diff --git a/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-back-updates-history-item.php b/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-back-updates-history-item.php index e306f3b..04f7b418 100644 --- a/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-back-updates-history-item.php +++ b/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-back-updates-history-item.php
@@ -10,13 +10,11 @@ ?> <script src='redirect-updates-history-item.js'></script> +<script src="/resources/prevent-bfcache.js"></script> <script> -onunload = function() { - // no page cache -} - onload = function() { setTimeout(function() { + preventBFCache(); // This code inserts a new history item using pushState, and then it // replaces that history item with a navigation to a page that just // navigates us back to this page. However, we set the "location"
diff --git a/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-reload-updates-history-item.php b/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-reload-updates-history-item.php index 1f9f317..7724e5b8 100644 --- a/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-reload-updates-history-item.php +++ b/third_party/blink/web_tests/http/tests/navigation/resources/redirect-on-reload-updates-history-item.php
@@ -10,13 +10,11 @@ ?> <script src='redirect-updates-history-item.js'></script> +<script src="/resources/prevent-bfcache.js"></script> <script> -onunload = function() { - // no page cache -} - onload = function() { setTimeout(function() { + preventBFCache(); // The first time through here (sessionStorage.done is false), this // code inserts a new history item using pushState, and then it // triggers a reload of the history item. However, we set the
diff --git a/third_party/blink/web_tests/resources/window-postmessage-open-close.html b/third_party/blink/web_tests/resources/window-postmessage-open-close.html index 3adb8ce..ae256c7 100644 --- a/third_party/blink/web_tests/resources/window-postmessage-open-close.html +++ b/third_party/blink/web_tests/resources/window-postmessage-open-close.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <!-- Used when testing access of a closed/detached window's properties --> <html> -<body onunload="opener.postMessage('closed', '*');"> +<body onpagehide="opener.postMessage('closed', '*');"> <script> opener.postMessage("opened", "*"); </script>
diff --git a/third_party/blink/web_tests/wpt_internal/css/css-anchor/cascade-fallback/try-initial-transition.html b/third_party/blink/web_tests/wpt_internal/css/css-anchor/cascade-fallback/try-initial-transition.html new file mode 100644 index 0000000..eb8dd9a --- /dev/null +++ b/third_party/blink/web_tests/wpt_internal/css/css-anchor/cascade-fallback/try-initial-transition.html
@@ -0,0 +1,39 @@ +<!DOCTYPE html> +<title>CSS Anchor Test: Initial @try does not trigger a transition</title> +<script src="/resources/testharness.js"></script> +<script src="/resources/testharnessreport.js"></script> +<div id=cb> + <div id=abs></div> +</div> +<style> + #cb { + position: relative; + width: 100px; + height: 100px; + background: lightpink; + } + #abs { + position: absolute; + background: darkcyan; + top: 10px; + left: 10px; + width: 25px; + height: 25px; + position-fallback: --pf; + transition-property: top, left; + transition-duration: 10s; + transition-timing-function: steps(2, start); + } + @position-fallback --pf { + @try { + top: 50px; + left: 50px; + } + } +</style> +<script> + test(() => { + assert_equals(getComputedStyle(abs).top, '50px'); + assert_equals(getComputedStyle(abs).left, '50px'); + }, 'No transition for initial style with @try'); +</script>
diff --git a/third_party/blink/web_tests/wpt_internal/speech/resources/window-postmessage-open-close.html b/third_party/blink/web_tests/wpt_internal/speech/resources/window-postmessage-open-close.html index 3adb8ce..ae256c7 100644 --- a/third_party/blink/web_tests/wpt_internal/speech/resources/window-postmessage-open-close.html +++ b/third_party/blink/web_tests/wpt_internal/speech/resources/window-postmessage-open-close.html
@@ -1,7 +1,7 @@ <!DOCTYPE html> <!-- Used when testing access of a closed/detached window's properties --> <html> -<body onunload="opener.postMessage('closed', '*');"> +<body onpagehide="opener.postMessage('closed', '*');"> <script> opener.postMessage("opened", "*"); </script>
diff --git a/third_party/cros-components/src b/third_party/cros-components/src index d04234e..99998f1 160000 --- a/third_party/cros-components/src +++ b/third_party/cros-components/src
@@ -1 +1 @@ -Subproject commit d04234ed17e4e8d2d95dc360b3bc3b0e6b0e3d6d +Subproject commit 99998f1608c8b13dab09cdc0585a0f8007211080
diff --git a/third_party/cros_system_api b/third_party/cros_system_api index 1d9711b..209d515 160000 --- a/third_party/cros_system_api +++ b/third_party/cros_system_api
@@ -1 +1 @@ -Subproject commit 1d9711b3bc06c08d92842b3df6f407f7edc029c5 +Subproject commit 209d5157d57fabac8ab61af5be7c5a4770c80436
diff --git a/third_party/dawn b/third_party/dawn index bfb695d..ff937f7 160000 --- a/third_party/dawn +++ b/third_party/dawn
@@ -1 +1 @@ -Subproject commit bfb695dd9b62203f1b8fdaf7998e5681c38bd3b9 +Subproject commit ff937f71a801fe382ac1c902f830b56719f4e1da
diff --git a/third_party/devtools-frontend-internal b/third_party/devtools-frontend-internal index 1c042a68..4b78cf0 160000 --- a/third_party/devtools-frontend-internal +++ b/third_party/devtools-frontend-internal
@@ -1 +1 @@ -Subproject commit 1c042a68ac0552324f7105843936b0f0218099f2 +Subproject commit 4b78cf0e89fdbdb7f917beab13a7ad62af3f05ef
diff --git a/third_party/devtools-frontend/src b/third_party/devtools-frontend/src index 4512381..e6bdd501 160000 --- a/third_party/devtools-frontend/src +++ b/third_party/devtools-frontend/src
@@ -1 +1 @@ -Subproject commit 45123813f5cb7335dc4a7e5151931dbe451b742c +Subproject commit e6bdd501b906e79f863decb8ca89598d4b1f317c
diff --git a/third_party/pdfium b/third_party/pdfium index aae740c..a5bb284 160000 --- a/third_party/pdfium +++ b/third_party/pdfium
@@ -1 +1 @@ -Subproject commit aae740cc19b3f5244751c768fa5e2550c6a716a2 +Subproject commit a5bb284fd0387fe11def18f1048516fa60313c77
diff --git a/third_party/perfetto b/third_party/perfetto index 0447454..510b65f 160000 --- a/third_party/perfetto +++ b/third_party/perfetto
@@ -1 +1 @@ -Subproject commit 0447454ec8cefdbaa41ec2c67ca7013a83188ac0 +Subproject commit 510b65fa04d733f3bfa9e4c6ea7ff98e0c449637
diff --git a/third_party/skia b/third_party/skia index 343b249..a874e29 160000 --- a/third_party/skia +++ b/third_party/skia
@@ -1 +1 @@ -Subproject commit 343b249b2cacaa694a07ca7430b1881274417da0 +Subproject commit a874e29d71c0f6491c733d878204270333e44038
diff --git a/third_party/webrtc b/third_party/webrtc index 0967247..f0907c6 160000 --- a/third_party/webrtc +++ b/third_party/webrtc
@@ -1 +1 @@ -Subproject commit 0967247662f6de824432992a7cc5e154e0fd6c29 +Subproject commit f0907c6f5bcdacf2e180acf4f15c4700f72d6982
diff --git a/tools/metrics/histograms/metadata/media/enums.xml b/tools/metrics/histograms/metadata/media/enums.xml index 49374d9..9d67933 100644 --- a/tools/metrics/histograms/metadata/media/enums.xml +++ b/tools/metrics/histograms/metadata/media/enums.xml
@@ -1042,6 +1042,9 @@ <enum name="GlobalMediaControlsEntryPoint"> <int value="0" label="Toolbar icon"/> <int value="1" label="Presentation API"/> + <int value="2" label="ChromeOS system tray"/> + <int value="3" label="ChromeOS quick settings mini player"/> + <int value="4" label="ChromeOS quick settings mini player (Cast button)"/> </enum> <enum name="HighlightedTabDiscardStatus">
diff --git a/tools/metrics/histograms/metadata/others/histograms.xml b/tools/metrics/histograms/metadata/others/histograms.xml index 6f4eaeb..93327ca 100644 --- a/tools/metrics/histograms/metadata/others/histograms.xml +++ b/tools/metrics/histograms/metadata/others/histograms.xml
@@ -5895,15 +5895,6 @@ </summary> </histogram> -<histogram name="IncompatibleApplicationsPage.AddedPostCrash" - enum="BooleanShown" expires_after="M85"> - <owner>pmonette@chromium.org</owner> - <summary> - Records whether the user was automatically shown the - chrome://settings/incompatibleApplications page following a Chrome crash. - </summary> -</histogram> - <histogram name="IncompatibleApplicationsPage.NumApplications" units="applications" expires_after="M85"> <owner>pmonette@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/password/histograms.xml b/tools/metrics/histograms/metadata/password/histograms.xml index 515e4c3d..a332003 100644 --- a/tools/metrics/histograms/metadata/password/histograms.xml +++ b/tools/metrics/histograms/metadata/password/histograms.xml
@@ -278,6 +278,17 @@ </histogram> <histogram + name="PasswordBubble.RelaunchChromeBubble.RestartButtonInBubbleClicked" + enum="BooleanYesNo" expires_after="M133"> + <owner>sygiet@google.com</owner> + <owner>vasilii@chromium.org</owner> + <summary> + Whether the user restarted Chrome from the RelaunchChrome bubble to fix the + keychain issue. + </summary> +</histogram> + +<histogram name="PasswordGeneration.EditsInGeneratedPassword.AlteredLengthIncreased" enum="GeneratedPasswordAlteredLengthIncreased" expires_after="2024-03-24"> <owner>kolos@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 57f885e..d19c2089 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 @@ "full_remote_path": "perfetto-luci-artifacts/6ba75cc5d93c39d4f86e2777709a460b30ce06fc/linux-arm64/trace_processor_shell" }, "win": { - "hash": "c09b8fc31ea9e154fbea216d3a762116a93267a7", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/0447454ec8cefdbaa41ec2c67ca7013a83188ac0/trace_processor_shell.exe" + "hash": "a64f374e4454cd938c0886356e057e98ce02c67b", + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/win/b1d5a98e15c379f1d52acca261841cfaf0b3eafc/trace_processor_shell.exe" }, "linux_arm": { "hash": "fa20dcbcab1b02524b23bb375c38fd8211e1268c", @@ -22,7 +22,7 @@ }, "linux": { "hash": "0f842e8a7f23c808271e9954581928e2734c5d97", - "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/0447454ec8cefdbaa41ec2c67ca7013a83188ac0/trace_processor_shell" + "full_remote_path": "chromium-telemetry/perfetto_binaries/trace_processor_shell/linux/b1d5a98e15c379f1d52acca261841cfaf0b3eafc/trace_processor_shell" } }, "power_profile.sql": {
diff --git a/ui/file_manager/file_manager/foreground/js/metadata/metadata_model_unittest.ts b/ui/file_manager/file_manager/foreground/js/metadata/metadata_model_unittest.ts index 6ce2ed8b..fa3bd8d 100644 --- a/ui/file_manager/file_manager/foreground/js/metadata/metadata_model_unittest.ts +++ b/ui/file_manager/file_manager/foreground/js/metadata/metadata_model_unittest.ts
@@ -4,7 +4,6 @@ import {assertEquals, assertThrows} from 'chrome://webui-test/chromeos/chai_assert.js'; -import {reportPromise} from '../../../common/js/test_error_reporting.js'; import {FilesAppEntry} from '../../../externs/files_app_entry_interfaces.js'; import {MetadataItem, MetadataKey} from './metadata_item.js'; @@ -86,102 +85,76 @@ return result[property]; } -export function testMetadataModelBasic(callback: () => void) { +export async function testMetadataModelBasic(done: VoidCallback) { const provider = new TestMetadataProvider(); const model = new MetadataModel(provider); - reportPromise( - model.get([entryA, entryB], ['thumbnailUrl']).then(results => { - assertEquals(1, provider.requestCount); - assertEquals( - 'filesystem://A:thumbnailUrl', - getProperty(results[0], 'thumbnailUrl')); - assertEquals( - 'filesystem://B:thumbnailUrl', - getProperty(results[1], 'thumbnailUrl')); - }), - callback); + const results = await model.get([entryA, entryB], ['thumbnailUrl']); + assertEquals(1, provider.requestCount); + assertEquals( + 'filesystem://A:thumbnailUrl', getProperty(results[0], 'thumbnailUrl')); + assertEquals( + 'filesystem://B:thumbnailUrl', getProperty(results[1], 'thumbnailUrl')); + done(); } -export function testMetadataModelRequestForCachedProperty( - callback: () => void) { +export async function testMetadataModelRequestForCachedProperty( + done: VoidCallback) { const provider = new TestMetadataProvider(); const model = new MetadataModel(provider); - reportPromise( - model.get([entryA, entryB], ['thumbnailUrl']) - .then(() => { - // All the results should be cached here. - return model.get([entryA, entryB], ['thumbnailUrl']); - }) - .then(results => { - assertEquals(1, provider.requestCount); - assertEquals( - 'filesystem://A:thumbnailUrl', - getProperty(results[0], 'thumbnailUrl')); - assertEquals( - 'filesystem://B:thumbnailUrl', - getProperty(results[1], 'thumbnailUrl')); - }), - callback); + await model.get([entryA, entryB], ['thumbnailUrl']); + // All the results should be cached here. + const results = await model.get([entryA, entryB], ['thumbnailUrl']); + assertEquals(1, provider.requestCount); + assertEquals( + 'filesystem://A:thumbnailUrl', getProperty(results[0], 'thumbnailUrl')); + assertEquals( + 'filesystem://B:thumbnailUrl', getProperty(results[1], 'thumbnailUrl')); + done(); } -export function testMetadataModelRequestForCachedAndNonCachedProperty( - callback: () => void) { +export async function testMetadataModelRequestForCachedAndNonCachedProperty( + done: VoidCallback) { const provider = new TestMetadataProvider(); const model = new MetadataModel(provider); - reportPromise( - model.get([entryA, entryB], ['mediaAlbum']) - .then(() => { - assertEquals(1, provider.requestCount); - // mediaArtist has not been cached here. - return model.get([entryA, entryB], ['mediaAlbum', 'mediaArtist']); - }) - .then(results => { - assertEquals(2, provider.requestCount); - assertEquals( - 'filesystem://A:mediaAlbum', - getProperty(results[0], 'mediaAlbum')); - assertEquals( - 'filesystem://A:mediaArtist', - getProperty(results[0], 'mediaArtist')); - assertEquals( - 'filesystem://B:mediaAlbum', - getProperty(results[1], 'mediaAlbum')); - assertEquals( - 'filesystem://B:mediaArtist', - getProperty(results[1], 'mediaArtist')); - }), - callback); + await model.get([entryA, entryB], ['mediaAlbum']); + assertEquals(1, provider.requestCount); + // mediaArtist has not been cached here. + const results = + await model.get([entryA, entryB], ['mediaAlbum', 'mediaArtist']); + assertEquals(2, provider.requestCount); + assertEquals( + 'filesystem://A:mediaAlbum', getProperty(results[0], 'mediaAlbum')); + assertEquals( + 'filesystem://A:mediaArtist', getProperty(results[0], 'mediaArtist')); + assertEquals( + 'filesystem://B:mediaAlbum', getProperty(results[1], 'mediaAlbum')); + assertEquals( + 'filesystem://B:mediaArtist', getProperty(results[1], 'mediaArtist')); + done(); } -export function testMetadataModelRequestForCachedAndNonCachedEntry( - callback: () => void) { +export async function testMetadataModelRequestForCachedAndNonCachedEntry( + done: VoidCallback) { const provider = new TestMetadataProvider(); const model = new MetadataModel(provider); - reportPromise( - model.get([entryA], ['thumbnailUrl']) - .then(() => { - assertEquals(1, provider.requestCount); - // entryB has not been cached here. - return model.get([entryA, entryB], ['thumbnailUrl']); - }) - .then(results => { - assertEquals(2, provider.requestCount); - assertEquals( - 'filesystem://A:thumbnailUrl', - getProperty(results[0], 'thumbnailUrl')); - assertEquals( - 'filesystem://B:thumbnailUrl', - getProperty(results[1], 'thumbnailUrl')); - }), - callback); + await model.get([entryA], ['thumbnailUrl']); + assertEquals(1, provider.requestCount); + // entryB has not been cached here. + const results = await model.get([entryA, entryB], ['thumbnailUrl']); + assertEquals(2, provider.requestCount); + assertEquals( + 'filesystem://A:thumbnailUrl', getProperty(results[0], 'thumbnailUrl')); + assertEquals( + 'filesystem://B:thumbnailUrl', getProperty(results[1], 'thumbnailUrl')); + done(); } -export function testMetadataModelRequestBeforeCompletingPreviousRequest( - callback: () => void) { +export async function testMetadataModelRequestBeforeCompletingPreviousRequest( + done: VoidCallback) { const provider = new TestMetadataProvider(); const model = new MetadataModel(provider); @@ -189,63 +162,53 @@ assertEquals(1, provider.requestCount); // The result of first call has not been fetched yet. - reportPromise( - model.get([entryA], ['thumbnailUrl']).then(results => { - assertEquals(1, provider.requestCount); - assertEquals( - 'filesystem://A:thumbnailUrl', - getProperty(results[0], 'thumbnailUrl')); - }), - callback); + const results = await model.get([entryA], ['thumbnailUrl']); + assertEquals(1, provider.requestCount); + assertEquals( + 'filesystem://A:thumbnailUrl', getProperty(results[0], 'thumbnailUrl')); + done(); } -export function testMetadataModelNotUpdateCachedResultAfterRequest( - callback: () => void) { +export async function testMetadataModelNotUpdateCachedResultAfterRequest( + done: VoidCallback) { const provider = new ManualTestMetadataProvider(); const model = new MetadataModel(provider); const promise = model.get([entryA], ['mediaAlbum']); provider.callback[0]!([{mediaAlbum: 'album1'}]); + await promise; - reportPromise( - promise - .then(() => { - // 'mediaAlbum' is cached here. - const promise1 = model.get([entryA], ['mediaAlbum', 'mediaArtist']); - const promise2 = model.get([entryA], ['alternateUrl']); - // Returns alternateUrl. - provider.callback[2]! - ([{mediaAlbum: 'album2', alternateUrl: 'urlC'}]); - provider.callback[1]!([{mediaArtist: 'artistB'}]); - return Promise.all([promise1, promise2]); - }) - .then(results => { - // The result should be cached value at the time when get was - // called. - assertEquals('album1', getProperty(results[0][0], 'mediaAlbum')); - assertEquals('artistB', getProperty(results[0][0], 'mediaArtist')); - assertEquals('urlC', getProperty(results[1][0], 'alternateUrl')); - }), - callback); + // 'mediaAlbum' is cached here. + const promise1 = model.get([entryA], ['mediaAlbum', 'mediaArtist']); + const promise2 = model.get([entryA], ['alternateUrl']); + // Returns alternateUrl. + provider.callback[2]!([{mediaAlbum: 'album2', alternateUrl: 'urlC'}]); + provider.callback[1]!([{mediaArtist: 'artistB'}]); + const results = await Promise.all([promise1, promise2]); + + // The result should be cached value at the time when get was + // called. + assertEquals('album1', getProperty(results[0][0], 'mediaAlbum')); + assertEquals('artistB', getProperty(results[0][0], 'mediaArtist')); + assertEquals('urlC', getProperty(results[1][0], 'alternateUrl')); + done(); } -export function testMetadataModelGetCache(callback: () => void) { +export async function testMetadataModelGetCache(done: VoidCallback) { const provider = new TestMetadataProvider(); const model = new MetadataModel(provider); const promise = model.get([entryA], ['thumbnailUrl']); - const cache = model.getCache([entryA], ['thumbnailUrl']); - assertEquals(null, getProperty(cache[0], 'thumbnailUrl')); + const emptyCacheResult = model.getCache([entryA], ['thumbnailUrl']); + assertEquals(null, getProperty(emptyCacheResult[0], 'thumbnailUrl')); - reportPromise( - promise.then(() => { - const cache = model.getCache([entryA], ['thumbnailUrl']); - assertEquals(1, provider.requestCount); - assertEquals( - 'filesystem://A:thumbnailUrl', - getProperty(cache[0], 'thumbnailUrl')); - }), - callback); + await promise; + const cachedResult = model.getCache([entryA], ['thumbnailUrl']); + assertEquals(1, provider.requestCount); + assertEquals( + 'filesystem://A:thumbnailUrl', + getProperty(cachedResult[0], 'thumbnailUrl')); + done(); } export function testMetadataModelUnknownProperty() { @@ -257,14 +220,12 @@ }); } -export function testMetadataModelEmptyResult(callback: () => void) { +export async function testMetadataModelEmptyResult(done: VoidCallback) { const provider = new TestEmptyMetadataProvider(); const model = new MetadataModel(provider); // getImpl returns empty result. - reportPromise( - model.get([entryA], ['thumbnailUrl']).then(results => { - assertEquals(undefined, getProperty(results[0], 'thumbnailUrl')); - }), - callback); + const results = await model.get([entryA], ['thumbnailUrl']); + assertEquals(undefined, getProperty(results[0], 'thumbnailUrl')); + done(); }
diff --git a/ui/file_manager/integration_tests/file_manager/drive_specific.js b/ui/file_manager/integration_tests/file_manager/drive_specific.js index 270b2d2..221a0fb5 100644 --- a/ui/file_manager/integration_tests/file_manager/drive_specific.js +++ b/ui/file_manager/integration_tests/file_manager/drive_specific.js
@@ -1768,3 +1768,32 @@ await remoteCall.waitForElement( appId, 'drive-out-of-organization-space-banner'); }; + +/** + * Tests that copy operation of a directory will start, but a error message will + * appear when encrypted files within that directory were skipped. + */ +testcase.copyDirectoryWithEncryptedFile = async () => { + const dir = ENTRIES.testCSEDirectory; + const file = ENTRIES.testCSEFileInDirectory; + const appId = await setupAndWaitUntilReady(RootPath.DRIVE, [], [dir, file]); + await sendTestMessage({name: 'mockDriveReadFailure', path: file.targetPath}); + + const directoryTree = await DirectoryTreePageObject.create(appId, remoteCall); + await directoryTree.navigateToPath('/My Drive'); + + await remoteCall.waitForFiles(appId, [dir.getExpectedRow()]); + await remoteCall.waitUntilSelected(appId, dir.nameText); + + await remoteCall.callRemoteTestUtil('execCommand', appId, ['copy']); + await directoryTree.navigateToPath('/My files/Downloads'); + await remoteCall.callRemoteTestUtil('execCommand', appId, ['paste']); + + const panelType = 3; // panelTypeError from PanelItem + const panel = await remoteCall.waitForElement( + appId, ['#progress-panel', `xf-panel-item[panel-type="${panelType}"]`]); + + chrome.test.assertEq( + 'Copy operation failed. The file or the directory is not usable.', + panel.attributes['primary-text']); +};
diff --git a/ui/file_manager/integration_tests/test_util.js b/ui/file_manager/integration_tests/test_util.js index ae30301..5a9cad0 100644 --- a/ui/file_manager/integration_tests/test_util.js +++ b/ui/file_manager/integration_tests/test_util.js
@@ -763,6 +763,27 @@ typeText: 'Plain text', }), + // The directory itself is not encrypted, but will contain encrypted entries + // like testCSEFileInDirectory + testCSEDirectory: new TestEntryInfo({ + type: EntryType.DIRECTORY, + targetPath: 'encrypted_files', + lastModifiedTime: 'Jan 1, 1980, 11:59 PM', + nameText: 'encrypted_files', + sizeText: '--', + typeText: 'Folder', + }), + + testCSEFileInDirectory: new TestEntryInfo({ + type: EntryType.FILE, + targetPath: 'encrypted_files/test.txt', + mimeType: 'application/vnd.google-gsuite.encrypted; content="text/plain"', + lastModifiedTime: 'Apr 10, 2013, 4:20 PM', + nameText: 'test.txt', + sizeText: '--', + typeText: 'Plain text', + }), + testDocument: new TestEntryInfo({ type: EntryType.FILE, targetPath: 'Test Document',
diff --git a/v8 b/v8 index 324cc1f..f2a4a2b 160000 --- a/v8 +++ b/v8
@@ -1 +1 @@ -Subproject commit 324cc1f85e9fb53da25afa270d6353a2167c9c96 +Subproject commit f2a4a2beba1d4056f6d1e66a16c15d70470c1051