diff --git a/DEPS b/DEPS index cc2d5d2b..5b34e362 100644 --- a/DEPS +++ b/DEPS
@@ -310,15 +310,15 @@ # 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': '2e28fe9de3788eafae518d23ff00c5e4adc3f316', + 'skia_revision': 'fbaad71dad8a7abfa20389328b5c39c649ac9ffb', # 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': '3c8fa8872aa3c71315a5e0de6e378692d3ce59cd', + 'v8_revision': '1c54e18f1bc19c30011502db657547f2780c7009', # 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': '82d68c577b1d4de4cf91ec3d531e325315e4dc09', + 'angle_revision': 'f586ec98d9245915b6e05789a2ebe33b368eae3b', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -381,7 +381,7 @@ # Three lines of non-changing comments so that # the commit queue can handle CLs rolling catapult # and whatever else without interference from each other. - 'catapult_revision': 'a02c178207f8ce794e10d587f30b0b8d97b5405d', + 'catapult_revision': 'b119dc414e34f9b572f778244fdafccc53ede286', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling CrossBench # and whatever else without interference from each other. @@ -397,7 +397,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': '18e5ec84a89d415ac0766257df40e3094311182a', + 'devtools_frontend_revision': '0fcdfce63229ef1ad6572d8ea339f22e46486b13', # 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. @@ -441,7 +441,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. - 'quiche_revision': '0cf55911ad11d31444f05a16e887fd86e4566db6', + 'quiche_revision': 'f45df57a4b14efe5dbfd9064f09410c62e787300', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling ios_webkit # and whatever else without interference from each other. @@ -828,7 +828,7 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - '253b2232f2e97a4b8061a25d24e92ff4d946a0ed', + 'dd96a3f48cb681e75aee6f597f4f79304439720f', 'condition': 'checkout_android and checkout_src_internal', }, @@ -837,7 +837,7 @@ }, 'src/ios/third_party/earl_grey2/src': { - 'url': Var('chromium_git') + '/external/github.com/google/EarlGrey.git' + '@' + '400b105586b4dd30f448ffffba9a4d085d4b443e', + 'url': Var('chromium_git') + '/external/github.com/google/EarlGrey.git' + '@' + 'a667114b53e993758f10525de180e65225eb5564', 'condition': 'checkout_ios', }, @@ -927,7 +927,7 @@ 'packages': [ { 'package': 'chromium/rts/model/linux-amd64', - 'version': 'WqYOUIgHb1z5-y1jFHWtRGkGh1BghLjKERx5prmk92MC', + 'version': 'L3SFUyXNZh5TGONBi75lNRsvYNMQchCI7-9wMAeQk-EC', }, ], 'dep_type': 'cipd', @@ -938,7 +938,7 @@ 'packages': [ { 'package': 'chromium/rts/model/mac-amd64', - 'version': 's--ut8OEgZIiRTlVPZWjRzVO6fTyb95k4gmgzPxocvcC', + 'version': 'Z1yB_HDvVAAG3JUgO5UVg2WsiuFBNFGE6-4O94j0Um0C', }, ], 'dep_type': 'cipd', @@ -949,7 +949,7 @@ 'packages': [ { 'package': 'chromium/rts/model/windows-amd64', - 'version': 'Rltx_q1bJNfQ4MGHYc7-wwfxbKiPP8fUgjPe9ITKSwAC', + 'version': 'h6ii5txwnl3YZ_QAiczeSzBSr_64B2F_tPBEARfPzA8C', }, ], 'dep_type': 'cipd', @@ -1264,13 +1264,13 @@ }, 'src/third_party/depot_tools': - Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + '82e4859614a2cb437fdb1e89bca2d690853ec6cc', + Var('chromium_git') + '/chromium/tools/depot_tools.git' + '@' + 'd411904b84c0d9f539bbdc84e3d63f9f282c658b', 'src/third_party/devtools-frontend/src': Var('chromium_git') + '/devtools/devtools-frontend' + '@' + Var('devtools_frontend_revision'), 'src/third_party/devtools-frontend-internal': { - 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + 'e55d0c62ef68aec1561306f68b7b4d24c3b3097d', + 'url': Var('chrome_git') + '/devtools/devtools-internal.git' + '@' + '897de235f54393522b0470b0bddde16aeaeabb1d', 'condition': 'checkout_src_internal', }, @@ -1739,7 +1739,7 @@ Var('pdfium_git') + '/pdfium.git' + '@' + Var('pdfium_revision'), 'src/third_party/perfetto': - Var('android_git') + '/platform/external/perfetto.git' + '@' + 'b818113360902219bf3ab4fb81993eb3832b2a37', + Var('android_git') + '/platform/external/perfetto.git' + '@' + 'f613d0c723807f40557bbe58b7398515b1cb1ae9', 'src/third_party/perl': { 'url': Var('chromium_git') + '/chromium/deps/perl.git' + '@' + '6f3e5028eb65d0b4c5fdd792106ac4c84eee1eb3', @@ -1924,7 +1924,7 @@ Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + 'f3351ce131a724fe67449ae1b411eceff2d93159', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + 'e546ff99a6b0298336eb3160b55096baddae252d', + Var('webrtc_git') + '/src.git' + '@' + '0689cfc6ce15d7c622ce225475c60817493fb048', # 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. @@ -4211,7 +4211,7 @@ 'src/ios_internal': { 'url': Var('chrome_git') + '/chrome/ios_internal.git' + '@' + - '199ebfcc600ad64edeb39838fc3c771f4e04315c', + '70e76f8998fe0df84debf6585cb3d96d128d2f98', 'condition': 'checkout_ios and checkout_src_internal', },
diff --git a/ash/BUILD.gn b/ash/BUILD.gn index 0fb6f527..6e91f49 100644 --- a/ash/BUILD.gn +++ b/ash/BUILD.gn
@@ -557,6 +557,8 @@ "events/keyboard_capability_delegate_impl.h", "events/keyboard_driven_event_rewriter.cc", "events/keyboard_driven_event_rewriter.h", + "events/peripheral_customization_event_rewriter.cc", + "events/peripheral_customization_event_rewriter.h", "events/select_to_speak_event_handler.cc", "events/select_to_speak_event_handler.h", "fast_ink/cursor/cursor_view.cc", @@ -3141,6 +3143,7 @@ "events/accessibility_event_rewriter_unittest.cc", "events/keyboard_capability_unittest.cc", "events/keyboard_driven_event_rewriter_unittest.cc", + "events/peripheral_customization_event_rewriter_unittest.cc", "events/select_to_speak_event_handler_unittest.cc", "extended_desktop_unittest.cc", "fast_ink/fast_ink_host_frame_utils_unittest.cc",
diff --git a/ash/ambient/ui/ambient_slideshow_pixeltest.cc b/ash/ambient/ui/ambient_slideshow_pixeltest.cc index 1b2be4c..b0b3072 100644 --- a/ash/ambient/ui/ambient_slideshow_pixeltest.cc +++ b/ash/ambient/ui/ambient_slideshow_pixeltest.cc
@@ -14,6 +14,8 @@ #include "ash/shell.h" #include "ash/test/pixel/ash_pixel_differ.h" #include "base/strings/strcat.h" +#include "base/test/scoped_feature_list.h" +#include "chromeos/constants/chromeos_features.h" #include "services/media_session/public/cpp/media_metadata.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -26,7 +28,8 @@ using TestParams = std::tuple<absl::optional<media_session::MediaMetadata>, /*dark_mode=*/bool, - /*rtl=*/bool>; + /*rtl=*/bool, + /*jelly=*/bool>; std::array<absl::optional<media_session::MediaMetadata>, 3> GetMediaMedataVariations() { @@ -49,6 +52,10 @@ return std::get<2>(param); } +bool IsJellyEnabled(const TestParams& param) { + return std::get<3>(param); +} + const absl::optional<media_session::MediaMetadata>& GetMediaMetadata( const TestParams& param) { return std::get<absl::optional<media_session::MediaMetadata>>(param); @@ -65,9 +72,14 @@ } else { metadata_description_text = "Longmedia"; } - return base::StrCat({metadata_description_text, - IsDarkMode(param_info.param) ? "Dark" : "Light", - IsRtl(param_info.param) ? "Rtl" : "Ltr"}); + std::vector<std::string> attributes = { + metadata_description_text, + IsDarkMode(param_info.param) ? "Dark" : "Light", + IsRtl(param_info.param) ? "Rtl" : "Ltr"}; + if (!IsJellyEnabled(param_info.param)) { + attributes.push_back("PreJelly"); + } + return base::StrCat(attributes); } } // namespace @@ -84,6 +96,8 @@ } void SetUp() override { + scoped_features_.InitWithFeatureState(chromeos::features::kJelly, + IsJellyEnabled(GetParam())); AmbientAshTestBase::SetUp(); SetAmbientTheme(AmbientTheme::kSlideshow); GetSessionControllerClient()->set_show_lock_screen_views(true); @@ -105,6 +119,9 @@ CloseAmbientScreen(); AmbientAshTestBase::TearDown(); } + + private: + base::test::ScopedFeatureList scoped_features_; }; INSTANTIATE_TEST_SUITE_P( @@ -112,6 +129,7 @@ AmbientSlideshowPixelTest, testing::Combine(::testing::ValuesIn(GetMediaMedataVariations()), testing::Bool(), + testing::Bool(), testing::Bool()), &GetName); @@ -127,8 +145,11 @@ media_session::mojom::MediaPlaybackState::kPlaying); } + // Revision 1 is with Jelly enabled. Revision 0 is with Jelly disabled to + // guard against regressions until the flag is fully launched. EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( - "AmbientSlideshow", /*revision_number=*/0, + "AmbientSlideshow", + /*revision_number=*/IsJellyEnabled(GetParam()) ? 1 : 0, ash::Shell::GetPrimaryRootWindow())); }
diff --git a/ash/app_list/views/app_list_view_pixeltest.cc b/ash/app_list/views/app_list_view_pixeltest.cc index 88fb3533..3f80757 100644 --- a/ash/app_list/views/app_list_view_pixeltest.cc +++ b/ash/app_list/views/app_list_view_pixeltest.cc
@@ -36,7 +36,7 @@ namespace { -using TestVariantsParam = std::tuple<bool, bool, bool>; +using TestVariantsParam = std::tuple<bool, bool, bool, bool>; bool IsRtl(TestVariantsParam param) { return std::get<0>(param); @@ -50,6 +50,10 @@ return std::get<2>(param); } +bool JellyEnabled(TestVariantsParam param) { + return std::get<3>(param); +} + std::string GenerateTestSuffix( const testing::TestParamInfo<TestVariantsParam>& info) { std::string suffix; @@ -58,6 +62,10 @@ suffix.append(IsDarkMode(info.param) ? "dark" : "light"); suffix.append("_"); suffix.append(IsTabletMode(info.param) ? "tablet" : "clamshell"); + // Only add a suffix is Jelly is disabled so this is easier to delete. + if (!JellyEnabled(info.param)) { + suffix.append("PreJelly"); + } return suffix; } @@ -258,6 +266,9 @@ } void SetUp() override { + scoped_features_.InitWithFeatureState(chromeos::features::kJelly, + JellyEnabled(GetParam())); + AssistantAshTestBase::SetUp(); DarkLightModeController::Get()->SetDarkModeEnabledForTest( @@ -272,12 +283,16 @@ true); GetAppListTestHelper()->GetSearchBoxView()->SetIsIphAllowed(true); } + + private: + base::test::ScopedFeatureList scoped_features_; }; INSTANTIATE_TEST_SUITE_P(RTL, AppListViewLauncherSearchIphTest, testing::Combine(testing::Bool(), testing::Bool(), + testing::Bool(), testing::Bool()), &GenerateTestSuffix); @@ -305,17 +320,20 @@ class AppListViewTabletPixelTest : public AshTestBase, - public testing::WithParamInterface</*tablet_mode=*/bool> { + public testing::WithParamInterface< + std::tuple</*jelly_enabled=*/bool, /*rtl=*/bool>> { public: // AshTestBase: absl::optional<pixel_test::InitParams> CreatePixelTestInitParams() const override { pixel_test::InitParams init_params; - init_params.under_rtl = GetParam(); + init_params.under_rtl = IsRtl(); return init_params; } void SetUp() override { + scoped_features_.InitWithFeatureState(chromeos::features::kJelly, + IsJellyEnabled()); AshTestBase::SetUp(); Shell::Get()->tablet_mode_controller()->SetEnabledForTest(true); @@ -326,15 +344,26 @@ /*num_apps=*/32, AppListTestHelper::IconColorType::kAlternativeColor, /*set_name=*/true); } + + protected: + bool IsJellyEnabled() const { return std::get<0>(GetParam()); } + + bool IsRtl() const { return std::get<1>(GetParam()); } + + private: + base::test::ScopedFeatureList scoped_features_; }; -INSTANTIATE_TEST_SUITE_P(RTL, AppListViewTabletPixelTest, testing::Bool()); +INSTANTIATE_TEST_SUITE_P(RTL, + AppListViewTabletPixelTest, + testing::Combine(testing::Bool(), testing::Bool())); // Verifies the default layout for tablet mode launcher. TEST_P(AppListViewTabletPixelTest, Basic) { EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( "tablet_launcher_basics", - /*revision_number=*/1, GetAppListTestHelper()->GetAppsContainerView())); + /*revision_number=*/IsJellyEnabled() ? 2 : 1, + GetAppListTestHelper()->GetAppsContainerView())); } // Verifies that the top gradient zone of the tablet mode launcher works @@ -355,7 +384,8 @@ EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( "tablet_launcher_top_gradient_zone", - /*revision_number=*/1, GetAppListTestHelper()->GetAppsContainerView())); + /*revision_number=*/IsJellyEnabled() ? 2 : 1, + GetAppListTestHelper()->GetAppsContainerView())); } // Verifies that the bottom gradient zone of the tablet mode launcher works @@ -376,7 +406,8 @@ EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( "tablet_launcher_bottom_gradient_zone", - /*revision_number=*/1, GetAppListTestHelper()->GetAppsContainerView())); + /*revision_number=*/IsJellyEnabled() ? 2 : 1, + GetAppListTestHelper()->GetAppsContainerView())); } TEST_P(AppListViewTabletPixelTest, SearchBoxViewActive) { @@ -385,7 +416,8 @@ search_box_view->SetSearchBoxActive(true, ui::EventType::ET_UNKNOWN); EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( - "search_box_view_active", /*revision_number=*/0, search_box_view)); + "search_box_view_active", + /*revision_number=*/IsJellyEnabled() ? 1 : 0, search_box_view)); } class AppListViewAssistantZeroStateTest @@ -418,7 +450,8 @@ AppListViewAssistantZeroStateTest, testing::Combine(/*IsRtl=*/testing::Bool(), /*IsDarkMode=*/testing::Bool(), - /*IsTabletMode=*/testing::Bool()), + /*IsTabletMode=*/testing::Bool(), + /*JellyEnabled=*/testing::Bool()), &GenerateTestSuffix); TEST_P(AppListViewAssistantZeroStateTest, Basic) { @@ -426,7 +459,8 @@ base::RunLoop().RunUntilIdle(); EXPECT_TRUE(GetPixelDiffer()->CompareUiComponentsOnPrimaryScreen( - "app_list_view_assistant_zero_state", /*revision_number=*/1, + "app_list_view_assistant_zero_state", + /*revision_number=*/JellyEnabled(GetParam()) ? 0 : 1, page_view()->GetViewByID(AssistantViewID::kZeroStateView))); }
diff --git a/ash/components/arc/metrics/stability_metrics_manager.h b/ash/components/arc/metrics/stability_metrics_manager.h index 7db4ac9..ff23a8e 100644 --- a/ash/components/arc/metrics/stability_metrics_manager.h +++ b/ash/components/arc/metrics/stability_metrics_manager.h
@@ -57,7 +57,7 @@ ~StabilityMetricsManager(); SEQUENCE_CHECKER(sequence_checker_); - const raw_ptr<PrefService, DanglingUntriaged | ExperimentalAsh> local_state_; + const raw_ptr<PrefService, ExperimentalAsh> local_state_; }; } // namespace arc
diff --git a/ash/events/OWNERS b/ash/events/OWNERS index 9bd82353..5c6747d 100644 --- a/ash/events/OWNERS +++ b/ash/events/OWNERS
@@ -1,3 +1,4 @@ per-file accessibility_event_rewriter*=file://ash/accessibility/OWNERS per-file select_to_speak_event_handler*=file://ash/accessibility/OWNERS per-file keyboard_capability*=zentaro@chromium.org,dpad@google.com +per-file peripheral_customization*=zentaro@chromium.org
diff --git a/ash/events/event_rewriter_controller_impl.cc b/ash/events/event_rewriter_controller_impl.cc index a8f8db2..7c8825b06 100644 --- a/ash/events/event_rewriter_controller_impl.cc +++ b/ash/events/event_rewriter_controller_impl.cc
@@ -7,11 +7,13 @@ #include <utility> #include "ash/accessibility/sticky_keys/sticky_keys_controller.h" +#include "ash/constants/ash_features.h" #include "ash/display/mirror_window_controller.h" #include "ash/display/privacy_screen_controller.h" #include "ash/display/window_tree_host_manager.h" #include "ash/events/accessibility_event_rewriter.h" #include "ash/events/keyboard_driven_event_rewriter.h" +#include "ash/events/peripheral_customization_event_rewriter.h" #include "ash/public/cpp/accessibility_event_rewriter_delegate.h" #include "ash/shell.h" #include "base/command_line.h" @@ -64,6 +66,15 @@ Shell::Get()->sticky_keys_controller(), privacy_screen_supported); event_rewriter_ash_ = event_rewriter_ash.get(); + std::unique_ptr<PeripheralCustomizationEventRewriter> + peripheral_customization_event_rewriter; + if (features::IsPeripheralCustomizationEnabled()) { + peripheral_customization_event_rewriter = + std::make_unique<PeripheralCustomizationEventRewriter>(); + peripheral_customization_event_rewriter_ = + peripheral_customization_event_rewriter.get(); + } + std::unique_ptr<AccessibilityEventRewriter> accessibility_event_rewriter = std::make_unique<AccessibilityEventRewriter>( event_rewriter_ash.get(), accessibility_event_rewriter_delegate); @@ -71,6 +82,9 @@ // EventRewriters are notified in the order they are added. AddEventRewriter(std::move(accessibility_event_rewriter)); + if (features::IsPeripheralCustomizationEnabled()) { + AddEventRewriter(std::move(peripheral_customization_event_rewriter)); + } AddEventRewriter(std::move(keyboard_driven_event_rewriter)); AddEventRewriter(std::move(event_rewriter_ash)); }
diff --git a/ash/events/event_rewriter_controller_impl.h b/ash/events/event_rewriter_controller_impl.h index 77d5a780..8ae4e90d 100644 --- a/ash/events/event_rewriter_controller_impl.h +++ b/ash/events/event_rewriter_controller_impl.h
@@ -9,6 +9,7 @@ #include <vector> #include "ash/ash_export.h" +#include "ash/events/peripheral_customization_event_rewriter.h" #include "ash/public/cpp/event_rewriter_controller.h" #include "base/memory/raw_ptr.h" #include "ui/aura/env_observer.h" @@ -66,6 +67,8 @@ // Owned by |rewriters_|. raw_ptr<AccessibilityEventRewriter, ExperimentalAsh> accessibility_event_rewriter_ = nullptr; + raw_ptr<PeripheralCustomizationEventRewriter, ExperimentalAsh> + peripheral_customization_event_rewriter_ = nullptr; raw_ptr<KeyboardDrivenEventRewriter, ExperimentalAsh> keyboard_driven_event_rewriter_ = nullptr; raw_ptr<ui::EventRewriterAsh, ExperimentalAsh> event_rewriter_ash_ = nullptr;
diff --git a/ash/events/peripheral_customization_event_rewriter.cc b/ash/events/peripheral_customization_event_rewriter.cc new file mode 100644 index 0000000..9cbdf04 --- /dev/null +++ b/ash/events/peripheral_customization_event_rewriter.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 "ash/events/peripheral_customization_event_rewriter.h" + +#include "ash/constants/ash_features.h" +#include "base/check.h" + +namespace ash { + +PeripheralCustomizationEventRewriter::PeripheralCustomizationEventRewriter() = + default; +PeripheralCustomizationEventRewriter::~PeripheralCustomizationEventRewriter() = + default; + +ui::EventDispatchDetails PeripheralCustomizationEventRewriter::RewriteEvent( + const ui::Event& event, + const Continuation continuation) { + DCHECK(features::IsPeripheralCustomizationEnabled()); + return SendEvent(continuation, &event); +} + +} // namespace ash
diff --git a/ash/events/peripheral_customization_event_rewriter.h b/ash/events/peripheral_customization_event_rewriter.h new file mode 100644 index 0000000..3482437 --- /dev/null +++ b/ash/events/peripheral_customization_event_rewriter.h
@@ -0,0 +1,35 @@ +// 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 ASH_EVENTS_PERIPHERAL_CUSTOMIZATION_EVENT_REWRITER_H_ +#define ASH_EVENTS_PERIPHERAL_CUSTOMIZATION_EVENT_REWRITER_H_ + +#include "ash/ash_export.h" +#include "ui/events/event.h" +#include "ui/events/event_rewriter.h" + +namespace ash { + +// PeripheralCustomizationEventRewriter recognizes and rewrites events from mice +// and graphics tablets to arbitrary `ui::KeyEvent`s configured by the user via +// the Settings SWA. +class ASH_EXPORT PeripheralCustomizationEventRewriter + : public ui::EventRewriter { + public: + PeripheralCustomizationEventRewriter(); + PeripheralCustomizationEventRewriter( + const PeripheralCustomizationEventRewriter&) = delete; + PeripheralCustomizationEventRewriter& operator=( + const PeripheralCustomizationEventRewriter&) = delete; + ~PeripheralCustomizationEventRewriter() override; + + // ui::EventRewriter: + ui::EventDispatchDetails RewriteEvent( + const ui::Event& event, + const Continuation continuation) override; +}; + +} // namespace ash + +#endif // ASH_EVENTS_PERIPHERAL_CUSTOMIZATION_EVENT_REWRITER_H_
diff --git a/ash/events/peripheral_customization_event_rewriter_unittest.cc b/ash/events/peripheral_customization_event_rewriter_unittest.cc new file mode 100644 index 0000000..9a1f1fb7 --- /dev/null +++ b/ash/events/peripheral_customization_event_rewriter_unittest.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 "ash/events/peripheral_customization_event_rewriter.h" + +#include "ash/test/ash_test_base.h" + +namespace ash { + +class PeripheralCustomizationEventRewriterTest : public AshTestBase { + public: + PeripheralCustomizationEventRewriterTest() = default; + PeripheralCustomizationEventRewriterTest( + const PeripheralCustomizationEventRewriterTest&) = delete; + PeripheralCustomizationEventRewriterTest& operator=( + const PeripheralCustomizationEventRewriterTest&) = delete; + ~PeripheralCustomizationEventRewriterTest() override = default; + + // testing::Test: + void SetUp() override { + AshTestBase::SetUp(); + rewriter_ = std::make_unique<PeripheralCustomizationEventRewriter>(); + } + + void TearDown() override { + rewriter_.reset(); + AshTestBase::TearDown(); + } + + protected: + std::unique_ptr<PeripheralCustomizationEventRewriter> rewriter_; +}; + +TEST_F(PeripheralCustomizationEventRewriterTest, InitializationTest) { + EXPECT_NE(rewriter_.get(), nullptr); +} + +} // namespace ash
diff --git a/ash/glanceables/tasks/glanceables_task_view.cc b/ash/glanceables/tasks/glanceables_task_view.cc index 9789f1b..95b4158 100644 --- a/ash/glanceables/tasks/glanceables_task_view.cc +++ b/ash/glanceables/tasks/glanceables_task_view.cc
@@ -18,6 +18,7 @@ #include "ui/color/color_provider.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/background.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/button_controller.h" #include "ui/views/controls/image_view.h" @@ -26,10 +27,12 @@ namespace { constexpr int kIconSize = 20; -constexpr int kTaskHeight = 48; -constexpr int kTaskWidth = 332; constexpr char kFormatterPattern[] = "EEE, MMM d"; // "Wed, Feb 28" +constexpr int kBackgroundRadius = 4; +constexpr auto kInteriorMargin = gfx::Insets::VH(8, 0); +constexpr auto kButtonMargin = gfx::Insets(18); + views::Label* SetupLabel(views::FlexLayoutView* parent) { views::Label* label = parent->AddChildView(std::make_unique<views::Label>()); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); @@ -63,6 +66,12 @@ GlanceablesTaskView::GlanceablesTaskView(const std::string& task_list_id, const GlanceablesTask* task) : task_list_id_(task_list_id), task_id_(task->id) { + SetCrossAxisAlignment(views::LayoutAlignment::kStretch); + SetInteriorMargin(kInteriorMargin); + + SetBackground(views::CreateThemedRoundedRectBackground( + cros_tokens::kCrosSysSystemOnBase, kBackgroundRadius)); + button_ = AddChildView(std::make_unique<views::ImageButton>(base::BindRepeating( &GlanceablesTaskView::ButtonPressed, base::Unretained(this)))); @@ -72,10 +81,16 @@ cros_tokens::kFocusRingColor, kIconSize)); // TODO(b:277268122): set accessible name once spec is available. button_->SetAccessibleName(u"Glanceables Task View Button"); + button_->SetProperty(views::kMarginsKey, kButtonMargin); contents_view_ = AddChildView(std::make_unique<views::FlexLayoutView>()); - contents_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStart); + contents_view_->SetCrossAxisAlignment(views::LayoutAlignment::kStretch); + contents_view_->SetMainAxisAlignment(views::LayoutAlignment::kCenter); contents_view_->SetOrientation(views::LayoutOrientation::kVertical); + contents_view_->SetProperty( + views::kFlexBehaviorKey, + views::FlexSpecification(views::MinimumFlexSizeRule::kPreferred, + views::MaximumFlexSizeRule::kUnbounded)); tasks_title_view_ = contents_view_->AddChildView(std::make_unique<views::FlexLayoutView>()); @@ -84,6 +99,8 @@ tasks_label->SetText(base::UTF8ToUTF16(task->title)); tasks_label->SetFontList(TypographyProvider::Get()->ResolveTypographyToken( TypographyToken::kCrosButton2)); + tasks_label->SetLineHeight(TypographyProvider::Get()->ResolveLineHeight( + TypographyToken::kCrosButton2)); if (chromeos::features::IsJellyEnabled()) { tasks_label->SetEnabledColorId(cros_tokens::kCrosSysOnSurface); } else { @@ -101,6 +118,8 @@ due_date_label->SetFontList( TypographyProvider::Get()->ResolveTypographyToken( TypographyToken::kCrosAnnotation1)); + tasks_label->SetLineHeight(TypographyProvider::Get()->ResolveLineHeight( + TypographyToken::kCrosAnnotation1)); if (chromeos::features::IsJellyEnabled()) { time_icon_view->SetImage(ui::ImageModel::FromVectorIcon( @@ -143,10 +162,6 @@ cros_tokens::kFocusRingColor, kIconSize)); } -gfx::Size GlanceablesTaskView::CalculatePreferredSize() const { - return gfx::Size(kTaskWidth, kTaskHeight); -} - BEGIN_METADATA(GlanceablesTaskView, views::View) END_METADATA
diff --git a/ash/glanceables/tasks/glanceables_task_view.h b/ash/glanceables/tasks/glanceables_task_view.h index 493eb9a..5d2fcdb 100644 --- a/ash/glanceables/tasks/glanceables_task_view.h +++ b/ash/glanceables/tasks/glanceables_task_view.h
@@ -46,9 +46,6 @@ void ButtonPressed(); void MarkedAsCompleted(bool success); - // views::View: - gfx::Size CalculatePreferredSize() const override; - const views::ImageButton* GetButtonForTest() const { return button_; } bool GetCompletedForTest() const { return completed_; }
diff --git a/ash/system/caps_lock_notification_controller.cc b/ash/system/caps_lock_notification_controller.cc index 55b4d7b..851346a9 100644 --- a/ash/system/caps_lock_notification_controller.cc +++ b/ash/system/caps_lock_notification_controller.cc
@@ -104,8 +104,7 @@ if (enabled) { base::RecordAction(base::UserMetricsAction("StatusArea_CapsLock_Popup")); MessageCenter::Get()->AddNotification(CreateNotification()); - } else if (MessageCenter::Get()->FindVisibleNotificationById( - kCapsLockNotificationId)) { + } else { MessageCenter::Get()->RemoveNotification(kCapsLockNotificationId, false); } }
diff --git a/ash/system/network/network_detailed_network_view.cc b/ash/system/network/network_detailed_network_view.cc index 37b5a24..3c69cfb1c 100644 --- a/ash/system/network/network_detailed_network_view.cc +++ b/ash/system/network/network_detailed_network_view.cc
@@ -33,4 +33,8 @@ g_test_factory = test_factory; } +int NetworkDetailedNetworkView::GetScrollPosition() { + return 0; +} + } // namespace ash \ No newline at end of file
diff --git a/ash/system/network/network_detailed_network_view.h b/ash/system/network/network_detailed_network_view.h index 2217b566..33e828b 100644 --- a/ash/system/network/network_detailed_network_view.h +++ b/ash/system/network/network_detailed_network_view.h
@@ -108,6 +108,11 @@ virtual void UpdateWifiStatus(bool enabled) = 0; virtual void UpdateMobileStatus(bool enabled) = 0; + // Provides some virtual methods to get and set the scroll view's position + // before and after reordering the network list. + virtual void ScrollToPosition(int position) {} + virtual int GetScrollPosition(); + protected: explicit NetworkDetailedNetworkView(Delegate* delegate);
diff --git a/ash/system/network/network_detailed_network_view_impl.cc b/ash/system/network/network_detailed_network_view_impl.cc index 70ff4ab..dedeb7c 100644 --- a/ash/system/network/network_detailed_network_view_impl.cc +++ b/ash/system/network/network_detailed_network_view_impl.cc
@@ -27,6 +27,7 @@ #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/controls/image_view.h" +#include "ui/views/controls/scroll_view.h" #include "ui/views/view.h" #include "ui/views/view_class_properties.h" @@ -237,6 +238,17 @@ } } +void NetworkDetailedNetworkViewImpl::ScrollToPosition(int position) { + if (GetScrollPosition() == position) { + return; + } + scroller()->ScrollToPosition(scroller()->vertical_scroll_bar(), position); +} + +int NetworkDetailedNetworkViewImpl::GetScrollPosition() { + return scroller()->GetVisibleRect().y(); +} + void NetworkDetailedNetworkViewImpl::OnMobileToggleClicked(bool new_state) { NetworkDetailedNetworkView::delegate()->OnMobileToggleClicked(new_state); }
diff --git a/ash/system/network/network_detailed_network_view_impl.h b/ash/system/network/network_detailed_network_view_impl.h index 19229960..e56c9105 100644 --- a/ash/system/network/network_detailed_network_view_impl.h +++ b/ash/system/network/network_detailed_network_view_impl.h
@@ -59,6 +59,8 @@ void MaybeRemoveFirstListView() override; void UpdateWifiStatus(bool enabled) override; void UpdateMobileStatus(bool enabled) override; + void ScrollToPosition(int position) override; + int GetScrollPosition() override; // NetworkListNetworkHeaderView::Delegate: void OnMobileToggleClicked(bool new_state) override;
diff --git a/ash/system/network/network_list_view_controller_impl.cc b/ash/system/network/network_list_view_controller_impl.cc index ff76c62..c008683 100644 --- a/ash/system/network/network_list_view_controller_impl.cc +++ b/ash/system/network/network_list_view_controller_impl.cc
@@ -185,6 +185,8 @@ void NetworkListViewControllerImpl::OnGetNetworkStateList( std::vector<NetworkStatePropertiesPtr> networks) { + int old_position = network_detailed_network_view()->GetScrollPosition(); + // Indicates the current position a view will be added to in // `NetworkDetailedNetworkView` scroll list. size_t index = 0; @@ -369,6 +371,10 @@ FocusLastSelectedView(); network_detailed_network_view()->NotifyNetworkListChanged(); + + // Resets the scrolling position to the old position to avoid and position + // change during reordering the child views in the list. + network_detailed_network_view()->ScrollToPosition(old_position); } void NetworkListViewControllerImpl::UpdateNetworkTypeExistence(
diff --git a/ash/system/network/network_list_view_controller_unittest.cc b/ash/system/network/network_list_view_controller_unittest.cc index f447e19..c945aa9db 100644 --- a/ash/system/network/network_list_view_controller_unittest.cc +++ b/ash/system/network/network_list_view_controller_unittest.cc
@@ -17,6 +17,7 @@ #include "ash/style/ash_color_provider.h" #include "ash/style/switch.h" #include "ash/system/model/system_tray_model.h" +#include "ash/system/network/network_detailed_network_view.h" #include "ash/system/network/network_detailed_network_view_impl.h" #include "ash/system/network/network_utils.h" #include "ash/system/network/tray_network_state_model.h" @@ -479,6 +480,11 @@ .IsRunning(); } + NetworkDetailedNetworkView* network_detailed_network_view() { + return static_cast<NetworkDetailedNetworkView*>( + network_list_view_controller_impl_->network_detailed_network_view_); + } + views::View* network_list(NetworkType type) { return static_cast<NetworkDetailedNetworkView*>( network_detailed_network_view_) @@ -937,6 +943,73 @@ } TEST_P(NetworkListViewControllerTest, + StaysInTheSamePositionAfterUpdatingNetworks) { + // Sets a screen with a limited height to make sure it can be scrollable. + UpdateDisplay("500x200"); + + // Adds an enabled wifi device. + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + kWifiName, NetworkType::kWiFi, ConnectionStateType::kNotConnected)); + + CheckNetworkListOrdering(/*ethernet_network_count=*/0, + /*mobile_network_count=*/-1, + /*wifi_network_count=*/1); + + // Adds mobile network. + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + kCellularName, NetworkType::kCellular, + ConnectionStateType::kConnected)); + + CheckNetworkListOrdering(/*ethernet_network_count=*/0, + /*mobile_network_count=*/1, + /*wifi_network_count=*/1); + + // Lets the network list scroll to a random number. + network_detailed_network_view()->ScrollToPosition(23); + + // Adds 5 more Wifi network. The scroll position should not change after each + // time the new network is added. + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + kWifiName2, NetworkType::kWiFi, ConnectionStateType::kNotConnected)); + EXPECT_EQ(23, network_detailed_network_view()->GetScrollPosition()); + + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + "wifi_3", NetworkType::kWiFi, ConnectionStateType::kNotConnected)); + EXPECT_EQ(23, network_detailed_network_view()->GetScrollPosition()); + + // Scrolls to another position. + network_detailed_network_view()->ScrollToPosition(37); + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + "wifi_4", NetworkType::kWiFi, ConnectionStateType::kNotConnected)); + EXPECT_EQ(37, network_detailed_network_view()->GetScrollPosition()); + + cros_network()->RemoveNthNetworks(0); + EXPECT_EQ(37, network_detailed_network_view()->GetScrollPosition()); + + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + "wifi_5", NetworkType::kWiFi, ConnectionStateType::kNotConnected)); + EXPECT_EQ(37, network_detailed_network_view()->GetScrollPosition()); + + cros_network()->RemoveNthNetworks(1); + EXPECT_EQ(37, network_detailed_network_view()->GetScrollPosition()); + + cros_network()->AddNetworkAndDevice( + CrosNetworkConfigTestHelper::CreateStandaloneNetworkProperties( + "wifi_6", NetworkType::kWiFi, ConnectionStateType::kNotConnected)); + + CheckNetworkListOrdering(/*ethernet_network_count=*/0, + /*mobile_network_count=*/1, + /*wifi_network_count=*/4); + EXPECT_EQ(37, network_detailed_network_view()->GetScrollPosition()); +} + +TEST_P(NetworkListViewControllerTest, CellularStatusMessageAndToggleButtonState) { EXPECT_THAT(GetMobileStatusMessage(), IsNull());
diff --git a/ash/system/toast/system_nudge_view.cc b/ash/system/toast/system_nudge_view.cc index 7305e23..8cfb180 100644 --- a/ash/system/toast/system_nudge_view.cc +++ b/ash/system/toast/system_nudge_view.cc
@@ -13,12 +13,14 @@ #include "ash/strings/grit/ash_strings.h" #include "ash/style/ash_color_id.h" #include "ash/style/pill_button.h" +#include "ash/style/system_shadow.h" #include "ash/style/typography.h" #include "chromeos/constants/chromeos_features.h" #include "ui/base/metadata/metadata_impl_macros.h" #include "ui/chromeos/styles/cros_tokens_color_mappings.h" #include "ui/compositor/layer.h" #include "ui/gfx/geometry/insets.h" +#include "ui/gfx/geometry/point.h" #include "ui/views/background.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" @@ -62,6 +64,9 @@ constexpr int kImageViewTrailingPadding = 20; constexpr int kTitleBottomPadding = 8; +// Shadow constants +constexpr gfx::Point kShadowOrigin = gfx::Point(8, 8); + void AddPaddingView(views::View* parent, int width, int height) { parent->AddChildView(std::make_unique<views::View>()) ->SetPreferredSize(gfx::Size(width, height)); @@ -221,6 +226,22 @@ SystemNudgeView::~SystemNudgeView() = default; +void SystemNudgeView::AddedToWidget() { + // Since nudges have a large corner radius, we use the shadow on texture + // layer. Refer to `ash::SystemShadowOnTextureLayer` for more details. + shadow_ = + SystemShadow::CreateShadowOnTextureLayer(SystemShadow::Type::kElevation4); + shadow_->SetRoundedCornerRadius(kNudgeCornerRadius); + shadow_->SetContentBounds(gfx::Rect(kShadowOrigin, GetPreferredSize())); + + // Attach the shadow at the bottom of the widget layer. + auto* shadow_layer = shadow_->GetLayer(); + auto* widget_layer = GetWidget()->GetLayer(); + + widget_layer->Add(shadow_layer); + widget_layer->StackAtBottom(shadow_layer); +} + void SystemNudgeView::SetLabelsMaxWidth(int max_width) { if (title_label_) { title_label_->SetMaximumWidthSingleLine(max_width);
diff --git a/ash/system/toast/system_nudge_view.h b/ash/system/toast/system_nudge_view.h index 8092716..6e68d6d 100644 --- a/ash/system/toast/system_nudge_view.h +++ b/ash/system/toast/system_nudge_view.h
@@ -19,6 +19,7 @@ namespace ash { struct AnchoredNudgeData; +class SystemShadow; // The System Nudge view. (go/cros-educationalnudge-spec) // This view supports different configurations depending on the provided @@ -48,6 +49,11 @@ raw_ptr<views::LabelButton> first_button_ = nullptr; raw_ptr<views::LabelButton> second_button_ = nullptr; + std::unique_ptr<SystemShadow> shadow_; + + // views::View: + void AddedToWidget() override; + // Sets the maximum width for `title_label_` and `body_label_`. void SetLabelsMaxWidth(int max_width);
diff --git a/ash/system/unified/tasks_bubble_view.cc b/ash/system/unified/tasks_bubble_view.cc index 5e2cf4b9..9eed8bb 100644 --- a/ash/system/unified/tasks_bubble_view.cc +++ b/ash/system/unified/tasks_bubble_view.cc
@@ -20,23 +20,22 @@ #include "ash/system/unified/tasks_combobox_model.h" #include "chromeos/constants/chromeos_features.h" #include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/compositor/layer.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/background.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/image_view.h" +#include "ui/views/layout/box_layout.h" #include "ui/views/layout/flex_layout_view.h" namespace { constexpr int kMaximumTasks = 5; -constexpr int kGlanceablesTaskHeaderHeight = 32; -constexpr int kGlanceablesTaskViewHeight = 48; -constexpr int kGlanceablesTaskFooterHeight = 24; -constexpr int kGlanceablesFooterMargin = 12; -constexpr int kGlanceableTaskVerticalMargin = 2; constexpr int kTasksIconRightPadding = 4; constexpr int kTasksIconViewSize = 32; +constexpr int kSpacingAboveListContainerView = 16; +constexpr int kInteriorGlanceableBubbleMargin = 16; constexpr char kTasksManagementPage[] = "https://calendar.google.com/calendar/u/0/r/week?opentasks=1"; @@ -47,9 +46,6 @@ TasksBubbleView::TasksBubbleView(DetailedViewDelegate* delegate) : GlanceableTrayChildBubble(delegate) { - SetBorder(views::CreateEmptyBorder(gfx::Insets::VH( - kGlanceablesVerticalMargin / 2, kGlanceablesLeftRightMargin / 2))); - if (ash::Shell::Get()->glanceables_v2_controller()->GetTasksClient()) { ash::Shell::Get() ->glanceables_v2_controller() @@ -75,21 +71,20 @@ node_data->SetName(u"Glanceables Bubble Task View Accessible Name"); } -gfx::Size TasksBubbleView::CalculatePreferredSize() const { - const int width = kRevampedTrayMenuWidth - 2 * kGlanceablesLeftRightMargin; - const int height = - kGlanceablesVerticalMargin * 3 + kGlanceablesTaskHeaderHeight + - kGlanceablesTaskFooterHeight + kGlanceablesFooterMargin * 2 + - kGlanceablesTaskViewHeight * std::max(num_tasks_shown_, 1); - return gfx::Size(width, height); -} - void TasksBubbleView::InitViews(ui::ListModel<GlanceablesTaskList>* task_list) { // TODO(b:277268122): Implement empty tasks glanceable state. if (task_list->item_count() == 0) { return; } + auto* layout_manager = + SetLayoutManager(std::make_unique<views::FlexLayout>()); + layout_manager + ->SetInteriorMargin(gfx::Insets::TLBR(kInteriorGlanceableBubbleMargin, + kInteriorGlanceableBubbleMargin, 0, + kInteriorGlanceableBubbleMargin)) + .SetOrientation(views::LayoutOrientation::kVertical); + tasks_header_view_ = AddChildView(std::make_unique<views::FlexLayoutView>()); tasks_header_view_->SetCrossAxisAlignment(views::LayoutAlignment::kCenter); tasks_header_view_->SetMainAxisAlignment(views::LayoutAlignment::kStart); @@ -100,24 +95,18 @@ views::MaximumFlexSizeRule::kPreferred) .WithOrder(1)); - task_items_container_view_ = - AddChildView(std::make_unique<views::FlexLayoutView>()); - task_items_container_view_->SetCrossAxisAlignment( - views::LayoutAlignment::kStart); - task_items_container_view_->SetMainAxisAlignment( - views::LayoutAlignment::kStart); - task_items_container_view_->SetOrientation( - views::LayoutOrientation::kVertical); + task_items_container_view_ = AddChildView(std::make_unique<views::View>()); task_items_container_view_->SetProperty( - views::kFlexBehaviorKey, - views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToMinimum, - views::MaximumFlexSizeRule::kPreferred) - .WithOrder(2)); - task_items_container_view_->SetBorder( - views::CreateEmptyBorder(gfx::Insets::TLBR(kGlanceablesVerticalMargin, 0, - kGlanceablesFooterMargin, 0))); - task_items_container_view_->SetInteriorMargin( - gfx::Insets::TLBR(kGlanceableTaskVerticalMargin, 0, 0, 0)); + views::kMarginsKey, + gfx::Insets::TLBR(kSpacingAboveListContainerView, 0, 0, 0)); + task_items_container_view_->SetPaintToLayer(); + task_items_container_view_->layer()->SetFillsBoundsOpaquely(false); + task_items_container_view_->layer()->SetRoundedCornerRadius( + gfx::RoundedCornersF(16)); + auto* layout = task_items_container_view_->SetLayoutManager( + std::make_unique<views::BoxLayout>( + views::BoxLayout::Orientation::kVertical)); + layout->set_between_child_spacing(2); task_icon_view_ = tasks_header_view_->AddChildView(std::make_unique<views::ImageView>());
diff --git a/ash/system/unified/tasks_bubble_view.h b/ash/system/unified/tasks_bubble_view.h index 2f56caa..254d7fc 100644 --- a/ash/system/unified/tasks_bubble_view.h +++ b/ash/system/unified/tasks_bubble_view.h
@@ -74,13 +74,12 @@ return task_list_combo_box_view_; } - views::FlexLayoutView* task_items_container_view() const { + views::View* task_items_container_view() const { return task_items_container_view_; } // views::View: void GetAccessibleNodeData(ui::AXNodeData* node_data) override; - gfx::Size CalculatePreferredSize() const override; private: friend class DateTrayTest; @@ -107,8 +106,7 @@ raw_ptr<views::ImageView, ExperimentalAsh> task_icon_view_ = nullptr; raw_ptr<views::Combobox, ExperimentalAsh> task_list_combo_box_view_ = nullptr; raw_ptr<views::FlexLayoutView, ExperimentalAsh> button_container_ = nullptr; - raw_ptr<views::FlexLayoutView, ExperimentalAsh> task_items_container_view_ = - nullptr; + raw_ptr<views::View, ExperimentalAsh> task_items_container_view_ = nullptr; raw_ptr<GlanceablesListFooterView, ExperimentalAsh> list_footer_view_ = nullptr;
diff --git a/ash/webui/shortcut_customization_ui/backend/accelerator_layout_table_unittest.cc b/ash/webui/shortcut_customization_ui/backend/accelerator_layout_table_unittest.cc index 7d82ee1..a41aaf2 100644 --- a/ash/webui/shortcut_customization_ui/backend/accelerator_layout_table_unittest.cc +++ b/ash/webui/shortcut_customization_ui/backend/accelerator_layout_table_unittest.cc
@@ -59,7 +59,7 @@ // Test that all ash accelerators should have a layout or should be added to the // exception list kAcceleratorsWithoutLayout. TEST_F(AcceleratorLayoutMetadataTest, - AcceleratorsNotInAllowedListShouldHaveLayouts) { + DISABLED_AcceleratorsNotInAllowedListShouldHaveLayouts) { for (size_t i = 0; i < ash::kAcceleratorDataLength; ++i) { const ash::AcceleratorData& accel_data = ash::kAcceleratorData[i]; if (ShouldNotHaveLayouts(accel_data.action)) {
diff --git a/base/android/jni_generator/jni_registration_generator.py b/base/android/jni_generator/jni_registration_generator.py index b844954..421b239 100644 --- a/base/android/jni_generator/jni_registration_generator.py +++ b/base/android/jni_generator/jni_registration_generator.py
@@ -908,5 +908,9 @@ _Generate(args, native_sources, java_sources=java_sources) if args.depfile: - all_inputs = native_sources + java_sources + # GN does not declare a dep on the sources files to avoid circular + # dependencies, so they need to be listed here. + all_inputs = native_sources + java_sources + [args.java_sources_file] + if args.native_sources_file: + all_inputs.append(args.native_sources_file) action_helpers.write_depfile(args.depfile, args.srcjar_path, all_inputs)
diff --git a/base/process/process.h b/base/process/process.h index 5d2584e..5560f31 100644 --- a/base/process/process.h +++ b/base/process/process.h
@@ -225,7 +225,7 @@ // Returns an integer representing the priority of a process. The meaning // of this value is OS dependent. - int GetPriority() const; + int GetOSPriority() const; #if BUILDFLAG(IS_CHROMEOS_ASH) // Get the PID in its PID namespace.
diff --git a/base/process/process_fuchsia.cc b/base/process/process_fuchsia.cc index d88dd1f..383fcd8 100644 --- a/base/process/process_fuchsia.cc +++ b/base/process/process_fuchsia.cc
@@ -281,7 +281,7 @@ return false; } -int Process::GetPriority() const { +int Process::GetOSPriority() const { DCHECK(IsValid()); // No process priorities on Fuchsia. return 0;
diff --git a/base/process/process_linux.cc b/base/process/process_linux.cc index 258061c..118bbf7 100644 --- a/base/process/process_linux.cc +++ b/base/process/process_linux.cc
@@ -207,7 +207,7 @@ } #endif // BUILDFLAG(IS_CHROMEOS) - return GetPriority() == kBackgroundPriority; + return GetOSPriority() == kBackgroundPriority; } bool Process::SetProcessBackgrounded(bool background) {
diff --git a/base/process/process_posix.cc b/base/process/process_posix.cc index 94d5c931..1f18dd2c 100644 --- a/base/process/process_posix.cc +++ b/base/process/process_posix.cc
@@ -385,7 +385,7 @@ #endif } -int Process::GetPriority() const { +int Process::GetOSPriority() const { DCHECK(IsValid()); return getpriority(PRIO_PROCESS, static_cast<id_t>(process_)); }
diff --git a/base/process/process_stubs.cc b/base/process/process_stubs.cc index 55edff3..0d02d33f 100644 --- a/base/process/process_stubs.cc +++ b/base/process/process_stubs.cc
@@ -110,7 +110,7 @@ return false; } -int Process::GetPriority() const { +int Process::GetOSPriority() const { return -1; }
diff --git a/base/process/process_unittest.cc b/base/process/process_unittest.cc index 5af7466..8be0ca5 100644 --- a/base/process/process_unittest.cc +++ b/base/process/process_unittest.cc
@@ -352,7 +352,7 @@ if (!Process::CanBackgroundProcesses()) return; Process process(SpawnChild("SimpleChildProcess")); - int old_priority = process.GetPriority(); + int old_os_priority = process.GetOSPriority(); #if BUILDFLAG(IS_APPLE) // On the Mac, backgrounding a process requires a port to that process. // In the browser it's available through the MachBroker class, which is not @@ -372,8 +372,8 @@ EXPECT_TRUE(process.SetProcessBackgrounded(false)); EXPECT_FALSE(process.IsProcessBackgrounded()); #endif - int new_priority = process.GetPriority(); - EXPECT_EQ(old_priority, new_priority); + int new_os_priority = process.GetOSPriority(); + EXPECT_EQ(old_os_priority, new_os_priority); } // Consumers can use WaitForExitWithTimeout(base::TimeDelta(), nullptr) to check
diff --git a/base/process/process_win.cc b/base/process/process_win.cc index b5e8cc5..499604b 100644 --- a/base/process/process_win.cc +++ b/base/process/process_win.cc
@@ -249,7 +249,7 @@ bool Process::IsProcessBackgrounded() const { DCHECK(IsValid()); - int priority = GetPriority(); + int priority = GetOSPriority(); if (priority == 0) return false; // Failure case. return ((priority == BELOW_NORMAL_PRIORITY_CLASS) || @@ -292,7 +292,7 @@ return (::SetPriorityClass(Handle(), priority) != 0); } -int Process::GetPriority() const { +int Process::GetOSPriority() const { DCHECK(IsValid()); return static_cast<int>(::GetPriorityClass(Handle())); }
diff --git a/base/test/launcher/test_launcher.cc b/base/test/launcher/test_launcher.cc index cb6038f9..632390a 100644 --- a/base/test/launcher/test_launcher.cc +++ b/base/test/launcher/test_launcher.cc
@@ -1800,6 +1800,23 @@ LOG(ERROR) << "Failed to get list of tests."; return false; } + + // Check for duplicate test names. These can cause difficult-to-diagnose + // crashes in the test runner as well as confusion about exactly what test is + // failing. See https://crbug.com/1463355 for details. + std::unordered_set<std::string> full_test_names; + bool dups_found = false; + for (auto& test : tests) { + const std::string full_test_name = + test.test_case_name + "." + test.test_name; + auto [it, inserted] = full_test_names.insert(full_test_name); + if (!inserted) { + LOG(WARNING) << "Duplicate test name found: " << full_test_name; + dups_found = true; + } + } + CHECK(!dups_found); + std::vector<std::string> uninstantiated_tests; for (const TestIdentifier& test_id : tests) { TestInfo test_info(test_id);
diff --git a/base/threading/platform_thread_win_unittest.cc b/base/threading/platform_thread_win_unittest.cc index 3fc3a9ef..9407e69 100644 --- a/base/threading/platform_thread_win_unittest.cc +++ b/base/threading/platform_thread_win_unittest.cc
@@ -39,7 +39,7 @@ EXPECT_EQ(::GetPriorityClass(Process::Current().Handle()), static_cast<DWORD>(NORMAL_PRIORITY_CLASS)); ::SetPriorityClass(Process::Current().Handle(), IDLE_PRIORITY_CLASS); - EXPECT_EQ(Process::Current().GetPriority(), + EXPECT_EQ(Process::Current().GetOSPriority(), static_cast<int>(IDLE_PRIORITY_CLASS)); // GetThreadPriority() stays NORMAL. Memory priority stays NORMAL.
diff --git a/build/config/chromeos/BUILD.gn b/build/config/chromeos/BUILD.gn index d6b383ac..f6cff26 100644 --- a/build/config/chromeos/BUILD.gn +++ b/build/config/chromeos/BUILD.gn
@@ -39,9 +39,6 @@ # Passing them redundantly is harmless and prepares for using Chromium's # toolchain for Lacros. if (is_chromeos_device) { - ldflags = [ - "--rtlib=compiler-rt", - "--unwindlib=libunwind", - ] + ldflags = [ "--rtlib=compiler-rt" ] } }
diff --git a/build/config/unwind.gni b/build/config/unwind.gni index fd2b597f..246e335 100644 --- a/build/config/unwind.gni +++ b/build/config/unwind.gni
@@ -3,5 +3,5 @@ declare_args() { # Use in-tree libunwind (buildtools/third_party/libunwind) instead of whatever # system library provides unwind symbols (e.g. libgcc). - use_custom_libunwind = is_fuchsia || is_android + use_custom_libunwind = is_fuchsia || is_android || is_chromeos }
diff --git a/chrome/android/java/src/com/google/ipc/invalidation/ticl/android2/channel/GcmRegistrationTaskService.java b/chrome/android/java/src/com/google/ipc/invalidation/ticl/android2/channel/GcmRegistrationTaskService.java index 7015c34..2049034 100644 --- a/chrome/android/java/src/com/google/ipc/invalidation/ticl/android2/channel/GcmRegistrationTaskService.java +++ b/chrome/android/java/src/com/google/ipc/invalidation/ticl/android2/channel/GcmRegistrationTaskService.java
@@ -11,7 +11,7 @@ /** * A class with this name was part of the cacheinvalidation library, which isn't used anymore and * has been deleted. However, this service is exported in the AndroidManifest.xml and thus is part - * of Chrome's public API, so we need to keep this dummy class around. + * of Chrome's public API, so we need to keep this placeholder class around. */ public class GcmRegistrationTaskService extends GcmTaskService { @Override
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java index 16be605..9563cc0 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/CompositorViewHolder.java
@@ -776,6 +776,7 @@ @Override public boolean dispatchTouchEvent(MotionEvent e) { + assert e != null : "The motion event dispatched shouldn't be null!"; updateLastActiveTouchEvent(e); updateIsInGesture(e); for (TouchEventObserver o : mTouchEventObservers) o.handleTouchEvent(e);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/stack/StackScroller.java b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/stack/StackScroller.java index 7bf9972..9d14532 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/stack/StackScroller.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/compositor/layouts/phone/stack/StackScroller.java
@@ -447,8 +447,8 @@ private static final int MAX_SNAP_SCROLL_MIN_VELOCITY = 5000; // If we receive a fling within this many milliseconds of receiving a previous fling that - // caused us to do a maximum distance scroll (and a few other sanity checks hold), we lower - // the velocity threshold for the new fling to also do a maximum velocity scroll; + // caused us to do a maximum distance scroll (and a few other validity checks hold), we + // lower the velocity threshold for the new fling to also do a maximum velocity scroll; private static final int REPEATED_FLING_TIMEOUT = 1500; // Minimum velocity for a "repeated fling" (see previous comment) to trigger a maximum // velocity scroll;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java index 78527231..b42a7d8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/ClientManager.java
@@ -800,7 +800,7 @@ /** Tries to bind to a client to keep it alive, and returns true for success. */ public synchronized boolean keepAliveForSession(CustomTabsSessionToken session, Intent intent) { // When an application is bound to a service, its priority is raised to - // be at least equal to the application's one. This binds to a dummy + // be at least equal to the application's one. This binds to a placeholder // service (no calls to this service are made). if (intent == null || intent.getComponent() == null) return false; SessionParams params = mSessionParams.get(session);
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabDelegateFactory.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabDelegateFactory.java index f2169d8..e754d33e 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabDelegateFactory.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabDelegateFactory.java
@@ -329,7 +329,7 @@ * Creates a basic/empty {@link TabDelegateFactory} for use when creating a hidden tab. It will * be replaced when the hidden Tab becomes shown. */ - static CustomTabDelegateFactory createDummy() { + static CustomTabDelegateFactory createEmpty() { return new CustomTabDelegateFactory(null, false, false, null, DisplayMode.BROWSER, false, null, null, null, null, ()
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java index 5d4932e..6b61529 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/CustomTabIntentDataProvider.java
@@ -207,7 +207,7 @@ private static final int DEFAULT_BREAKPOINT_DP = 840; - private static final int MAX_CUSTOM_MENU_ITEMS = 5; + private static final int MAX_CUSTOM_MENU_ITEMS = 7; private static final int MAX_CUSTOM_TOOLBAR_ITEMS = 2;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/HiddenTabHolder.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/HiddenTabHolder.java index 2ee2fd5..b5f4482 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/HiddenTabHolder.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/HiddenTabHolder.java
@@ -156,7 +156,7 @@ Tab tab = new TabBuilder() .setWindow(new WindowAndroid(context)) .setLaunchType(TabLaunchType.FROM_SPECULATIVE_BACKGROUND_CREATION) - .setDelegateFactory(CustomTabDelegateFactory.createDummy()) + .setDelegateFactory(CustomTabDelegateFactory.createEmpty()) .setInitiallyHidden(true) .build();
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/IncognitoCustomTabIntentDataProvider.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/IncognitoCustomTabIntentDataProvider.java index 3256626..e73e3525 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/IncognitoCustomTabIntentDataProvider.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/IncognitoCustomTabIntentDataProvider.java
@@ -47,7 +47,7 @@ * to activity re-creation. */ public class IncognitoCustomTabIntentDataProvider extends BrowserServicesIntentDataProvider { - private static final int MAX_CUSTOM_MENU_ITEMS = 5; + private static final int MAX_CUSTOM_MENU_ITEMS = 7; private final Intent mIntent; private final CustomTabsSessionToken mSession;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabBaseStrategy.java b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabBaseStrategy.java index 4b488856..6e56b7a 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabBaseStrategy.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabBaseStrategy.java
@@ -14,6 +14,7 @@ import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; +import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.InsetDrawable; import android.os.Handler; @@ -479,6 +480,9 @@ protected void resetCoordinatorLayoutInsets() { ViewGroup coordinatorLayout = getCoordinatorLayout(); + Drawable backgroundDrawable = coordinatorLayout.getBackground(); + if (backgroundDrawable == null) return; + // Get the insets of the CoordinatorLayout int insetLeft = coordinatorLayout.getPaddingLeft(); int insetTop = coordinatorLayout.getPaddingTop(); @@ -486,8 +490,8 @@ int insetBottom = coordinatorLayout.getPaddingBottom(); // Set the CoordinatorLayout to a new InsetDrawable with insets all offset back to 0. - InsetDrawable newDrawable = new InsetDrawable(coordinatorLayout.getBackground(), -insetLeft, - -insetTop, -insetRight, -insetBottom); + InsetDrawable newDrawable = new InsetDrawable( + backgroundDrawable, -insetLeft, -insetTop, -insetRight, -insetBottom); coordinatorLayout.setBackground(newDrawable); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationHandler.java b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationHandler.java index 71bd4ff..1d660b1 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationHandler.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationHandler.java
@@ -162,7 +162,8 @@ @Override public void handleTouchEvent(MotionEvent e) { - if (!shouldProcessTouchEvents()) return; + assert e != null : "The motion event in NavigationHandler shouldn't be null!"; + if (e == null || !shouldProcessTouchEvents()) return; mDetector.onTouchEvent(e); if (e.getAction() == MotionEvent.ACTION_UP) release(true); }
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheet.java b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheet.java index 6357283d..4d37f98 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheet.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/gesturenav/NavigationSheet.java
@@ -62,9 +62,9 @@ } /** - * Dummy object that does nothing. Saves lots of null checks. + * Placeholder object that does nothing. Saves lots of null checks. */ - static final NavigationSheet DUMMY = new NavigationSheet() { + static final NavigationSheet PLACEHOLDER = new NavigationSheet() { @Override public void setDelegate(Delegate delegate) {}
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java index 5c804e1..ed4d955 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/init/ChromeBrowserInitializer.java
@@ -467,7 +467,7 @@ /** * For unit testing of clients. - * @param initializer The (dummy or mocked) initializer to use. + * @param initializer The (placeholder or mocked) initializer to use. */ public static void setForTesting(ChromeBrowserInitializer initializer) { var oldValue = sChromeBrowserInitializer; @@ -477,7 +477,7 @@ /** * Set {@link BrowserStartupController ) to use for unit testing. - * @param controller The (dummy or mocked) {@link BrowserStartupController) instance. + * @param controller The (placeholder or mocked) {@link BrowserStartupController) instance. */ public static void setBrowserStartupControllerForTesting(BrowserStartupController controller) { var oldValue = sBrowserStartupController;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java b/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java index 1fe93d4..32e3a94aa 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/media/PictureInPictureActivity.java
@@ -265,20 +265,20 @@ actions.add(mHangUp); } - // Insert a disabled dummy remote action with transparent icon if action list is empty. - // This is a workaround of the issue that android picture-in-picture will fallback to - // default MediaSession when action list given is empty. + // Insert a disabled placeholder remote action with transparent icon if action list is + // empty. This is a workaround of the issue that android picture-in-picture will + // fallback to default MediaSession when action list given is empty. // TODO (jazzhsu): Remove this when android picture-in-picture can accept empty list and // not fallback to default MediaSession. if (actions.isEmpty()) { - RemoteAction dummyAction = new RemoteAction( + RemoteAction placeholderAction = new RemoteAction( Icon.createWithBitmap(Bitmap.createBitmap( new int[] {Color.TRANSPARENT}, 1, 1, Bitmap.Config.ARGB_8888)), "", "", PendingIntent.getBroadcast(getApplicationContext(), -1, new Intent(MEDIA_ACTION), PendingIntent.FLAG_IMMUTABLE)); - dummyAction.setEnabled(false); - actions.add(dummyAction); + placeholderAction.setEnabled(false); + actions.add(placeholderAction); } return actions;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaBase.java b/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaBase.java index b569dc8..33e232ec 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaBase.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaBase.java
@@ -468,7 +468,7 @@ /** * Reads the data back from the file it was saved to. Uses SharedPreferences to handle I/O. - * Sanity checks are performed on the timestamps to guard against clock changing. + * Validity checks are performed on the timestamps to guard against clock changing. */ private void restoreState() { if (mStateHasBeenRestored) return;
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omaha/RequestGenerator.java b/chrome/android/java/src/org/chromium/chrome/browser/omaha/RequestGenerator.java index 8671800..c13b1f4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omaha/RequestGenerator.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omaha/RequestGenerator.java
@@ -53,7 +53,7 @@ /** * Generates the XML for the current request. Follows the format laid out at * https://github.com/google/omaha/blob/master/doc/ServerProtocolV3.md - * with some additional dummy values supplied. + * with some additional placeholder values supplied. */ public String generateXML(String sessionID, String versionName, long installAge, int lastCheckDate, RequestData data) throws RequestFailureException {
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/omaha/ResponseParser.java b/chrome/android/java/src/org/chromium/chrome/browser/omaha/ResponseParser.java index d4d3f670..49526db4 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/omaha/ResponseParser.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/omaha/ResponseParser.java
@@ -23,10 +23,10 @@ * </urls> * <manifest version="0.16.4130.199"> * <packages> - * <package hash="0" name="dummy.apk" required="true" size="0"/> + * <package hash="0" name="placeholder.apk" required="true" size="0"/> * </packages> * <actions> - * <action event="install" run="dummy.apk"/> + * <action event="install" run="placeholder.apk"/> * <action event="postinstall"/> * </actions> * </manifest>
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/EventTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/EventTracker.java index 4574588..adbcd66 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/EventTracker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/EventTracker.java
@@ -25,7 +25,7 @@ public EventTracker(UsageStatsBridge bridge) { mBridge = bridge; mRootPromise = new Promise<>(); - // We need to add a dummy exception handler so that Promise doesn't complain when we + // We need to add a placeholder exception handler so that Promise doesn't complain when we // call variants of then() that don't take a single callback. These variants set an // exception handler on the returned promise, so they expect there to be one on the root // promise.
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/SuspensionTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/SuspensionTracker.java index 379a0d5..74c8f205 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/SuspensionTracker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/SuspensionTracker.java
@@ -34,7 +34,7 @@ */ public Promise<Void> setWebsitesSuspended(List<String> fqdns, boolean suspended) { Promise<Void> newWritePromise = new Promise<>(); - mWritePromise.then((dummyResult) -> { + mWritePromise.then((placeholderResult) -> { mRootPromise.then((result) -> { // We copy result so that the mutation isn't reflected in result until persistence // succeeds. @@ -63,10 +63,10 @@ newWritePromise.reject(); } }); - // We need to add a dummy exception handler so that Promise doesn't complain when we - // call variants of then() that don't take a single callback. These variants set an - // exception handler on the returned promise, so they expect there to be one on the - // root promise. + // We need to add a placeholder exception handler so that Promise doesn't complain + // when we call variants of then() that don't take a single callback. These variants + // set an exception handler on the returned promise, so they expect there to be one + // on the root promise. }, (e) -> {}); });
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/TokenTracker.java b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/TokenTracker.java index deb3492e..196a42b8 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/TokenTracker.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/usage_stats/TokenTracker.java
@@ -33,7 +33,7 @@ mRootPromise.fulfill(result); }); - // We need to add a dummy exception handler so that Promise doesn't complain when we + // We need to add a placeholder exception handler so that Promise doesn't complain when we // call variants of then() that don't take a single callback. These variants set an // exception handler on the returned promise, so they expect there to be one on the root // promise.
diff --git a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityAppMenuTest.java b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityAppMenuTest.java index 936df5a..b0c7b88 100644 --- a/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityAppMenuTest.java +++ b/chrome/android/javatests/src/org/chromium/chrome/browser/customtabs/CustomTabActivityAppMenuTest.java
@@ -86,7 +86,7 @@ */ @RunWith(ChromeJUnit4ClassRunner.class) public class CustomTabActivityAppMenuTest { - private static final int MAX_MENU_CUSTOM_ITEMS = 5; + private static final int MAX_MENU_CUSTOM_ITEMS = 7; private static final int NUM_CHROME_MENU_ITEMS = 5; private static final int NUM_CHROME_MENU_ITEMS_WITH_DIVIDER = 6; private static final String TEST_PAGE = "/chrome/test/data/android/google.html"; @@ -434,13 +434,13 @@ } /** - * Test that only up to 5 entries are added to the custom menu. + * Test that only up to 7 entries are added to the custom menu. */ @Test @SmallTest public void testMaxMenuItems() throws Exception { Intent intent = createMinimalCustomTabIntent(); - int numMenuEntries = 7; + int numMenuEntries = 9; Assert.assertTrue(MAX_MENU_CUSTOM_ITEMS < numMenuEntries); CustomTabsIntentTestUtils.addMenuEntriesToIntent(intent, numMenuEntries, TEST_MENU_TITLE); mCustomTabActivityTestRule.startCustomTabActivityWithIntent(intent);
diff --git a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabTestRule.java b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabTestRule.java index 6e657dbe..d3b146a 100644 --- a/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabTestRule.java +++ b/chrome/android/junit/src/org/chromium/chrome/browser/customtabs/features/partialcustomtab/PartialCustomTabTestRule.java
@@ -197,6 +197,7 @@ when(mContentFrame.getLayoutParams()).thenReturn(mLayoutParams); when(mContentFrame.getHeight()).thenReturn(DEVICE_HEIGHT - NAVBAR_HEIGHT); when(mCoordinatorLayout.getLayoutParams()).thenReturn(mCoordinatorLayoutParams); + when(mCoordinatorLayout.getBackground()).thenReturn(mDragBarBackground); when(mHandleView.getLayoutParams()).thenReturn(mLayoutParams); when(mHandleView.getBackground()).thenReturn(mDragBarBackground); when(mHandleView.findViewById(R.id.drag_bar)).thenReturn(mDragBar);
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 480c768..8ad47436 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -14817,6 +14817,9 @@ <message name="IDS_DEEP_SCANNING_DIALOG_UPLOAD_BYPASS_JUSTIFICATION_LABEL" desc="Text displayed in the label above the bypass justification text area, explaining to the user that they have to enter a justification for uploading the file/pasted data even though there was a data loss prevention warning."> Please enter a reason for uploading this data: </message> + <message name="IDS_DEEP_SCANNING_DIALOG_DOWNLOAD_BYPASS_JUSTIFICATION_LABEL" desc="Text displayed in the label above the bypass justification text area, explaining to the user that they have to enter a justification for downloading a file even though there was a data loss prevention warning."> + Please enter a reason for downloading this data: + </message> <message name="IDS_DEEP_SCANNING_DIALOG_BYPASS_JUSTIFICATION_TEXT_LIMIT_LABEL" desc="A label that contains the current amount of characters in the bypass justification text box, as well as the maximum limit of characters. This is displayed to the user so they know when the limit is exceeded."> <ph name="ACTUAL_CHAR_COUNT">$1<ex>10</ex></ph>/<ph name="MAX_CHAR_COUNT">$2<ex>280</ex></ph> </message>
diff --git a/chrome/app/generated_resources_grd/IDS_DEEP_SCANNING_DIALOG_DOWNLOAD_BYPASS_JUSTIFICATION_LABEL.png.sha1 b/chrome/app/generated_resources_grd/IDS_DEEP_SCANNING_DIALOG_DOWNLOAD_BYPASS_JUSTIFICATION_LABEL.png.sha1 new file mode 100644 index 0000000..158a6b1 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_DEEP_SCANNING_DIALOG_DOWNLOAD_BYPASS_JUSTIFICATION_LABEL.png.sha1
@@ -0,0 +1 @@ +455cf2054c079a543851906e6dd9699d78966580 \ No newline at end of file
diff --git a/chrome/app/settings_strings.grdp b/chrome/app/settings_strings.grdp index 23fb3d7..ce9f0fb 100644 --- a/chrome/app/settings_strings.grdp +++ b/chrome/app/settings_strings.grdp
@@ -681,9 +681,12 @@ <message name="IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC" desc="Text that describes the 'Auto Sign-in' functionality to users."> Automatically sign in to sites and apps using saved credentials. If turned off, you'll be asked for confirmation every time before signing in to a site or app. </message> - <message name="IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL" desc="Label for a checkbox that allows users to choose whether chrome should check that credentials have been part of a leak."> + <message name="IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL" desc="Label for a checkbox that allows users to choose whether Chrome should check that credentials have been part of a leak."> Warn you if passwords are exposed in a data breach </message> + <message name="IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL_UPDATED" desc="Label for a checkbox that allows users to choose whether chrome should check that credentials have been part of a leak."> + Warn you if a password was compromised in a data breach + </message> <message name="IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_ENABLED_DESC" desc="Text that describes the 'Password Leak Detection' functionality to signed-out users who have not disabled the feature. This text always follows a sentence describing the feature."> When you sign in to your Google Account, this feature is turned on. </message> @@ -2587,6 +2590,9 @@ <message name="IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC" desc="Description for safe browsing standard protection mode"> Standard protection against websites, downloads, and extensions that are known to be dangerous </message> + <message name="IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC_UPDATED" desc="Description for safe browsing standard protection mode"> + Protects against sites, downloads, and extensions that are known to be dangerous. If a page does something suspicious, URLs and bits of page content are sent to Google Safe Browsing. + </message> <message name="IDS_SETTINGS_SAFEBROWSING_STANDARD_EXPAND_ACCESSIBILITY_LABEL" desc="Label for the button that toggles showing the detailed description of safe browsing standard protection. Only visible by screen reader software."> Show standard protection details </message>
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL_UPDATED.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL_UPDATED.png.sha1 new file mode 100644 index 0000000..dd6be71 --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL_UPDATED.png.sha1
@@ -0,0 +1 @@ +af4a782f07afb2382e7db9c0a8a060aea29c532b \ No newline at end of file
diff --git a/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC_UPDATED.png.sha1 b/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC_UPDATED.png.sha1 new file mode 100644 index 0000000..64f4446 --- /dev/null +++ b/chrome/app/settings_strings_grdp/IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC_UPDATED.png.sha1
@@ -0,0 +1 @@ +724b3e9fc22576b9b9383f768f24e2d8b6ce33f6 \ No newline at end of file
diff --git a/chrome/browser/ash/arc/input_overlay/display_overlay_controller.cc b/chrome/browser/ash/arc/input_overlay/display_overlay_controller.cc index 97c820aa..888f931 100644 --- a/chrome/browser/ash/arc/input_overlay/display_overlay_controller.cc +++ b/chrome/browser/ash/arc/input_overlay/display_overlay_controller.cc
@@ -517,8 +517,9 @@ void DisplayOverlayController::AddEditMessage(const base::StringPiece& message, MessageType message_type) { + // No need to show edit message for Beta version. // There is no instance for unittest. - if (!ash::Shell::HasInstance()) { + if (IsBeta() || !ash::Shell::HasInstance()) { return; }
diff --git a/chrome/browser/ash/policy/remote_commands/device_command_fetch_support_packet_job.cc b/chrome/browser/ash/policy/remote_commands/device_command_fetch_support_packet_job.cc index 1f22e02..580aa3a 100644 --- a/chrome/browser/ash/policy/remote_commands/device_command_fetch_support_packet_job.cc +++ b/chrome/browser/ash/policy/remote_commands/device_command_fetch_support_packet_job.cc
@@ -38,6 +38,7 @@ #include "components/reporting/client/report_queue.h" #include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/client/report_queue_factory.h" +#include "components/reporting/proto/synced/record.pb.h" #include "components/reporting/util/status.h" #include "third_party/abseil-cpp/absl/types/optional.h" @@ -364,8 +365,13 @@ return; } - reporting::ReportQueueFactory::Create( - reporting::EventType::kDevice, reporting::Destination::LOG_UPLOAD, + ::reporting::SourceInfo source_info; + source_info.set_source(::reporting::SourceInfo::ASH); + ::reporting::ReportQueueFactory::Create( + ::reporting::ReportQueueConfiguration::Create( + {.event_type = ::reporting::EventType::kDevice, + .destination = ::reporting::Destination::LOG_UPLOAD}) + .SetSourceInfo(std::move(source_info)), base::BindOnce(&DeviceCommandFetchSupportPacketJob::OnReportQueueCreated, weak_ptr_factory_.GetWeakPtr())); }
diff --git a/chrome/browser/ash/printing/history/print_job_reporting_service_impl.cc b/chrome/browser/ash/printing/history/print_job_reporting_service_impl.cc index 6906a27..e7942719 100644 --- a/chrome/browser/ash/printing/history/print_job_reporting_service_impl.cc +++ b/chrome/browser/ash/printing/history/print_job_reporting_service_impl.cc
@@ -22,7 +22,9 @@ #include "chromeos/ash/components/settings/cros_settings_names.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/reporting/client/report_queue.h" +#include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/client/report_queue_factory.h" +#include "components/reporting/proto/synced/record.pb.h" #include "components/reporting/proto/synced/record_constants.pb.h" #include "components/reporting/proto/synced/status.pb.h" #include "components/reporting/util/status.h" @@ -191,9 +193,14 @@ // static std::unique_ptr<PrintJobReportingService> PrintJobReportingService::Create() { + ::reporting::SourceInfo source_info; + source_info.set_source(::reporting::SourceInfo::ASH); auto report_queue = ::reporting::ReportQueueFactory::CreateSpeculativeReportQueue( - ::reporting::EventType::kUser, ::reporting::Destination::PRINT_JOBS); + ::reporting::ReportQueueConfiguration::Create( + {.event_type = ::reporting::EventType::kUser, + .destination = ::reporting::Destination::PRINT_JOBS}) + .SetSourceInfo(std::move(source_info))); return std::make_unique<PrintJobReportingServiceImpl>( std::move(report_queue)); }
diff --git a/chrome/browser/ash/settings/owner_pending_setting_controller.h b/chrome/browser/ash/settings/owner_pending_setting_controller.h index ebbdd47..ee88423 100644 --- a/chrome/browser/ash/settings/owner_pending_setting_controller.h +++ b/chrome/browser/ash/settings/owner_pending_setting_controller.h
@@ -112,7 +112,7 @@ SEQUENCE_CHECKER(sequence_checker_); - raw_ptr<PrefService, DanglingUntriaged | ExperimentalAsh> local_state_; + raw_ptr<PrefService, ExperimentalAsh> local_state_; absl::optional<base::Value> value_notified_to_observers_; base::RepeatingClosureList callback_list_; base::CallbackListSubscription setting_subscription_;
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h b/chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h index a45bfba..3e2f43b 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h
@@ -40,6 +40,7 @@ constexpr DataType DATA_TYPE_ACCOUNT_PASSWORDS = DATA_TYPE_EMBEDDER_BEGIN << 11; constexpr DataType DATA_TYPE_LOCAL_CUSTOM_DICTIONARY = DATA_TYPE_EMBEDDER_BEGIN << 12; +constexpr DataType DATA_TYPE_CONTROLLED_FRAME = DATA_TYPE_EMBEDDER_BEGIN << 13; // Group datatypes. @@ -54,6 +55,7 @@ #endif DATA_TYPE_SITE_USAGE_DATA | DATA_TYPE_DURABLE_PERMISSION | DATA_TYPE_EXTERNAL_PROTOCOL_DATA | DATA_TYPE_ISOLATED_ORIGINS | + DATA_TYPE_CONTROLLED_FRAME | content::BrowsingDataRemover::DATA_TYPE_PRIVACY_SANDBOX; // Datatypes protected by Important Sites.
diff --git a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc index 9991179a..e16c3ac 100644 --- a/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc +++ b/chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.cc
@@ -158,9 +158,13 @@ #endif // BUILDFLAG(IS_ANDROID) #if !BUILDFLAG(IS_ANDROID) +#include "chrome/browser/web_applications/web_app.h" #include "chrome/browser/web_applications/web_app_command_scheduler.h" #include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/browser/web_applications/web_app_registrar.h" #include "chrome/browser/web_applications/web_app_utils.h" +#include "content/public/browser/isolated_web_apps_policy.h" +#include "content/public/browser/storage_partition_config.h" #endif // !BUILDFLAG(IS_ANDROID) #if BUILDFLAG(ENABLE_EXTENSIONS) @@ -1273,6 +1277,59 @@ (constants::DATA_TYPE_SITE_DATA | constants::DATA_TYPE_HISTORY)) { login_detection::prefs::RemoveLoginDetectionData(prefs); } + +#if !BUILDFLAG(IS_ANDROID) + ////////////////////////////////////////////////////////////////////////////// + // Isolated Web Apps. + // If no StoragePartition was specified in the filter, make additional + // BrowsingDataRemover::Remove* calls for each StoragePartition of Isolated + // Web Apps (IWA) that match the filter. + // + // The data types specified in `remove_mask` will be removed from the + // primary StoragePartition of an IWA, but all data will be removed from + // Controlled Frame StoragePartitions if DATA_TYPE_CONTROLLED_FRAME is + // specified in `remove_mask`. + if (!filter_builder->GetStoragePartitionConfig().has_value() && + content::IsolatedWebAppsPolicy::AreIsolatedWebAppsEnabled(profile_)) { + const web_app::WebAppRegistrar& web_app_registrar = + web_app::WebAppProvider::GetForLocalAppsUnchecked(profile_) + ->registrar_unsafe(); + for (const web_app::WebApp& web_app : web_app_registrar.GetApps()) { + if (!web_app_registrar.IsIsolated(web_app.app_id()) || + !filter.Run(web_app.scope())) { + continue; + } + std::vector<content::StoragePartitionConfig> partitions = + web_app_registrar.GetIsolatedWebAppStoragePartitionConfigs( + web_app.app_id()); + for (const content::StoragePartitionConfig& partition : partitions) { + // The filter specified a StoragePartition, so only delete data that + // lives in a StoragePartition. + uint64_t iwa_remove_mask = + content::BrowsingDataRemover::DATA_TYPE_ON_STORAGE_PARTITION; + bool is_primary_partition = partition.partition_name().empty(); + if (is_primary_partition) { + iwa_remove_mask &= remove_mask; + } else { + if (!(remove_mask & constants::DATA_TYPE_CONTROLLED_FRAME)) { + continue; + } + // For Controlled Frame partitions, all data should be deleted, so + // |iwa_remove_mask| should stay DATA_TYPE_ON_STORAGE_PARTITION. + } + + // We can't wait for the `RemoveWithFilter` call to finish because + // BrowsingDataRemover doesn't support nested Remove calls. + auto iwa_filter_builder = content::BrowsingDataFilterBuilder::Create( + content::BrowsingDataFilterBuilder::Mode::kPreserve); + iwa_filter_builder->SetStoragePartitionConfig(partition); + profile_->GetBrowsingDataRemover()->RemoveWithFilter( + delete_begin, delete_end, iwa_remove_mask, origin_type_mask, + std::move(iwa_filter_builder)); + } + } + } +#endif // !BUILDFLAG(IS_ANDROID) } void ChromeBrowsingDataRemoverDelegate::OnTaskStarted(
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 c68f036c..1222b476 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
@@ -85,6 +85,7 @@ #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" +#include "chrome/test/base/testing_profile_manager.h" #include "components/autofill/core/browser/autofill_test_utils.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/data_model/credit_card.h" @@ -189,10 +190,15 @@ #endif // BUILDFLAG(IS_ANDROID) #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) +#include "base/test/test_future.h" +#include "chrome/browser/ui/web_applications/test/isolated_web_app_test_utils.h" +#include "chrome/browser/web_applications/isolated_web_apps/get_controlled_frame_partition_command.h" +#include "chrome/browser/web_applications/locks/app_lock.h" #include "chrome/browser/web_applications/test/fake_web_app_provider.h" #include "chrome/browser/web_applications/test/web_app_install_test_utils.h" #include "chrome/browser/web_applications/test/web_app_test_utils.h" #include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_command_scheduler.h" #include "chrome/browser/web_applications/web_app_sync_bridge.h" #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) @@ -228,6 +234,12 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #endif // BUILDFLAG(ENABLE_REPORTING) +#if BUILDFLAG(ENABLE_NACL) +#include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h" +#include "components/nacl/browser/nacl_browser.h" +#include "components/nacl/common/buildflags.h" +#endif // BUILDFLAG(ENABLE_NACL) + using content::BrowsingDataFilterBuilder; using domain_reliability::DomainReliabilityClearMode; using domain_reliability::DomainReliabilityMonitor; @@ -242,6 +254,7 @@ using testing::MatchResultListener; using testing::Return; using testing::SizeIs; +using testing::UnorderedElementsAre; using testing::WithArgs; namespace constants = chrome_browsing_data_remover; @@ -532,16 +545,7 @@ RemoveUkmDataTester(const RemoveUkmDataTester&) = delete; RemoveUkmDataTester& operator=(const RemoveUkmDataTester&) = delete; - ~RemoveUkmDataTester() { - TestingBrowserProcess::GetGlobal()->SetProfileManager(nullptr); - } - [[nodiscard]] bool Init(Profile* profile) { - // Setup required dependencies for segmentation platform: - EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); - TestingBrowserProcess::GetGlobal()->SetProfileManager( - std::make_unique<FakeProfileManager>(temp_dir_.GetPath())); - // Create the platform to kick off initialization. segmentation_platform::SegmentationPlatformServiceFactory::GetForProfile( profile); @@ -574,7 +578,6 @@ private: ukm::TestUkmRecorder ukm_recorder_; - base::ScopedTempDir temp_dir_; raw_ptr<history::HistoryService> history_service_; segmentation_platform::UkmDataManagerTestUtils test_utils_; @@ -1207,6 +1210,20 @@ } // namespace autofill +#if BUILDFLAG(ENABLE_NACL) +class ScopedNaClBrowserDelegate { + public: + ~ScopedNaClBrowserDelegate() { + nacl::NaClBrowser::ClearAndDeleteDelegateForTest(); + } + + void Init(ProfileManager* profile_manager) { + nacl::NaClBrowser::SetDelegate( + std::make_unique<NaClBrowserDelegateImpl>(profile_manager)); + } +}; +#endif // BUILDFLAG(ENABLE_NACL) + // Test Class ----------------------------------------------------------------- class ChromeBrowsingDataRemoverDelegateTest : public testing::Test { @@ -1227,39 +1244,41 @@ // that initialize a ScopedFeatureList in their constructors can do so // before the code below potentially kicks off tasks on other threads that // check if a feature is enabled, to avoid tsan data races. - profile_ = - TestingProfile::Builder() - .AddTestingFactory( - StatefulSSLHostStateDelegateFactory::GetInstance(), - StatefulSSLHostStateDelegateFactory:: - GetDefaultFactoryForTesting()) - .AddTestingFactory(BookmarkModelFactory::GetInstance(), - BookmarkModelFactory::GetDefaultFactory()) - .AddTestingFactory(HistoryServiceFactory::GetInstance(), - HistoryServiceFactory::GetDefaultFactory()) - .AddTestingFactory(FaviconServiceFactory::GetInstance(), - FaviconServiceFactory::GetDefaultFactory()) - .AddTestingFactory( - SpellcheckServiceFactory::GetInstance(), - base::BindRepeating([](content::BrowserContext* profile) - -> std::unique_ptr<KeyedService> { - return std::make_unique<SpellcheckService>( - static_cast<Profile*>(profile)); - })) - .AddTestingFactory(TrustedVaultServiceFactory::GetInstance(), - TrustedVaultServiceFactory::GetDefaultFactory()) - .AddTestingFactory(SyncServiceFactory::GetInstance(), - SyncServiceFactory::GetDefaultFactory()) - .AddTestingFactory( - ChromeSigninClientFactory::GetInstance(), - base::BindRepeating(&signin::BuildTestSigninClient)) - .AddTestingFactory(WebDataServiceFactory::GetInstance(), - WebDataServiceFactory::GetDefaultFactory()) - .Build(); + profile_manager_ = std::make_unique<TestingProfileManager>( + TestingBrowserProcess::GetGlobal()); + CHECK(profile_manager_->SetUp()); + profile_ = profile_manager_->CreateTestingProfile( + "test_profile", + {{StatefulSSLHostStateDelegateFactory::GetInstance(), + StatefulSSLHostStateDelegateFactory::GetDefaultFactoryForTesting()}, + {BookmarkModelFactory::GetInstance(), + BookmarkModelFactory::GetDefaultFactory()}, + {HistoryServiceFactory::GetInstance(), + HistoryServiceFactory::GetDefaultFactory()}, + {FaviconServiceFactory::GetInstance(), + FaviconServiceFactory::GetDefaultFactory()}, + {SpellcheckServiceFactory::GetInstance(), + base::BindRepeating([](content::BrowserContext* profile) + -> std::unique_ptr<KeyedService> { + return std::make_unique<SpellcheckService>( + static_cast<Profile*>(profile)); + })}, + {TrustedVaultServiceFactory::GetInstance(), + TrustedVaultServiceFactory::GetDefaultFactory()}, + {SyncServiceFactory::GetInstance(), + SyncServiceFactory::GetDefaultFactory()}, + {ChromeSigninClientFactory::GetInstance(), + base::BindRepeating(&signin::BuildTestSigninClient)}, + {WebDataServiceFactory::GetInstance(), + WebDataServiceFactory::GetDefaultFactory()}}); + +#if BUILDFLAG(ENABLE_NACL) + // Clearing Cache will clear PNACL cache, which needs this delegate set. + nacl_browser_delegate_.Init(profile_manager_->profile_manager()); +#endif // BUILDFLAG(ENABLE_NACL) #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) - web_app_provider_ = web_app::FakeWebAppProvider::Get(profile_.get()); - web_app_provider_->StartWithSubsystems(); + web_app::test::AwaitStartWebAppProviderAndSubsystems(profile_.get()); #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) remover_ = profile_->GetBrowsingDataRemover(); @@ -1283,9 +1302,6 @@ ProtocolHandlerRegistryFactory::GetInstance()->SetTestingFactory( profile_.get(), base::BindRepeating(&BuildProtocolHandlerRegistry)); - local_state_ = std::make_unique<ScopedTestingLocalState>( - TestingBrowserProcess::GetGlobal()); - #if BUILDFLAG(IS_ANDROID) static_cast<ChromeBrowsingDataRemoverDelegate*>( profile_->GetBrowsingDataRemoverDelegate()) @@ -1306,21 +1322,18 @@ // the profile should fix the race. content::RunAllTasksUntilIdle(); - // Drop unowned references before profile destroys owned references. + // Drop unowned references before ProfileManager destroys owned references. remover_ = nullptr; -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) - web_app_provider_ = nullptr; -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) + profile_ = nullptr; // TestingProfile contains a DOMStorageContext. BrowserContext's destructor // posts a message to the WEBKIT thread to delete some of its member // variables. We need to ensure that the profile is destroyed, and that // the message loop is cleared out, before destroying the threads and loop. // Otherwise we leak memory. - profile_.reset(); + profile_manager_.reset(); base::RunLoop().RunUntilIdle(); - local_state_.reset(); TestingBrowserProcess::GetGlobal()->SetLocalState(nullptr); } @@ -1403,6 +1416,8 @@ network::NetworkContext* network_context() { return network_context_.get(); } + TestingProfileManager* GetProfileManager() { return profile_manager_.get(); } + TestingProfile* GetProfile() { return profile_.get(); } bool Match(const GURL& origin, @@ -1416,10 +1431,6 @@ return &task_environment_; } -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) - web_app::FakeWebAppProvider* web_app_provider() { return web_app_provider_; } -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) - protected: // |feature_list_| needs to be destroyed after |task_environment_|, to avoid // tsan flakes caused by other tasks running while |feature_list_| is @@ -1430,14 +1441,14 @@ // Cached pointer to BrowsingDataRemover for access to testing methods. raw_ptr<content::BrowsingDataRemover> remover_; +#if BUILDFLAG(ENABLE_NACL) + ScopedNaClBrowserDelegate nacl_browser_delegate_; +#endif // BUILDFLAG(ENABLE_NACL) content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; std::unique_ptr<network::NetworkContext> network_context_; - std::unique_ptr<TestingProfile> profile_; - std::unique_ptr<ScopedTestingLocalState> local_state_; -#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) - raw_ptr<web_app::FakeWebAppProvider> web_app_provider_; -#endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) + std::unique_ptr<TestingProfileManager> profile_manager_; + raw_ptr<TestingProfile> profile_; // Owned by `profile_manager_`. }; #if BUILDFLAG(ENABLE_REPORTING) @@ -1550,7 +1561,7 @@ #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) TEST_F(ChromeBrowsingDataRemoverDelegateTest, ClearWebAppData) { - auto* provider = web_app_provider(); + auto* provider = web_app::FakeWebAppProvider::Get(GetProfile()); ASSERT_TRUE(provider); // Make sure WebAppProvider's subsystems are ready. @@ -1592,6 +1603,222 @@ EXPECT_EQ(constants::DATA_TYPE_HISTORY, GetRemovalMask()); } + +class IsolatedWebAppChromeBrowsingDataRemoverDelegateTest + : public ChromeBrowsingDataRemoverDelegateTest { + public: + struct RemovalInfo { + uint64_t remove_mask; + absl::optional<content::StoragePartitionConfig> storage_partition_config = + absl::nullopt; + }; + + IsolatedWebAppChromeBrowsingDataRemoverDelegateTest() { + feature_list_.InitWithFeatures( + {features::kIsolatedWebApps, features::kIsolatedWebAppDevMode}, {}); + } + + protected: + content::BrowsingDataRemover::DataType DATA_TYPE_INDEXED_DB = + content::BrowsingDataRemover::DATA_TYPE_INDEXED_DB; + content::BrowsingDataRemover::DataType DATA_TYPE_ON_STORAGE_PARTITION = + content::BrowsingDataRemover::DATA_TYPE_ON_STORAGE_PARTITION; + content::BrowsingDataRemover::DataType DATA_TYPE_SITE_DATA = + constants::DATA_TYPE_SITE_DATA; + + web_app::IsolatedWebAppUrlInfo InstallIsolatedWebApp(const GURL& iwa_url) { + web_app::AddDummyIsolatedAppToRegistry(GetProfile(), iwa_url, "IWA Name"); + return web_app::IsolatedWebAppUrlInfo::Create(iwa_url).value(); + } + + content::StoragePartitionConfig CreateControlledFrameStoragePartition( + const web_app::IsolatedWebAppUrlInfo& iwa_url_info, + const std::string& partition_name) { + auto* provider = web_app::FakeWebAppProvider::Get(GetProfile()); + CHECK(provider); + base::test::TestFuture<absl::optional<content::StoragePartitionConfig>> + future; + provider->scheduler().ScheduleCallbackWithLock( + "GetControlledFramePartition", + std::make_unique<web_app::AppLockDescription>(iwa_url_info.app_id()), + base::BindOnce(&web_app::GetControlledFramePartitionWithLock, + GetProfile(), iwa_url_info, partition_name, + /*in_memory=*/false, future.GetCallback()), + FROM_HERE); + return future.Get().value(); + } + + std::vector<RemovalInfo> ClearDataAndWait( + const base::Time& delete_begin, + const base::Time& delete_end, + uint64_t remove_mask, + std::unique_ptr<BrowsingDataFilterBuilder> filter_builder) { + std::vector<RemovalInfo> removal_tasks; + base::RunLoop run_loop; + auto* browsing_data_remover = GetProfile()->GetBrowsingDataRemover(); + browsing_data_remover->SetWouldCompleteCallbackForTesting( + base::BindLambdaForTesting([&](base::OnceClosure callback) { + removal_tasks.push_back( + {browsing_data_remover->GetLastUsedRemovalMaskForTesting(), + browsing_data_remover + ->GetLastUsedStoragePartitionConfigForTesting()}); + if (browsing_data_remover->GetPendingTaskCountForTesting() == 1) { + run_loop.Quit(); + } + std::move(callback).Run(); + })); + + BlockUntilOriginDataRemoved(delete_begin, delete_end, remove_mask, + std::move(filter_builder)); + run_loop.Run(); + + browsing_data_remover->SetWouldCompleteCallbackForTesting( + base::DoNothing()); + return removal_tasks; + } +}; +bool operator==( + const IsolatedWebAppChromeBrowsingDataRemoverDelegateTest::RemovalInfo& a, + const IsolatedWebAppChromeBrowsingDataRemoverDelegateTest::RemovalInfo& b) { + return a.remove_mask == b.remove_mask && + a.storage_partition_config == b.storage_partition_config; +} + +TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, ClearData) { + const GURL iwa_url1( + "isolated-app://" + "berugqztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info1 = + InstallIsolatedWebApp(iwa_url1); + content::StoragePartitionConfig controlled_frame_partition1 = + CreateControlledFrameStoragePartition(iwa_url_info1, "controlled_frame"); + + const GURL iwa_url2( + "isolated-app://" + "abcdefztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info2 = + InstallIsolatedWebApp(iwa_url2); + + std::vector<RemovalInfo> removal_tasks = + ClearDataAndWait(base::Time(), base::Time::Max(), DATA_TYPE_SITE_DATA, + BrowsingDataFilterBuilder::Create( + BrowsingDataFilterBuilder::Mode::kPreserve)); + + EXPECT_THAT( + removal_tasks, + UnorderedElementsAre( + RemovalInfo{DATA_TYPE_SITE_DATA}, + RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION & DATA_TYPE_SITE_DATA, + iwa_url_info1.storage_partition_config(GetProfile())}, + RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION, + controlled_frame_partition1}, + RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION & DATA_TYPE_SITE_DATA, + iwa_url_info2.storage_partition_config(GetProfile())})); +} + +TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, + ControlledFramesNotClearedIfNotInFilter) { + const GURL iwa_url( + "isolated-app://" + "berugqztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info = InstallIsolatedWebApp(iwa_url); + content::StoragePartitionConfig controlled_frame_partition = + CreateControlledFrameStoragePartition(iwa_url_info, "controlled_frame"); + + std::vector<RemovalInfo> removal_tasks = + ClearDataAndWait(base::Time(), base::Time::Max(), DATA_TYPE_INDEXED_DB, + BrowsingDataFilterBuilder::Create( + BrowsingDataFilterBuilder::Mode::kPreserve)); + + EXPECT_THAT( + removal_tasks, + UnorderedElementsAre( + RemovalInfo{DATA_TYPE_INDEXED_DB}, + RemovalInfo{DATA_TYPE_INDEXED_DB, + iwa_url_info.storage_partition_config(GetProfile())})); +} + +TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, + FilterOriginRespected) { + const GURL iwa_url1( + "isolated-app://" + "berugqztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info1 = + InstallIsolatedWebApp(iwa_url1); + + const GURL iwa_url2( + "isolated-app://" + "abcdefztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info2 = + InstallIsolatedWebApp(iwa_url2); + + auto filter_builder = BrowsingDataFilterBuilder::Create( + BrowsingDataFilterBuilder::Mode::kDelete); + filter_builder->AddOrigin(iwa_url_info1.origin()); + std::vector<RemovalInfo> removal_tasks = + ClearDataAndWait(base::Time(), base::Time::Max(), DATA_TYPE_INDEXED_DB, + std::move(filter_builder)); + + EXPECT_THAT( + removal_tasks, + UnorderedElementsAre( + RemovalInfo{DATA_TYPE_INDEXED_DB}, + RemovalInfo{DATA_TYPE_INDEXED_DB, + iwa_url_info1.storage_partition_config(GetProfile())})); +} + +TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, + ControlledFramesIgnoreFilter) { + const GURL iwa_url( + "isolated-app://" + "berugqztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info = InstallIsolatedWebApp(iwa_url); + content::StoragePartitionConfig controlled_frame_partition = + CreateControlledFrameStoragePartition(iwa_url_info, "controlled_frame"); + + std::vector<RemovalInfo> removal_tasks = + ClearDataAndWait(base::Time(), base::Time::Max(), + DATA_TYPE_INDEXED_DB | constants::DATA_TYPE_HISTORY | + constants::DATA_TYPE_CONTROLLED_FRAME, + BrowsingDataFilterBuilder::Create( + BrowsingDataFilterBuilder::Mode::kPreserve)); + + EXPECT_THAT( + removal_tasks, + UnorderedElementsAre( + RemovalInfo{DATA_TYPE_INDEXED_DB | constants::DATA_TYPE_HISTORY | + constants::DATA_TYPE_CONTROLLED_FRAME}, + RemovalInfo{DATA_TYPE_INDEXED_DB, + iwa_url_info.storage_partition_config(GetProfile())}, + RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION, + controlled_frame_partition})); +} + +TEST_F(IsolatedWebAppChromeBrowsingDataRemoverDelegateTest, + TimeRangeSpecified) { + const GURL iwa_url( + "isolated-app://" + "berugqztij5biqquuk3mfwpsaibuegaqcitgfchwuosuofdjabzqaaic"); + web_app::IsolatedWebAppUrlInfo iwa_url_info = InstallIsolatedWebApp(iwa_url); + content::StoragePartitionConfig controlled_frame_partition = + CreateControlledFrameStoragePartition(iwa_url_info, "controlled_frame"); + + std::vector<RemovalInfo> removal_tasks = ClearDataAndWait( + AnHourAgo(), base::Time::Max(), + DATA_TYPE_INDEXED_DB | constants::DATA_TYPE_CONTROLLED_FRAME, + BrowsingDataFilterBuilder::Create( + BrowsingDataFilterBuilder::Mode::kPreserve)); + + EXPECT_THAT( + removal_tasks, + UnorderedElementsAre( + RemovalInfo{DATA_TYPE_INDEXED_DB | + constants::DATA_TYPE_CONTROLLED_FRAME}, + RemovalInfo{DATA_TYPE_INDEXED_DB, + iwa_url_info.storage_partition_config(GetProfile())}, + RemovalInfo{DATA_TYPE_ON_STORAGE_PARTITION, + controlled_frame_partition})); +} #endif // !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_CHROMEOS_LACROS) TEST_F(ChromeBrowsingDataRemoverDelegateTest, RemoveHistoryForever) { @@ -1932,14 +2159,22 @@ // Regression test for: https://crbug.com/1207632. TEST_F(ChromeBrowsingDataRemoverDelegateTest, DeleteBookmarksDoesNothingWhenModelNotLoaded) { - TestingProfile* profile = GetProfile(); + TestingProfile* profile = GetProfileManager()->CreateTestingProfile( + "bookmark_profile", {{BookmarkModelFactory::GetInstance(), + BookmarkModelFactory::GetDefaultFactory()}}); bookmarks::BookmarkModel* bookmark_model = BookmarkModelFactory::GetForBrowserContext(profile); // For this test to exercise the code path that lead to the crash the // model must not be loaded yet. EXPECT_FALSE(bookmark_model->loaded()); - BlockUntilBrowsingDataRemoved(base::Time(), base::Time::Max(), - constants::DATA_TYPE_BOOKMARKS, false); + + content::BrowsingDataRemover* remover = profile->GetBrowsingDataRemover(); + content::BrowsingDataRemoverCompletionObserver completion_observer(remover); + remover->RemoveAndReply( + base::Time(), base::Time::Max(), constants::DATA_TYPE_BOOKMARKS, + content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB, + &completion_observer); + completion_observer.BlockUntilCompletion(); // No crash means test passes. }
diff --git a/chrome/browser/chrome_browser_main.cc b/chrome/browser/chrome_browser_main.cc index 4b55f9a..2911f6b8 100644 --- a/chrome/browser/chrome_browser_main.cc +++ b/chrome/browser/chrome_browser_main.cc
@@ -2006,6 +2006,14 @@ profile_init_manager_.reset(); +#if BUILDFLAG(IS_CHROMEOS_ASH) + // These controllers make use of `browser_process_->local_state()`, so they + // must be destroyed before `browser_process_`. + ash::HWDataUsageController::Shutdown(); + arc::StabilityMetricsManager::Shutdown(); + ash::StatsReportingController::Shutdown(); +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + // The below call to browser_shutdown::ShutdownPostThreadsStop() deletes // |browser_process_|. We release it so that we don't keep holding onto an // invalid reference. @@ -2037,9 +2045,10 @@ device_event_log::Shutdown(); #if BUILDFLAG(IS_CHROMEOS_ASH) - ash::HWDataUsageController::Shutdown(); - arc::StabilityMetricsManager::Shutdown(); - ash::StatsReportingController::Shutdown(); + // CrosSettings must out-live `browser_process_->browser_policy_connector()`. + // TODO(elkurin): CrosSettings should be shutdown before + // `browser_process_->local_state()` but there is a circular dependency here. + // Resolve this after browser policy connector dependency is resolved. ash::CrosSettings::Shutdown(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) #endif // BUILDFLAG(IS_ANDROID)
diff --git a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc index 5b0a9653..dcdfebf 100644 --- a/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc +++ b/chrome/browser/chromeos/policy/dlp/dlp_reporting_manager.cc
@@ -16,7 +16,9 @@ #include "chrome/browser/chromeos/policy/dlp/dlp_rules_manager_factory.h" #include "chrome/browser/policy/dm_token_utils.h" #include "components/reporting/client/report_queue.h" +#include "components/reporting/client/report_queue_configuration.h" #include "components/reporting/client/report_queue_factory.h" +#include "components/reporting/proto/synced/record_constants.pb.h" #include "components/reporting/util/status.h" #include "url/gurl.h" @@ -274,9 +276,14 @@ DlpReportingManager::DlpReportingManager() : report_queue_( - ::reporting::ReportQueueFactory::CreateSpeculativeReportQueue( - ::reporting::EventType::kUser, - ::reporting::Destination::DLP_EVENTS)) {} + ::reporting::ReportQueueFactory::CreateSpeculativeReportQueue([]() { + ::reporting::SourceInfo source_info; + source_info.set_source(::reporting::SourceInfo::ASH); + return ::reporting::ReportQueueConfiguration::Create( + {.event_type = ::reporting::EventType::kUser, + .destination = ::reporting::Destination::DLP_EVENTS}) + .SetSourceInfo(std::move(source_info)); + }())) {} DlpReportingManager::~DlpReportingManager() = default;
diff --git a/chrome/browser/companion/visual_search/visual_search_suggestions_service.cc b/chrome/browser/companion/visual_search/visual_search_suggestions_service.cc index 590d2bb..fe49b6f 100644 --- a/chrome/browser/companion/visual_search/visual_search_suggestions_service.cc +++ b/chrome/browser/companion/visual_search/visual_search_suggestions_service.cc
@@ -51,10 +51,21 @@ : model_provider_(model_provider), background_task_runner_(background_task_runner) { if (model_provider_) { + // Prepare metadata for requesting a specific version of the config proto. + optimization_guide::proto::Any any_metadata; + any_metadata.set_type_url( + "type.googleapis.com/lens.prime.csc.VisualSearchModelMetadata"); + optimization_guide::proto::VisualSearchModelMetadata vs_model_metadata; + // Version 2 includes the new additions to the proto spec for + // sorting and for z score handling. There is no explicitly named + // version 1. The version before version 2 is only the base features. + vs_model_metadata.set_metadata_version(2); + vs_model_metadata.SerializeToString(any_metadata.mutable_value()); + model_provider_->AddObserverForOptimizationTargetModel( optimization_guide::proto:: OPTIMIZATION_TARGET_VISUAL_SEARCH_CLASSIFICATION, - /*model_metadata=*/absl::nullopt, this); + any_metadata, this); } }
diff --git a/chrome/browser/companion/visual_search/visual_search_suggestions_service_factory.cc b/chrome/browser/companion/visual_search/visual_search_suggestions_service_factory.cc index 1ba5447..21e122b2 100644 --- a/chrome/browser/companion/visual_search/visual_search_suggestions_service_factory.cc +++ b/chrome/browser/companion/visual_search/visual_search_suggestions_service_factory.cc
@@ -50,8 +50,8 @@ return nullptr; } - // The optimization guide service must be available for the translate model - // service to be created. + // The optimization guide service must be available for the visual search + // suggestion service to be created. auto* opt_guide = OptimizationGuideKeyedServiceFactory::GetForProfile( Profile::FromBrowserContext(context)); if (opt_guide) {
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.cc b/chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.cc index d4eaf844..3579ed40 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.cc +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_delegate.cc
@@ -512,7 +512,8 @@ if (!dialog_) return false; - return dialog_->CancelDialogAndDelete(); + dialog_->CancelDialogAndDelete(); + return true; } void ContentAnalysisDelegate::PageRequestCallback(
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc index 9e42ed50..d4c36a7 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.cc
@@ -231,6 +231,7 @@ files_count_(files_count), download_item_(download_item), is_cloud_(is_cloud) { + DVLOG(1) << __func__; DCHECK(delegate_); SetOwnedByWidget(true); set_fixed_width(views::LayoutProvider::Get()->GetDistanceMetric( @@ -256,6 +257,7 @@ top_level_contents_->SetIgnoreInputEvents(true); if (ShowDialogDelay().is_zero() || !is_pending()) { + DVLOG(1) << __func__ << ": Showing in ctor"; ShowDialogNow(); } else { content::GetUIThreadTaskRunner({})->PostDelayedTask( @@ -273,9 +275,15 @@ } void ContentAnalysisDialog::ShowDialogNow() { + if (will_be_deleted_soon_) { + DVLOG(1) << __func__ << ": aborting since dialog will be deleted soon"; + return; + } + // If the web contents is still valid when the delay timer goes off and the // dialog has not yet been shown, show it now. if (web_contents_ && !contents_view_) { + DVLOG(1) << __func__ << ": first time"; first_shown_timestamp_ = base::TimeTicks::Now(); constrained_window::ShowWebModalDialogViews(this, web_contents_); if (observer_for_testing) @@ -359,6 +367,7 @@ views::View* ContentAnalysisDialog::GetContentsView() { if (!contents_view_) { + DVLOG(1) << __func__ << ": first time"; contents_view_ = new views::BoxLayoutView(); // Owned by caller. contents_view_->SetOrientation(views::BoxLayout::Orientation::kVertical); // Padding to distance the top image from the icon and message. @@ -461,6 +470,8 @@ } ContentAnalysisDialog::~ContentAnalysisDialog() { + DVLOG(1) << __func__; + if (top_level_contents_) { top_level_contents_->SetIgnoreInputEvents(false); top_level_contents_->RestoreFocus(); @@ -969,14 +980,15 @@ return access_point_ == safe_browsing::DeepScanAccessPoint::PRINT; } -bool ContentAnalysisDialog::CancelDialogAndDelete() { +void ContentAnalysisDialog::CancelDialogAndDelete() { if (contents_view_) { + DVLOG(1) << __func__ << ": dialog will be canceled"; CancelDialog(); } else { + DVLOG(1) << __func__ << ": dialog will be deleted soon"; + will_be_deleted_soon_ = true; content::GetUIThreadTaskRunner({})->DeleteSoon(FROM_HERE, this); } - - return true; } ui::ColorId ContentAnalysisDialog::GetSideImageLogoColor() const {
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h index a8bd650..15f43cb 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_dialog.h
@@ -142,10 +142,9 @@ return delegate_->BypassRequiresJustification(); } - // Cancels the dialog if it was visible, then deletes the object. Returns - // false if the UI was not visible to indicate that the object is simply - // deletng itself. - bool CancelDialogAndDelete(); + // Cancels the dialog an schedules it for deletion if visible, otherwise + // simply deletes it soon. + void CancelDialogAndDelete(); // Returns the side image's logo color depending on `dialog_state_`. ui::ColorId GetSideImageLogoColor() const; @@ -339,6 +338,11 @@ // a locally based content analysis. bool is_cloud_ = true; + // Set to true once `DeleteSoon()` is called in `CancelDialogAndDelete()`. + // This is used by other pending tasks, such as `ShowDialogNow()` to do + // nothing if the dialog has been scheduled for deletion. + bool will_be_deleted_soon_ = false; + // A reference to the top level web contents of the tab whose content is // being analyzed. Input events of this contents are ignored for the life // time of the dialog.
diff --git a/chrome/browser/enterprise/connectors/analysis/content_analysis_downloads_delegate.cc b/chrome/browser/enterprise/connectors/analysis/content_analysis_downloads_delegate.cc index 45a4639..618e016 100644 --- a/chrome/browser/enterprise/connectors/analysis/content_analysis_downloads_delegate.cc +++ b/chrome/browser/enterprise/connectors/analysis/content_analysis_downloads_delegate.cc
@@ -90,11 +90,8 @@ std::u16string ContentAnalysisDownloadsDelegate::GetBypassJustificationLabel() const { - // TODO(crbug.com/1278000): Change this to a downloads-specific string when - // this feature is supported for downloads. Returning a non-empty string is - // required to avoid a DCHECK in the a11y code that looks for an a11y label. return l10n_util::GetStringUTF16( - IDS_DEEP_SCANNING_DIALOG_UPLOAD_BYPASS_JUSTIFICATION_LABEL); + IDS_DEEP_SCANNING_DIALOG_DOWNLOAD_BYPASS_JUSTIFICATION_LABEL); } absl::optional<std::u16string>
diff --git a/chrome/browser/enterprise/idle/action_runner_unittest.cc b/chrome/browser/enterprise/idle/action_runner_unittest.cc index 8b0a66a..07b029c 100644 --- a/chrome/browser/enterprise/idle/action_runner_unittest.cc +++ b/chrome/browser/enterprise/idle/action_runner_unittest.cc
@@ -327,6 +327,11 @@ uint64_t GetLastUsedOriginTypeMaskForTesting() override { return origin_type_mask_; } + absl::optional<content::StoragePartitionConfig> + GetLastUsedStoragePartitionConfigForTesting() override { + return absl::nullopt; + } + uint64_t GetPendingTaskCountForTesting() override { return 0; } void SetFailedDataTypesForTesting(uint64_t failed_data_types) { failed_data_types_ = failed_data_types;
diff --git a/chrome/browser/feature_engagement/java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitorImpl.java b/chrome/browser/feature_engagement/java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitorImpl.java index fbc7a4f4..9fca1d3 100644 --- a/chrome/browser/feature_engagement/java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitorImpl.java +++ b/chrome/browser/feature_engagement/java/src/org/chromium/chrome/browser/feature_engagement/ScreenshotMonitorImpl.java
@@ -62,7 +62,7 @@ Log.d(TAG, "Detected change to the media database " + uri); String uriPath = uri.toString(); - // Sanity check the uri before processing it. + // Validate the uri before processing it. if (uri == null || !uri.toString().startsWith(Media.EXTERNAL_CONTENT_URI.toString())) { Log.w(TAG, "uri: %s is not valid. Returning without processing screenshot", uri); return;
diff --git a/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java b/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java index 97fa0e8..cea9d24 100644 --- a/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java +++ b/chrome/browser/feedback/android/java/src/org/chromium/chrome/browser/feedback/FeedbackCollector.java
@@ -75,7 +75,7 @@ identityManager.getPrimaryAccountInfo(ConsentLevel.SIGNIN)); } - // Sanity check in case a source is added to the wrong list. + // Validation check in case a source is added to the wrong list. for (FeedbackSource source : mSynchronousSources) { assert !(source instanceof AsyncFeedbackSource); } @@ -92,7 +92,7 @@ // 4. Kick off a task to timeout the async sources. ThreadUtils.postOnUiThreadDelayed(this, TIMEOUT_MS); - // 5. Sanity check in case everything finished or we have no sources. + // 5. Validation check in case everything finished or we have no sources. checkIfReady(); }
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index 38b67bb..6d1bf89c 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -595,6 +595,11 @@ "expiry_milestone": 125 }, { + "name": "autofill-enable-payments-mandatory-reauth-on-bling", + "owners": [ "siyua" ], + "expiry_milestone": 125 + }, + { "name": "autofill-enable-ranking-formula-address-profiles", "owners": [ "alexandertekle@google.com", "koerber@google.com" ], "expiry_milestone": 120 @@ -2354,11 +2359,6 @@ "expiry_milestone": -1 }, { - "name": "enable-default-following-feed-sort-type", - "owners": [ "adamta", "sczs"], - "expiry_milestone": 115 - }, - { "name": "enable-delay-temp-strip-removal", "owners": [ "skavuluru@google.com", "nemco@google.com", "clank-app-team@google.com" ], "expiry_milestone": 120 @@ -8047,11 +8047,6 @@ "expiry_milestone": 122 }, { - "name": "web-feed-ios", - "owners": [ "adamta", "sczs", "tinazwang" ], - "expiry_milestone": 122 - }, - { "name": "web-feed-onboarding", "owners": ["//chrome/android/feed/OWNERS", "feed@chromium.org" ], "expiry_milestone": 122
diff --git a/chrome/browser/omaha/android/java/src/org/chromium/chrome/browser/omaha/ExponentialBackoffScheduler.java b/chrome/browser/omaha/android/java/src/org/chromium/chrome/browser/omaha/ExponentialBackoffScheduler.java index 16240ce..3880b57d 100644 --- a/chrome/browser/omaha/android/java/src/org/chromium/chrome/browser/omaha/ExponentialBackoffScheduler.java +++ b/chrome/browser/omaha/android/java/src/org/chromium/chrome/browser/omaha/ExponentialBackoffScheduler.java
@@ -114,7 +114,7 @@ delay = Math.min(backoffCoefficient * mBaseMilliseconds, mMaxMilliseconds); } - // Save the delay for sanity checks. + // Save the delay for validation checks. SharedPreferences preferences = getSharedPreferences(); preferences.edit().putLong(PREFERENCE_DELAY, delay).apply(); return delay;
diff --git a/chrome/browser/page_load_metrics/integration_tests/soft_navigation_metrics_browsertest.cc b/chrome/browser/page_load_metrics/integration_tests/soft_navigation_metrics_browsertest.cc index 5c4217c..28f9a73 100644 --- a/chrome/browser/page_load_metrics/integration_tests/soft_navigation_metrics_browsertest.cc +++ b/chrome/browser/page_load_metrics/integration_tests/soft_navigation_metrics_browsertest.cc
@@ -78,9 +78,10 @@ base::test::ScopedFeatureList feature_list_; }; -// TODO(crbug.com/1466868): Investigate timeout issue on linux-lacros-rel -// when retrieving web exposed soft nav lcp entries using the EvalJs method. -#if BUILDFLAG(IS_CHROMEOS_LACROS) +// TODO(crbug.com/1466868): Investigate timeout issue on linux-lacros-rel and +// linux-wayland when retrieving web exposed soft nav lcp entries using the +// EvalJs method. +#if BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_LINUX) #define MAYBE_LargestContentfulPaint DISABLED_LargestContentfulPaint #else #define MAYBE_LargestContentfulPaint LargestContentfulPaint
diff --git a/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc b/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc index 818c624..f07f8df 100644 --- a/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc +++ b/chrome/browser/picture_in_picture/document_picture_in_picture_window_controller_browsertest.cc
@@ -12,6 +12,7 @@ #include "base/scoped_observation.h" #include "base/strings/strcat.h" #include "base/test/scoped_feature_list.h" +#include "base/test/test_timeouts.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_content_browser_client.h" @@ -87,7 +88,8 @@ FILE_PATH_LITERAL("media/picture-in-picture/document-pip.html"); class DocumentPictureInPictureWindowControllerBrowserTest - : public InProcessBrowserTest { + : public InProcessBrowserTest, + public testing::WithParamInterface<gfx::Size> { public: DocumentPictureInPictureWindowControllerBrowserTest() = default; @@ -167,6 +169,23 @@ EXPECT_TRUE(WaitForRenderFrameReady(contents->GetPrimaryMainFrame())); } + bool IsOriginSet(BrowserView* browser_view) { + // Document Picture In Picture windows are always positioned relative to the + // bottom-right corner. Therefore we can assert that the origin is set + // whenever it is not located at the top-left corner. + return browser_view->GetBounds().origin() != gfx::Point(0, 0); + } + + void CheckOriginSet(BrowserView* browser_view) { + ui_test_utils::CheckWaiter( + base::BindRepeating( + &DocumentPictureInPictureWindowControllerBrowserTest::IsOriginSet, + base::Unretained(this), browser_view), + true, base::Minutes(1)) + .Wait(); + EXPECT_NE(browser_view->GetBounds().origin(), gfx::Point(0, 0)); + } + // Watch for destruction of a WebContents. `is_destroyed()` will report if the // WebContents has been destroyed yet. class DestructionObserver : public content::WebContentsObserver { @@ -530,3 +549,56 @@ ASSERT_EQ(expected_size, window->GetBoundsInScreen().size()); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) + +INSTANTIATE_TEST_SUITE_P(WindowSizes, + DocumentPictureInPictureWindowControllerBrowserTest, + testing::Values(gfx::Size(1, 1), + gfx::Size(22, 22), + gfx::Size(300, 300), + gfx::Size(500, 500), + gfx::Size(250, 670))); + +#if BUILDFLAG(IS_LINUX) +// TODO(crbug.com/1465020): Fix and re-enable this test for Linux. +// This test is flaky on Linux, sometimes the window origin is not updated +// before the test harness timeout. +#define MAYBE_VerifyWindowMargins DISABLED_VerifyWindowMargins +#else +#define MAYBE_VerifyWindowMargins VerifyWindowMargins +#endif +// Test that the document PiP window margins are correct. +IN_PROC_BROWSER_TEST_P(DocumentPictureInPictureWindowControllerBrowserTest, + MAYBE_VerifyWindowMargins) { + const BrowserWindow* const browser_window = browser()->window(); + const gfx::NativeWindow native_window = browser_window->GetNativeWindow(); + const display::Screen* const screen = display::Screen::GetScreen(); + const display::Display display = + screen->GetDisplayNearestWindow(native_window); + + // Create a Document PiP window with the given size. + LoadTabAndEnterPictureInPicture(browser(), GetParam()); + auto* pip_web_contents = window_controller()->GetChildWebContents(); + ASSERT_NE(nullptr, pip_web_contents); + WaitForPageLoad(pip_web_contents); + auto* browser_view = static_cast<BrowserView*>( + BrowserWindow::FindBrowserWindowWithWebContents(pip_web_contents)); + + // Wait for the window origin location to be set. This is needed to eliminate + // test flakiness. + CheckOriginSet(browser_view); + + // Make sure that the right and bottom window margins are equal. + gfx::Rect window_bounds = browser_view->GetBounds(); + gfx::Rect work_area = display.work_area(); + int window_diff_width = work_area.right() - window_bounds.width(); + int window_diff_height = work_area.bottom() - window_bounds.height(); + ASSERT_EQ(work_area.right() - window_bounds.right(), + work_area.bottom() - window_bounds.bottom()); + + // Make sure that the right and bottom window margins have distance of 2% the + // average of the two window size differences. + int buffer = (window_diff_width + window_diff_height) / 2 * 0.02; + gfx::Point expected_origin = + gfx::Point(window_diff_width - buffer, window_diff_height - buffer); + ASSERT_EQ(window_bounds.origin(), expected_origin); +}
diff --git a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc index e4c1a69..c5d98fa 100644 --- a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc +++ b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.cc
@@ -179,10 +179,10 @@ } // static -gfx::Rect -PictureInPictureWindowManager::CalculateInitialPictureInPictureWindowBounds( +gfx::Rect PictureInPictureWindowManager::CalculatePictureInPictureWindowBounds( const blink::mojom::PictureInPictureWindowOptions& pip_options, - const display::Display& display) { + const display::Display& display, + const gfx::Size& minimum_outer_window_size) { // TODO(https://crbug.com/1327797): This copies a bunch of logic from // VideoOverlayWindowViews. That class and this one should be refactored so // VideoOverlayWindowViews uses PictureInPictureWindowManager to calculate @@ -195,7 +195,7 @@ gfx::Size window_size(base::saturated_cast<int>(pip_options.width), base::saturated_cast<int>(pip_options.height)); window_size.SetToMin(GetMaximumWindowSize(display)); - window_size.SetToMax(GetMinimumInnerWindowSize()); + window_size.SetToMax(minimum_outer_window_size); window_bounds = gfx::Rect(window_size); } else { // Otherwise, fall back to the aspect ratio. @@ -204,7 +204,7 @@ : 1.0; gfx::Size window_size(work_area.width() / 5, work_area.height() / 5); window_size.SetToMin(GetMaximumWindowSize(display)); - window_size.SetToMax(GetMinimumInnerWindowSize()); + window_size.SetToMax(minimum_outer_window_size); window_bounds = gfx::Rect(window_size); gfx::SizeRectToAspectRatio(gfx::ResizeEdge::kTopLeft, initial_aspect_ratio, GetMinimumInnerWindowSize(), @@ -226,6 +226,24 @@ } // static +gfx::Rect +PictureInPictureWindowManager::CalculateInitialPictureInPictureWindowBounds( + const blink::mojom::PictureInPictureWindowOptions& pip_options, + const display::Display& display) { + return CalculatePictureInPictureWindowBounds(pip_options, display, + GetMinimumInnerWindowSize()); +} + +// static +gfx::Rect PictureInPictureWindowManager::AdjustPictureInPictureWindowBounds( + const blink::mojom::PictureInPictureWindowOptions& pip_options, + const display::Display& display, + const gfx::Size& minimum_window_size) { + return CalculatePictureInPictureWindowBounds(pip_options, display, + minimum_window_size); +} + +// static gfx::Size PictureInPictureWindowManager::GetMinimumInnerWindowSize() { return kMinWindowSize; }
diff --git a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.h b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.h index 7d23321..988c373 100644 --- a/chrome/browser/picture_in_picture/picture_in_picture_window_manager.h +++ b/chrome/browser/picture_in_picture/picture_in_picture_window_manager.h
@@ -85,11 +85,27 @@ // picture-in-picture if either of them is present. absl::optional<gfx::Rect> GetPictureInPictureWindowBounds() const; - // Used for Document picture-in-picture windows only. + // Used for Document picture-in-picture windows only. The returned dimensions + // represent the outer window bounds. + // This method is called from the |BrowserNavigator|. Note that the window + // bounds may be later re-adjusted by the |PictureInPictureBrowserFrameView| + // to accommodate non-client view elements, while respecting the minimum inner + // window size. static gfx::Rect CalculateInitialPictureInPictureWindowBounds( const blink::mojom::PictureInPictureWindowOptions& pip_options, const display::Display& display); + // Used for Document picture-in-picture windows only. The returned dimensions + // represent the outer window bounds. + // This method is called from |PictureInPictureBrowserFrameView|. Picture in + // picture window bounds are only adjusted when, the requested window size + // would cause the minimum inner window size to be smaller than the allowed + // minimum (|GetMinimumInnerWindowSize|). + static gfx::Rect AdjustPictureInPictureWindowBounds( + const blink::mojom::PictureInPictureWindowOptions& pip_options, + const display::Display& display, + const gfx::Size& minimum_window_size); + // Used for Document picture-in-picture windows only. // Note that this is meant to represent the inner window bounds. When the pip // window is drawn, outer bounds may be greater than kMinWindowSize to @@ -107,6 +123,13 @@ class DocumentWebContentsObserver; #endif // !BUILDFLAG(IS_ANDROID) + // Helper method Used to calculate the outer window bounds for Document + // picture-in-picture windows only. + static gfx::Rect CalculatePictureInPictureWindowBounds( + const blink::mojom::PictureInPictureWindowOptions& pip_options, + const display::Display& display, + const gfx::Size& minimum_outer_window_size); + // Create a Picture-in-Picture window and register it in order to be closed // when needed. // This is suffixed with "Internal" because `CreateWindow` is part of the
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/BaseChromePreferenceKeyChecker.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/BaseChromePreferenceKeyChecker.java index 3050d8c..aca69c4b 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/BaseChromePreferenceKeyChecker.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/BaseChromePreferenceKeyChecker.java
@@ -5,7 +5,7 @@ package org.chromium.chrome.browser.preferences; /** - * A dummy key checker that never throws exceptions. Used in production builds. + * A placeholder key checker that never throws exceptions. Used in production builds. */ class BaseChromePreferenceKeyChecker { void checkIsKeyInUse(String key) {
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java index 2ae82ec..50e5d6e7 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/ChromePreferenceKeys.java
@@ -44,7 +44,7 @@ * 3. Delete the KeyPrefix constant. * * Tests in ChromePreferenceKeysTest and checks in {@link ChromePreferenceKeyChecker} ensure the - * sanity of this file. + * validity of this file. */ public final class ChromePreferenceKeys { /**
diff --git a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/SharedPreferencesManager.java b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/SharedPreferencesManager.java index acd1b72..843d8da4 100644 --- a/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/SharedPreferencesManager.java +++ b/chrome/browser/preferences/android/java/src/org/chromium/chrome/browser/preferences/SharedPreferencesManager.java
@@ -42,7 +42,7 @@ private SharedPreferencesManager() { maybeInitializeChecker(); - // In production builds, use a dummy key checker. + // In production builds, use a placeholder key checker. if (mKeyChecker == null) { mKeyChecker = new BaseChromePreferenceKeyChecker(); }
diff --git a/chrome/browser/printing/browser_printing_context_factory_for_test.cc b/chrome/browser/printing/browser_printing_context_factory_for_test.cc index acf5859..c3bd9d2 100644 --- a/chrome/browser/printing/browser_printing_context_factory_for_test.cc +++ b/chrome/browser/printing/browser_printing_context_factory_for_test.cc
@@ -79,11 +79,9 @@ context->SetUserSettings(*test::MakeUserModifiedPrintSettings(printer_name_)); - context->SetOnNewDocumentCallback( - base::BindRepeating(&BrowserPrintingContextFactoryForTest::OnNewDocument, - base::Unretained(this))); + context->SetOnNewDocumentCallback(on_new_document_callback_); - return std::move(context); + return context; } void BrowserPrintingContextFactoryForTest::SetPrinterNameForSubsequentContexts( @@ -139,10 +137,9 @@ } #endif -void BrowserPrintingContextFactoryForTest::OnNewDocument( - const PrintSettings& settings) { - ++new_document_called_count_; - document_print_settings_ = settings; +void BrowserPrintingContextFactoryForTest::SetOnNewDocumentCallback( + TestPrintingContext::OnNewDocumentCallback callback) { + on_new_document_callback_ = std::move(callback); } } // namespace printing
diff --git a/chrome/browser/printing/browser_printing_context_factory_for_test.h b/chrome/browser/printing/browser_printing_context_factory_for_test.h index a866537..c5d10d7 100644 --- a/chrome/browser/printing/browser_printing_context_factory_for_test.h +++ b/chrome/browser/printing/browser_printing_context_factory_for_test.h
@@ -10,10 +10,9 @@ #include "build/build_config.h" #include "printing/buildflags/buildflags.h" -#include "printing/print_settings.h" #include "printing/printing_context.h" #include "printing/printing_context_factory_for_test.h" -#include "third_party/abseil-cpp/absl/types/optional.h" +#include "printing/test_printing_context.h" namespace printing { @@ -41,13 +40,8 @@ #if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) void SetCancelErrorOnAskUserForSettings(); #endif - void OnNewDocument(const PrintSettings& settings); - - int new_document_called_count() { return new_document_called_count_; } - - const absl::optional<PrintSettings>& document_print_settings() const { - return document_print_settings_; - } + void SetOnNewDocumentCallback( + TestPrintingContext::OnNewDocumentCallback callback); private: std::string printer_name_; @@ -64,8 +58,7 @@ #if BUILDFLAG(ENABLE_BASIC_PRINT_DIALOG) bool cancel_on_ask_user_for_settings_ = false; #endif - int new_document_called_count_ = 0; - absl::optional<PrintSettings> document_print_settings_; + TestPrintingContext::OnNewDocumentCallback on_new_document_callback_; }; } // namespace printing
diff --git a/chrome/browser/printing/print_browsertest.cc b/chrome/browser/printing/print_browsertest.cc index a54aea659..49725db 100644 --- a/chrome/browser/printing/print_browsertest.cc +++ b/chrome/browser/printing/print_browsertest.cc
@@ -418,6 +418,8 @@ void PrintBrowserTest::SetUp() { test_print_backend_ = base::MakeRefCounted<TestPrintBackend>(); PrintBackend::SetPrintBackendForTesting(test_print_backend_.get()); + test_printing_context_factory_.SetOnNewDocumentCallback(base::BindRepeating( + &PrintBrowserTest::OnNewDocument, base::Unretained(this))); PrintingContext::SetPrintingContextFactoryForTest( &test_printing_context_factory_); @@ -589,6 +591,12 @@ base::Unretained(GetFrameContent(render_frame_host)))); } +void PrintBrowserTest::OnNewDocument(const PrintSettings& settings) { + new_document_called_count_++; + DVLOG(1) << " Observed: new document"; + document_print_settings_ = settings; +} + void PrintBrowserTest::ShowPrintErrorDialog() { ++error_dialog_shown_count_; CheckForQuit();
diff --git a/chrome/browser/printing/print_browsertest.h b/chrome/browser/printing/print_browsertest.h index 809d976..e4bbbce 100644 --- a/chrome/browser/printing/print_browsertest.h +++ b/chrome/browser/printing/print_browsertest.h
@@ -70,6 +70,8 @@ } protected: + void OnNewDocument(const PrintSettings& settings); + TestPrintBackend* test_print_backend() { return test_print_backend_.get(); } BrowserPrintingContextFactoryForTest* test_printing_context_factory() { @@ -80,8 +82,10 @@ rendered_page_count_ = page_count; } + int new_document_called_count() const { return new_document_called_count_; } + const absl::optional<PrintSettings>& document_print_settings() const { - return test_printing_context_factory_.document_print_settings(); + return document_print_settings_; } private: @@ -92,6 +96,8 @@ void OverrideBinderForTesting(content::RenderFrameHost* render_frame_host); void ShowPrintErrorDialog(); + int new_document_called_count_ = 0; + absl::optional<PrintSettings> document_print_settings_; uint32_t error_dialog_shown_count_ = 0; uint32_t rendered_page_count_ = 0; unsigned int num_expected_messages_;
diff --git a/chrome/browser/printing/system_access_process_print_browsertest.cc b/chrome/browser/printing/system_access_process_print_browsertest.cc index 0cf173c..c713221 100644 --- a/chrome/browser/printing/system_access_process_print_browsertest.cc +++ b/chrome/browser/printing/system_access_process_print_browsertest.cc
@@ -2313,10 +2313,6 @@ return manager_ptr; } - int new_document_called_count() { - return test_printing_context_factory()->new_document_called_count(); - } - int scanning_responses_count() { return scanning_responses_; } bool SandboxService() override { return true; }
diff --git a/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.html b/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.html index 40ade7f..5556568 100644 --- a/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.html +++ b/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.html
@@ -3,12 +3,10 @@ padding: 0 var(--cr-controlled-by-spacing); } </style> -<os-settings-animated-pages id="pages" - section="[[section_]]" - focus-config="[[focusConfig_]]"> +<os-settings-animated-pages id="pages" section="[[section_]]"> <div route-path="default"> <settings-card header-text="$i18n{multidevicePageTitle}"> - <div id="multidevice-item" + <div id="multideviceItem" class="settings-box first two-line no-padding"> <div class="link-wrapper" id="suiteLinkWrapper" actionable$="[[doesClickOpenSubpage_(pageContentData)]]"
diff --git a/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.ts b/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.ts index d1b439d..86aa218 100644 --- a/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.ts +++ b/chrome/browser/resources/ash/settings/multidevice_page/multidevice_page.ts
@@ -29,7 +29,7 @@ import {recordSettingChange} from '../metrics_recorder.js'; import {Section} from '../mojom-webui/routes.mojom-webui.js'; import {Setting} from '../mojom-webui/setting.mojom-webui.js'; -import {RouteObserverMixin} from '../route_observer_mixin.js'; +import {RouteOriginMixin} from '../route_origin_mixin.js'; import {Route, Router, routes} from '../router.js'; import {MultiDeviceBrowserProxy, MultiDeviceBrowserProxyImpl} from './multidevice_browser_proxy.js'; @@ -40,7 +40,7 @@ import TokenInfo = chrome.quickUnlockPrivate.TokenInfo; const SettingsMultidevicePageElementBase = - NearbyShareSettingsMixin(MultiDeviceFeatureMixin(RouteObserverMixin( + NearbyShareSettingsMixin(MultiDeviceFeatureMixin(RouteOriginMixin( DeepLinkingMixin(PrefsMixin(WebUiListenerMixin(PolymerElement)))))); class SettingsMultidevicePageElement extends @@ -62,24 +62,6 @@ }, /** - * A Map specifying which element should be focused when exiting a - * subpage. The key of the map holds a Route path, and the value holds a - * query selector that identifies the desired element. - */ - focusConfig_: { - type: Object, - value() { - const map = new Map<string, string>(); - if (routes.MULTIDEVICE_FEATURES) { - map.set( - routes.MULTIDEVICE_FEATURES.path, - '#multidevice-item .subpage-arrow'); - } - return map; - }, - }, - - /** * Authentication token provided by password-prompt-dialog. */ authToken_: { @@ -192,6 +174,9 @@ constructor() { super(); + /** RouteOriginMixin override */ + this.route = routes.MULTIDEVICE; + this.browserProxy_ = MultiDeviceBrowserProxyImpl.getInstance(); } @@ -217,6 +202,9 @@ 'settings.OnScreenLockStatusChanged', this.onScreenLockStatusChanged_.bind(this)); + this.addFocusConfig( + routes.MULTIDEVICE_FEATURES, '#multideviceItem .subpage-arrow'); + this.browserProxy_.getPageContentData().then( (data) => this.onInitialPageContentDataFetched_(data)); } @@ -231,11 +219,13 @@ /** * RouteObserverMixin override */ - override currentRouteChanged(route: Route): void { + override currentRouteChanged(newRoute: Route, oldRoute?: Route): void { + super.currentRouteChanged(newRoute, oldRoute); + this.leaveNestedPageIfNoHostIsSet_(); // Does not apply to this page. - if (route !== routes.MULTIDEVICE) { + if (newRoute !== this.route) { return; }
diff --git a/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.html b/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.html index 96380f8..4a908c4 100644 --- a/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.html +++ b/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.html
@@ -1,22 +1,20 @@ <style include="settings-shared"> - #appManagement, - #appNotifications { - border-bottom: var(--cr-separator-line); + #appManagementRow, + #appNotificationsRow { + border-bottom: var(--cr-separator-line); } </style> -<os-settings-animated-pages id="pages" - section="[[section_]]" - focus-config="[[focusConfig_]]"> +<os-settings-animated-pages id="pages" section="[[section_]]"> <div route-path="default"> <settings-card header-text="$i18n{appsPageTitle}"> - <cr-link-row id="appManagement" + <cr-link-row id="appManagementRow" label="$i18n{appManagementTitle}" on-click="onClickAppManagement_" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> <template is="dom-if" if="[[showAppNotificationsRow_]]"> - <cr-link-row id="appNotifications" + <cr-link-row id="appNotificationsRow" label="$i18n{appNotificationsTitle}" on-click="onClickAppNotifications_" role-description="$i18n{subpageArrowRoleDescription}" @@ -26,7 +24,7 @@ </template> <template is="dom-if" if="[[showAndroidApps_]]"> <template is="dom-if" if="[[isPlayStoreAvailable_]]" restamp> - <div id="android-apps" class="settings-box first" + <div id="androidApps" class="settings-box first" actionable$="[[androidAppsInfo.playStoreEnabled]]" on-click="onAndroidAppsSubpageClick_"> <div class="start settings-box-text">
diff --git a/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.ts b/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.ts index f0299adf..60f0d0a 100644 --- a/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.ts +++ b/chrome/browser/resources/ash/settings/os_apps_page/os_apps_page.ts
@@ -41,7 +41,7 @@ import {App as AppWithNotifications, AppNotificationsHandlerInterface, AppNotificationsObserverReceiver, Readiness} from '../mojom-webui/app_notification_handler.mojom-webui.js'; import {Section} from '../mojom-webui/routes.mojom-webui.js'; import {Setting} from '../mojom-webui/setting.mojom-webui.js'; -import {RouteObserverMixin} from '../route_observer_mixin.js'; +import {RouteOriginMixin} from '../route_origin_mixin.js'; import {Route, Router, routes} from '../router.js'; import {AndroidAppsBrowserProxyImpl, AndroidAppsInfo} from './android_apps_browser_proxy.js'; @@ -65,7 +65,7 @@ } } -const OsSettingsAppsPageElementBase = DeepLinkingMixin(RouteObserverMixin( +const OsSettingsAppsPageElementBase = DeepLinkingMixin(RouteOriginMixin( PrefsMixin(AppManagementStoreMixin(I18nMixin(PolymerElement))))); class OsSettingsAppsPageElement extends OsSettingsAppsPageElementBase { @@ -142,22 +142,6 @@ readOnly: true, }, - focusConfig_: { - type: Object, - value() { - const map = new Map(); - if (routes.APP_MANAGEMENT) { - map.set(routes.APP_MANAGEMENT.path, '#appManagement'); - } - if (routes.ANDROID_APPS_DETAILS) { - map.set( - routes.ANDROID_APPS_DETAILS.path, - '#android-apps .subpage-arrow'); - } - return map; - }, - }, - app_: Object, appsWithNotifications_: { @@ -204,7 +188,6 @@ private app_: App; private appNotificationsObserverReceiver_: AppNotificationsObserverReceiver; private appsWithNotifications_: AppWithNotifications[]; - private focusConfig_: Map<string, string>; private isArcVmManageUsbAvailable_: boolean; private isDndEnabled_: boolean; private isPlayStoreAvailable_: boolean; @@ -216,6 +199,13 @@ private showAppNotificationsRow_: boolean; private showStartup_: boolean; + constructor() { + super(); + + /** RouteOriginMixin override */ + this.route = routes.APPS; + } + override connectedCallback(): void { super.connectedCallback(); @@ -242,9 +232,20 @@ }); } - override currentRouteChanged(route: Route): void { + override ready() { + super.ready(); + + this.addFocusConfig(routes.APP_MANAGEMENT, '#appManagementRow'); + this.addFocusConfig(routes.APP_NOTIFICATIONS, '#appNotificationsRow'); + this.addFocusConfig( + routes.ANDROID_APPS_DETAILS, '#androidApps .subpage-arrow'); + } + + override currentRouteChanged(newRoute: Route, oldRoute?: Route): void { + super.currentRouteChanged(newRoute, oldRoute); + // Does not apply to this page. - if (route !== routes.APPS) { + if (newRoute !== this.route) { return; }
diff --git a/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.html b/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.html index e192910..61e06cac 100644 --- a/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.html +++ b/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.html
@@ -1,10 +1,8 @@ <style include="settings-shared"></style> -<os-settings-animated-pages id="pages" - section="[[section_]]" - focus-config="[[focusConfig_]]"> +<os-settings-animated-pages id="pages" section="[[section_]]"> <div route-path="default"> <settings-card header-text="$i18n{printingPageTitle}"> - <cr-link-row id="cupsPrinters" label="$i18n{cupsPrintersTitle}" + <cr-link-row id="cupsPrintersRow" label="$i18n{cupsPrintersTitle}" on-click="onTapCupsPrinters_" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row>
diff --git a/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.ts b/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.ts index 1059734..0517a2a9 100644 --- a/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.ts +++ b/chrome/browser/resources/ash/settings/os_printing_page/os_printing_page.ts
@@ -15,19 +15,19 @@ import {recordSettingChange} from '../metrics_recorder.js'; import {Section} from '../mojom-webui/routes.mojom-webui.js'; import {Setting} from '../mojom-webui/setting.mojom-webui.js'; -import {RouteObserverMixin} from '../route_observer_mixin.js'; +import {RouteOriginMixin} from '../route_origin_mixin.js'; import {Route, Router, routes} from '../router.js'; import {CupsPrintersBrowserProxy, CupsPrintersBrowserProxyImpl} from './cups_printers_browser_proxy.js'; import {getTemplate} from './os_printing_page.html.js'; const OsSettingsPrintingPageElementBase = - DeepLinkingMixin(RouteObserverMixin(PolymerElement)); + DeepLinkingMixin(RouteOriginMixin(PolymerElement)); export class OsSettingsPrintingPageElement extends OsSettingsPrintingPageElementBase { - static get is(): string { - return 'os-settings-printing-page'; + static get is() { + return 'os-settings-printing-page' as const; } static get template() { @@ -57,17 +57,6 @@ type: String, }, - focusConfig_: { - type: Object, - value() { - const map = new Map(); - if (routes.CUPS_PRINTERS) { - map.set(routes.CUPS_PRINTERS.path, '#cupsPrinters'); - } - return map; - }, - }, - /** * Used by DeepLinkingMixin to focus this page's deep links. */ @@ -83,18 +72,28 @@ searchTerm: string; private browserProxy_: CupsPrintersBrowserProxy; - private focusConfig_: Map<string, string>; private section_: Section; constructor() { super(); + /** RouteOriginMixin override */ + this.route = routes.OS_PRINTING; + this.browserProxy_ = CupsPrintersBrowserProxyImpl.getInstance(); } - override currentRouteChanged(route: Route): void { + override ready(): void { + super.ready(); + + this.addFocusConfig(routes.CUPS_PRINTERS, '#cupsPrintersRow'); + } + + override currentRouteChanged(newRoute: Route, oldRoute?: Route): void { + super.currentRouteChanged(newRoute, oldRoute); + // Does not apply to this page. - if (route !== routes.OS_PRINTING) { + if (newRoute !== this.route) { return; } @@ -117,7 +116,7 @@ declare global { interface HTMLElementTagNameMap { - 'os-settings-printing-page': OsSettingsPrintingPageElement; + [OsSettingsPrintingPageElement.is]: OsSettingsPrintingPageElement; } }
diff --git a/chrome/browser/resources/chromeos/login/components/oobe_display_size_selector.html b/chrome/browser/resources/chromeos/login/components/oobe_display_size_selector.html index e6ed379..42d72d1 100644 --- a/chrome/browser/resources/chromeos/login/components/oobe_display_size_selector.html +++ b/chrome/browser/resources/chromeos/login/components/oobe_display_size_selector.html
@@ -133,8 +133,11 @@ grid-column-gap: 28px; } } -</style> + :host-context(.jelly-enabled) cr-button.sign-button { + background-color: transparent; + } +</style> <div id="displaySizeSelector"> <!-- Preview Section --> <div id="preview" aria-hidden="true">
diff --git a/chrome/browser/resources/nearby_share/shared/nearby_device.html b/chrome/browser/resources/nearby_share/shared/nearby_device.html index 9938098..d4c4f12 100644 --- a/chrome/browser/resources/nearby_share/shared/nearby_device.html +++ b/chrome/browser/resources/nearby_share/shared/nearby_device.html
@@ -19,30 +19,61 @@ outline: none; } - :host(:focus) #wrapper { + /* TODO(b/279623883): Remove once Jelly is launched. */ + :host-context(body:not(.jelly-enabled)):host(:focus) #wrapper{ box-shadow: 0 0 0 2px var(--cros-focus-aura-color); } - :host([is-selected]) #wrapper { + :host-context(body.jelly-enabled):host(:focus) #wrapper { + border: 2px solid var(--cros-sys-focus_ring); + } + + :host-context(body.jelly-enabled):host(:hover) #wrapper { + background-color: var(--cros-sys-hover_on_subtle); + } + + /* TODO(b/279623883): Remove once Jelly is launched. */ + :host-context(body:not(.jelly-enabled)):host([is-selected]) #wrapper { border-color: var(--cros-button-icon-color-secondary); } + :host-context(body.jelly-enabled):host([is-selected]) #wrapper { + background-color: var(--cros-sys-primary_container); + } + :host([is-selected]) #done { display: flex; } - :host([is-selected]) #name { + /* TODO(b/279623883): Remove once Jelly is launched. */ + :host-context(body:not(.jelly-enabled)):host([is-selected]) #name { color: var(--cros-text-color-prominent); } + :host-context(body.jelly-enabled):host([is-selected]) #name { + color: var(--cros-sys-primary); + } + + :host-context(body.jelly-enabled):host([is-selected]) #share-target-image { + border: 1px solid var(--cros-sys-primary); + } + #done { - color: var(--cros-text-color-prominent); display: none; flex-shrink: 0; height: 17px; width: 17px; } + /* TODO(b/279623883): Remove once Jelly is launched. */ + :host-context(body:not(.jelly-enabled)) #done { + color: var(--cros-text-color-prominent); + } + + :host-context(body.jelly-enabled) #done { + color: var(--cros-sys-primary); + } + #icon { --nearby-device-icon-size: 15px; flex-shrink: 0; @@ -50,6 +81,16 @@ width: var(--target-image-size); } + :host-context(body.jelly-enabled) #icon { + --nearby-device-icon-color: var(--cros-sys-on_primary_container); + --nearby-device-icon-background-color: var(--cros-sys-primary_container); + } + + :host-context(body.jelly-enabled):host([is-selected]) #icon { + --nearby-device-icon-color: var(--cros-sys-on_primary); + --nearby-device-icon-background-color: var(--cros-sys-primary); + } + #share-target-image { border-radius: 50%; /* Hide the image until it's downloaded. */ @@ -59,10 +100,13 @@ width: var(--target-image-size); } + :host-context(body.jelly-enabled) #share-target-image { + /* Have a placeholder so that the image doesn't enlarge when focused. */ + border: 1px solid var(--cr-card-background-color); + } + #name { - color: var(--cros-text-color-secondary); flex-grow: 1; - letter-spacing: 0.3px; margin-inline-start: 11px; overflow: hidden; text-overflow: ellipsis; @@ -71,14 +115,16 @@ /* TODO(b/279623883): Remove once Jelly is launched. */ :host-context(body:not(.jelly-enabled)) #name { + color: var(--cros-text-color-secondary); font-size: 11px; font-weight: 500; + letter-spacing: 0.3px; } :host-context(body.jelly-enabled) #name { + color: var(--cros-sys-secondary); font: var(--cros-button-2-font); } - </style> <div id="wrapper" title="[[shareTarget.name]]">
diff --git a/chrome/browser/resources/settings/privacy_page/security_page.html b/chrome/browser/resources/settings/privacy_page/security_page.html index 37b8e676..39fade8 100644 --- a/chrome/browser/resources/settings/privacy_page/security_page.html +++ b/chrome/browser/resources/settings/privacy_page/security_page.html
@@ -76,31 +76,31 @@ <div slot="collapse"> <div class="bullet-line"> <iron-icon icon="cr:security"></iron-icon> - <div class="secondary"> + <div class="cr-secondary-text"> $i18n{safeBrowsingEnhancedBulOne} </div> </div> <div class="bullet-line"> <iron-icon icon="settings20:googleg"></iron-icon> - <div class="secondary"> + <div class="cr-secondary-text"> $i18n{safeBrowsingEnhancedBulTwo} </div> </div> <div class="bullet-line"> <iron-icon icon="settings:public"></iron-icon> - <div class="secondary"> + <div class="cr-secondary-text"> $i18n{safeBrowsingEnhancedBulThree} </div> </div> <div class="bullet-line"> <iron-icon icon="settings20:vpn-key"></iron-icon> - <div class="secondary"> + <div class="cr-secondary-text"> $i18n{safeBrowsingEnhancedBulFour} </div> </div> <div class="bullet-line last-collapse-item"> <iron-icon icon="settings20:data"></iron-icon> - <div class="secondary cr-padded-text"> + <div class="cr-secondary-text cr-padded-text"> $i18n{safeBrowsingEnhancedBulFive} </div> </div> @@ -110,26 +110,29 @@ name="[[safeBrowsingSettingEnum_.STANDARD]]" pref="[[prefs.generated.safe_browsing]]" label="$i18n{safeBrowsingStandard}" - sub-label="$i18n{safeBrowsingStandardDesc}" + sub-label="[[getSafeBrowsingStandardSubLabel_( + enableFriendlierSafeBrowsingSettings_)]]" indicator-aria-label="$i18n{controlledSettingPolicy}" expand-aria-label="$i18n{safeBrowsingStandardExpandA11yLabel}" info-opened="{{infoOpened_}}" on-expand-clicked="onStandardProtectionExpandButtonClicked_" no-automatic-collapse> - <div slot="collapse"> - <div class="bullet-line"> - <iron-icon icon="cr:security"></iron-icon> - <div class="secondary"> + <template is="dom-if" if="[[!enableFriendlierSafeBrowsingSettings_]]"> + <div slot="collapse"> + <div class="bullet-line"> + <iron-icon icon="cr:security"></iron-icon> + <div class="cr-secondary-text"> $i18n{safeBrowsingStandardBulOne} + </div> </div> - </div> - <div class="bullet-line"> - <iron-icon icon="settings20:data"></iron-icon> - <div class="secondary cr-padded-text"> + <div class="bullet-line"> + <iron-icon icon="settings20:data"></iron-icon> + <div class="cr-secondary-text cr-padded-text"> $i18n{safeBrowsingStandardBulTwo} + </div> </div> </div> - </div> + </template> <div slot="noSelectionCollapse"> <settings-toggle-button id="safeBrowsingReportingToggle" pref="{{prefs.safebrowsing.scout_reporting_enabled}}" @@ -140,9 +143,11 @@ prefs.generated.safe_browsing.*)]]"> </settings-toggle-button> <settings-toggle-button id="passwordsLeakToggle" - label="$i18n{passwordsLeakDetectionLabel}" + label="[[getPasswordsLeakToggleLabel_( + enableFriendlierSafeBrowsingSettings_)]]" pref="{{prefs.generated.password_leak_detection}}" sub-label="[[getPasswordsLeakToggleSubLabel_( + enableFriendlierSafeBrowsingSettings_, prefs.profile.password_manager_leak_detection.*, prefs.generated.password_leak_detection.*)]]"> </settings-toggle-button>
diff --git a/chrome/browser/resources/settings/privacy_page/security_page.ts b/chrome/browser/resources/settings/privacy_page/security_page.ts index 2ee5e67..b8bb8b79 100644 --- a/chrome/browser/resources/settings/privacy_page/security_page.ts +++ b/chrome/browser/resources/settings/privacy_page/security_page.ts
@@ -166,6 +166,14 @@ observer: 'focusConfigChanged_', }, + enableFriendlierSafeBrowsingSettings_: { + type: Boolean, + value() { + return loadTimeData.getBoolean( + 'enableFriendlierSafeBrowsingSettings'); + }, + }, + showDisableSafebrowsingDialog_: Boolean, }; } @@ -182,6 +190,7 @@ private enableSecurityKeysSubpage_: boolean; focusConfig: FocusConfig; private showDisableSafebrowsingDialog_: boolean; + private enableFriendlierSafeBrowsingSettings_: boolean; private browserProxy_: PrivacyPageBrowserProxy = PrivacyPageBrowserProxyImpl.getInstance(); @@ -281,18 +290,37 @@ SafeBrowsingSetting.STANDARD; } + private getSafeBrowsingStandardSubLabel_(): string { + return this.i18n( + this.enableFriendlierSafeBrowsingSettings_ ? + 'safeBrowsingStandardDescUpdated' : + 'safeBrowsingStandardDesc'); + } + + private getPasswordsLeakToggleLabel_(): string { + return this.i18n( + this.enableFriendlierSafeBrowsingSettings_ ? + 'passwordsLeakDetectionLabelUpdated' : + 'passwordsLeakDetectionLabel'); + } + private getPasswordsLeakToggleSubLabel_(): string { - let subLabel = this.i18n('passwordsLeakDetectionGeneralDescription'); + let subLabel = this.i18n( + this.enableFriendlierSafeBrowsingSettings_ ? + 'passwordsLeakDetectionGeneralDescriptionUpdated' : + 'passwordsLeakDetectionGeneralDescription'); // If the backing password leak detection preference is enabled, but the // generated preference is off and user control is disabled, then additional // text explaining that the feature will be enabled if the user signs in is // added. - const generatedPref = this.getPref('generated.password_leak_detection'); - if (this.getPref('profile.password_manager_leak_detection').value && - !generatedPref.value && generatedPref.userControlDisabled) { - subLabel += - ' ' + // Whitespace is a valid sentence separator w.r.t. i18n. - this.i18n('passwordsLeakDetectionSignedOutEnabledDescription'); + if (this.prefs !== undefined) { + const generatedPref = this.getPref('generated.password_leak_detection'); + if (this.getPref('profile.password_manager_leak_detection').value && + !generatedPref.value && generatedPref.userControlDisabled) { + subLabel += + ' ' + // Whitespace is a valid sentence separator w.r.t. i18n. + this.i18n('passwordsLeakDetectionSignedOutEnabledDescription'); + } } return subLabel; }
diff --git a/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html b/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html index 59fdc6a..52bb36a 100644 --- a/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html +++ b/chrome/browser/resources/side_panel/bookmarks/power_bookmarks_list.html
@@ -125,6 +125,10 @@ padding-block-start: 0; } + :host-context([chrome-refresh-2023]) .sp-scroller:has([is-full-card]) { + border-bottom: solid 1px transparent; + } + :host-context([chrome-refresh-2023]) #shownBookmarksIronList[is-full-card] { margin-block-end: var(--sp-body-padding); }
diff --git a/chrome/browser/resources/side_panel/shared/sp_shared_style.css b/chrome/browser/resources/side_panel/shared/sp_shared_style.css index eef022e..816fdc1 100644 --- a/chrome/browser/resources/side_panel/shared/sp_shared_style.css +++ b/chrome/browser/resources/side_panel/shared/sp_shared_style.css
@@ -44,7 +44,7 @@ :host-context([chrome-refresh-2023]) .sp-scroller::-webkit-scrollbar-thumb { background: var(--color-side-panel-scrollbar-thumb); background-clip: content-box; - border: solid 2px transparent; + border: solid 1.5px transparent; border-radius: 100px; }
diff --git a/chrome/browser/ui/BUILD.gn b/chrome/browser/ui/BUILD.gn index 064b808f..4fd521d 100644 --- a/chrome/browser/ui/BUILD.gn +++ b/chrome/browser/ui/BUILD.gn
@@ -6099,8 +6099,6 @@ "web_applications/tabbed_web_app_navigation_throttle.h", "web_applications/web_app_browser_controller.cc", "web_applications/web_app_browser_controller.h", - "web_applications/web_app_dialog_manager.cc", - "web_applications/web_app_dialog_manager.h", "web_applications/web_app_dialog_utils.cc", "web_applications/web_app_dialog_utils.h", "web_applications/web_app_launch_process.cc", @@ -6121,7 +6119,6 @@ "web_applications/web_app_ui_manager_impl.h", "web_applications/web_app_ui_utils.cc", "web_applications/web_app_ui_utils.h", - "web_applications/web_app_uninstall_dialog.h", "web_applications/webui_web_app_navigation_throttle.cc", "web_applications/webui_web_app_navigation_throttle.h", "webui/extensions/extension_basic_info.cc",
diff --git a/chrome/browser/ui/android/night_mode/java/src/org/chromium/chrome/browser/night_mode/GlobalNightModeStateProviderHolder.java b/chrome/browser/ui/android/night_mode/java/src/org/chromium/chrome/browser/night_mode/GlobalNightModeStateProviderHolder.java index e1f61dc5..250b27f 100644 --- a/chrome/browser/ui/android/night_mode/java/src/org/chromium/chrome/browser/night_mode/GlobalNightModeStateProviderHolder.java +++ b/chrome/browser/ui/android/night_mode/java/src/org/chromium/chrome/browser/night_mode/GlobalNightModeStateProviderHolder.java
@@ -22,10 +22,10 @@ /** * Created when night mode is not available or not supported. */ - private static class DummyNightModeStateProvider implements NightModeStateProvider { + private static class PlaceholderNightModeStateProvider implements NightModeStateProvider { final boolean mIsNightModeForceEnabled; - private DummyNightModeStateProvider() { + private PlaceholderNightModeStateProvider() { mIsNightModeForceEnabled = CommandLine.getInstance().hasSwitch(ChromeSwitches.FORCE_ENABLE_NIGHT_MODE); // Always stay in night mode if night mode is force enabled, and always stay in light @@ -57,7 +57,7 @@ if (sInstance == null) { if (CommandLine.getInstance().hasSwitch(ChromeSwitches.FORCE_ENABLE_NIGHT_MODE) || !NightModeUtils.isNightModeSupported()) { - sInstance = new DummyNightModeStateProvider(); + sInstance = new PlaceholderNightModeStateProvider(); } else { sInstance = new GlobalNightModeStateController(SystemNightModeMonitor.getInstance(), PowerSavingModeMonitor.getInstance(),
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/PreWarmingRecycledViewPool.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/PreWarmingRecycledViewPool.java index 85943c4a..d091ca7c 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/PreWarmingRecycledViewPool.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/suggestions/PreWarmingRecycledViewPool.java
@@ -48,7 +48,7 @@ private OmniboxSuggestionsDropdownAdapter mAdapter; private final Handler mHandler; - private final FrameLayout mDummyParent; + private final FrameLayout mPlaceholderParent; private boolean mStopCreatingViews; private final List<ViewHolder> mPrewarmedViews = new ArrayList<>(22); @@ -56,7 +56,7 @@ OmniboxSuggestionsDropdownAdapter adapter, Context context, Handler handler) { mAdapter = adapter; mHandler = handler; - mDummyParent = new FrameLayout(context); + mPlaceholderParent = new FrameLayout(context); // The list below should include suggestions defined in OmniboxSuggestionUiType // and specify the maximum anticipated volume of suggestions of each type. // For readability reasons, keep the order of this list same as the order of @@ -115,7 +115,7 @@ private void createViewHolder(@OmniboxSuggestionUiType int viewType) { if (mAdapter == null || mStopCreatingViews) return; try (TraceEvent t = TraceEvent.scoped("PreWarmingRecycledViewPool.createNextViewHolder")) { - mPrewarmedViews.add(mAdapter.createViewHolder(mDummyParent, viewType)); + mPrewarmedViews.add(mAdapter.createViewHolder(mPlaceholderParent, viewType)); } }
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/RecognitionTestHelper.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/RecognitionTestHelper.java index 5a4c9ffe..6e1644d 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/RecognitionTestHelper.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/RecognitionTestHelper.java
@@ -45,7 +45,7 @@ * @param texts the queries representing transcription results * @param confidences confidence values for corresponding queries */ - public static Bundle createDummyBundle(String[] texts, float[] confidences) { + public static Bundle createPlaceholderBundle(String[] texts, float[] confidences) { Bundle b = new Bundle(); b.putStringArrayList(
diff --git a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/VoiceRecognitionHandlerUnitTest.java b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/VoiceRecognitionHandlerUnitTest.java index 14a5d66..84a7254b 100644 --- a/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/VoiceRecognitionHandlerUnitTest.java +++ b/chrome/browser/ui/android/omnibox/java/src/org/chromium/chrome/browser/omnibox/voice/VoiceRecognitionHandlerUnitTest.java
@@ -187,7 +187,7 @@ var intent = new Intent(); var bundle = new Bundle(); if (text != null) { - bundle = RecognitionTestHelper.createDummyBundle( + bundle = RecognitionTestHelper.createPlaceholderBundle( new String[] {text}, new float[] {confidence}); } intent.putExtras(bundle); @@ -493,10 +493,10 @@ @SmallTest public void testParseResults_MismatchedTextAndConfidenceScores() { Assert.assertNull( - mHandler.convertBundleToVoiceResults(RecognitionTestHelper.createDummyBundle( + mHandler.convertBundleToVoiceResults(RecognitionTestHelper.createPlaceholderBundle( new String[] {"blah"}, new float[] {0f, 1f}))); Assert.assertNull( - mHandler.convertBundleToVoiceResults(RecognitionTestHelper.createDummyBundle( + mHandler.convertBundleToVoiceResults(RecognitionTestHelper.createPlaceholderBundle( new String[] {"blah", "foo"}, new float[] {7f}))); } @@ -507,7 +507,7 @@ float[] confidences = new float[] {0.8f, 1.0f, 1.0f}; List<VoiceResult> results = mHandler.convertBundleToVoiceResults( - RecognitionTestHelper.createDummyBundle(texts, confidences)); + RecognitionTestHelper.createPlaceholderBundle(texts, confidences)); Assert.assertEquals(3, results.size()); RecognitionTestHelper.assertVoiceResultsAreEqual(results, texts, confidences); } @@ -524,7 +524,7 @@ String[] texts = new String[] {"a", "www. b .co .uk", "engadget .com", "www.google.com"}; float[] confidences = new float[] {1.0f, 1.0f, 1.0f, 1.0f}; List<VoiceResult> results = mHandler.convertBundleToVoiceResults( - RecognitionTestHelper.createDummyBundle(texts, confidences)); + RecognitionTestHelper.createPlaceholderBundle(texts, confidences)); RecognitionTestHelper.assertVoiceResultsAreEqual(results, new String[] {"a", "www.b.co.uk", "engadget.com", "www.google.com"},
diff --git a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/SettableThemeColorProvider.java b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/SettableThemeColorProvider.java index 963584d..7604454 100644 --- a/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/SettableThemeColorProvider.java +++ b/chrome/browser/ui/android/toolbar/java/src/org/chromium/chrome/browser/toolbar/SettableThemeColorProvider.java
@@ -11,7 +11,7 @@ import org.chromium.chrome.browser.ui.theme.BrandedColorScheme; /** - * {@link ThemeColorProvider} that blindly tracks whatever primary color it's set to. + * {@link ThemeColorProvider} that tracks whatever primary color it's set to. * It contains no actual tracking logic; to function properly, setPrimaryColor must be called each * time the color changes. */
diff --git a/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.cc b/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.cc index bece423..f5d9958 100644 --- a/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.cc +++ b/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.cc
@@ -160,10 +160,18 @@ return state == GlanceablesClassroomStudentSubmissionState::kTurnedIn || state == GlanceablesClassroomStudentSubmissionState::kGraded; }); + auto sort_comparator = base::BindRepeating( + [](const std::unique_ptr<GlanceablesClassroomAssignment>& lhs, + const std::unique_ptr<GlanceablesClassroomAssignment>& rhs) { + // TODO(b/291609743): Order by when a student submission is turned-in + // in descending order. + return true; + }); InvokeOnceStudentDataFetched(base::BindOnce( &GlanceablesClassroomClientImpl::GetFilteredStudentAssignments, weak_factory_.GetWeakPtr(), std::move(due_predicate), - std::move(submission_state_predicate), std::move(callback))); + std::move(submission_state_predicate), std::move(sort_comparator), + std::move(callback))); } void GlanceablesClassroomClientImpl:: @@ -180,10 +188,17 @@ base::BindRepeating([](GlanceablesClassroomStudentSubmissionState state) { return state == GlanceablesClassroomStudentSubmissionState::kAssigned; }); + auto sort_comparator = base::BindRepeating( + [](const std::unique_ptr<GlanceablesClassroomAssignment>& lhs, + const std::unique_ptr<GlanceablesClassroomAssignment>& rhs) { + // Order by due date in ascending order. + return lhs->due < rhs->due; + }); InvokeOnceStudentDataFetched(base::BindOnce( &GlanceablesClassroomClientImpl::GetFilteredStudentAssignments, weak_factory_.GetWeakPtr(), std::move(due_predicate), - std::move(submission_state_predicate), std::move(callback))); + std::move(submission_state_predicate), std::move(sort_comparator), + std::move(callback))); } void GlanceablesClassroomClientImpl::GetStudentAssignmentsWithMissedDueDate( @@ -199,10 +214,17 @@ base::BindRepeating([](GlanceablesClassroomStudentSubmissionState state) { return state == GlanceablesClassroomStudentSubmissionState::kAssigned; }); + auto sort_comparator = base::BindRepeating( + [](const std::unique_ptr<GlanceablesClassroomAssignment>& lhs, + const std::unique_ptr<GlanceablesClassroomAssignment>& rhs) { + // Order by due date in descending order. + return lhs->due > rhs->due; + }); InvokeOnceStudentDataFetched(base::BindOnce( &GlanceablesClassroomClientImpl::GetFilteredStudentAssignments, weak_factory_.GetWeakPtr(), std::move(due_predicate), - std::move(submission_state_predicate), std::move(callback))); + std::move(submission_state_predicate), std::move(sort_comparator), + std::move(callback))); } void GlanceablesClassroomClientImpl::GetStudentAssignmentsWithoutDueDate( @@ -215,10 +237,17 @@ base::BindRepeating([](GlanceablesClassroomStudentSubmissionState state) { return state == GlanceablesClassroomStudentSubmissionState::kAssigned; }); + auto sort_comparator = base::BindRepeating( + [](const std::unique_ptr<GlanceablesClassroomAssignment>& lhs, + const std::unique_ptr<GlanceablesClassroomAssignment>& rhs) { + // TODO(b/291609743): Order by publish date in descending order. + return true; + }); InvokeOnceStudentDataFetched(base::BindOnce( &GlanceablesClassroomClientImpl::GetFilteredStudentAssignments, weak_factory_.GetWeakPtr(), std::move(due_predicate), - std::move(submission_state_predicate), std::move(callback))); + std::move(submission_state_predicate), std::move(sort_comparator), + std::move(callback))); } void GlanceablesClassroomClientImpl::IsTeacherRoleActive( @@ -815,6 +844,7 @@ due_predicate, base::RepeatingCallback<bool(GlanceablesClassroomStudentSubmissionState)> submission_state_predicate, + SortComparator sort_comparator, GetAssignmentsCallback callback) { CHECK(due_predicate); CHECK(submission_state_predicate); @@ -842,6 +872,13 @@ } } + std::sort(filtered_assignments.begin(), filtered_assignments.end(), + [sort_comparator]( + const std::unique_ptr<GlanceablesClassroomAssignment>& lhs, + const std::unique_ptr<GlanceablesClassroomAssignment>& rhs) { + return sort_comparator.Run(lhs, rhs); + }); + std::move(callback).Run(std::move(filtered_assignments)); }
diff --git a/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.h b/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.h index 318d3d8d..bf0a7340 100644 --- a/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.h +++ b/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl.h
@@ -332,12 +332,15 @@ // satisfies filtering requirements. // `submission_state_predicate` - returns `true` if passed submission state // satisfies filtering requirements. + // `sort_comparator` - the function used when comparing two + // assignments for sorting. // `callback` - invoked with filtered results. void GetFilteredStudentAssignments( base::RepeatingCallback<bool(const absl::optional<base::Time>&)> due_predicate, base::RepeatingCallback<bool(GlanceablesClassroomStudentSubmissionState)> submission_state_predicate, + SortComparator sort_comparator, GetAssignmentsCallback callback); // Selects teacher assignments that satisfy the filtering below.
diff --git a/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl_unittest.cc b/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl_unittest.cc index db0918c..82c8717 100644 --- a/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl_unittest.cc +++ b/chrome/browser/ui/ash/glanceables/glanceables_classroom_client_impl_unittest.cc
@@ -1201,17 +1201,17 @@ EXPECT_EQ(assignments.at(0)->course_title, "Active Course 1"); EXPECT_EQ(assignments.at(0)->course_work_title, - "Math assignment - submission graded"); + "Math assignment - submission turned in"); EXPECT_EQ(assignments.at(0)->link, - "https://classroom.google.com/test-link-2"); + "https://classroom.google.com/test-link-3"); EXPECT_FALSE(assignments.at(0)->due); EXPECT_FALSE(assignments.at(0)->submissions_state); EXPECT_EQ(assignments.at(1)->course_title, "Active Course 1"); EXPECT_EQ(assignments.at(1)->course_work_title, - "Math assignment - submission turned in"); + "Math assignment - submission graded"); EXPECT_EQ(assignments.at(1)->link, - "https://classroom.google.com/test-link-3"); + "https://classroom.google.com/test-link-2"); EXPECT_FALSE(assignments.at(1)->due); EXPECT_FALSE(assignments.at(1)->submissions_state); } @@ -1263,6 +1263,32 @@ "seconds": 25, "nanos": 250000000 } + }, + { + "id": "course-work-item-4", + "title": "Math assignment - approaching due date two", + "state": "PUBLISHED", + "alternateLink": "https://classroom.google.com/test-link-4", + "dueDate": {"year": 2023, "month": 6, "day": 25}, + "dueTime": { + "hours": 15, + "minutes": 9, + "seconds": 25, + "nanos": 250000000 + } + }, + { + "id": "course-work-item-5", + "title": "Math assignment - approaching due date three", + "state": "PUBLISHED", + "alternateLink": "https://classroom.google.com/test-link-5", + "dueDate": {"year": 2023, "month": 5, "day": 25}, + "dueTime": { + "hours": 15, + "minutes": 9, + "seconds": 25, + "nanos": 250000000 + } } ] })")))); @@ -1287,6 +1313,16 @@ "courseWorkId": "course-work-item-3", "state": "RETURNED", "assignedGrade": 50.0 + }, + { + "id": "student-submission-4", + "courseWorkId": "course-work-item-4", + "state": "NEW" + }, + { + "id": "student-submission-5", + "courseWorkId": "course-work-item-5", + "state": "NEW" } ] })")))); @@ -1296,7 +1332,7 @@ client()->GetStudentAssignmentsWithApproachingDueDate(future.GetCallback()); const auto assignments = future.Take(); - ASSERT_EQ(assignments.size(), 1u); + ASSERT_EQ(assignments.size(), 3u); EXPECT_EQ(assignments.at(0)->course_title, "Active Course 1"); EXPECT_EQ(assignments.at(0)->course_work_title, @@ -1306,6 +1342,24 @@ EXPECT_EQ(FormatTimeAsString(assignments.at(0)->due.value()), "2023-04-25T15:09:25.250Z"); EXPECT_FALSE(assignments.at(0)->submissions_state); + + EXPECT_EQ(assignments.at(1)->course_title, "Active Course 1"); + EXPECT_EQ(assignments.at(1)->course_work_title, + "Math assignment - approaching due date three"); + EXPECT_EQ(assignments.at(1)->link, + "https://classroom.google.com/test-link-5"); + EXPECT_EQ(FormatTimeAsString(assignments.at(1)->due.value()), + "2023-05-25T15:09:25.250Z"); + EXPECT_FALSE(assignments.at(1)->submissions_state); + + EXPECT_EQ(assignments.at(2)->course_title, "Active Course 1"); + EXPECT_EQ(assignments.at(2)->course_work_title, + "Math assignment - approaching due date two"); + EXPECT_EQ(assignments.at(2)->link, + "https://classroom.google.com/test-link-4"); + EXPECT_EQ(FormatTimeAsString(assignments.at(2)->due.value()), + "2023-06-25T15:09:25.250Z"); + EXPECT_FALSE(assignments.at(2)->submissions_state); } TEST_F(GlanceablesClassroomClientImplTest, @@ -1322,7 +1376,7 @@ "title": "Math assignment - missed due date", "state": "PUBLISHED", "alternateLink": "https://classroom.google.com/test-link-1", - "dueDate": {"year": 2023, "month": 4, "day": 5}, + "dueDate": {"year": 2023, "month": 3, "day": 20}, "dueTime": { "hours": 15, "minutes": 9, @@ -1368,6 +1422,32 @@ "seconds": 25, "nanos": 250000000 } + }, + { + "id": "course-work-item-5", + "title": "Math assignment - missed due date two", + "state": "PUBLISHED", + "alternateLink": "https://classroom.google.com/test-link-5", + "dueDate": {"year": 2023, "month": 4, "day": 5}, + "dueTime": { + "hours": 15, + "minutes": 9, + "seconds": 25, + "nanos": 250000000 + } + }, + { + "id": "course-work-item-6", + "title": "Math assignment - missed due date three", + "state": "PUBLISHED", + "alternateLink": "https://classroom.google.com/test-link-6", + "dueDate": {"year": 2023, "month": 3, "day": 25}, + "dueTime": { + "hours": 15, + "minutes": 9, + "seconds": 25, + "nanos": 250000000 + } } ] })")))); @@ -1397,6 +1477,16 @@ "id": "student-submission-4", "courseWorkId": "course-work-item-4", "state": "TURNED_IN" + }, + { + "id": "student-submission-5", + "courseWorkId": "course-work-item-5", + "state": "NEW" + }, + { + "id": "student-submission-6", + "courseWorkId": "course-work-item-6", + "state": "NEW" } ] })")))); @@ -1406,16 +1496,34 @@ client()->GetStudentAssignmentsWithMissedDueDate(future.GetCallback()); const auto assignments = future.Take(); - ASSERT_EQ(assignments.size(), 1u); + ASSERT_EQ(assignments.size(), 3u); EXPECT_EQ(assignments.at(0)->course_title, "Active Course 1"); EXPECT_EQ(assignments.at(0)->course_work_title, - "Math assignment - missed due date"); + "Math assignment - missed due date two"); EXPECT_EQ(assignments.at(0)->link, - "https://classroom.google.com/test-link-1"); + "https://classroom.google.com/test-link-5"); EXPECT_EQ(FormatTimeAsString(assignments.at(0)->due.value()), "2023-04-05T15:09:25.250Z"); EXPECT_FALSE(assignments.at(0)->submissions_state); + + EXPECT_EQ(assignments.at(1)->course_title, "Active Course 1"); + EXPECT_EQ(assignments.at(1)->course_work_title, + "Math assignment - missed due date three"); + EXPECT_EQ(assignments.at(1)->link, + "https://classroom.google.com/test-link-6"); + EXPECT_EQ(FormatTimeAsString(assignments.at(1)->due.value()), + "2023-03-25T15:09:25.250Z"); + EXPECT_FALSE(assignments.at(1)->submissions_state); + + EXPECT_EQ(assignments.at(2)->course_title, "Active Course 1"); + EXPECT_EQ(assignments.at(2)->course_work_title, + "Math assignment - missed due date"); + EXPECT_EQ(assignments.at(2)->link, + "https://classroom.google.com/test-link-1"); + EXPECT_EQ(FormatTimeAsString(assignments.at(2)->due.value()), + "2023-03-20T15:09:25.250Z"); + EXPECT_FALSE(assignments.at(2)->submissions_state); } TEST_F(GlanceablesClassroomClientImplTest,
diff --git a/chrome/browser/ui/browser.h b/chrome/browser/ui/browser.h index e72c913d..d42e9b96 100644 --- a/chrome/browser/ui/browser.h +++ b/chrome/browser/ui/browser.h
@@ -320,9 +320,8 @@ // maximizable. bool can_maximize = true; - // Aspect ratio parameters specific to TYPE_PICTURE_IN_PICTURE. - double initial_aspect_ratio = 1.0; - bool lock_aspect_ratio = false; + // Document Picture in Picture options, specific to TYPE_PICTURE_IN_PICTURE. + absl::optional<blink::mojom::PictureInPictureWindowOptions> pip_options; private: friend class Browser;
diff --git a/chrome/browser/ui/browser_dialogs.h b/chrome/browser/ui/browser_dialogs.h index 8fd5e214..86adaf2 100644 --- a/chrome/browser/ui/browser_dialogs.h +++ b/chrome/browser/ui/browser_dialogs.h
@@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_UI_BROWSER_DIALOGS_H_ #define CHROME_BROWSER_UI_BROWSER_DIALOGS_H_ +#include <map> #include <memory> #include <string> #include <utility> @@ -16,10 +17,13 @@ #include "chrome/browser/ui/bookmarks/bookmark_editor.h" #include "chrome/browser/web_applications/web_app_callback_app_identity.h" #include "chrome/browser/web_applications/web_app_id.h" +#include "chrome/browser/web_applications/web_app_install_info.h" +#include "components/webapps/browser/installable/installable_metrics.h" #include "content/public/browser/bluetooth_delegate.h" #include "content/public/browser/login_delegate.h" #include "extensions/buildflags/buildflags.h" #include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/base/interaction/element_identifier.h" #include "ui/base/models/dialog_model.h" @@ -188,6 +192,16 @@ content::WebContents* web_contents, web_app::AppIdentityDialogCallback callback); +// Shows the web app uninstallation dialog on a page whenever user has decided +// to uninstall an installed dPWA from a variety of OS surfaces and chrome. +void ShowWebAppUninstallDialog( + Profile* profile, + const web_app::AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent, + std::map<SquareSizePx, SkBitmap> icon_bitmaps, + base::OnceCallback<void(bool)> uninstall_dialog_result_callback); + #if !BUILDFLAG(IS_ANDROID) // Callback used to indicate whether a user has accepted the launch of a // web app. The |allowed| is true when the user allows the app to launch.
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index 4ca0438..3219332 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -289,6 +289,12 @@ return {nullptr, -1}; } + pip_options->initial_aspect_ratio = + pip_options->initial_aspect_ratio > 0.0 + ? pip_options->initial_aspect_ratio + : 1.0; + browser_params.pip_options = pip_options; + const BrowserWindow* const browser_window = params.browser->window(); const gfx::NativeWindow native_window = browser_window ? browser_window->GetNativeWindow() @@ -301,11 +307,6 @@ browser_params.initial_bounds = PictureInPictureWindowManager:: CalculateInitialPictureInPictureWindowBounds(*pip_options, display); - browser_params.initial_aspect_ratio = - pip_options->initial_aspect_ratio > 0.0 - ? pip_options->initial_aspect_ratio - : 1.0; - browser_params.lock_aspect_ratio = pip_options->lock_aspect_ratio; browser_params.omit_from_session_restore = true; return {Browser::Create(browser_params), -1};
diff --git a/chrome/browser/ui/views/dark_mode_manager_linux.cc b/chrome/browser/ui/views/dark_mode_manager_linux.cc index 4127327..6f054ab7 100644 --- a/chrome/browser/ui/views/dark_mode_manager_linux.cc +++ b/chrome/browser/ui/views/dark_mode_manager_linux.cc
@@ -67,7 +67,7 @@ if (auto* linux_ui_theme = ui::GetDefaultLinuxUiTheme()) { auto* native_theme = linux_ui_theme->GetNativeTheme(); native_theme_observer_.Observe(native_theme); - SetColorScheme(native_theme->ShouldUseDarkColors()); + SetColorScheme(native_theme->ShouldUseDarkColors(), true); } } @@ -80,7 +80,7 @@ void DarkModeManagerLinux::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { - SetColorScheme(observed_theme->ShouldUseDarkColors()); + SetColorScheme(observed_theme->ShouldUseDarkColors(), true); } void DarkModeManagerLinux::OnSignalConnected(const std::string& interface_name, @@ -114,7 +114,7 @@ return; } - SetColorScheme(new_color_scheme == kFreedesktopColorSchemeDark); + SetColorScheme(new_color_scheme == kFreedesktopColorSchemeDark, false); } void DarkModeManagerLinux::OnReadColorSchemeResponse(dbus::Response* response) { @@ -137,13 +137,23 @@ return; } - // Ignore future updates from the toolkit theme. - native_theme_observer_.Reset(); + // Once we read the org.freedesktop.appearance color-scheme setting successfully, + // it should always take precedence over the toolkit color scheme. + ignore_toolkit_theme_changes_ = true; - SetColorScheme(new_color_scheme == kFreedesktopColorSchemeDark); + SetColorScheme(new_color_scheme == kFreedesktopColorSchemeDark, false); } -void DarkModeManagerLinux::SetColorScheme(bool prefer_dark_theme) { +void DarkModeManagerLinux::SetColorScheme(bool prefer_dark_theme, + bool from_toolkit_theme) { + if (from_toolkit_theme && ignore_toolkit_theme_changes_) { + return; + } + if (!from_toolkit_theme) { + for (auto* linux_ui_theme : ui::GetLinuxUiThemes()) { + linux_ui_theme->SetDarkTheme(prefer_dark_theme); + } + } if (prefer_dark_theme_ == prefer_dark_theme) { return; }
diff --git a/chrome/browser/ui/views/dark_mode_manager_linux.h b/chrome/browser/ui/views/dark_mode_manager_linux.h index 34b07ff..e00d861 100644 --- a/chrome/browser/ui/views/dark_mode_manager_linux.h +++ b/chrome/browser/ui/views/dark_mode_manager_linux.h
@@ -44,12 +44,13 @@ void OnReadColorSchemeResponse(dbus::Response* response); // Sets `prefer_dark_theme_` and propagates to the web theme. - void SetColorScheme(bool prefer_dark_theme); + void SetColorScheme(bool prefer_dark_theme, bool from_toolkit_theme); scoped_refptr<dbus::Bus> bus_; raw_ptr<dbus::ObjectProxy> settings_proxy_; bool prefer_dark_theme_ = false; + bool ignore_toolkit_theme_changes_ = false; base::ScopedObservation<NativeTheme, NativeThemeObserver> native_theme_observer_{this};
diff --git a/chrome/browser/ui/views/frame/browser_view.cc b/chrome/browser/ui/views/frame/browser_view.cc index a053599a..b9bcbc6 100644 --- a/chrome/browser/ui/views/frame/browser_view.cc +++ b/chrome/browser/ui/views/frame/browser_view.cc
@@ -1195,11 +1195,20 @@ } float BrowserView::GetInitialAspectRatio() const { - return browser_->create_params().initial_aspect_ratio; + const absl::optional<blink::mojom::PictureInPictureWindowOptions> + pip_options = browser_->create_params().pip_options; + return pip_options.has_value() ? pip_options->initial_aspect_ratio : 1.0; +} + +absl::optional<blink::mojom::PictureInPictureWindowOptions> +BrowserView::GetDocumentPictureInPictureOptions() const { + return browser_->create_params().pip_options; } bool BrowserView::GetLockAspectRatio() const { - return browser_->create_params().lock_aspect_ratio; + const absl::optional<blink::mojom::PictureInPictureWindowOptions> + pip_options = browser_->create_params().pip_options; + return pip_options.has_value() ? pip_options->lock_aspect_ratio : false; } bool BrowserView::GetTopControlsSlideBehaviorEnabled() const {
diff --git a/chrome/browser/ui/views/frame/browser_view.h b/chrome/browser/ui/views/frame/browser_view.h index 850137c7..4aca3728 100644 --- a/chrome/browser/ui/views/frame/browser_view.h +++ b/chrome/browser/ui/views/frame/browser_view.h
@@ -314,6 +314,11 @@ // Valid only for PictureInPicture browsers. float GetInitialAspectRatio() const; + // Returns the document picture in picture options from |browser_|'s + // CreateParams. + absl::optional<blink::mojom::PictureInPictureWindowOptions> + GetDocumentPictureInPictureOptions() const; + // Returns the lock_aspect_ratio parameter from |browser_|'s CreateParams. // Valid only for PictureInPicture browsers. bool GetLockAspectRatio() const;
diff --git a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc index 81aea5d..c188e84 100644 --- a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc +++ b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.cc
@@ -40,6 +40,11 @@ #include "ui/views/window/frame_background.h" #include "ui/views/window/window_shape.h" +#if BUILDFLAG(IS_WIN) +#include "ui/base/win/hwnd_metrics.h" +#include "ui/views/win/hwnd_util.h" +#endif + #if !BUILDFLAG(IS_MAC) // Mac does not use Aura #include "ui/aura/window.h" @@ -414,6 +419,52 @@ return 0; } +void PictureInPictureBrowserFrameView::OnBrowserViewInitViewsComplete() { + BrowserNonClientFrameView::OnBrowserViewInitViewsComplete(); + +#if BUILDFLAG(IS_WIN) + const gfx::Insets insets = GetClientAreaInsets( + MonitorFromWindow(HWNDForView(this), MONITOR_DEFAULTTONEAREST)); +#else + const gfx::Insets insets; +#endif + + const gfx::Size initial_browser_size = + browser_view()->browser()->override_bounds().size(); + if (initial_browser_size.width() >= + GetMinimumSize().width() + insets.width() && + initial_browser_size.height() >= + GetMinimumSize().height() + insets.height()) { + return; + } + + const absl::optional<blink::mojom::PictureInPictureWindowOptions> + pip_options = browser_view()->GetDocumentPictureInPictureOptions(); + + if (!pip_options.has_value()) { + return; + } + + // Get the current display. This is needed by + // |AdjustPictureInPictureWindowBounds| to determine the work area + // dimensions and the allowed maximum window size. + const BrowserWindow* const browser_window = + browser_view()->browser()->window(); + const gfx::NativeWindow native_window = + browser_window ? browser_window->GetNativeWindow() : gfx::NativeWindow(); + const display::Screen* const screen = display::Screen::GetScreen(); + const display::Display display = + browser_window ? screen->GetDisplayNearestWindow(native_window) + : screen->GetDisplayForNewWindows(); + + const gfx::Rect window_bounds = + PictureInPictureWindowManager::AdjustPictureInPictureWindowBounds( + pip_options.value(), display, + GetMinimumSize() + gfx::Size(insets.width(), insets.height())); + + browser_view()->browser()->set_override_bounds(window_bounds); +} + gfx::Rect PictureInPictureBrowserFrameView::GetBoundsForClientView() const { auto border_thickness = FrameBorderInsets(); int top_height = GetTopAreaHeight(); @@ -941,6 +992,15 @@ } #endif +#if BUILDFLAG(IS_WIN) +gfx::Insets PictureInPictureBrowserFrameView::GetClientAreaInsets( + HMONITOR monitor) const { + const int frame_thickness = ui::GetFrameThickness(monitor); + return gfx::Insets::TLBR(0, frame_thickness, frame_thickness, + frame_thickness); +} +#endif + // Helper functions for testing. std::vector<gfx::Animation*> PictureInPictureBrowserFrameView::GetRenderActiveAnimationsForTesting() {
diff --git a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h index d61e217..1bfcfbb 100644 --- a/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h +++ b/chrome/browser/ui/views/frame/picture_in_picture_browser_frame_view.h
@@ -62,6 +62,7 @@ views::Label& window_title_label) const override; int GetTopInset(bool restored) const override; int GetThemeBackgroundXInset() const override; + void OnBrowserViewInitViewsComplete() override; void UpdateThrobber(bool running) override {} gfx::Rect GetBoundsForClientView() const override; gfx::Rect GetWindowBoundsForClientBounds( @@ -176,6 +177,10 @@ static gfx::ShadowValues GetShadowValues(); #endif +#if BUILDFLAG(IS_WIN) + gfx::Insets GetClientAreaInsets(HMONITOR monitor) const; +#endif + // Helper functions for testing. std::vector<gfx::Animation*> GetRenderActiveAnimationsForTesting(); std::vector<gfx::Animation*> GetRenderInactiveAnimationsForTesting();
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller.cc b/chrome/browser/ui/views/tabs/tab_drag_controller.cc index c3f3643..93b4ae7 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller.cc
@@ -495,6 +495,13 @@ NOTREACHED_NORETURN(); } } + + // Start listening for tabs to be closed or replaced in `source_context_`, in + // case this happens before the mouse is moved enough to fully start the drag. + // See crbug/1445776. + attached_context_tabs_closed_tracker_ = + std::make_unique<DraggedTabsClosedTracker>( + source_context_->GetTabStripModel(), this); } // static @@ -589,6 +596,13 @@ if (!CanStartDrag(point_in_screen)) return; // User hasn't dragged far enough yet. + // If any of the tabs have disappeared (e.g. closed or discarded), cancel + // the drag session. See crbug.com/1445776. + if (GetViewsMatchingDraggedContents(source_context_).empty()) { + EndDrag(END_DRAG_CANCEL); + return; + } + // On windows SaveFocus() may trigger a capture lost, which destroys us. { base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr()); @@ -1740,10 +1754,11 @@ std::vector<TabSlotView*> TabDragController::GetViewsMatchingDraggedContents( TabDragContext* context) { - TabStripModel* model = attached_context_->GetTabStripModel(); + const TabStripModel* const model = context->GetTabStripModel(); std::vector<TabSlotView*> views; for (size_t i = first_tab_index(); i < drag_data_.size(); ++i) { - int model_index = model->GetIndexOfWebContents(drag_data_[i].contents); + const int model_index = + model->GetIndexOfWebContents(drag_data_[i].contents); if (model_index == TabStripModel::kNoTab) return std::vector<TabSlotView*>(); views.push_back(context->GetTabAt(model_index));
diff --git a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc index c2e8c2f5..5426472 100644 --- a/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc +++ b/chrome/browser/ui/views/tabs/tab_drag_controller_interactive_uitest.cc
@@ -29,6 +29,7 @@ #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_list.h" @@ -1995,6 +1996,53 @@ EXPECT_FALSE(GetIsDragged(browser())); } +// Replaces a tab being dragged before the user moved enough to start a drag. +#if (BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_CHROMEOS_ASH)) +// TODO(crbug.com/1466682) Test is flaky on ChromeOS/Lacros - releasing input +// does not always end the drag. +#define MAYBE_ReplaceBeforeStartedDragging DISABLED_ReplaceBeforeStartedDragging +#else +#define MAYBE_ReplaceBeforeStartedDragging ReplaceBeforeStartedDragging +#endif +IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, + MAYBE_ReplaceBeforeStartedDragging) { + AddTabsAndResetBrowser(browser(), 1); + TabStrip* tab_strip = GetTabStripForBrowser(browser()); + + // Click on the first tab, but don't move it. + gfx::Point tab_0_center(GetCenterInScreenCoordinates(tab_strip->tab_at(0))); + ASSERT_TRUE(PressInput(tab_0_center)); + + // A drag session should exist, but the drag should not have started. + ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive()); + ASSERT_TRUE(TabDragController::IsActive()); + ASSERT_FALSE(HasDragStarted(tab_strip)); + + // Replace the tab being dragged. + std::unique_ptr<content::WebContents> new_web_contents = + content::WebContents::Create( + content::WebContents::CreateParams(browser()->profile())); + browser()->tab_strip_model()->ReplaceWebContentsAt( + 0, std::move(new_web_contents)); + + // The drag session should still exist, and still not be started. + ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive()); + ASSERT_TRUE(TabDragController::IsActive()); + ASSERT_FALSE(HasDragStarted(tab_strip)); + + // Move the mouse enough to start the drag. It doesn't matter whether this + // is enough to create a window or not. + ASSERT_TRUE(DragInputTo(gfx::Point(tab_0_center.x() + 40, tab_0_center.y()))); + + // Drag should now have started. + ASSERT_TRUE(HasDragStarted(tab_strip)); + + // The replaced webcontents should not have an id character. + EXPECT_EQ("? 1", IDString(browser()->tab_strip_model())); + + EXPECT_TRUE(ReleaseInput()); +} + IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, DragDoesntStartFromClick) { AddTabsAndResetBrowser(browser(), 1);
diff --git a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc index cd2117a..3e3bf375 100644 --- a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc +++ b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.cc
@@ -9,9 +9,9 @@ #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.h" +#include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" #include "chrome/browser/web_applications/web_app_callback_app_identity.h" #include "chrome/browser/web_applications/web_app_provider.h" -#include "chrome/browser/web_applications/web_app_ui_manager.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" #include "components/vector_icons/vector_icons.h" @@ -170,17 +170,23 @@ } bool WebAppIdentityUpdateConfirmationView::Cancel() { - uninstall_dialog_ = std::make_unique<WebAppUninstallDialogViews>( - profile_, GetWidget()->GetNativeWindow()); - uninstall_dialog_->ConfirmUninstall( - app_id_, webapps::WebappUninstallSource::kAppMenu, base::DoNothing(), + auto* provider = web_app::WebAppProvider::GetForWebApps(profile_); + DCHECK(provider); + web_app::WebAppUiManagerImpl::Get(provider)->PresentUserUninstallDialog( + app_id_, webapps::WebappUninstallSource::kAppMenu, + GetWidget()->GetNativeWindow(), base::DoNothing(), base::BindOnce( &WebAppIdentityUpdateConfirmationView::OnWebAppUninstallScheduled, weak_factory_.GetWeakPtr())); return false; } -void WebAppIdentityUpdateConfirmationView::OnWebAppUninstallScheduled() { +void WebAppIdentityUpdateConfirmationView::OnWebAppUninstallScheduled( + bool uninstall_scheduled) { + if (!uninstall_scheduled) { + return; + } + DCHECK(callback_); if (GetWidget()) { std::move(callback_).Run(web_app::AppIdentityUpdate::kUninstall);
diff --git a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.h b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.h index e2d498c2..e30c8a078 100644 --- a/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.h +++ b/chrome/browser/ui/views/web_apps/web_app_identity_update_confirmation_view.h
@@ -20,7 +20,6 @@ class Profile; class SkBitmap; -class WebAppUninstallDialogViews; // WebAppIdentityUpdateConfirmationView provides views for showing which parts // of the app's identity changed so the user can make a determination whether to @@ -55,7 +54,7 @@ bool Cancel() override; void OnDialogAccepted(); - void OnWebAppUninstallScheduled(); + void OnWebAppUninstallScheduled(bool uninstall_scheduled); const raw_ptr<Profile> profile_; @@ -70,9 +69,6 @@ // A callback to relay the results of the app identity update dialog. web_app::AppIdentityDialogCallback callback_; - // The app uninstall dialog, shown to confirm the uninstallation. - std::unique_ptr<WebAppUninstallDialogViews> uninstall_dialog_; - base::WeakPtrFactory<WebAppIdentityUpdateConfirmationView> weak_factory_{ this}; };
diff --git a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_browsertest.cc b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_browsertest.cc index b2eeb80..bcccbd3 100644 --- a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_browsertest.cc +++ b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_browsertest.cc
@@ -4,10 +4,10 @@ #include <memory> -#include "base/barrier_closure.h" #include "base/functional/callback_helpers.h" #include "base/run_loop.h" #include "base/test/bind.h" +#include "base/test/test_future.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/profiles/profile.h" @@ -19,6 +19,7 @@ #include "chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.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/ui/web_applications/web_app_ui_manager_impl.h" #include "chrome/browser/web_applications/mojom/user_display_mode.mojom.h" #include "chrome/browser/web_applications/os_integration/os_integration_manager.h" #include "chrome/browser/web_applications/test/web_app_icon_test_utils.h" @@ -35,6 +36,7 @@ #include "extensions/browser/extension_dialog_auto_confirm.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/native_widget_types.h" +#include "ui/views/widget/any_widget_observer.h" using web_app::AppId; @@ -55,72 +57,61 @@ class WebAppUninstallDialogViewBrowserTest : public web_app::WebAppControllerBrowserTest { + public: + web_app::WebAppProvider* provider() { + return web_app::WebAppProvider::GetForTest(browser()->profile()); + } + private: web_app::OsIntegrationManager::ScopedSuppressForTesting os_hooks_suppress_; }; -// Test that WebAppUninstallDialog cancels the uninstall if the Window -// which is passed to WebAppUninstallDialog::Create() is destroyed before -// WebAppUninstallDialogDelegateView is created. IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, - TrackParentWindowDestruction) { + TrackParentWindowDestructionBeforeViewCreation) { AppId app_id = InstallTestWebApp(browser()->profile()); - std::unique_ptr<web_app::WebAppUninstallDialog> dialog( - web_app::WebAppUninstallDialog::Create( - browser()->profile(), browser()->window()->GetNativeWindow())); + web_app::WebAppUiManagerImpl* ui_manager_impl = + web_app::WebAppUiManagerImpl::Get(provider()); + base::test::TestFuture<webapps::UninstallResultCode> test_future; browser()->window()->Close(); - base::RunLoop().RunUntilIdle(); - - base::RunLoop run_loop; - dialog->ConfirmUninstall( + ui_manager_impl->PresentUserUninstallDialog( app_id, webapps::WebappUninstallSource::kAppMenu, - base::BindLambdaForTesting([&](webapps::UninstallResultCode code) { - EXPECT_EQ(code, webapps::UninstallResultCode::kCancelled); - run_loop.Quit(); - }), - base::DoNothing()); - run_loop.Run(); + browser()->window()->GetNativeWindow(), test_future.GetCallback()); + + EXPECT_TRUE(test_future.Wait()); + EXPECT_EQ(test_future.Get<webapps::UninstallResultCode>(), + webapps::UninstallResultCode::kCancelled); } -#if BUILDFLAG(IS_MAC) -// https://crbug.com/1224161 -#define MAYBE_TrackParentWindowDestructionAfterViewCreation \ - DISABLED_TrackParentWindowDestructionAfterViewCreation -#else -#define MAYBE_TrackParentWindowDestructionAfterViewCreation \ - TrackParentWindowDestructionAfterViewCreation -#endif -// Test that WebAppUninstallDialog cancels the uninstall if the Window -// which is passed to WebAppUninstallDialog::Create() is destroyed after -// WebAppUninstallDialogDelegateView is created. IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, - MAYBE_TrackParentWindowDestructionAfterViewCreation) { + TrackParentWindowDestructionAfterViewCreation) { AppId app_id = InstallTestWebApp(browser()->profile()); - std::unique_ptr<web_app::WebAppUninstallDialog> dialog( - web_app::WebAppUninstallDialog::Create( - browser()->profile(), browser()->window()->GetNativeWindow())); - base::RunLoop().RunUntilIdle(); - - base::RunLoop run_loop; - dialog->ConfirmUninstall( + web_app::WebAppUiManagerImpl* ui_manager_impl = + web_app::WebAppUiManagerImpl::Get(provider()); + base::test::TestFuture<webapps::UninstallResultCode> test_future; + ui_manager_impl->PresentUserUninstallDialog( app_id, webapps::WebappUninstallSource::kAppMenu, - base::BindLambdaForTesting([&](webapps::UninstallResultCode code) { - EXPECT_EQ(code, webapps::UninstallResultCode::kCancelled); - run_loop.Quit(); - }), - base::DoNothing()); + browser()->window()->GetNativeWindow(), test_future.GetCallback()); + + views::NamedWidgetShownWaiter uninstall_dialog_waiter( + views::test::AnyWidgetTestPasskey{}, "WebAppUninstallDialogDelegateView"); + auto* uninstall_widget = uninstall_dialog_waiter.WaitIfNeededAndGet(); + EXPECT_NE(uninstall_widget, nullptr); // Kill parent window. browser()->window()->Close(); - run_loop.Run(); + EXPECT_TRUE(test_future.Wait()); + EXPECT_EQ(test_future.Get<webapps::UninstallResultCode>(), + webapps::UninstallResultCode::kCancelled); } // Uninstalling with no browser window open can cause the view to be destroyed -// before the views object. Test that this does not cause a UAF. -// See https://crbug.com/1150798. +// before the views object. Test that this does not cause a UAF. See +// https://crbug.com/1150798. +// Also tests that we don't crash when uninstalling a web app from a web app +// window in Ash. See https://crbug.com/825554. IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, UninstallWithNoBrowserWindow) { extensions::ScopedTestDialogAutoConfirm auto_confirm( @@ -130,61 +121,16 @@ web_app::LaunchWebAppBrowser(browser()->profile(), app_id); chrome::CloseWindow(browser()); - std::unique_ptr<web_app::WebAppUninstallDialog> dialog( - web_app::WebAppUninstallDialog::Create( - browser()->profile(), app_browser->window()->GetNativeWindow())); - base::RunLoop().RunUntilIdle(); - - base::RunLoop run_loop; - dialog->ConfirmUninstall( + web_app::WebAppUiManagerImpl* ui_manager_impl = + web_app::WebAppUiManagerImpl::Get(provider()); + base::test::TestFuture<webapps::UninstallResultCode> test_future; + ui_manager_impl->PresentUserUninstallDialog( app_id, webapps::WebappUninstallSource::kAppMenu, - base::BindLambdaForTesting([&](webapps::UninstallResultCode code) { - EXPECT_EQ(code, webapps::UninstallResultCode::kSuccess); - run_loop.Quit(); - }), - base::DoNothing()); - run_loop.Run(); -} + app_browser->window()->GetNativeWindow(), test_future.GetCallback()); -#if BUILDFLAG(IS_MAC) -// https://crbug.com/1224161 -#define MAYBE_UninstallOnCancelShutdownBrowser \ - DISABLED_UninstallOnCancelShutdownBrowser -#else -#define MAYBE_UninstallOnCancelShutdownBrowser UninstallOnCancelShutdownBrowser -#endif -IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, - MAYBE_UninstallOnCancelShutdownBrowser) { - extensions::ScopedTestDialogAutoConfirm auto_confirm( - extensions::ScopedTestDialogAutoConfirm::CANCEL); - AppId app_id = InstallTestWebApp(browser()->profile()); - - std::unique_ptr<web_app::WebAppUninstallDialog> dialog( - web_app::WebAppUninstallDialog::Create(browser()->profile(), - gfx::NativeWindow())); - - base::RunLoop().RunUntilIdle(); - - base::RunLoop run_loop; - // ScopedKeepAlive is used by `UninstallWebAppWithDialogFromStartupSwitch`. - // ScopedKeepAlive's destruction triggers browser shutdown when there is no - // open window. This verifies the destruction doesn't race with the dialog - // shutdown itself. - std::unique_ptr<ScopedKeepAlive> scoped_keep_alive = - std::make_unique<ScopedKeepAlive>(KeepAliveOrigin::WEB_APP_UNINSTALL, - KeepAliveRestartOption::DISABLED); - - chrome::CloseWindow(browser()); - - dialog->ConfirmUninstall( - app_id, webapps::WebappUninstallSource::kAppMenu, - base::BindLambdaForTesting([&](webapps::UninstallResultCode code) { - EXPECT_EQ(code, webapps::UninstallResultCode::kCancelled); - scoped_keep_alive.reset(); - run_loop.Quit(); - }), - base::DoNothing()); - run_loop.Run(); + EXPECT_TRUE(test_future.Wait()); + EXPECT_EQ(test_future.Get<webapps::UninstallResultCode>(), + webapps::UninstallResultCode::kSuccess); } IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, @@ -193,22 +139,16 @@ extensions::ScopedTestDialogAutoConfirm::CANCEL); AppId app_id = InstallTestWebApp(browser()->profile()); - WebAppUninstallDialogViews dialog(browser()->profile(), - browser()->window()->GetNativeWindow()); - - base::RunLoop run_loop; - auto callback = - base::BarrierClosure(/*num_closures=*/2, run_loop.QuitClosure()); - - dialog.SetDialogShownCallbackForTesting(callback); - dialog.ConfirmUninstall( + web_app::WebAppUiManagerImpl* ui_manager_impl = + web_app::WebAppUiManagerImpl::Get(provider()); + base::test::TestFuture<webapps::UninstallResultCode> test_future; + ui_manager_impl->PresentUserUninstallDialog( app_id, webapps::WebappUninstallSource::kAppMenu, - base::BindLambdaForTesting([&](webapps::UninstallResultCode code) { - EXPECT_EQ(code, webapps::UninstallResultCode::kCancelled); - callback.Run(); - }), - base::DoNothing()); - run_loop.Run(); + browser()->window()->GetNativeWindow(), test_future.GetCallback()); + + EXPECT_TRUE(test_future.Wait()); + EXPECT_EQ(test_future.Get<webapps::UninstallResultCode>(), + webapps::UninstallResultCode::kCancelled); } IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, @@ -217,81 +157,14 @@ extensions::ScopedTestDialogAutoConfirm::ACCEPT_AND_OPTION); AppId app_id = InstallTestWebApp(browser()->profile()); - WebAppUninstallDialogViews dialog(browser()->profile(), - browser()->window()->GetNativeWindow()); - - base::RunLoop run_loop; - auto callback = - base::BarrierClosure(/*num_closures=*/2, run_loop.QuitClosure()); - - dialog.SetDialogShownCallbackForTesting(callback); - dialog.ConfirmUninstall( + web_app::WebAppUiManagerImpl* ui_manager_impl = + web_app::WebAppUiManagerImpl::Get(provider()); + base::test::TestFuture<webapps::UninstallResultCode> test_future; + ui_manager_impl->PresentUserUninstallDialog( app_id, webapps::WebappUninstallSource::kAppMenu, - base::BindLambdaForTesting([&](webapps::UninstallResultCode code) { - EXPECT_EQ(code, webapps::UninstallResultCode::kSuccess); - callback.Run(); - }), - base::DoNothing()); + browser()->window()->GetNativeWindow(), test_future.GetCallback()); - run_loop.Run(); -} - -#if BUILDFLAG(IS_CHROMEOS_ASH) -// Test that we don't crash when uninstalling a web app from a web app window in -// Ash. Context: crbug.com/825554 -// TODO(crbug.com/1332923): The test is flaky. -IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewBrowserTest, - DISABLED_WebAppWindowAshCrash) { - AppId app_id = InstallTestWebApp(browser()->profile()); - Browser* app_browser = - web_app::LaunchWebAppBrowser(browser()->profile(), app_id); - - std::unique_ptr<web_app::WebAppUninstallDialog> dialog; - { - base::RunLoop run_loop; - dialog = web_app::WebAppUninstallDialog::Create( - app_browser->profile(), app_browser->window()->GetNativeWindow()); - run_loop.RunUntilIdle(); - } - - { - base::RunLoop run_loop; - dialog->ConfirmUninstall(app_id, webapps::WebappUninstallSource::kAppMenu, - base::DoNothing(), base::DoNothing()); - run_loop.RunUntilIdle(); - } -} -#endif // BUILDFLAG(IS_CHROMEOS_ASH) - -class WebAppUninstallDialogViewInteractiveBrowserTest - : public DialogBrowserTest { - public: - void ShowUi(const std::string& name) override { - AppId app_id = InstallTestWebApp(browser()->profile()); - - dialog_ = web_app::WebAppUninstallDialog::Create( - browser()->profile(), browser()->window()->GetNativeWindow()); - - base::RunLoop run_loop; - dialog_->SetDialogShownCallbackForTesting(run_loop.QuitClosure()); - - dialog_->ConfirmUninstall(app_id, webapps::WebappUninstallSource::kAppMenu, - base::DoNothing(), base::DoNothing()); - - run_loop.Run(); - } - - private: - void TearDownOnMainThread() override { - // Dialog holds references to the profile, so it needs to tear down before - // profiles are deleted. - dialog_.reset(); - } - - std::unique_ptr<web_app::WebAppUninstallDialog> dialog_; -}; - -IN_PROC_BROWSER_TEST_F(WebAppUninstallDialogViewInteractiveBrowserTest, - InvokeUi_ManualUninstall) { - ShowAndVerifyUi(); + EXPECT_TRUE(test_future.Wait()); + EXPECT_EQ(test_future.Get<webapps::UninstallResultCode>(), + webapps::UninstallResultCode::kSuccess); }
diff --git a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc index c89a8f5..1f610da 100644 --- a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc +++ b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.cc
@@ -6,12 +6,12 @@ #include "base/functional/bind.h" #include "base/functional/callback_helpers.h" +#include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" -#include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" -#include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/web_apps/web_app_info_image_source.h" #include "chrome/browser/web_applications/web_app_command_scheduler.h" @@ -20,7 +20,6 @@ #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "components/constrained_window/constrained_window_views.h" -#include "components/strings/grit/components_strings.h" #include "components/url_formatter/elide_url.h" #include "components/webapps/browser/installable/installable_metrics.h" #include "components/webapps/browser/uninstall_result_code.h" @@ -31,11 +30,11 @@ #include "ui/base/models/image_model.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/image/image_skia.h" +#include "ui/gfx/native_widget_types.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/image_view.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" -#include "ui/views/native_window_tracker.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/window/dialog_delegate.h" @@ -59,15 +58,17 @@ WebAppUninstallDialogDelegateView::WebAppUninstallDialogDelegateView( Profile* profile, - WebAppUninstallDialogViews* dialog_view, web_app::AppId app_id, webapps::WebappUninstallSource uninstall_source, - std::map<SquareSizePx, SkBitmap> icon_bitmaps) - : dialog_(dialog_view), app_id_(std::move(app_id)), profile_(profile) { - auto* provider = web_app::WebAppProvider::GetForWebApps(profile_); - DCHECK(provider); + std::map<SquareSizePx, SkBitmap> icon_bitmaps, + UninstallChoiceCallback uninstall_choice_callback) + : app_id_(std::move(app_id)), + profile_(profile), + uninstall_choice_callback_(std::move(uninstall_choice_callback)) { + provider_ = web_app::WebAppProvider::GetForWebApps(profile_)->AsWeakPtr(); + DCHECK(provider_); - app_start_url_ = provider->registrar_unsafe().GetAppStartUrl(app_id_); + app_start_url_ = provider_->registrar_unsafe().GetAppStartUrl(app_id_); DCHECK(!app_start_url_.is_empty()); DCHECK(app_start_url_.is_valid()); @@ -86,7 +87,7 @@ SetTitle(l10n_util::GetStringFUTF16( IDS_EXTENSION_PROMPT_UNINSTALL_TITLE, base::UTF8ToUTF16( - provider->registrar_unsafe().GetAppShortName(app_id_)))); + provider_->registrar_unsafe().GetAppShortName(app_id_)))); SetButtonLabel( ui::DIALOG_BUTTON_OK, @@ -113,7 +114,7 @@ // For IWAs checkbox will not be displayed, removal of // storage is automatically enforced. - if (!provider->registrar_unsafe().IsIsolated(app_id_)) { + if (!provider_->registrar_unsafe().IsIsolated(app_id_)) { std::u16string checkbox_label = l10n_util::GetStringFUTF16( IDS_EXTENSION_UNINSTALL_PROMPT_REMOVE_DATA_CHECKBOX, url_formatter::FormatUrlForSecurityDisplay( @@ -125,20 +126,19 @@ } uninstall_source_ = uninstall_source; + install_manager_observation_.Observe(&provider_->install_manager()); } WebAppUninstallDialogDelegateView::~WebAppUninstallDialogDelegateView() { - if (dialog_) - dialog_->UninstallCancelled(); + install_manager_observation_.Reset(); + if (uninstall_choice_callback_) { + std::move(uninstall_choice_callback_).Run(/*uninstalled=*/false); + } } void WebAppUninstallDialogDelegateView::OnDialogAccepted() { - if (!dialog_) - return; - - auto* provider = web_app::WebAppProvider::GetForWebApps(profile_); - DCHECK(provider); - bool is_isolated_web_app = provider->registrar_unsafe().IsIsolated(app_id_); + DCHECK(provider_); + bool is_isolated_web_app = provider_->registrar_unsafe().IsIsolated(app_id_); HistogramCloseAction action = is_isolated_web_app || (checkbox_ && checkbox_->GetChecked()) @@ -147,7 +147,6 @@ UMA_HISTOGRAM_ENUMERATION("Webapp.UninstallDialogAction", action); Uninstall(); - if (is_isolated_web_app || (checkbox_ && checkbox_->GetChecked())) { ClearWebAppSiteData(); } @@ -156,33 +155,36 @@ void WebAppUninstallDialogDelegateView::OnDialogCanceled() { UMA_HISTOGRAM_ENUMERATION("Webapp.UninstallDialogAction", HistogramCloseAction::kCancelled); - // `dialog_->UninstallCancelled()` is handled in the destructor. + // The user_dialog_choice_callback_ is run in the destructor. +} + +void WebAppUninstallDialogDelegateView::OnWebAppInstallManagerDestroyed() { + install_manager_observation_.Reset(); + CancelDialog(); } ui::ImageModel WebAppUninstallDialogDelegateView::GetWindowIcon() { return ui::ImageModel::FromImageSkia(image_); } -void WebAppUninstallDialogDelegateView::Uninstall() { - auto* provider = web_app::WebAppProvider::GetForWebApps(profile_); - DCHECK(provider); +void WebAppUninstallDialogDelegateView::OnWebAppWillBeUninstalled( + const web_app::AppId& app_id) { + // Handle the case when web app was uninstalled externally and we have to + // cancel current dialog. + if (app_id == app_id_) { + CancelDialog(); + } +} - if (!provider->registrar_unsafe().CanUserUninstallWebApp(app_id_)) { - std::exchange(dialog_, nullptr)->UninstallCancelled(); +void WebAppUninstallDialogDelegateView::Uninstall() { + DCHECK(provider_); + if (!provider_->registrar_unsafe().CanUserUninstallWebApp(app_id_)) { + std::move(uninstall_choice_callback_).Run(/*uninstalled=*/false); return; } - // Forward callback from the WebAppUninstallDialogViews because - // WebAppUninstallDialogDelegateView lifetime is controlled by Widget and it - // is terminiated as soon as dialog is closed regardless of web app - // uninstallation. - provider->scheduler().UninstallWebApp(app_id_, uninstall_source_, - dialog_->UninstallStarted()); - std::move(dialog_->TakeUninstallScheduledCallback()).Run(); - // We successfully call Web App Uninstall routine, then - // WebAppUninstallDialogDelegateView can be terminated, but can't call the - // callback of the dialog caller. - dialog_ = nullptr; + std::move(uninstall_choice_callback_).Run(/*uninstalled=*/true); + install_manager_observation_.Reset(); } void WebAppUninstallDialogDelegateView::ClearWebAppSiteData() { @@ -221,115 +223,20 @@ BEGIN_METADATA(WebAppUninstallDialogDelegateView, views::DialogDelegateView) END_METADATA -WebAppUninstallDialogViews::WebAppUninstallDialogViews(Profile* profile, - gfx::NativeWindow parent) - : parent_(parent), profile_(profile) { - if (parent) - parent_window_tracker_ = views::NativeWindowTracker::Create(parent); -} +namespace chrome { -WebAppUninstallDialogViews::~WebAppUninstallDialogViews() { - if (view_) - view_->CancelDialog(); -} - -void WebAppUninstallDialogViews::ConfirmUninstall( +void ShowWebAppUninstallDialog( + Profile* profile, const web_app::AppId& app_id, webapps::WebappUninstallSource uninstall_source, - WebAppUninstallDialogViews::OnWebAppUninstallDialogClosed closed_callback, - base::OnceClosure uninstall_scheduled_callback) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - app_id_ = app_id; - closed_callback_ = std::move(closed_callback); - uninstall_scheduled_callback_ = std::move(uninstall_scheduled_callback); - - if (parent_ && parent_window_tracker_->WasNativeWindowDestroyed()) { - UninstallCancelled(); - return; - } - - auto* provider = web_app::WebAppProvider::GetForWebApps(profile_); - DCHECK(provider); - - install_manager_observation_.Observe(&provider->install_manager()); - - provider->icon_manager().ReadIcons( - app_id, IconPurpose::ANY, - provider->registrar_unsafe().GetAppDownloadedIconSizesAny(app_id), - base::BindOnce(&WebAppUninstallDialogViews::OnIconsRead, - weak_ptr_factory_.GetWeakPtr(), uninstall_source)); + gfx::NativeWindow parent, + std::map<SquareSizePx, SkBitmap> icon_bitmaps, + base::OnceCallback<void(bool)> uninstall_dialog_result_callback) { + auto* view = new WebAppUninstallDialogDelegateView( + profile, app_id, uninstall_source, std::move(icon_bitmaps), + std::move(uninstall_dialog_result_callback)); + constrained_window::CreateBrowserModalDialogViews(view, parent)->Show(); + view->ProcessAutoConfirmValue(); } -void WebAppUninstallDialogViews::SetDialogShownCallbackForTesting( - base::OnceClosure callback) { - dialog_shown_callback_for_testing_ = std::move(callback); -} - -void WebAppUninstallDialogViews::OnIconsRead( - webapps::WebappUninstallSource uninstall_source, - std::map<SquareSizePx, SkBitmap> icon_bitmaps) { - DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); - - if (parent_ && parent_window_tracker_->WasNativeWindowDestroyed()) { - UninstallCancelled(); - return; - } - - view_ = new WebAppUninstallDialogDelegateView( - profile_, this, app_id_, uninstall_source, std::move(icon_bitmaps)); - - constrained_window::CreateBrowserModalDialogViews(view_, parent_)->Show(); - - if (dialog_shown_callback_for_testing_) - std::move(dialog_shown_callback_for_testing_).Run(); - - // This should be a tail call because it destroys |this|: - view_->ProcessAutoConfirmValue(); -} - -void WebAppUninstallDialogViews::OnWebAppWillBeUninstalled( - const web_app::AppId& app_id) { - // Handle the case when web app was uninstalled externally and we have to - // cancel current dialog. - if (app_id == app_id_ && view_) - view_->CancelDialog(); -} - -void WebAppUninstallDialogViews::OnWebAppInstallManagerDestroyed() { - install_manager_observation_.Reset(); - if (view_) - view_->CancelDialog(); -} - -base::OnceCallback<void(webapps::UninstallResultCode code)> -WebAppUninstallDialogViews::UninstallStarted() { - DCHECK(closed_callback_); - // Next OnWebAppWillBeUninstalled should be ignored. Unsubscribe: - install_manager_observation_.Reset(); - // The view can now be destroyed without us knowing, so clear it to prevent - // UAF in the destructor. - view_ = nullptr; - return base::BindOnce( - [](OnWebAppUninstallDialogClosed callback, - webapps::UninstallResultCode code) { std::move(callback).Run(code); }, - std::move(closed_callback_)); -} - -base::OnceClosure WebAppUninstallDialogViews::TakeUninstallScheduledCallback() { - DCHECK(uninstall_scheduled_callback_); - return std::move(uninstall_scheduled_callback_); -} - -void WebAppUninstallDialogViews::UninstallCancelled() { - DCHECK(closed_callback_); - view_ = nullptr; - std::move(closed_callback_).Run(webapps::UninstallResultCode::kCancelled); -} - -// static -std::unique_ptr<web_app::WebAppUninstallDialog> -web_app::WebAppUninstallDialog::Create(Profile* profile, - gfx::NativeWindow parent) { - return std::make_unique<WebAppUninstallDialogViews>(profile, parent); -} +} // namespace chrome
diff --git a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.h b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.h index 4848ed6..a3837e0 100644 --- a/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.h +++ b/chrome/browser/ui/views/web_apps/web_app_uninstall_dialog_view.h
@@ -13,11 +13,10 @@ #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" -#include "base/threading/thread_checker.h" -#include "chrome/browser/ui/web_applications/web_app_uninstall_dialog.h" #include "chrome/browser/web_applications/web_app_id.h" #include "chrome/browser/web_applications/web_app_install_manager.h" #include "chrome/browser/web_applications/web_app_install_manager_observer.h" +#include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/metadata/metadata_header_macros.h" @@ -27,7 +26,6 @@ #include "url/gurl.h" class Profile; -class WebAppUninstallDialogViews; namespace webapps { enum class UninstallResultCode; @@ -36,20 +34,23 @@ namespace views { class Checkbox; -class NativeWindowTracker; } +using UninstallChoiceCallback = base::OnceCallback<void(bool)>; + // The dialog's view, owned by the views framework. -class WebAppUninstallDialogDelegateView : public views::DialogDelegateView { +class WebAppUninstallDialogDelegateView + : public views::DialogDelegateView, + public web_app::WebAppInstallManagerObserver { public: METADATA_HEADER(WebAppUninstallDialogDelegateView); // Constructor for view component of dialog. WebAppUninstallDialogDelegateView( Profile* profile, - WebAppUninstallDialogViews* dialog_view, web_app::AppId app_id, webapps::WebappUninstallSource uninstall_source, - std::map<SquareSizePx, SkBitmap> icon_bitmaps); + std::map<SquareSizePx, SkBitmap> icon_bitmaps, + UninstallChoiceCallback uninstall_choice_callback); WebAppUninstallDialogDelegateView(const WebAppUninstallDialogDelegateView&) = delete; WebAppUninstallDialogDelegateView& operator=( @@ -69,7 +70,9 @@ void OnDialogAccepted(); void OnDialogCanceled(); - raw_ptr<WebAppUninstallDialogViews, AcrossTasksDanglingUntriaged> dialog_; + // web_app::WebAppInstallManagerObserver: + void OnWebAppWillBeUninstalled(const web_app::AppId& app_id) override; + void OnWebAppInstallManagerDestroyed() override; raw_ptr<views::Checkbox> checkbox_ = nullptr; gfx::ImageSkia image_; @@ -79,81 +82,15 @@ // The dialog needs start_url copy even if app gets uninstalled. GURL app_start_url_; - const raw_ptr<Profile, AcrossTasksDanglingUntriaged> profile_; - - webapps::WebappUninstallSource uninstall_source_; -}; - -// The implementation of the uninstall dialog for web apps. -class WebAppUninstallDialogViews - : public web_app::WebAppUninstallDialog, - public web_app::WebAppInstallManagerObserver { - public: - // Implement this callback to handle checking for the dialog's header message. - using OnWillShowCallback = - base::RepeatingCallback<void(WebAppUninstallDialogViews*)>; - - WebAppUninstallDialogViews(Profile* profile, gfx::NativeWindow parent); - WebAppUninstallDialogViews(const WebAppUninstallDialogViews&) = delete; - WebAppUninstallDialogViews& operator=(const WebAppUninstallDialogViews&) = - delete; - ~WebAppUninstallDialogViews() override; - - // web_app::WebAppUninstallDialog: - void ConfirmUninstall( - const web_app::AppId& app_id, - webapps::WebappUninstallSource uninstall_source, - OnWebAppUninstallDialogClosed closed_callback, - base::OnceClosure uninstall_scheduled_callback) override; - void SetDialogShownCallbackForTesting(base::OnceClosure callback) override; - - // The following methods are used by WebAppUninstallDialogDelegateView to - // report the uninstallation request status. After calling one of these - // methods, it is invalid to call any of them again. - - // Called when the view is triggering an uninstallation with the - // WebAppProvider system. Returns a callback to be passed to this system. - base::OnceCallback<void(webapps::UninstallResultCode code)> - UninstallStarted(); - base::OnceClosure TakeUninstallScheduledCallback(); - - // Called to signify that the uninstall has been cancelled. - void UninstallCancelled(); - - private: - // web_app::WebAppInstallManagerObserver: - void OnWebAppWillBeUninstalled(const web_app::AppId& app_id) override; - void OnWebAppInstallManagerDestroyed() override; - - void OnIconsRead(webapps::WebappUninstallSource uninstall_source, - std::map<SquareSizePx, SkBitmap> icon_bitmaps); - - // The dialog's parent window. - const gfx::NativeWindow parent_; - - // The callback we will call Accepted/Canceled on after confirmation dialog. - OnWebAppUninstallDialogClosed closed_callback_; - base::OnceClosure uninstall_scheduled_callback_; - - base::OnceClosure dialog_shown_callback_for_testing_; - - // Tracks whether |parent_| got destroyed. - std::unique_ptr<views::NativeWindowTracker> parent_window_tracker_; + base::WeakPtr<web_app::WebAppProvider> provider_; + UninstallChoiceCallback uninstall_choice_callback_; base::ScopedObservation<web_app::WebAppInstallManager, web_app::WebAppInstallManagerObserver> install_manager_observation_{this}; - raw_ptr<WebAppUninstallDialogDelegateView> view_ = nullptr; - - // The web app we are showing the dialog for. - web_app::AppId app_id_; - const raw_ptr<Profile, AcrossTasksDanglingUntriaged> profile_; - - THREAD_CHECKER(thread_checker_); - - base::WeakPtrFactory<WebAppUninstallDialogViews> weak_ptr_factory_{this}; + webapps::WebappUninstallSource uninstall_source_; }; #endif // CHROME_BROWSER_UI_VIEWS_WEB_APPS_WEB_APP_UNINSTALL_DIALOG_VIEW_H_
diff --git a/chrome/browser/ui/web_applications/web_app_browser_controller.cc b/chrome/browser/ui/web_applications/web_app_browser_controller.cc index 6b96911f..c009dad 100644 --- a/chrome/browser/ui/web_applications/web_app_browser_controller.cc +++ b/chrome/browser/ui/web_applications/web_app_browser_controller.cc
@@ -22,7 +22,6 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_menu_model_factory.h" -#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h" #include "chrome/browser/ui/web_applications/web_app_launch_utils.h" #include "chrome/browser/ui/web_applications/web_app_tabbed_utils.h" #include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" @@ -601,9 +600,9 @@ void WebAppBrowserController::Uninstall( webapps::WebappUninstallSource webapp_uninstall_source) { WebAppUiManagerImpl::Get(&*provider_) - ->dialog_manager() - .UninstallWebApp(app_id(), webapps::WebappUninstallSource::kAppMenu, - browser()->window(), base::DoNothing()); + ->PresentUserUninstallDialog(app_id(), + webapps::WebappUninstallSource::kAppMenu, + browser()->window(), base::DoNothing()); } bool WebAppBrowserController::IsInstalled() const {
diff --git a/chrome/browser/ui/web_applications/web_app_dialog_manager.cc b/chrome/browser/ui/web_applications/web_app_dialog_manager.cc deleted file mode 100644 index e6284b6c..0000000 --- a/chrome/browser/ui/web_applications/web_app_dialog_manager.cc +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2019 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/web_applications/web_app_dialog_manager.h" - -#include "base/functional/bind.h" -#include "base/functional/callback.h" -#include "base/functional/callback_helpers.h" -#include "base/metrics/histogram_functions.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/web_applications/web_app_uninstall_dialog.h" -#include "chrome/browser/web_applications/web_app_install_finalizer.h" -#include "chrome/browser/web_applications/web_app_provider.h" -#include "components/webapps/browser/uninstall_result_code.h" - -namespace web_app { - -WebAppDialogManager::WebAppDialogManager(Profile* profile) - : profile_(profile) {} - -WebAppDialogManager::~WebAppDialogManager() = default; - -void WebAppDialogManager::UninstallWebApp( - const AppId& app_id, - webapps::WebappUninstallSource uninstall_source, - BrowserWindow* parent_window, - Callback callback) { - UninstallWebApp(app_id, uninstall_source, - parent_window ? parent_window->GetNativeWindow() : nullptr, - std::move(callback)); -} - -void WebAppDialogManager::UninstallWebApp( - const AppId& app_id, - webapps::WebappUninstallSource uninstall_source, - gfx::NativeWindow parent_window, - Callback callback) { - std::unique_ptr<WebAppUninstallDialog> uninstall_dialog = - WebAppUninstallDialog::Create(profile_, - parent_window ? parent_window : nullptr); - - uninstall_dialog->ConfirmUninstall( - app_id, uninstall_source, - base::BindOnce(&WebAppDialogManager::OnWebAppUninstallDialogClosed, - base::Unretained(this), uninstall_dialog.get(), - std::move(callback)), - base::DoNothing()); - - dialogs_.insert(std::move(uninstall_dialog)); -} - -void WebAppDialogManager::OnWebAppUninstallDialogClosed( - WebAppUninstallDialog* dialog, - Callback callback, - webapps::UninstallResultCode code) { - DCHECK(dialogs_.contains(dialog)); - dialogs_.erase(dialog); - - std::move(callback).Run(code); -} - -} // namespace web_app
diff --git a/chrome/browser/ui/web_applications/web_app_dialog_manager.h b/chrome/browser/ui/web_applications/web_app_dialog_manager.h deleted file mode 100644 index 8e205fb..0000000 --- a/chrome/browser/ui/web_applications/web_app_dialog_manager.h +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2019 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_WEB_APPLICATIONS_WEB_APP_DIALOG_MANAGER_H_ -#define CHROME_BROWSER_UI_WEB_APPLICATIONS_WEB_APP_DIALOG_MANAGER_H_ - -#include <memory> - -#include "base/containers/flat_set.h" -#include "base/containers/unique_ptr_adapters.h" -#include "base/functional/callback_forward.h" -#include "base/memory/raw_ptr.h" -#include "chrome/browser/web_applications/web_app_id.h" -#include "ui/gfx/native_widget_types.h" - -class BrowserWindow; -class Profile; - -namespace webapps { -enum class UninstallResultCode; -enum class WebappUninstallSource; -} - -namespace web_app { - -class WebAppUninstallDialog; - -class WebAppDialogManager { - public: - explicit WebAppDialogManager(Profile* profile); - WebAppDialogManager(const WebAppDialogManager&) = delete; - WebAppDialogManager& operator=(const WebAppDialogManager&) = delete; - ~WebAppDialogManager(); - - using Callback = base::OnceCallback<void(webapps::UninstallResultCode code)>; - - // The uninstall dialog will be modal to |parent_window|, or a non-modal if - // |parent_window| is nullptr. - void UninstallWebApp(const AppId& app_id, - webapps::WebappUninstallSource uninstall_source, - BrowserWindow* parent_window, - Callback callback); - - void UninstallWebApp(const AppId& app_id, - webapps::WebappUninstallSource uninstall_source, - gfx::NativeWindow parent_window, - Callback callback); - - private: - void OnWebAppUninstallDialogClosed(WebAppUninstallDialog* dialog, - Callback callback, - webapps::UninstallResultCode code); - - // All owned dialogs, running in parallel. - base::flat_set<std::unique_ptr<WebAppUninstallDialog>, - base::UniquePtrComparator> - dialogs_; - - const raw_ptr<Profile> profile_; -}; - -} // namespace web_app - -#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_WEB_APP_DIALOG_MANAGER_H_
diff --git a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc index cbf03cb..fd90de7 100644 --- a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc +++ b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" +#include <map> #include <memory> #include <utility> @@ -23,10 +24,10 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" +#include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/web_applications/app_browser_controller.h" #include "chrome/browser/ui/web_applications/commands/launch_web_app_command.h" -#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h" #include "chrome/browser/ui/web_applications/web_app_dialog_utils.h" #include "chrome/browser/ui/web_applications/web_app_launch_utils.h" #include "chrome/browser/ui/web_applications/web_app_metrics.h" @@ -51,7 +52,14 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/page_transition_types.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/views/native_window_tracker.h" + +#if !BUILDFLAG(IS_MAC) +#include "ui/aura/window.h" +#endif // !BUILDFLAG(IS_MAC) #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/public/cpp/shelf_model.h" @@ -75,7 +83,6 @@ #include "chrome/browser/web_applications/web_app_install_finalizer.h" #include "components/keep_alive_registry/keep_alive_types.h" #include "components/keep_alive_registry/scoped_keep_alive.h" -#include "ui/gfx/native_widget_types.h" #endif // BUILDFLAG(IS_WIN) namespace web_app { @@ -94,7 +101,7 @@ std::make_unique<ScopedKeepAlive>(KeepAliveOrigin::WEB_APP_UNINSTALL, KeepAliveRestartOption::DISABLED); if (provider->registrar_unsafe().CanUserUninstallWebApp(app_id)) { - WebAppUiManagerImpl::Get(provider)->dialog_manager().UninstallWebApp( + WebAppUiManagerImpl::Get(provider)->PresentUserUninstallDialog( app_id, webapps::WebappUninstallSource::kOsSettings, gfx::NativeWindow(), base::BindOnce([](std::unique_ptr<ScopedKeepAlive> scoped_keep_alive, @@ -141,8 +148,7 @@ } WebAppUiManagerImpl::WebAppUiManagerImpl(Profile* profile) - : dialog_manager_(std::make_unique<WebAppDialogManager>(profile)), - profile_(profile) {} + : profile_(profile) {} WebAppUiManagerImpl::~WebAppUiManagerImpl() = default; @@ -169,10 +175,6 @@ started_ = false; } -WebAppDialogManager& WebAppUiManagerImpl::dialog_manager() { - return *dialog_manager_; -} - WebAppUiManagerImpl* WebAppUiManagerImpl::AsImpl() { return this; } @@ -353,6 +355,56 @@ webapps::WebappInstallSource::OMNIBOX_INSTALL_ICON, base::DoNothing()); } +void WebAppUiManagerImpl::PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + BrowserWindow* parent_window, + UninstallCompleteCallback callback) { + PresentUserUninstallDialog( + app_id, uninstall_source, + parent_window ? parent_window->GetNativeWindow() : nullptr, + std::move(callback), base::DoNothing()); +} + +void WebAppUiManagerImpl::PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow native_window, + UninstallCompleteCallback callback) { + PresentUserUninstallDialog(app_id, uninstall_source, native_window, + std::move(callback), base::DoNothing()); +} + +void WebAppUiManagerImpl::PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback uninstall_complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback) { + std::unique_ptr<views::NativeWindowTracker> parent_window_tracker; + if (parent_window) { + parent_window_tracker = views::NativeWindowTracker::Create(parent_window); + } + + if (parent_window && parent_window_tracker->WasNativeWindowDestroyed()) { + OnUninstallCancelled(std::move(uninstall_complete_callback), + std::move(uninstall_scheduled_callback)); + return; + } + + WebAppProvider* provider = WebAppProvider::GetForWebApps(profile_); + CHECK(provider); + + provider->icon_manager().ReadIcons( + app_id, IconPurpose::ANY, + provider->registrar_unsafe().GetAppDownloadedIconSizesAny(app_id), + base::BindOnce(&WebAppUiManagerImpl::OnIconsReadForUninstall, + weak_ptr_factory_.GetWeakPtr(), app_id, uninstall_source, + parent_window, std::move(parent_window_tracker), + std::move(uninstall_complete_callback), + std::move(uninstall_scheduled_callback))); +} + void WebAppUiManagerImpl::OnBrowserAdded(Browser* browser) { DCHECK(started_); if (!IsBrowserForInstalledApp(browser)) @@ -409,4 +461,51 @@ return browser->app_controller()->app_id(); } +void WebAppUiManagerImpl::OnIconsReadForUninstall( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + std::unique_ptr<views::NativeWindowTracker> parent_window_tracker, + UninstallCompleteCallback complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback, + std::map<SquareSizePx, SkBitmap> icon_bitmaps) { + if (parent_window && parent_window_tracker->WasNativeWindowDestroyed()) { + OnUninstallCancelled(std::move(complete_callback), + std::move(uninstall_scheduled_callback)); + return; + } + + chrome::ShowWebAppUninstallDialog( + profile_, app_id, uninstall_source, parent_window, + std::move(icon_bitmaps), + base::BindOnce(&WebAppUiManagerImpl::ScheduleUninstallIfUserRequested, + weak_ptr_factory_.GetWeakPtr(), app_id, uninstall_source, + std::move(complete_callback), + std::move(uninstall_scheduled_callback))); +} + +void WebAppUiManagerImpl::ScheduleUninstallIfUserRequested( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + UninstallCompleteCallback complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback, + bool user_wants_uninstall) { + if (user_wants_uninstall) { + WebAppProvider* provider = WebAppProvider::GetForWebApps(profile_); + CHECK(provider); + provider->scheduler().UninstallWebApp(app_id, uninstall_source, + std::move(complete_callback)); + } else { + std::move(complete_callback).Run(webapps::UninstallResultCode::kCancelled); + } + std::move(uninstall_scheduled_callback).Run(user_wants_uninstall); +} + +void WebAppUiManagerImpl::OnUninstallCancelled( + UninstallCompleteCallback complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback) { + std::move(uninstall_scheduled_callback).Run(false); + std::move(complete_callback).Run(webapps::UninstallResultCode::kCancelled); +} + } // namespace web_app
diff --git a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h index 4def9ea..33b9eb6 100644 --- a/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h +++ b/chrome/browser/ui/web_applications/web_app_ui_manager_impl.h
@@ -9,15 +9,25 @@ #include <memory> #include <vector> +#include "base/containers/unique_ptr_adapters.h" #include "base/functional/callback_forward.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "build/build_config.h" #include "chrome/browser/ui/browser_list_observer.h" +#include "chrome/browser/web_applications/web_app_install_info.h" #include "chrome/browser/web_applications/web_app_ui_manager.h" +#include "components/webapps/browser/installable/installable_metrics.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "ui/gfx/native_widget_types.h" -class Profile; class Browser; +class BrowserWindow; +class Profile; + +namespace views { +class NativeWindowTracker; +} // namespace views namespace web_app { @@ -83,6 +93,25 @@ content::WebContents* CreateNewTab() override; void TriggerInstallDialog(content::WebContents* web_contents) override; + void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + BrowserWindow* parent_window, + UninstallCompleteCallback callback) override; + + void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback) override; + + void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback, + UninstallScheduledCallback scheduled_callback) override; + // BrowserListObserver: void OnBrowserAdded(Browser* browser) override; void OnBrowserRemoved(Browser* browser) override; @@ -103,16 +132,32 @@ void OnExtensionSystemReady(); - std::unique_ptr<WebAppDialogManager> dialog_manager_; + void OnIconsReadForUninstall( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + std::unique_ptr<views::NativeWindowTracker> parent_window_tracker, + UninstallCompleteCallback complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback, + std::map<SquareSizePx, SkBitmap> icon_bitmaps); + + void ScheduleUninstallIfUserRequested( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + UninstallCompleteCallback complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback, + bool user_wants_uninstall); + + void OnUninstallCancelled( + UninstallCompleteCallback complete_callback, + UninstallScheduledCallback uninstall_scheduled_callback); const raw_ptr<Profile> profile_; - std::map<AppId, std::vector<base::OnceClosure>> windows_closed_requests_map_; std::map<AppId, size_t> num_windows_for_apps_map_; bool started_ = false; base::WeakPtrFactory<WebAppUiManagerImpl> weak_ptr_factory_{this}; - }; } // namespace web_app
diff --git a/chrome/browser/ui/web_applications/web_app_uninstall_dialog.h b/chrome/browser/ui/web_applications/web_app_uninstall_dialog.h deleted file mode 100644 index 1b03a86..0000000 --- a/chrome/browser/ui/web_applications/web_app_uninstall_dialog.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2019 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_WEB_APPLICATIONS_WEB_APP_UNINSTALL_DIALOG_H_ -#define CHROME_BROWSER_UI_WEB_APPLICATIONS_WEB_APP_UNINSTALL_DIALOG_H_ - -#include <memory> - -#include "base/functional/callback_forward.h" -#include "chrome/browser/web_applications/web_app_id.h" -#include "ui/gfx/native_widget_types.h" - -class Profile; - -namespace webapps { -enum class UninstallResultCode; -enum class WebappUninstallSource; -} - -namespace web_app { - -// The interface of the uninstall dialog for web apps. -class WebAppUninstallDialog { - public: - WebAppUninstallDialog(const WebAppUninstallDialog&) = delete; - WebAppUninstallDialog& operator=(const WebAppUninstallDialog&) = delete; - - virtual ~WebAppUninstallDialog() = default; - - // Create an implementation of WebAppUninstallDialog. The - // dialog will be modal to |parent|, or a non-modal dialog if |parent| is - // nullptr. - static std::unique_ptr<WebAppUninstallDialog> Create( - Profile* profile, - gfx::NativeWindow parent); - - // Called when the dialog closes. - using OnWebAppUninstallDialogClosed = - base::OnceCallback<void(webapps::UninstallResultCode code)>; - - // Starts the process of showing a confirmation UI. - virtual void ConfirmUninstall( - const AppId& app_id, - webapps::WebappUninstallSource uninstall_source, - OnWebAppUninstallDialogClosed closed_callback, - base::OnceClosure uninstall_scheduled_callback) = 0; - - virtual void SetDialogShownCallbackForTesting(base::OnceClosure callback) = 0; - - protected: - WebAppUninstallDialog() = default; -}; - -} // namespace web_app - -#endif // CHROME_BROWSER_UI_WEB_APPLICATIONS_WEB_APP_UNINSTALL_DIALOG_H_
diff --git a/chrome/browser/ui/webui/app_home/app_home_page_handler.cc b/chrome/browser/ui/webui/app_home/app_home_page_handler.cc index 175e2ce5..0b08bc973 100644 --- a/chrome/browser/ui/webui/app_home/app_home_page_handler.cc +++ b/chrome/browser/ui/webui/app_home/app_home_page_handler.cc
@@ -31,7 +31,6 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/extensions/extension_enable_flow.h" #include "chrome/browser/ui/tab_dialogs.h" -#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h" #include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" #include "chrome/browser/ui/webui/app_home/app_home.mojom-shared.h" #include "chrome/browser/ui/webui/extensions/extension_icon_source.h" @@ -526,10 +525,9 @@ Browser* browser = GetCurrentBrowser(); CHECK(browser); web_app::WebAppUiManagerImpl::Get(web_app_provider_) - ->dialog_manager() - .UninstallWebApp(web_app_id, webapps::WebappUninstallSource::kAppsPage, - browser->window(), - std::move(uninstall_success_callback)); + ->PresentUserUninstallDialog( + web_app_id, webapps::WebappUninstallSource::kAppsPage, + browser->window(), std::move(uninstall_success_callback)); return; }
diff --git a/chrome/browser/ui/webui/ntp/app_launcher_handler.cc b/chrome/browser/ui/webui/ntp/app_launcher_handler.cc index 6c9c3d4a..e829631 100644 --- a/chrome/browser/ui/webui/ntp/app_launcher_handler.cc +++ b/chrome/browser/ui/webui/ntp/app_launcher_handler.cc
@@ -47,7 +47,6 @@ #include "chrome/browser/ui/extensions/extension_enable_flow.h" #include "chrome/browser/ui/tab_dialogs.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h" #include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" #include "chrome/browser/ui/webui/extensions/extension_basic_info.h" #include "chrome/browser/ui/webui/extensions/extension_icon_source.h" @@ -1027,11 +1026,10 @@ Browser* browser = chrome::FindBrowserWithWebContents(web_ui()->GetWebContents()); web_app::WebAppUiManagerImpl::Get(web_app_provider_) - ->dialog_manager() - .UninstallWebApp(extension_id_prompting_, - webapps::WebappUninstallSource::kAppsPage, - browser->window(), - std::move(uninstall_success_callback)); + ->PresentUserUninstallDialog( + extension_id_prompting_, + webapps::WebappUninstallSource::kAppsPage, browser->window(), + std::move(uninstall_success_callback)); } return; }
diff --git a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc index 28ce520..7bee381 100644 --- a/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc +++ b/chrome/browser/ui/webui/settings/settings_localized_strings_provider.cc
@@ -1078,8 +1078,12 @@ IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC}, {"passwordsLeakDetectionLabel", IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL}, + {"passwordsLeakDetectionLabelUpdated", + IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_LABEL_UPDATED}, {"passwordsLeakDetectionGeneralDescription", IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE}, + {"passwordsLeakDetectionGeneralDescriptionUpdated", + IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE_UPDATED}, {"passwordsLeakDetectionSignedOutEnabledDescription", IDS_SETTINGS_PASSWORDS_LEAK_DETECTION_SIGNED_OUT_ENABLED_DESC}, {"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING}, @@ -1799,6 +1803,8 @@ IDS_SETTINGS_SAFEBROWSING_ENHANCED_BULLET_FIVE}, {"safeBrowsingStandard", IDS_SETTINGS_SAFEBROWSING_STANDARD}, {"safeBrowsingStandardDesc", IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC}, + {"safeBrowsingStandardDescUpdated", + IDS_SETTINGS_SAFEBROWSING_STANDARD_DESC_UPDATED}, {"safeBrowsingStandardExpandA11yLabel", IDS_SETTINGS_SAFEBROWSING_STANDARD_EXPAND_ACCESSIBILITY_LABEL}, {"safeBrowsingStandardBulOne",
diff --git a/chrome/browser/ui/webui/settings/settings_ui.cc b/chrome/browser/ui/webui/settings/settings_ui.cc index e86838df..d00c95b 100644 --- a/chrome/browser/ui/webui/settings/settings_ui.cc +++ b/chrome/browser/ui/webui/settings/settings_ui.cc
@@ -331,6 +331,10 @@ "enableEsbCollapse", safe_browsing::kEsbIphBubbleAndCollapseSettingsEnableCollapse.Get()); + html_source->AddBoolean("enableFriendlierSafeBrowsingSettings", + base::FeatureList::IsEnabled( + safe_browsing::kFriendlierSafeBrowsingSettings)); + html_source->AddBoolean("downloadBubbleEnabled", download::IsDownloadBubbleEnabled(profile));
diff --git a/chrome/browser/web_applications/BUILD.gn b/chrome/browser/web_applications/BUILD.gn index 0b4d971..97af49b 100644 --- a/chrome/browser/web_applications/BUILD.gn +++ b/chrome/browser/web_applications/BUILD.gn
@@ -882,6 +882,7 @@ "//chrome/app:command_ids", "//chrome/browser/apps/app_service", "//chrome/browser/apps/app_service:test_support", + "//chrome/browser/browsing_data:constants", "//chrome/browser/devtools:test_support", "//chrome/browser/profiles:profile", "//chrome/test:test_support",
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 4ca5bed3..14647710 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
@@ -57,7 +57,6 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/web_applications/web_app_dialog_manager.h" #include "chrome/browser/ui/web_applications/web_app_ui_manager_impl.h" #include "chrome/browser/web_applications/locks/app_lock.h" #include "chrome/browser/web_applications/mojom/user_display_mode.mojom.h" @@ -412,13 +411,11 @@ } if (provider->registrar_unsafe().CanUserUninstallWebApp(app_id)) { - WebAppDialogManager& web_app_dialog_manager = - web_app_ui_manager->dialog_manager(); webapps::WebappUninstallSource webapp_uninstall_source = WebAppPublisherHelper::ConvertUninstallSourceToWebAppUninstallSource( uninstall_source); - web_app_dialog_manager.UninstallWebApp(app_id, webapp_uninstall_source, - parent_window, base::DoNothing()); + web_app_ui_manager->PresentUserUninstallDialog( + app_id, webapp_uninstall_source, parent_window, base::DoNothing()); } }
diff --git a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_browsing_data_browsertest.cc b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_browsing_data_browsertest.cc index f205c3f..3854ebe 100644 --- a/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_browsing_data_browsertest.cc +++ b/chrome/browser/web_applications/isolated_web_apps/isolated_web_app_browsing_data_browsertest.cc
@@ -6,9 +6,12 @@ #include <string> #include "base/check_deref.h" +#include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "base/test/test_future.h" #include "base/time/time.h" +#include "chrome/browser/browsing_data/chrome_browsing_data_remover_constants.h" +#include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/web_applications/test/isolated_web_app_test_utils.h" @@ -16,6 +19,8 @@ #include "chrome/browser/web_applications/web_app_command_scheduler.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "components/services/storage/public/mojom/local_storage_control.mojom.h" +#include "content/public/browser/browsing_data_filter_builder.h" +#include "content/public/browser/browsing_data_remover.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" @@ -70,7 +75,7 @@ : 0; } - void AddUsageIfMissing(const content::ToRenderFrameHost& target) { + void AddLocalStorageIfMissing(const content::ToRenderFrameHost& target) { EXPECT_TRUE( ExecJs(target, "localStorage.setItem('test', '!'.repeat(1000))")); @@ -116,7 +121,7 @@ EXPECT_THAT(GetIwaUsage(url_info), Eq(0)); // Add some usage to the IWA and make sure it's counted. - AddUsageIfMissing(web_contents); + AddLocalStorageIfMissing(web_contents); EXPECT_THAT(GetIwaUsage(url_info), IsApproximately(1000)); // Create a persisted <controlledframe>, add some usage to it. @@ -124,7 +129,7 @@ dev_server()->GetURL("/empty_title.html"), "persist:partition_name")); ASSERT_EQ(1UL, web_contents->GetInnerWebContents().size()); - AddUsageIfMissing(web_contents->GetInnerWebContents()[0]); + AddLocalStorageIfMissing(web_contents->GetInnerWebContents()[0]); EXPECT_THAT(GetIwaUsage(url_info), IsApproximately(2000)); // Create another persisted <controlledframe> with a different partition name. @@ -132,23 +137,49 @@ dev_server()->GetURL("/empty_title.html"), "persist:partition_name_2")); ASSERT_EQ(2UL, web_contents->GetInnerWebContents().size()); - AddUsageIfMissing(web_contents->GetInnerWebContents()[0]); - AddUsageIfMissing(web_contents->GetInnerWebContents()[1]); + AddLocalStorageIfMissing(web_contents->GetInnerWebContents()[0]); + AddLocalStorageIfMissing(web_contents->GetInnerWebContents()[1]); EXPECT_THAT(GetIwaUsage(url_info), IsApproximately(3000)); // Create an in-memory <controlledframe> that won't count towards IWA usage. ASSERT_TRUE(CreateControlledFrame( web_contents, dev_server()->GetURL("/empty_title.html"), "unpersisted")); ASSERT_EQ(3UL, web_contents->GetInnerWebContents().size()); - AddUsageIfMissing(web_contents->GetInnerWebContents()[0]); - AddUsageIfMissing(web_contents->GetInnerWebContents()[1]); - AddUsageIfMissing(web_contents->GetInnerWebContents()[2]); + AddLocalStorageIfMissing(web_contents->GetInnerWebContents()[0]); + AddLocalStorageIfMissing(web_contents->GetInnerWebContents()[1]); + AddLocalStorageIfMissing(web_contents->GetInnerWebContents()[2]); EXPECT_THAT(GetIwaUsage(url_info), IsApproximately(3000)); } class IsolatedWebAppBrowsingDataClearingTest : public IsolatedWebAppBrowsingDataTest { protected: + void ClearData(const IsolatedWebAppUrlInfo& url_info) { + base::RunLoop run_loop; + auto* browsing_data_remover = profile()->GetBrowsingDataRemover(); + browsing_data_remover->SetWouldCompleteCallbackForTesting( + base::BindLambdaForTesting([&](base::OnceClosure callback) { + if (browsing_data_remover->GetPendingTaskCountForTesting() == 1) { + run_loop.Quit(); + } + std::move(callback).Run(); + })); + + auto filter = content::BrowsingDataFilterBuilder::Create( + content::BrowsingDataFilterBuilder::Mode::kDelete); + filter->AddOrigin(url_info.origin()); + + browsing_data_remover->RemoveWithFilter( + /*delete_begin=*/base::Time(), /*delete_end=*/base::Time::Max(), + chrome_browsing_data_remover::DATA_TYPE_SITE_DATA & + ~content::BrowsingDataRemover::DATA_TYPE_COOKIES, + chrome_browsing_data_remover::ALL_ORIGIN_TYPES, std::move(filter)); + run_loop.Run(); + + browsing_data_remover->SetWouldCompleteCallbackForTesting( + base::DoNothing()); + } + int64_t GetCacheSize(const IsolatedWebAppUrlInfo& url_info) { base::test::TestFuture<bool, int64_t> future; @@ -208,6 +239,40 @@ } }; +IN_PROC_BROWSER_TEST_F(IsolatedWebAppBrowsingDataClearingTest, + LocalStorageCleared) { + // Install 2 IWAs and add data to each. + IsolatedWebAppUrlInfo url_info1 = InstallIsolatedWebApp(); + Browser* browser1 = LaunchWebAppBrowserAndWait(url_info1.app_id()); + content::WebContents* web_contents1 = + browser1->tab_strip_model()->GetActiveWebContents(); + + EXPECT_THAT(GetIwaUsage(url_info1), Eq(0)); + AddLocalStorageIfMissing(web_contents1); + EXPECT_THAT(GetIwaUsage(url_info1), IsApproximately(1000)); + + IsolatedWebAppUrlInfo url_info2 = InstallIsolatedWebApp(); + Browser* browser2 = LaunchWebAppBrowserAndWait(url_info2.app_id()); + content::WebContents* web_contents2 = + browser2->tab_strip_model()->GetActiveWebContents(); + + EXPECT_THAT(GetIwaUsage(url_info2), Eq(0)); + AddLocalStorageIfMissing(web_contents2); + EXPECT_THAT(GetIwaUsage(url_info2), IsApproximately(1000)); + + ASSERT_TRUE(CreateControlledFrame(web_contents2, + dev_server()->GetURL("/empty_title.html"), + "persist:partition_name")); + ASSERT_EQ(1UL, web_contents2->GetInnerWebContents().size()); + AddLocalStorageIfMissing(web_contents2->GetInnerWebContents()[0]); + EXPECT_THAT(GetIwaUsage(url_info2), IsApproximately(2000)); + + ClearData(url_info2); + + EXPECT_THAT(GetIwaUsage(url_info1), IsApproximately(1000)); + EXPECT_THAT(GetIwaUsage(url_info2), Eq(0)); +} + IN_PROC_BROWSER_TEST_F(IsolatedWebAppBrowsingDataClearingTest, CacheCleared) { IsolatedWebAppUrlInfo url_info = InstallIsolatedWebApp();
diff --git a/chrome/browser/web_applications/test/fake_web_app_ui_manager.cc b/chrome/browser/web_applications/test/fake_web_app_ui_manager.cc index 78b0fe3..7167872 100644 --- a/chrome/browser/web_applications/test/fake_web_app_ui_manager.cc +++ b/chrome/browser/web_applications/test/fake_web_app_ui_manager.cc
@@ -13,6 +13,7 @@ #include "base/test/bind.h" #include "chrome/browser/web_applications/web_app_callback_app_identity.h" #include "components/services/app_service/public/cpp/app_launch_util.h" +#include "components/webapps/browser/uninstall_result_code.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace web_app { @@ -160,4 +161,30 @@ void FakeWebAppUiManager::TriggerInstallDialog( content::WebContents* web_contents) {} +void FakeWebAppUiManager::PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + BrowserWindow* parent_window, + UninstallCompleteCallback callback) { + std::move(callback).Run(webapps::UninstallResultCode::kSuccess); +} + +void FakeWebAppUiManager::PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback) { + std::move(callback).Run(webapps::UninstallResultCode::kSuccess); +} + +void FakeWebAppUiManager::PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback, + UninstallScheduledCallback scheduled_callback) { + std::move(scheduled_callback).Run(/*uninstall_scheduled=*/true); + std::move(callback).Run(webapps::UninstallResultCode::kSuccess); +} + } // namespace web_app
diff --git a/chrome/browser/web_applications/test/fake_web_app_ui_manager.h b/chrome/browser/web_applications/test/fake_web_app_ui_manager.h index 38da105..cd2e7bb3 100644 --- a/chrome/browser/web_applications/test/fake_web_app_ui_manager.h +++ b/chrome/browser/web_applications/test/fake_web_app_ui_manager.h
@@ -80,6 +80,25 @@ content::WebContents* CreateNewTab() override; void TriggerInstallDialog(content::WebContents* web_contents) override; + void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + BrowserWindow* parent_window, + UninstallCompleteCallback callback) override; + + void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback) override; + + void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback, + UninstallScheduledCallback scheduled_callback) override; + private: base::flat_map<AppId, size_t> app_id_to_num_windows_map_; // Closures waiting to be called when all windows for a given `AppId` are
diff --git a/chrome/browser/web_applications/web_app_provider.cc b/chrome/browser/web_applications/web_app_provider.cc index d87f7a7..78dc42d 100644 --- a/chrome/browser/web_applications/web_app_provider.cc +++ b/chrome/browser/web_applications/web_app_provider.cc
@@ -298,6 +298,10 @@ is_registry_ready_ = false; } +base::WeakPtr<WebAppProvider> WebAppProvider::AsWeakPtr() { + return weak_ptr_factory_.GetWeakPtr(); +} + void WebAppProvider::StartImpl() { StartSyncBridge(); MaybeScheduleGarbageCollection(); @@ -393,8 +397,8 @@ } void WebAppProvider::StartSyncBridge() { - sync_bridge_->Init(base::BindOnce(&WebAppProvider::OnSyncBridgeReady, - weak_ptr_factory_.GetWeakPtr())); + sync_bridge_->Init( + base::BindOnce(&WebAppProvider::OnSyncBridgeReady, AsWeakPtr())); } void WebAppProvider::OnSyncBridgeReady() { @@ -413,7 +417,7 @@ return; provider->on_external_managers_synchronized_.Signal(); }, - weak_ptr_factory_.GetWeakPtr())); + AsWeakPtr())); registrar_->Start(); install_finalizer_->Start();
diff --git a/chrome/browser/web_applications/web_app_provider.h b/chrome/browser/web_applications/web_app_provider.h index 173d809f..0a80931b 100644 --- a/chrome/browser/web_applications/web_app_provider.h +++ b/chrome/browser/web_applications/web_app_provider.h
@@ -210,6 +210,8 @@ // Returns whether the app registry is ready. bool is_registry_ready() const { return is_registry_ready_; } + base::WeakPtr<WebAppProvider> AsWeakPtr(); + protected: virtual void StartImpl();
diff --git a/chrome/browser/web_applications/web_app_ui_manager.h b/chrome/browser/web_applications/web_app_ui_manager.h index b3c5db3..2d07ebe3 100644 --- a/chrome/browser/web_applications/web_app_ui_manager.h +++ b/chrome/browser/web_applications/web_app_ui_manager.h
@@ -20,8 +20,11 @@ #include "chrome/browser/web_applications/web_app_callback_app_identity.h" #include "chrome/browser/web_applications/web_app_id.h" #include "components/services/app_service/public/cpp/app_launch_util.h" +#include "components/webapps/browser/uninstall_result_code.h" +#include "ui/gfx/native_widget_types.h" class Browser; +class BrowserWindow; class Profile; namespace content { @@ -35,6 +38,10 @@ // WebAppUiManagerImpl can be used only in UI code. class WebAppUiManagerImpl; +using UninstallScheduledCallback = base::OnceCallback<void(bool)>; +using UninstallCompleteCallback = + base::OnceCallback<void(webapps::UninstallResultCode code)>; + // Overrides the app identity update dialog's behavior for testing, allowing the // test to auto-accept or auto-skip the dialog. base::AutoReset<absl::optional<AppIdentityUpdate>> @@ -172,6 +179,32 @@ // is already installed. virtual void TriggerInstallDialog(content::WebContents* web_contents) = 0; + // The uninstall dialog will be modal to |parent_window|, or a non-modal if + // |parent_window| is nullptr. Use this API if a Browser window needs to be + // passed in along with an UninstallCompleteCallback. + virtual void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + BrowserWindow* parent_window, + UninstallCompleteCallback callback) = 0; + + // Use this API if a gfx::NativeWindow needs to be passed in along with an + // UninstallCompleteCallback. + virtual void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback) = 0; + + // Use this API if a gfx::NativeWindow needs to be passed in along with a + // UninstallCompleteCallback and an UninstallScheduledCallback. + virtual void PresentUserUninstallDialog( + const AppId& app_id, + webapps::WebappUninstallSource uninstall_source, + gfx::NativeWindow parent_window, + UninstallCompleteCallback callback, + UninstallScheduledCallback scheduled_callback) = 0; + private: base::ObserverList<WebAppUiManagerObserver, /*check_empty=*/true> observers_;
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 582bfdb..5c52d0b8 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1689940694-cd64b022a0f21f2ef329f50e3e467cfae614e67f.profdata +chrome-linux-main-1689962149-88b950365f24cbf49c1f3c86e5a00e56f2e8279f.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index b4a087f..1ee82927 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1689962149-237226421e8247dd12d1183d18efd180e9a7d6a3.profdata +chrome-mac-arm-main-1689969576-186f51381bd7b7c223b3a560dd266f0c2cab3802.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index 3315a3a2..7275bf35 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1689951535-c2e5ac8a626f7dc2264faa284f85e23767b56ea1.profdata +chrome-win32-main-1689962149-5cfb71f523e91d5ae2d1279b84cc4e059f7e7922.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 03bab6a..3d92dba7 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1689951535-752323b76a913bce49e9a579e7fe68087d2f34e9.profdata +chrome-win64-main-1689962149-b4be7d0dc314468b799f485c4d6e50a77c6b5f0b.profdata
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index 01e30d3..0d5c9da6 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -249,6 +249,8 @@ "base/chromeos/crosier/chromeos_test_launcher.h", "base/chromeos/crosier/chromeos_test_suite.cc", "base/chromeos/crosier/chromeos_test_suite.h", + "base/chromeos/crosier/crosier_mixin.cc", + "base/chromeos/crosier/crosier_mixin.h", ] }
diff --git a/chrome/test/base/chromeos/crosier/chromeos_test_suite.cc b/chrome/test/base/chromeos/crosier/chromeos_test_suite.cc index e31a8b61..bbad391 100644 --- a/chrome/test/base/chromeos/crosier/chromeos_test_suite.cc +++ b/chrome/test/base/chromeos/crosier/chromeos_test_suite.cc
@@ -8,6 +8,8 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/test/ui_controls_ash.h" +#include "base/command_line.h" +#include "content/public/common/content_switches.h" #elif BUILDFLAG(IS_CHROMEOS_LACROS) #include "base/check.h" #include "base/files/file_util.h" @@ -23,6 +25,8 @@ content::ContentTestSuiteBase::Initialize(); #if BUILDFLAG(IS_CHROMEOS_ASH) ash::test::EnableUIControlsAsh(); + base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); + cmdline->AppendSwitch(switches::kDisableMojoBroker); #elif BUILDFLAG(IS_CHROMEOS_LACROS) // The lacros binary receives certain paths from ash very early in startup. // Simulate that behavior here. See chrome_paths_lacros.cc for details. The
diff --git a/chrome/test/base/chromeos/crosier/crosier_mixin.cc b/chrome/test/base/chromeos/crosier/crosier_mixin.cc new file mode 100644 index 0000000..41518362 --- /dev/null +++ b/chrome/test/base/chromeos/crosier/crosier_mixin.cc
@@ -0,0 +1,30 @@ +// 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/test/base/chromeos/crosier/crosier_mixin.h" + +#include "build/chromeos_buildflags.h" + +#if BUILDFLAG(IS_CHROMEOS_ASH) +#include "base/command_line.h" +#include "base/path_service.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" +#endif + +bool CrosierMixin::SetUpUserDataDirectory() { +#if BUILDFLAG(IS_CHROMEOS_ASH) + // Always have --user-data-dir present in commandline arguments. + // Without the argument, there are some permission issues. Here the logic + // is: a temporary dir is created in base framework and set in PathService. + // Then we retrieve the dir and append it to the commandline arguments. + base::FilePath user_data_dir; + CHECK(base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)); + base::CommandLine* cmdline = base::CommandLine::ForCurrentProcess(); + if (!cmdline->HasSwitch(switches::kUserDataDir)) { + cmdline->AppendSwitchPath(switches::kUserDataDir, user_data_dir); + } +#endif + return InProcessBrowserTestMixin::SetUpUserDataDirectory(); +}
diff --git a/chrome/test/base/chromeos/crosier/crosier_mixin.h b/chrome/test/base/chromeos/crosier/crosier_mixin.h new file mode 100644 index 0000000..75b768f --- /dev/null +++ b/chrome/test/base/chromeos/crosier/crosier_mixin.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 CHROME_TEST_BASE_CHROMEOS_CROSIER_CROSIER_MIXIN_H_ +#define CHROME_TEST_BASE_CHROMEOS_CROSIER_CROSIER_MIXIN_H_ + +#include "chrome/test/base/mixin_based_in_process_browser_test.h" + +// Any crosier tests should use CrosierMixin test helper which +// provides the framework setup. +class CrosierMixin : public InProcessBrowserTestMixin { + public: + explicit CrosierMixin(InProcessBrowserTestMixinHost* host) + : InProcessBrowserTestMixin(host) {} + CrosierMixin(const CrosierMixin&) = delete; + CrosierMixin& operator=(const CrosierMixin&) = delete; + ~CrosierMixin() override = default; + + // InProcessBrowserTestMixin: + bool SetUpUserDataDirectory() override; +}; + +#endif // CHROME_TEST_BASE_CHROMEOS_CROSIER_CROSIER_MIXIN_H_
diff --git a/chrome/test/base/chromeos/crosier/demo_integration_test.cc b/chrome/test/base/chromeos/crosier/demo_integration_test.cc index b1187fb..9b22b0c 100644 --- a/chrome/test/base/chromeos/crosier/demo_integration_test.cc +++ b/chrome/test/base/chromeos/crosier/demo_integration_test.cc
@@ -6,6 +6,7 @@ #include "base/test/test_switches.h" #include "build/chromeos_buildflags.h" #include "chrome/browser/ui/browser_list.h" +#include "chrome/test/base/chromeos/crosier/crosier_mixin.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/test/browser_test.h" #include "net/dns/mock_host_resolver.h" @@ -61,7 +62,7 @@ // 1. See http://go/crosint-run for instructions. // 2. You can optionally add --test-launcher-interactive to play with the // browser after the test finishes. -class DemoIntegrationTest : public InProcessBrowserTest { +class DemoIntegrationTest : public MixinBasedInProcessBrowserTest { public: #if BUILDFLAG(IS_CHROMEOS_ASH) void SetUpCommandLine(base::CommandLine* cmd_line) override { @@ -99,6 +100,9 @@ InProcessBrowserTest::TearDownOnMainThread(); } #endif // BUILDFLAG(IS_CHROMEOS_ASH) + + private: + CrosierMixin crosier_mixin_{&mixin_host_}; }; IN_PROC_BROWSER_TEST_F(DemoIntegrationTest, NewTab) {
diff --git a/chrome/test/base/ui_test_utils.cc b/chrome/test/base/ui_test_utils.cc index 4d4332a..6eb99f91 100644 --- a/chrome/test/base/ui_test_utils.cc +++ b/chrome/test/base/ui_test_utils.cc
@@ -678,4 +678,47 @@ } } +/////////////////////////////////////////////////////////////////////////////// +// CheckWaiter: + +CheckWaiter::CheckWaiter(base::RepeatingCallback<bool()> callback, + bool expected, + const base::TimeDelta& timeout) + : callback_(callback), + expected_(expected), + timeout_(base::TimeTicks::Now() + timeout) {} + +CheckWaiter::~CheckWaiter() = default; + +void CheckWaiter::Wait() { + if (Check()) { + return; + } + + base::RunLoop run_loop; + quit_ = run_loop.QuitClosure(); + run_loop.Run(); +} + +bool CheckWaiter::Check() { + if (callback_.Run() != expected_ && base::TimeTicks::Now() < timeout_) { + // Check again after a short timeout. Important: Don't use an immediate + // task to check again, because the pump would be allowed to run it + // immediately without processing system events (system events are + // required for the state to change). + base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, + base::BindOnce(base::IgnoreResult(&CheckWaiter::Check), + base::Unretained(this)), + TestTimeouts::tiny_timeout()); + return false; + } + + // Quit the run_loop to end the wait. + if (!quit_.is_null()) { + std::move(quit_).Run(); + } + return true; +} + } // namespace ui_test_utils
diff --git a/chrome/test/base/ui_test_utils.h b/chrome/test/base/ui_test_utils.h index facd373..ac7c996 100644 --- a/chrome/test/base/ui_test_utils.h +++ b/chrome/test/base/ui_test_utils.h
@@ -319,6 +319,31 @@ base::RunLoop run_loop_; }; +// Encapsulates waiting for the browser window to change state. This is +// needed for example on Chrome desktop linux, where window state change is done +// asynchronously as an event received from a different process. +class CheckWaiter { + public: + CheckWaiter(base::RepeatingCallback<bool()> callback, + bool expected, + const base::TimeDelta& timeout); + CheckWaiter(const CheckWaiter&) = delete; + CheckWaiter& operator=(const CheckWaiter&) = delete; + ~CheckWaiter(); + + // Blocks until the browser window becomes maximized. + void Wait(); + + private: + bool Check(); + + base::RepeatingCallback<bool()> callback_; + bool expected_; + const base::TimeTicks timeout_; + // The waiter's RunLoop quit closure. + base::RepeatingClosure quit_; +}; + } // namespace ui_test_utils #endif // CHROME_TEST_BASE_UI_TEST_UTILS_H_
diff --git a/chrome/test/data/webui/settings/chromeos/apps_page_test.js b/chrome/test/data/webui/settings/chromeos/apps_page_test.js index e2cf0a3..8d84d2e 100644 --- a/chrome/test/data/webui/settings/chromeos/apps_page_test.js +++ b/chrome/test/data/webui/settings/chromeos/apps_page_test.js
@@ -4,13 +4,14 @@ import 'chrome://os-settings/os_settings.js'; -import {AndroidAppsBrowserProxyImpl, appNotificationHandlerMojom, Router, routes, routesMojom, setAppNotificationProviderForTesting} from 'chrome://os-settings/os_settings.js'; +import {AndroidAppsBrowserProxyImpl, appNotificationHandlerMojom, createRouterForTesting, Router, routes, routesMojom, setAppNotificationProviderForTesting} from 'chrome://os-settings/os_settings.js'; import {loadTimeData} from 'chrome://resources/ash/common/load_time_data.m.js'; import {getDeepActiveElement} from 'chrome://resources/ash/common/util.js'; import {createBoolPermission} from 'chrome://resources/cr_components/app_management/permission_util.js'; import {PromiseResolver} from 'chrome://resources/js/promise_resolver.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; +import {eventToPromise} from 'chrome://webui-test/test_util.js'; import {TestAndroidAppsBrowserProxy} from './test_android_apps_browser_proxy.js'; @@ -225,9 +226,9 @@ }); const queryAndroidAppsRow = () => - appsPage.shadowRoot.querySelector('#android-apps'); + appsPage.shadowRoot.querySelector('#androidApps'); const queryAppManagementRow = () => - appsPage.shadowRoot.querySelector('#appManagement'); + appsPage.shadowRoot.querySelector('#appManagementRow'); const queryAppsOnStartupRow = () => appsPage.shadowRoot.querySelector('#onStartupDropdown'); @@ -269,6 +270,80 @@ }); }); +suite('<os-apps-page> Subpage trigger focusing', () => { + /** @type {OsSettingsAppsPageElement} */ + let appsPage; + + function initPage() { + Router.getInstance().navigateTo(routes.APPS); + appsPage = document.createElement('os-settings-apps-page'); + appsPage.prefs = getFakePrefs(); + appsPage.androidAppsInfo = { + playStoreEnabled: true, + }; + document.body.appendChild(appsPage); + flush(); + } + + setup(() => { + loadTimeData.overrideValues({ + androidAppsVisible: true, + showOsSettingsAppNotificationsRow: true, + }); + + // Reinitialize Router and routes based on load time data + const testRouter = createRouterForTesting(); + Router.resetInstanceForTesting(testRouter); + + androidAppsBrowserProxy = new TestAndroidAppsBrowserProxy(); + AndroidAppsBrowserProxyImpl.setInstanceForTesting(androidAppsBrowserProxy); + PolymerTest.clearBody(); + }); + + teardown(() => { + appsPage.remove(); + Router.getInstance().resetRouteForTesting(); + }); + + [{ + triggerSelector: '#appManagementRow', + routeName: 'APP_MANAGEMENT', + }, + { + triggerSelector: '#appNotificationsRow', + routeName: 'APP_NOTIFICATIONS', + }, + { + triggerSelector: '#androidApps .subpage-arrow', + routeName: 'ANDROID_APPS_DETAILS', + }, + ].forEach(({triggerSelector, routeName}) => { + test( + `${routeName} subpage trigger is focused when returning from subpage`, + async () => { + initPage(); + + const subpageTrigger = + appsPage.shadowRoot.querySelector(triggerSelector); + assertTrue(!!subpageTrigger); + + // Sub-page trigger navigates to Detailed build info subpage + subpageTrigger.click(); + assertEquals(routes[routeName], Router.getInstance().currentRoute); + + // Navigate back + const popStateEventPromise = eventToPromise('popstate', window); + Router.getInstance().navigateToPreviousRoute(); + await popStateEventPromise; + await waitAfterNextRender(appsPage); + + assertEquals( + subpageTrigger, appsPage.shadowRoot.activeElement, + `${triggerSelector} should be focused.`); + }); + }); +}); + suite('AppsPageTests', function() { /** * @type { @@ -324,7 +399,7 @@ }); test('App notification row', async () => { - const rowLink = appsPage.shadowRoot.querySelector('#appNotifications'); + const rowLink = appsPage.shadowRoot.querySelector('#appNotificationsRow'); assertTrue(!!rowLink); // Test default is to have 0 apps. assertEquals('0 apps', rowLink.subLabel);
diff --git a/chrome/test/data/webui/settings/chromeos/multidevice_page/multidevice_page_tests.js b/chrome/test/data/webui/settings/chromeos/multidevice_page/multidevice_page_tests.js index 92e69e0..49bbe16 100644 --- a/chrome/test/data/webui/settings/chromeos/multidevice_page/multidevice_page_tests.js +++ b/chrome/test/data/webui/settings/chromeos/multidevice_page/multidevice_page_tests.js
@@ -11,7 +11,7 @@ import {FakeContactManager} from 'chrome://webui-test/nearby_share/shared/fake_nearby_contact_manager.js'; import {FakeNearbyShareSettings} from 'chrome://webui-test/nearby_share/shared/fake_nearby_share_settings.js'; import {waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; -import {isChildVisible} from 'chrome://webui-test/test_util.js'; +import {eventToPromise, isChildVisible} from 'chrome://webui-test/test_util.js'; import {createFakePageContentData, HOST_DEVICE, TestMultideviceBrowserProxy} from './test_multidevice_browser_proxy.js'; @@ -419,6 +419,32 @@ 'settings-multidevice-feature-item')); }); + test( + 'Multidevice subpage trigger should be focused after returning from ' + + 'subpage', + async () => { + Router.getInstance().navigateTo(routes.MULTIDEVICE); + setHostData(MultiDeviceSettingsMode.HOST_SET_VERIFIED); + + // Sub-page trigger navigates to Multidevice Features subpage + const triggerSelector = '#multideviceItem .subpage-arrow'; + const subpageTrigger = + multidevicePage.shadowRoot.querySelector(triggerSelector); + subpageTrigger.click(); + assertEquals( + routes.MULTIDEVICE_FEATURES, Router.getInstance().currentRoute); + + // Navigate back + const popStateEventPromise = eventToPromise('popstate', window); + Router.getInstance().navigateToPreviousRoute(); + await popStateEventPromise; + await waitAfterNextRender(multidevicePage); + + assertEquals( + subpageTrigger, multidevicePage.shadowRoot.activeElement, + `${triggerSelector} should be focused.`); + }); + test('policy prohibited suite shows policy indicator', function() { setHostData(MultiDeviceSettingsMode.NO_ELIGIBLE_HOSTS); assertFalse(
diff --git a/chrome/test/data/webui/settings/chromeos/os_printing_page/os_printing_page_test.ts b/chrome/test/data/webui/settings/chromeos/os_printing_page/os_printing_page_test.ts index f70ee0f..e469c838 100644 --- a/chrome/test/data/webui/settings/chromeos/os_printing_page/os_printing_page_test.ts +++ b/chrome/test/data/webui/settings/chromeos/os_printing_page/os_printing_page_test.ts
@@ -11,6 +11,7 @@ import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; +import {eventToPromise} from 'chrome://webui-test/test_util.js'; suite('<os-settings-printing-page>', function() { let printingPage: OsSettingsPrintingPageElement; @@ -60,4 +61,27 @@ deepLinkElement, getDeepActiveElement(), 'Scanning app button should be focused for settingId=1403.'); }); + + test('Printers row is focused after returning from subpage', async () => { + Router.getInstance().navigateTo(routes.OS_PRINTING); + + const triggerSelector = '#cupsPrintersRow'; + const subpageTrigger = + printingPage.shadowRoot!.querySelector<HTMLElement>(triggerSelector); + assert(subpageTrigger); + + // Sub-page trigger navigates to Printers subpage + subpageTrigger.click(); + assertEquals(routes.CUPS_PRINTERS, Router.getInstance().currentRoute); + + // Navigate back + const popStateEventPromise = eventToPromise('popstate', window); + Router.getInstance().navigateToPreviousRoute(); + await popStateEventPromise; + await waitAfterNextRender(printingPage); + + assertEquals( + subpageTrigger, printingPage.shadowRoot!.activeElement, + `${triggerSelector} should be focused.`); + }); });
diff --git a/chrome/test/data/webui/settings/security_page_test.ts b/chrome/test/data/webui/settings/security_page_test.ts index 8dac62d..4158c4be2 100644 --- a/chrome/test/data/webui/settings/security_page_test.ts +++ b/chrome/test/data/webui/settings/security_page_test.ts
@@ -57,6 +57,7 @@ enableSecurityKeysSubpage: true, showHttpsOnlyModeSetting: true, showChromeRootStoreCertificates: true, + enableFriendlierSafeBrowsingSettings: true, }); }); @@ -155,6 +156,22 @@ assertEquals(lockedSubLabel, toggle.subLabel); }); + test('UpdatedStandardProtectionDropdown', function() { + const standardProtection = page.$.safeBrowsingStandard; + const updatedSpSubLabel = + loadTimeData.getString('safeBrowsingStandardDescUpdated'); + assertEquals(updatedSpSubLabel, standardProtection.subLabel); + + const passwordsLeakToggle = page.$.passwordsLeakToggle; + const updatedPasswordLeakLabel = + loadTimeData.getString('passwordsLeakDetectionLabelUpdated'); + assertEquals(updatedPasswordLeakLabel, passwordsLeakToggle.label); + + const updatedPasswordLeakSubLabel = loadTimeData.getString( + 'passwordsLeakDetectionGeneralDescriptionUpdated'); + assertEquals(updatedPasswordLeakSubLabel, passwordsLeakToggle.subLabel); + }); + }); suite('SecurityPage_FlagsDisabled', function() { @@ -164,6 +181,7 @@ loadTimeData.overrideValues({ enableSecurityKeysSubpage: false, showHttpsOnlyModeSetting: false, + enableFriendlierSafeBrowsingSettings: false, }); }); @@ -201,6 +219,23 @@ test('HttpsOnlyModeSettingHidden', function() { assertFalse(isChildVisible(page, '#httpsOnlyModeToggle')); }); + + // TODO(crbug.com/1466292): Remove once friendlier safe browsing settings + // launched. + test('NotUpdatedStandardProtectionDropdown', function() { + const standardProtection = page.$.safeBrowsingStandard; + const spSubLabel = loadTimeData.getString('safeBrowsingStandardDesc'); + assertEquals(spSubLabel, standardProtection.subLabel); + + const passwordsLeakToggle = page.$.passwordsLeakToggle; + const passwordLeakLabel = + loadTimeData.getString('passwordsLeakDetectionLabel'); + assertEquals(passwordLeakLabel, passwordsLeakToggle.label); + + const passwordLeakSubLabel = + loadTimeData.getString('passwordsLeakDetectionGeneralDescription'); + assertEquals(passwordLeakSubLabel, passwordsLeakToggle.subLabel); + }); }); // Separate test suite for tests specifically related to Safe Browsing controls.
diff --git a/chrome/test/enterprise/e2e/connector/common/device_trust_ui_test.py b/chrome/test/enterprise/e2e/connector/common/device_trust_ui_test.py index bc1a2d5..cb82697 100644 --- a/chrome/test/enterprise/e2e/connector/common/device_trust_ui_test.py +++ b/chrome/test/enterprise/e2e/connector/common/device_trust_ui_test.py
@@ -82,7 +82,6 @@ # Wait up to 120s till the idp_urls fields are filled. while count < 20: driver.get(_POLICY_URL) - WebDriverWait(driver=driver, timeout=_TIMEOUT) count += 1 # Only click `Reload-policies` button on the key_creation because # a newly enrolled Chrome does not have policies cached. The button @@ -91,7 +90,6 @@ if test_case == 'key_creation': wait_element(driver, By.CSS_SELECTOR, '#reload-policies') driver.find_element(By.CSS_SELECTOR, '#reload-policies').click() - WebDriverWait(driver=driver, timeout=30) wait_element(driver, By.CSS_SELECTOR, 'policy-table') policy_table = driver.find_element(By.CSS_SELECTOR, 'policy-table') row_groups = getElementsFromShadowRoot(driver, policy_table, @@ -136,12 +134,9 @@ while count < 20: count += 1 driver.get(_CONNECTOR_INTERNAL_URL) - WebDriverWait(driver=driver, timeout=_TIMEOUT) wait_element(driver, By.CSS_SELECTOR, 'connectors-internals-app') connectors_internals_app = driver.find_element( By.CSS_SELECTOR, 'connectors-internals-app') - WebDriverWait(driver=driver, timeout=_TIMEOUT) - connectors_tabs = getElementFromShadowRoot(driver, connectors_internals_app, 'connectors-tabs') @@ -198,9 +193,6 @@ result['FakeIdP'] = idp_url result['DeviceId'] = device_id driver.get(idp_url) - WebDriverWait(driver=driver, timeout=_TIMEOUT) - # artificially wait for another 3 seconds - time.sleep(3) wait_element(driver, By.XPATH, '//*[@id="content"]/div[2]/a') driver.find_element(By.XPATH, '//*[@id="content"]/div[2]/a').click()
diff --git a/chrome/test/enterprise/e2e/policy/cloud_management_enrollment_token/cloud_enrollment_webdriver.py b/chrome/test/enterprise/e2e/policy/cloud_management_enrollment_token/cloud_enrollment_webdriver.py index d7d8451a..1dcc484 100644 --- a/chrome/test/enterprise/e2e/policy/cloud_management_enrollment_token/cloud_enrollment_webdriver.py +++ b/chrome/test/enterprise/e2e/policy/cloud_management_enrollment_token/cloud_enrollment_webdriver.py
@@ -6,6 +6,7 @@ from absl import app import time from selenium import webdriver +from selenium.webdriver.common.by import By from test_util import create_chrome_webdriver from test_util import getElementFromShadowRoot @@ -23,16 +24,16 @@ # Verify Policy status legend in chrome://policy page policy_url = "chrome://policy" driver.get(policy_url) - driver.find_element_by_id('reload-policies').click + driver.find_element(By.ID, 'reload-policies').click # Give the page 2 seconds to render the legend time.sleep(2) - status_box = driver.find_element_by_css_selector("status-box") - el = getElementFromShadowRoot(driver, status_box, "fieldset") + status_box = driver.find_element(By.CSS_SELECTOR, "status-box") + el = getElementFromShadowRoot(driver, status_box, ".status-box-fields") - print(el.find_element_by_class_name('legend').text) - print(el.find_element_by_class_name('machine-enrollment-name').text) - print(el.find_element_by_class_name('machine-enrollment-token').text) - print(el.find_element_by_class_name('status').text) + print(el.find_element(By.CLASS_NAME, 'status-box-heading').text) + print(el.find_element(By.CLASS_NAME, 'machine-enrollment-name').text) + print(el.find_element(By.CLASS_NAME, 'machine-enrollment-token').text) + print(el.find_element(By.CLASS_NAME, 'status').text) except Exception as error: print(error) finally:
diff --git a/chrome/updater/run_all_unittests.cc b/chrome/updater/run_all_unittests.cc index 9189ddf..6cc7d47 100644 --- a/chrome/updater/run_all_unittests.cc +++ b/chrome/updater/run_all_unittests.cc
@@ -166,7 +166,7 @@ #if BUILDFLAG(IS_WIN) updater::test::MaybeExcludePathsFromWindowsDefender(); - VLOG(0) << "Process priority: " << base::Process::Current().GetPriority(); + VLOG(0) << "Process priority: " << base::Process::Current().GetOSPriority(); VLOG(0) << updater::GetUACState(); // The test suite runner expects the swarming task to run with normal priority
diff --git a/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client.cc b/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client.cc index 58979cf..74dfd73 100644 --- a/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client.cc +++ b/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client.cc
@@ -37,6 +37,7 @@ namespace { LorgnetteManagerClient* g_instance = nullptr; +constexpr char kListScannersDiscoveryClientId[] = "ListScanners"; // The LorgnetteManagerClient implementation used in production. class LorgnetteManagerClientImpl : public LorgnetteManagerClient { @@ -50,6 +51,26 @@ void ListScanners( chromeos::DBusMethodCallback<lorgnette::ListScannersResponse> callback) override { + if (features::IsAsynchronousScannerDiscoveryEnabled()) { + lorgnette::StartScannerDiscoveryRequest request; + // ListScanners doesn't support concurrent calls and completes the session + // before it finishes, so hardcoding a single client id shouldn't cause + // cross-caller interference. + request.set_client_id(kListScannersDiscoveryClientId); + request.set_preferred_only(true); + + StartScannerDiscovery( + std::move(request), + base::BindRepeating( + &LorgnetteManagerClientImpl::ListScannersDiscoveryScannersUpdated, + weak_ptr_factory_.GetWeakPtr()), + base::BindOnce( + &LorgnetteManagerClientImpl::OnListScannersDiscoverySession, + weak_ptr_factory_.GetWeakPtr(), std::move(callback))); + + return; + } + dbus::MethodCall method_call(lorgnette::kManagerServiceInterface, lorgnette::kListScannersMethod); lorgnette_daemon_proxy_->CallMethod( @@ -280,9 +301,13 @@ struct DiscoverySessionState { absl::optional< + chromeos::DBusMethodCallback<lorgnette::ListScannersResponse>> + session_end_callback; + absl::optional< base::RepeatingCallback<void(lorgnette::ScannerListChangedSignal)>> signal_callback; std::string session_id; + lorgnette::ListScannersResponse response; }; // Helper function to send a GetNextImage request to lorgnette for the scan @@ -579,6 +604,23 @@ std::move(response_callback).Run(std::move(response)); } + void OnListScannersDiscoverySession( + chromeos::DBusMethodCallback<lorgnette::ListScannersResponse> callback, + absl::optional<lorgnette::StartScannerDiscoveryResponse> response) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + if (!response.has_value()) { + std::move(callback).Run(absl::nullopt); + return; + } + + // This will have been created already by OnStartScannerDiscoveryResponse, + // so no need to search for it first. + DCHECK(base::Contains(discovery_sessions_, response->session_id())); + discovery_sessions_[response->session_id()].session_end_callback = + std::move(callback); + } + void OnStopScannerDiscoveryResponse( std::string session_id, chromeos::DBusMethodCallback<lorgnette::StopScannerDiscoveryResponse> @@ -675,6 +717,37 @@ session.signal_callback->Run(std::move(signal)); } + void ListScannersDiscoveryScannersUpdated( + lorgnette::ScannerListChangedSignal signal) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + DCHECK(base::Contains(discovery_sessions_, signal.session_id())); + DiscoverySessionState& session = discovery_sessions_[signal.session_id()]; + + switch (signal.event_type()) { + case lorgnette::ScannerListChangedSignal::SCANNER_ADDED: + PRINTER_LOG(EVENT) << "Discovered SANE scanner: " + << signal.scanner().name(); + *session.response.add_scanners() = std::move(signal.scanner()); + break; + case lorgnette::ScannerListChangedSignal::SCANNER_REMOVED: + break; + case lorgnette::ScannerListChangedSignal::ENUM_COMPLETE: { + lorgnette::StopScannerDiscoveryRequest request; + request.set_session_id(session.session_id); + StopScannerDiscovery(request, base::DoNothing()); + break; + } + case lorgnette::ScannerListChangedSignal::SESSION_ENDING: + DCHECK(session.session_end_callback); + std::move(*session.session_end_callback) + .Run(std::move(session.response)); + discovery_sessions_.erase(session.session_id); + break; + default: + NOTREACHED(); + } + } + void LorgnetteSignalConnected(const std::string& interface_name, const std::string& signal_name, bool success) {
diff --git a/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client_unittest.cc b/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client_unittest.cc index 5c770c8..08194116 100644 --- a/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client_unittest.cc +++ b/chromeos/ash/components/dbus/lorgnette_manager/lorgnette_manager_client_unittest.cc
@@ -601,6 +601,54 @@ run_loop.Run(); } +TEST_F(LorgnetteManagerClientTest, ListScannersViaAsyncDiscovery) { + auto feature = base::test::ScopedFeatureList( + ash::features::kAsynchronousScannerDiscovery); + + std::unique_ptr<dbus::Response> response = dbus::Response::CreateEmpty(); + const lorgnette::StartScannerDiscoveryResponse kExpectedResponse = + CreateStartScannerDiscoveryResponse("session"); + const lorgnette::ListScannersResponse kExpectedScannerList = + CreateListScannersResponse(); + ASSERT_TRUE(dbus::MessageWriter(response.get()) + .AppendProtoAsArrayOfBytes(kExpectedResponse)); + SetStartScannerDiscoveryExpectation(response.get()); + + std::unique_ptr<dbus::Response> stop_response = dbus::Response::CreateEmpty(); + const lorgnette::StopScannerDiscoveryResponse kExpectedStopResponse = + CreateStopScannerDiscoveryResponse(); + ASSERT_TRUE(dbus::MessageWriter(stop_response.get()) + .AppendProtoAsArrayOfBytes(kExpectedStopResponse)); + SetStopScannerDiscoveryExpectation(stop_response.get()); + + base::RunLoop run_loop; + GetClient()->ListScanners(base::BindLambdaForTesting( + [&](absl::optional<lorgnette::ListScannersResponse> result) { + ASSERT_TRUE(result.has_value()); + EXPECT_THAT(result.value(), ProtobufEquals(kExpectedScannerList)); + run_loop.Quit(); + })); + + run_loop.RunUntilIdle(); + + // Discover all scanners. + for (const auto& scanner : kExpectedScannerList.scanners()) { + EmitScannerListChangedSignal( + "session", lorgnette::ScannerListChangedSignal::SCANNER_ADDED, scanner); + } + + // Tell client all scanners have been found. The client will call + // StopScannerDiscovery. + EmitScannerListChangedSignal( + "session", lorgnette::ScannerListChangedSignal::ENUM_COMPLETE, {}); + + // Tell client the session is ending so ListScanners can return its response. + EmitScannerListChangedSignal( + "session", lorgnette::ScannerListChangedSignal::SESSION_ENDING, {}); + + run_loop.Run(); +} + // Test that the client handles a null response to a kListScannersMethod D-Bus // call. TEST_F(LorgnetteManagerClientTest, NullResponseToListScanners) { @@ -671,11 +719,8 @@ case lorgnette::ScannerListChangedSignal::ENUM_COMPLETE: { lorgnette::StopScannerDiscoveryRequest request; request.set_session_id("session"); - GetClient()->StopScannerDiscovery( - std::move(request), - base::BindOnce( - [](absl::optional< - lorgnette::StopScannerDiscoveryResponse>) {})); + GetClient()->StopScannerDiscovery(std::move(request), + base::DoNothing()); break; } case lorgnette::ScannerListChangedSignal::SESSION_ENDING:
diff --git a/chromeos/services/network_config/public/cpp/fake_cros_network_config.cc b/chromeos/services/network_config/public/cpp/fake_cros_network_config.cc index 91b15828..e3732bf 100644 --- a/chromeos/services/network_config/public/cpp/fake_cros_network_config.cc +++ b/chromeos/services/network_config/public/cpp/fake_cros_network_config.cc
@@ -159,6 +159,15 @@ base::RunLoop().RunUntilIdle(); } +void FakeCrosNetworkConfig::RemoveNthNetworks(size_t index) { + DCHECK(index < visible_networks_.size() && index >= 0); + visible_networks_.erase(visible_networks_.begin() + index); + for (auto& observer : observers_) { + observer->OnDeviceStateListChanged(); + } + base::RunLoop().RunUntilIdle(); +} + int FakeCrosNetworkConfig::GetScanCount(mojom::NetworkType type) { return scan_count_[type]; }
diff --git a/chromeos/services/network_config/public/cpp/fake_cros_network_config.h b/chromeos/services/network_config/public/cpp/fake_cros_network_config.h index b2846fc..df17239 100644 --- a/chromeos/services/network_config/public/cpp/fake_cros_network_config.h +++ b/chromeos/services/network_config/public/cpp/fake_cros_network_config.h
@@ -128,6 +128,10 @@ // and `OnActiveNetworksChanged` for all observers in `observers_`. void ClearNetworksAndDevices(); + // Removes the passed in `index` of the current networks from the list and + // calls `OnDeviceStateListChanged` for all observer in `observers_`. + void RemoveNthNetworks(size_t index); + // Returns how many times `RequestNetworkScan` was requested for the specified // network type. int GetScanCount(mojom::NetworkType type);
diff --git a/chromeos/tast_control.gni b/chromeos/tast_control.gni index 23808b51..2c48dbe 100644 --- a/chromeos/tast_control.gni +++ b/chromeos/tast_control.gni
@@ -331,6 +331,7 @@ "inputs.VirtualKeyboardHandwriting.docked", "inputs.VirtualKeyboardHandwriting.floating", "inputs.VirtualKeyboardTypingApps", + "inputs.VirtualKeyboardTypingOmnibox.a11y_lacros", "inputs.VirtualKeyboardTypingUserMode.incognito", # b/287525851
diff --git a/components/autofill/core/common/autofill_payments_features.cc b/components/autofill/core/common/autofill_payments_features.cc index 9d71dc592..db59caf 100644 --- a/components/autofill/core/common/autofill_payments_features.cc +++ b/components/autofill/core/common/autofill_payments_features.cc
@@ -292,6 +292,14 @@ BASE_FEATURE(kAutofillUseTwoDotsForLastFourDigits, "AutofillUseTwoDotsForLastFourDigits", base::FEATURE_DISABLED_BY_DEFAULT); + +// When this and the above `kAutofillEnablePaymentsMandatoryReauth` are both +// enabled, in use-cases where we would not have triggered any user-visible +// authentication to autofill payment methods, we will trigger a device +// authentication on Bling. +BASE_FEATURE(kAutofillEnablePaymentsMandatoryReauthOnBling, + "AutofillEnablePaymentsMandatoryReauthOnBling", + base::FEATURE_DISABLED_BY_DEFAULT); #endif bool ShouldShowImprovedUserConsentForCreditCardSave() {
diff --git a/components/autofill/core/common/autofill_payments_features.h b/components/autofill/core/common/autofill_payments_features.h index 29c356d..0c5a7f34 100644 --- a/components/autofill/core/common/autofill_payments_features.h +++ b/components/autofill/core/common/autofill_payments_features.h
@@ -61,6 +61,7 @@ #if BUILDFLAG(IS_IOS) BASE_DECLARE_FEATURE(kAutofillUseTwoDotsForLastFourDigits); +BASE_DECLARE_FEATURE(kAutofillEnablePaymentsMandatoryReauthOnBling); #endif // Return whether a [No thanks] button and new messaging is shown in the save
diff --git a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/selectable_list/SelectableListLayout.java b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/selectable_list/SelectableListLayout.java index 081bade..3e76c07 100644 --- a/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/selectable_list/SelectableListLayout.java +++ b/components/browser_ui/widget/android/java/src/org/chromium/components/browser_ui/widget/selectable_list/SelectableListLayout.java
@@ -237,7 +237,7 @@ public TextView initializeEmptyView(int emptyStringResId) { setEmptyViewText(emptyStringResId); - // Dummy listener to have the touch events dispatched to this view tree for navigation UI. + // Empty listener to have the touch events dispatched to this view tree for navigation UI. mEmptyViewWrapper.setOnTouchListener((v, event) -> true); return mEmptyView;
diff --git a/components/cloud_devices/common/printer_description.cc b/components/cloud_devices/common/printer_description.cc index e27a4c5..2cefef2 100644 --- a/components/cloud_devices/common/printer_description.cc +++ b/components/cloud_devices/common/printer_description.cc
@@ -86,6 +86,8 @@ constexpr char kMediaImageableAreaBottom[] = "imageable_area_bottom_microns"; constexpr char kMediaImageableAreaRight[] = "imageable_area_right_microns"; constexpr char kMediaImageableAreaTop[] = "imageable_area_top_microns"; +constexpr char kMediaMinHeight[] = "min_height_microns"; +constexpr char kMediaMaxHeight[] = "max_height_microns"; constexpr char kPageRangeInterval[] = "interval"; constexpr char kPageRangeEnd[] = "end"; @@ -945,30 +947,37 @@ } Media::Media() - : size_name(MediaSize::CUSTOM_MEDIA), is_continuous_feed(false) {} + : size_name(MediaSize::CUSTOM_MEDIA), + is_continuous_feed(false), + max_height_um(0) {} Media::Media(const Media& other) = default; Media& Media::operator=(const Media& other) = default; bool Media::IsValid() const { + if (size_um.width() <= 0 || size_um.height() <= 0) { + return false; + } + if (is_continuous_feed) { - if (size_um.width() <= 0 && size_um.height() <= 0) - return false; - } else { - if (size_um.width() <= 0 || size_um.height() <= 0) - return false; - if (!gfx::Rect(size_um).Contains(printable_area_um)) { + if (max_height_um <= size_um.height()) { return false; } } + + if (!gfx::Rect(size_um).Contains(printable_area_um)) { + return false; + } + return true; } bool Media::operator==(const Media& other) const { return size_name == other.size_name && size_um == other.size_um && is_continuous_feed == other.is_continuous_feed && - printable_area_um == other.printable_area_um; + printable_area_um == other.printable_area_um && + max_height_um == other.max_height_um; } MediaBuilder::MediaBuilder() = default; @@ -1017,6 +1026,11 @@ return WithSizeAndDefaultPrintableArea(FindMediaSizeByType(size_name_)); } +MediaBuilder& MediaBuilder::WithMaxHeight(int max_height_um) { + max_height_um_ = max_height_um; + return *this; +} + Media MediaBuilder::Build() const { Media result; result.size_name = size_name_; @@ -1025,11 +1039,12 @@ result.custom_display_name = custom_display_name_; result.vendor_id = vendor_id_; result.printable_area_um = printable_area_um_; + result.max_height_um = max_height_um_; return result; } bool MediaBuilder::IsContinuousFeed() const { - return size_um_.width() <= 0 || size_um_.height() <= 0; + return max_height_um_ > 0; } Interval::Interval() : start(0), end(0) { @@ -1401,15 +1416,6 @@ if (type && !TypeFromString(kMediaDefinitions, *type, &option->size_name)) { return false; } - absl::optional<int> width_um = dict.FindInt(kMediaWidth); - if (width_um) - option->size_um.set_width(width_um.value()); - absl::optional<int> height_um = dict.FindInt(kMediaHeight); - if (height_um) - option->size_um.set_height(height_um.value()); - absl::optional<bool> is_continuous_feed = dict.FindBool(kMediaIsContinuous); - if (is_continuous_feed) - option->is_continuous_feed = is_continuous_feed.value(); const std::string* custom_display_name = dict.FindString(kKeyCustomDisplayName); if (custom_display_name) @@ -1417,14 +1423,36 @@ const std::string* vendor_id = dict.FindString(kKeyVendorId); if (vendor_id) option->vendor_id = *vendor_id; + absl::optional<int> width_um = dict.FindInt(kMediaWidth); + if (width_um) { + option->size_um.set_width(width_um.value()); + } + absl::optional<bool> is_continuous_feed = dict.FindBool(kMediaIsContinuous); + if (is_continuous_feed) { + option->is_continuous_feed = is_continuous_feed.value(); + } + if (is_continuous_feed.value_or(false)) { + // The min/max height is required for continuous feed media. + absl::optional<int> min_height_um = dict.FindInt(kMediaMinHeight); + absl::optional<int> max_height_um = dict.FindInt(kMediaMaxHeight); + if (!min_height_um || !max_height_um) { + return false; + } + // For variable height media, the min height is stored in the height + // attribute of the `size_um` parameter. + option->size_um.set_height(min_height_um.value()); + option->max_height_um = max_height_um.value(); - if (is_continuous_feed && *is_continuous_feed) { // When `option` is a continuous feed, the printable area is not // applicable. For consistency with the constructors, set the printable // area to the default page size value. option->printable_area_um = gfx::Rect(option->size_um); return true; } + absl::optional<int> height_um = dict.FindInt(kMediaHeight); + if (height_um) { + option->size_um.set_height(height_um.value()); + } absl::optional<int> imageable_area_left = dict.FindInt(kMediaImageableAreaLeft); absl::optional<int> imageable_area_bottom = @@ -1456,11 +1484,16 @@ dict->Set(kKeyVendorId, option.vendor_id); if (option.size_um.width() > 0) dict->Set(kMediaWidth, option.size_um.width()); - if (option.size_um.height() > 0) - dict->Set(kMediaHeight, option.size_um.height()); - if (option.is_continuous_feed) + if (option.is_continuous_feed) { + // For variable height media, the height from `size_um` represents the min + // height, so it gets stored in `kMediaMinHeight`, not in `kMediaHeight`. dict->Set(kMediaIsContinuous, true); - if (!option.printable_area_um.IsEmpty() && + dict->Set(kMediaMinHeight, option.size_um.height()); + dict->Set(kMediaMaxHeight, option.max_height_um); + } else if (option.size_um.height() > 0) { + dict->Set(kMediaHeight, option.size_um.height()); + } + if (!option.is_continuous_feed && !option.printable_area_um.IsEmpty() && gfx::Rect(option.size_um).Contains(option.printable_area_um)) { dict->Set(kMediaImageableAreaLeft, option.printable_area_um.x()); dict->Set(kMediaImageableAreaBottom, option.printable_area_um.y());
diff --git a/components/cloud_devices/common/printer_description.h b/components/cloud_devices/common/printer_description.h index ffe146cb..eba90e0 100644 --- a/components/cloud_devices/common/printer_description.h +++ b/components/cloud_devices/common/printer_description.h
@@ -489,6 +489,11 @@ std::string custom_display_name; std::string vendor_id; gfx::Rect printable_area_um; + // When `is_continuous_feed` is true, the min height will be stored in + // `size_um` and the max height is stored in `max_height_um`. When + // `is_continuous_feed` is false, `max_height_um` is not used. This only + // supports a variable height, not width, so the width is always fixed. + int max_height_um; }; // Builds `Media` structs. The caller must call at least one method that sets @@ -516,6 +521,7 @@ MediaBuilder& WithSizeAndDefaultPrintableArea(const gfx::Size& size_um); MediaBuilder& WithSizeAndPrintableArea(const gfx::Size& size_um, const gfx::Rect& printable_area_um); + MediaBuilder& WithMaxHeight(int max_height_um); // This is equivalent to calling WithCustomName(), except it also tries to // match the name to a standard `MediaSize`. @@ -543,6 +549,7 @@ gfx::Size size_um_; gfx::Rect printable_area_um_; + int max_height_um_ = 0; }; struct Interval {
diff --git a/components/cloud_devices/common/printer_description_unittest.cc b/components/cloud_devices/common/printer_description_unittest.cc index aa932c4..6ac89de 100644 --- a/components/cloud_devices/common/printer_description_unittest.cc +++ b/components/cloud_devices/common/printer_description_unittest.cc
@@ -153,6 +153,8 @@ "height_microns": 7777 }, { "width_microns": 1111, + "min_height_microns": 2222, + "max_height_microns": 9999, "is_continuous_feed": true, "custom_display_name": "Feed", "vendor_id": "FEED" @@ -534,6 +536,77 @@ })"; #endif // BUILDFLAG(IS_CHROMEOS) +// Invalid because `is_continuous_feed` is true and `min_height_microns` is +// missing. +const char kInvalidCustomMediaNoMinHeightCdd[] = R"( + { + "version": "1.0", + "printer": { + "media_size": { + "option": [ { + "width_microns": 1111, + "max_height_microns": 9999, + "is_continuous_feed": true, + "custom_display_name": "Feed", + "vendor_id": "FEED" + } ] + } + } + })"; + +// Invalid because `is_continuous_feed` is true and `width_microns` is missing. +const char kInvalidCustomMediaNoWidthCdd[] = R"( + { + "version": "1.0", + "printer": { + "media_size": { + "option": [ { + "min_height_microns": 1111, + "max_height_microns": 9999, + "is_continuous_feed": true, + "custom_display_name": "Feed", + "vendor_id": "FEED" + } ] + } + } + })"; + +// Invalid because `max_height_microns` is less than `min_height_microns`. +const char kInvalidCustomMediaBadMaxHeightCdd[] = R"( + { + "version": "1.0", + "printer": { + "media_size": { + "option": [ { + "width_microns": 1111, + "min_height_microns": 9999, + "max_height_microns": 2222, + "is_continuous_feed": true, + "custom_display_name": "Feed", + "vendor_id": "FEED" + } ] + } + } + })"; + +// Invalid because `min_height_microns` is 0. +const char kInvalidCustomMediaBadMinHeightCdd[] = R"( + { + "version": "1.0", + "printer": { + "media_size": { + "option": [ { + "width_microns": 1111, + "min_height_microns": 0, + "max_height_microns": 2222, + "is_continuous_feed": true, + "custom_display_name": "Feed", + "vendor_id": "FEED" + } ] + } + } + })"; + const char kCjt[] = R"( { "version": "1.0", @@ -758,7 +831,8 @@ .Build()); media.AddOption(MediaBuilder() .WithCustomName("Feed", "FEED") - .WithSizeAndDefaultPrintableArea({1111, 0}) + .WithSizeAndDefaultPrintableArea({1111, 2222}) + .WithMaxHeight(9999) .Build()); collate.set_default_value(false); @@ -1160,6 +1234,34 @@ } #endif // BUILDFLAG(IS_CHROMEOS) +TEST(PrinterDescriptionTest, CddInvalidCustomMediaNoMinHeight) { + CloudDeviceDescription description; + ASSERT_TRUE(description.InitFromString(kInvalidCustomMediaNoMinHeightCdd)); + MediaCapability media_capability; + EXPECT_FALSE(media_capability.LoadFrom(description)); +} + +TEST(PrinterDescriptionTest, CddInvalidCustomMediaNoWidth) { + CloudDeviceDescription description; + ASSERT_TRUE(description.InitFromString(kInvalidCustomMediaNoWidthCdd)); + MediaCapability media_capability; + EXPECT_FALSE(media_capability.LoadFrom(description)); +} + +TEST(PrinterDescriptionTest, CddInvalidCustomMediaBadMaxHeight) { + CloudDeviceDescription description; + ASSERT_TRUE(description.InitFromString(kInvalidCustomMediaBadMaxHeightCdd)); + MediaCapability media_capability; + EXPECT_FALSE(media_capability.LoadFrom(description)); +} + +TEST(PrinterDescriptionTest, CddInvalidCustomMediaBadMinHeight) { + CloudDeviceDescription description; + ASSERT_TRUE(description.InitFromString(kInvalidCustomMediaBadMinHeightCdd)); + MediaCapability media_capability; + EXPECT_FALSE(media_capability.LoadFrom(description)); +} + TEST(PrinterDescriptionTest, CddGetAll) { CloudDeviceDescription description; ASSERT_TRUE(description.InitFromString(kCdd)); @@ -1190,7 +1292,6 @@ EXPECT_TRUE(media.LoadFrom(description)); EXPECT_TRUE(collate.LoadFrom(description)); EXPECT_TRUE(reverse.LoadFrom(description)); - EXPECT_TRUE(media.LoadFrom(description)); EXPECT_TRUE(pwg_raster_config.LoadFrom(description)); EXPECT_TRUE(content_types.Contains("image/pwg-raster")); @@ -1253,7 +1354,8 @@ .Build())); EXPECT_TRUE(media.Contains(MediaBuilder() .WithCustomName("Feed", "FEED") - .WithSizeAndDefaultPrintableArea({1111, 0}) + .WithSizeAndDefaultPrintableArea({1111, 2222}) + .WithMaxHeight(9999) .Build())); EXPECT_EQ(default_media, media.GetDefault()); @@ -1454,6 +1556,7 @@ EXPECT_TRUE(media_a1.custom_display_name.empty()); EXPECT_TRUE(media_a1.vendor_id.empty()); EXPECT_EQ(gfx::Rect(100, 200), media_a1.printable_area_um); + EXPECT_EQ(0, media_a1.max_height_um); EXPECT_TRUE(media_a1.IsValid()); Media media_a4_with_printable_area = @@ -1469,6 +1572,7 @@ EXPECT_TRUE(media_a4_with_printable_area.vendor_id.empty()); EXPECT_EQ(gfx::Rect(5, 6, 50, 60), media_a4_with_printable_area.printable_area_um); + EXPECT_EQ(0, media_a4_with_printable_area.max_height_um); EXPECT_TRUE(media_a4_with_printable_area.IsValid()); } @@ -1485,6 +1589,7 @@ EXPECT_EQ("name", media_custom1.custom_display_name); EXPECT_EQ("id", media_custom1.vendor_id); EXPECT_EQ(gfx::Rect(100, 150, 1800, 2000), media_custom1.printable_area_um); + EXPECT_EQ(0, media_custom1.max_height_um); EXPECT_TRUE(media_custom1.IsValid()); Media media_custom2 = @@ -1499,6 +1604,7 @@ EXPECT_EQ("name2", media_custom2.custom_display_name); EXPECT_TRUE(media_custom2.vendor_id.empty()); EXPECT_EQ(gfx::Rect(50, 60, 120, 200), media_custom2.printable_area_um); + EXPECT_EQ(0, media_custom2.max_height_um); EXPECT_TRUE(media_custom2.IsValid()); } @@ -1510,11 +1616,11 @@ EXPECT_EQ(MediaSize::NA_LETTER, media_empty_size.size_name); EXPECT_EQ(gfx::Size(0, 0), media_empty_size.size_um); - // While this value is true, the media as a whole is invalid. - EXPECT_TRUE(media_empty_size.is_continuous_feed); + EXPECT_FALSE(media_empty_size.is_continuous_feed); EXPECT_TRUE(media_empty_size.custom_display_name.empty()); EXPECT_TRUE(media_empty_size.vendor_id.empty()); EXPECT_EQ(gfx::Rect(0, 0), media_empty_size.printable_area_um); + EXPECT_EQ(0, media_empty_size.max_height_um); EXPECT_FALSE(media_empty_size.IsValid()); Media media_no_size = @@ -1522,41 +1628,45 @@ EXPECT_EQ(MediaSize::NA_LEGAL, media_no_size.size_name); EXPECT_EQ(gfx::Size(0, 0), media_no_size.size_um); - // While this value is true, the media as a whole is invalid. - EXPECT_TRUE(media_no_size.is_continuous_feed); + EXPECT_FALSE(media_no_size.is_continuous_feed); EXPECT_TRUE(media_no_size.custom_display_name.empty()); EXPECT_TRUE(media_no_size.vendor_id.empty()); EXPECT_EQ(gfx::Rect(0, 0), media_no_size.printable_area_um); + EXPECT_EQ(0, media_no_size.max_height_um); EXPECT_FALSE(media_no_size.IsValid()); } -TEST(PrinterDescriptionMediaBuilderTest, ContinuousFeedWidth) { - Media media_continuous_width = MediaBuilder() - .WithStandardName(MediaSize::NA_LETTER) - .WithSizeAndDefaultPrintableArea({0, 100}) - .Build(); +TEST(PrinterDescriptionMediaBuilderTest, EmptyWidth) { + Media media_empty_width = MediaBuilder() + .WithStandardName(MediaSize::NA_LETTER) + .WithSizeAndDefaultPrintableArea({0, 100}) + .Build(); - EXPECT_EQ(MediaSize::NA_LETTER, media_continuous_width.size_name); - EXPECT_EQ(gfx::Size(0, 100), media_continuous_width.size_um); - EXPECT_TRUE(media_continuous_width.is_continuous_feed); - EXPECT_TRUE(media_continuous_width.custom_display_name.empty()); - EXPECT_TRUE(media_continuous_width.vendor_id.empty()); - EXPECT_EQ(gfx::Rect(0, 100), media_continuous_width.printable_area_um); - EXPECT_TRUE(media_continuous_width.IsValid()); + EXPECT_EQ(MediaSize::NA_LETTER, media_empty_width.size_name); + EXPECT_EQ(gfx::Size(0, 100), media_empty_width.size_um); + EXPECT_FALSE(media_empty_width.is_continuous_feed); + EXPECT_TRUE(media_empty_width.custom_display_name.empty()); + EXPECT_TRUE(media_empty_width.vendor_id.empty()); + EXPECT_EQ(gfx::Rect(0, 100), media_empty_width.printable_area_um); + EXPECT_EQ(0, media_empty_width.max_height_um); + EXPECT_FALSE(media_empty_width.IsValid()); } TEST(PrinterDescriptionMediaBuilderTest, ContinuousFeedHeight) { - Media media_continuous_height = MediaBuilder() - .WithStandardName(MediaSize::NA_LETTER) - .WithSizeAndDefaultPrintableArea({200, 0}) - .Build(); + Media media_continuous_height = + MediaBuilder() + .WithCustomName("FEED", "feed") + .WithSizeAndDefaultPrintableArea({100, 200}) + .WithMaxHeight(500) + .Build(); - EXPECT_EQ(MediaSize::NA_LETTER, media_continuous_height.size_name); - EXPECT_EQ(gfx::Size(200, 0), media_continuous_height.size_um); + EXPECT_EQ(MediaSize::CUSTOM_MEDIA, media_continuous_height.size_name); + EXPECT_EQ(gfx::Size(100, 200), media_continuous_height.size_um); EXPECT_TRUE(media_continuous_height.is_continuous_feed); - EXPECT_TRUE(media_continuous_height.custom_display_name.empty()); - EXPECT_TRUE(media_continuous_height.vendor_id.empty()); - EXPECT_EQ(gfx::Rect(200, 0), media_continuous_height.printable_area_um); + EXPECT_EQ("FEED", media_continuous_height.custom_display_name); + EXPECT_EQ("feed", media_continuous_height.vendor_id); + EXPECT_EQ(gfx::Rect(100, 200), media_continuous_height.printable_area_um); + EXPECT_EQ(500, media_continuous_height.max_height_um); EXPECT_TRUE(media_continuous_height.IsValid()); } @@ -1574,6 +1684,7 @@ EXPECT_EQ("custom_letter", media_letter.custom_display_name); EXPECT_EQ("vendor_letter", media_letter.vendor_id); EXPECT_EQ(gfx::Rect(215900, 279400), media_letter.printable_area_um); + EXPECT_EQ(0, media_letter.max_height_um); EXPECT_TRUE(media_letter.IsValid()); Media media_non_standard = @@ -1589,6 +1700,7 @@ EXPECT_EQ("123x456", media_non_standard.custom_display_name); EXPECT_EQ("vendor_123x456", media_non_standard.vendor_id); EXPECT_EQ(gfx::Rect(123000, 456000), media_non_standard.printable_area_um); + EXPECT_EQ(0, media_non_standard.max_height_um); EXPECT_TRUE(media_non_standard.IsValid()); } @@ -1605,6 +1717,7 @@ EXPECT_TRUE(media.custom_display_name.empty()); EXPECT_TRUE(media.vendor_id.empty()); EXPECT_EQ(gfx::Rect(297000, 420000), media.printable_area_um); + EXPECT_EQ(0, media.max_height_um); EXPECT_TRUE(media.IsValid()); } @@ -1621,6 +1734,7 @@ EXPECT_TRUE(media1.custom_display_name.empty()); EXPECT_TRUE(media1.vendor_id.empty()); EXPECT_EQ(gfx::Rect(100, 200), media1.printable_area_um); + EXPECT_EQ(0, media1.max_height_um); EXPECT_TRUE(media1.IsValid()); EXPECT_EQ(media1.size_name, media2.size_name); @@ -1629,6 +1743,7 @@ EXPECT_EQ(media1.custom_display_name, media2.custom_display_name); EXPECT_EQ(media1.vendor_id, media2.vendor_id); EXPECT_EQ(media1.printable_area_um, media2.printable_area_um); + EXPECT_EQ(media1.max_height_um, media2.max_height_um); EXPECT_TRUE(media2.IsValid()); }
diff --git a/components/gwp_asan/crash_handler/crash_analyzer.cc b/components/gwp_asan/crash_handler/crash_analyzer.cc index 7e26726..9335028b 100644 --- a/components/gwp_asan/crash_handler/crash_analyzer.cc +++ b/components/gwp_asan/crash_handler/crash_analyzer.cc
@@ -239,6 +239,8 @@ bool seen_candidate_id = false; absl::optional<LightweightDetector::MetadataId> metadata_id; + std::vector<uint64_t> candidate_addresses; + #if defined(ARCH_CPU_X86_64) if (exception->Context()->architecture != crashpad::kCPUArchitectureX86_64) { ReportHistogram( @@ -268,62 +270,55 @@ #endif // BUILDFLAG(IS_WIN) ) { auto& context = *exception->Context()->x86_64; - uint64_t cpu_regs[] = {context.rax, context.rbx, context.rcx, context.rdx, + candidate_addresses = {context.rax, context.rbx, context.rcx, context.rdx, context.rdi, context.rsi, context.rbp, context.rsp, context.r8, context.r9, context.r10, context.r11, context.r12, context.r13, context.r14, context.r15, context.rip}; - - for (auto cpu_reg : cpu_regs) { - auto candidate_id = LightweightDetector::ExtractMetadataId(cpu_reg); - if (!candidate_id.has_value()) { - continue; - } - seen_candidate_id = true; - - if (valid_state.HasLightweightMetadataForId(*candidate_id, - metadata_arr.get())) { - if (!metadata_id.has_value()) { - // It's the first time we see an ID with a matching valid slot. - metadata_id = candidate_id; - } else if (metadata_id != candidate_id) { - ReportHistogram(Crash_Allocator_PARTITIONALLOC, - GwpAsanCrashAnalysisResult:: - kErrorConflictingLightweightMetadataIds); - proto->set_missing_metadata(true); - proto->set_internal_error( - "Found conflicting lightweight metadata IDs."); - return true; - } - } - } } #else // defined(ARCH_CPU_X86_64) - auto candidate_id = - LightweightDetector::ExtractMetadataId(GetAccessAddress(*exception)); - if (candidate_id.has_value()) { - seen_candidate_id = true; - if (valid_state.HasLightweightMetadataForId(*candidate_id, - metadata_arr.get())) { - metadata_id = candidate_id; - } - } + candidate_addresses = {GetAccessAddress(*exception)}; #endif // defined(ARCH_CPU_X86_64) - if (!metadata_id.has_value()) { - if (seen_candidate_id) { - ReportHistogram(Crash_Allocator_PARTITIONALLOC, - GwpAsanCrashAnalysisResult:: - kErrorInvalidOrOutdatedLightweightMetadataIndex); - proto->set_missing_metadata(true); - proto->set_internal_error( - "The computed lightweight metadata index was invalid or outdated."); - return true; + for (auto candidate_address : candidate_addresses) { + auto candidate_id = + LightweightDetector::ExtractMetadataId(candidate_address); + if (!candidate_id.has_value()) { + continue; } + seen_candidate_id = true; + if (valid_state.HasLightweightMetadataForId(*candidate_id, + metadata_arr.get())) { + if (!metadata_id.has_value()) { + // It's the first time we see an ID with a matching valid slot. + metadata_id = candidate_id; + } else if (metadata_id != candidate_id) { + ReportHistogram(Crash_Allocator_PARTITIONALLOC, + GwpAsanCrashAnalysisResult:: + kErrorConflictingLightweightMetadataIds); + proto->set_missing_metadata(true); + proto->set_internal_error( + "Found conflicting lightweight metadata IDs."); + return true; + } + } + } + + if (!seen_candidate_id) { return false; } + if (!metadata_id.has_value()) { + ReportHistogram(Crash_Allocator_PARTITIONALLOC, + GwpAsanCrashAnalysisResult:: + kErrorInvalidOrOutdatedLightweightMetadataIndex); + proto->set_missing_metadata(true); + proto->set_internal_error( + "The computed lightweight metadata index was invalid or outdated."); + return true; + } + auto& metadata = valid_state.GetLightweightSlotMetadataById( *metadata_id, metadata_arr.get());
diff --git a/components/omnibox/browser/android/java/src/org/chromium/components/omnibox/AutocompleteMatchBuilder.java b/components/omnibox/browser/android/java/src/org/chromium/components/omnibox/AutocompleteMatchBuilder.java index 9481107..13c34d6 100644 --- a/components/omnibox/browser/android/java/src/org/chromium/components/omnibox/AutocompleteMatchBuilder.java +++ b/components/omnibox/browser/android/java/src/org/chromium/components/omnibox/AutocompleteMatchBuilder.java
@@ -55,8 +55,8 @@ public static AutocompleteMatchBuilder searchWithType(@OmniboxSuggestionType int type) { return new AutocompleteMatchBuilder(type) .setIsSearch(true) - .setDisplayText("Dummy Suggestion") - .setDescription("Dummy Description") + .setDisplayText("Placeholder Suggestion") + .setDescription("Placeholder Description") // Use either JUnitTest or actual GURL (depends on whether ShadowGURL is applied). .setUrl(new GURL(JUnitTestGURLs.SEARCH_URL)); }
diff --git a/components/optimization_guide/core/prediction_manager.cc b/components/optimization_guide/core/prediction_manager.cc index 9877731..bf5c219 100644 --- a/components/optimization_guide/core/prediction_manager.cc +++ b/components/optimization_guide/core/prediction_manager.cc
@@ -175,7 +175,10 @@ model_metadata.type_url() == "type.googleapis.com/" "google.internal.chrome.optimizationguide.v1." - "ClientSidePhishingModelMetadata"; + "ClientSidePhishingModelMetadata" || + model_metadata.type_url() == + "type.googleapis.com/" + "lens.prime.csc.VisualSearchModelMetadata"; } void RecordModelAvailableAtRegistration(
diff --git a/components/password_manager_strings.grdp b/components/password_manager_strings.grdp index 4cdf7c5..a0b9733 100644 --- a/components/password_manager_strings.grdp +++ b/components/password_manager_strings.grdp
@@ -54,6 +54,10 @@ <message name="IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE" desc="The text is shown in a popup that explains to the user why they are seeing a warning about leaked passwords. This is a stand-alone string and the only content of the popup dialog."> Chrome periodically checks your passwords against lists that have been published online. When doing this, your passwords and usernames are encrypted, so they can’t be read by anyone, including Google. </message> + <!-- TODO(crbug.com/1466971): Add Chromium counterpart string --> + <message name="IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE_UPDATED" desc="The text is shown in a popup that explains to the user why they are seeing a warning about leaked passwords. This is a stand-alone string and the only content of the popup dialog."> + When you use a password, Chrome warns you if it has been published online. When doing this, your passwords and usernames are encrypted, so they can’t be read by anyone, including Google. + </message> <message name="IDS_MANAGE_PASSWORDS_AUTO_SIGNIN_TITLE" desc="The title of the auto-signin toast."> Signing in as <ph name="username">$1<ex>chef@google.com</ex></ph> </message>
diff --git a/components/password_manager_strings_grdp/IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE_UPDATED.png.sha1 b/components/password_manager_strings_grdp/IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE_UPDATED.png.sha1 new file mode 100644 index 0000000..dd6be71 --- /dev/null +++ b/components/password_manager_strings_grdp/IDS_PASSWORD_MANAGER_LEAK_HELP_MESSAGE_UPDATED.png.sha1
@@ -0,0 +1 @@ +af4a782f07afb2382e7db9c0a8a060aea29c532b \ No newline at end of file
diff --git a/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc b/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc index 65e1892..96bf7ec 100644 --- a/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc +++ b/components/pdf/renderer/pdf_accessibility_tree_browsertest.cc
@@ -2431,21 +2431,6 @@ uint32_t pages_plus_status_node_count = doc_info_.page_count + 1u; ASSERT_EQ(pages_plus_status_node_count, root_node->children().size()); - ui::AXNode* page_node = root_node->children()[1]; - ASSERT_NE(nullptr, page_node); - ASSERT_EQ(ax::mojom::Role::kRegion, page_node->GetRole()); - ASSERT_EQ(1u, page_node->children().size()); - - ui::AXNode* paragraph_node = page_node->children()[0]; - ASSERT_NE(nullptr, paragraph_node); - ASSERT_EQ(ax::mojom::Role::kParagraph, paragraph_node->GetRole()); - ASSERT_EQ(1u, paragraph_node->children().size()); - - ui::AXNode* image_node = paragraph_node->children()[0]; - ASSERT_NE(nullptr, image_node); - ASSERT_EQ(ax::mojom::Role::kImage, image_node->GetRole()); - ASSERT_EQ(0u, image_node->children().size()); - PdfAccessibilityTree::PdfOcrService* ocr_service = pdf_accessibility_tree.CreateOcrService(); ASSERT_NE(nullptr, ocr_service); @@ -2454,6 +2439,21 @@ fake_annotator.BindNewPipeAndPassRemote()); for (uint32_t i = 0; i < doc_info_.page_count; ++i) { + ui::AXNode* page_node = root_node->children()[i + 1]; + ASSERT_NE(nullptr, page_node); + ASSERT_EQ(ax::mojom::Role::kRegion, page_node->GetRole()); + ASSERT_EQ(1u, page_node->children().size()); + + ui::AXNode* paragraph_node = page_node->children()[0]; + ASSERT_NE(nullptr, paragraph_node); + ASSERT_EQ(ax::mojom::Role::kParagraph, paragraph_node->GetRole()); + ASSERT_EQ(1u, paragraph_node->children().size()); + + ui::AXNode* image_node = paragraph_node->children()[0]; + ASSERT_NE(nullptr, image_node); + ASSERT_EQ(ax::mojom::Role::kImage, image_node->GetRole()); + ASSERT_EQ(0u, image_node->children().size()); + base::queue<PdfAccessibilityTree::PdfOcrRequest> requests; requests.emplace(image_node->id(), image, paragraph_node->id()); ocr_service->ScheduleOcrRequests(requests);
diff --git a/components/performance_manager/graph/process_node_impl_describer.cc b/components/performance_manager/graph/process_node_impl_describer.cc index abdd89b4..690cfc9 100644 --- a/components/performance_manager/graph/process_node_impl_describer.cc +++ b/components/performance_manager/graph/process_node_impl_describer.cc
@@ -92,7 +92,7 @@ if (process.IsValid()) { // These properties can only be accessed for valid processes. - ret.Set("os_priority", process.GetPriority()); + ret.Set("os_priority", process.GetOSPriority()); #if !BUILDFLAG(IS_APPLE) ret.Set("is_backgrounded", process.IsProcessBackgrounded()); #endif
diff --git a/components/printing/common/cloud_print_cdd_conversion.cc b/components/printing/common/cloud_print_cdd_conversion.cc index 2551b705..d2c57fe 100644 --- a/components/printing/common/cloud_print_cdd_conversion.cc +++ b/components/printing/common/cloud_print_cdd_conversion.cc
@@ -67,6 +67,14 @@ printer::Media ConvertPaperToMedia( const printing::PrinterSemanticCapsAndDefaults::Paper& paper) { + if (paper.SupportsCustomSize()) { + return printer::MediaBuilder() + .WithCustomName(paper.display_name(), paper.vendor_id()) + .WithSizeAndDefaultPrintableArea(paper.size_um()) + .WithMaxHeight(paper.max_height_um()) + .Build(); + } + gfx::Size paper_size = paper.size_um(); gfx::Rect paper_printable_area = paper.printable_area_um(); // When converting to Media, the size and printable area should have a larger
diff --git a/components/printing/common/cloud_print_cdd_conversion_unittest.cc b/components/printing/common/cloud_print_cdd_conversion_unittest.cc index c0dd396..4b7639b 100644 --- a/components/printing/common/cloud_print_cdd_conversion_unittest.cc +++ b/components/printing/common/cloud_print_cdd_conversion_unittest.cc
@@ -112,11 +112,9 @@ "width_microns": 6600 }, { "custom_display_name": "Custom", - "height_microns": 5080, - "imageable_area_bottom_microns": 0, - "imageable_area_left_microns": 0, - "imageable_area_right_microns": 2540, - "imageable_area_top_microns": 5080, + "is_continuous_feed": true, + "max_height_microns": 20000, + "min_height_microns": 5080, "width_microns": 2540 } ]})json"; @@ -190,11 +188,9 @@ "width_microns": 6600 }, { "custom_display_name": "Custom", - "height_microns": 5080, - "imageable_area_bottom_microns": 0, - "imageable_area_left_microns": 0, - "imageable_area_right_microns": 2540, - "imageable_area_top_microns": 5080, + "is_continuous_feed": true, + "max_height_microns": 20000, + "min_height_microns": 5080, "width_microns": 2540 } ]})json";
diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index ce00f9d..59c7a51 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc
@@ -83,6 +83,8 @@ #include "third_party/blink/public/web/web_view_client.h" #include "third_party/skia/include/core/SkCanvas.h" #include "ui/base/resource/resource_bundle.h" +#include "ui/gfx/geometry/rect_conversions.h" +#include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/geometry/size_f.h" #if BUILDFLAG(ENABLE_TAGGED_PDF) @@ -346,13 +348,15 @@ gfx::Size* page_size, gfx::Rect* content_area, gfx::Rect* canvas_area) { - *page_size = gfx::Size(page_layout.content_width + page_layout.margin_right + - page_layout.margin_left, - page_layout.content_height + page_layout.margin_top + - page_layout.margin_bottom); - *content_area = - gfx::Rect(page_layout.margin_left, page_layout.margin_top, - page_layout.content_width, page_layout.content_height); + // Note: Use {rect,size}_conversions code to avoid truncating float values. + float page_width = page_layout.content_width + page_layout.margin_left + + page_layout.margin_right; + float page_height = page_layout.content_height + page_layout.margin_top + + page_layout.margin_bottom; + *page_size = gfx::ToRoundedSize(gfx::SizeF(page_width, page_height)); + *content_area = gfx::ToEnclosedRect( + gfx::RectF(page_layout.margin_left, page_layout.margin_top, + page_layout.content_width, page_layout.content_height)); *canvas_area = params.display_header_footer ? gfx::Rect(*page_size) : *content_area; }
diff --git a/components/printing/test/print_render_frame_helper_browsertest.cc b/components/printing/test/print_render_frame_helper_browsertest.cc index a2d9ad9..76ba0427 100644 --- a/components/printing/test/print_render_frame_helper_browsertest.cc +++ b/components/printing/test/print_render_frame_helper_browsertest.cc
@@ -1163,16 +1163,14 @@ int expected_margin_right, bool expected_all_pages_have_custom_size, bool expected_all_pages_have_custom_orientation) { - EXPECT_NE(preview_ui()->page_layout(), nullptr); - EXPECT_EQ(expected_content_width, - preview_ui()->page_layout()->content_width); - EXPECT_EQ(expected_content_height, - preview_ui()->page_layout()->content_height); - EXPECT_EQ(expected_margin_top, preview_ui()->page_layout()->margin_top); - EXPECT_EQ(expected_margin_right, preview_ui()->page_layout()->margin_right); - EXPECT_EQ(expected_margin_left, preview_ui()->page_layout()->margin_left); - EXPECT_EQ(expected_margin_bottom, - preview_ui()->page_layout()->margin_bottom); + const mojom::PageSizeMargins* page_layout = preview_ui()->page_layout(); + ASSERT_TRUE(page_layout); + EXPECT_EQ(expected_content_width, page_layout->content_width); + EXPECT_EQ(expected_content_height, page_layout->content_height); + EXPECT_EQ(expected_margin_top, page_layout->margin_top); + EXPECT_EQ(expected_margin_right, page_layout->margin_right); + EXPECT_EQ(expected_margin_left, page_layout->margin_left); + EXPECT_EQ(expected_margin_bottom, page_layout->margin_bottom); EXPECT_EQ(expected_all_pages_have_custom_size, preview_ui()->all_pages_have_custom_size()); EXPECT_EQ(expected_all_pages_have_custom_orientation,
diff --git a/components/strictmode/android/java/src/org/chromium/components/strictmode/StrictModePolicyViolation.java b/components/strictmode/android/java/src/org/chromium/components/strictmode/StrictModePolicyViolation.java index 7f83b60..7e5f5a3 100644 --- a/components/strictmode/android/java/src/org/chromium/components/strictmode/StrictModePolicyViolation.java +++ b/components/strictmode/android/java/src/org/chromium/components/strictmode/StrictModePolicyViolation.java
@@ -4,7 +4,7 @@ package org.chromium.components.strictmode; -/** Dummy exception thrown for the custom death penalty. */ +/** Placeholder exception thrown for the custom death penalty. */ public final class StrictModePolicyViolation extends Error { public StrictModePolicyViolation(Violation v) { super(v.violationString());
diff --git a/components/ui_devtools/tracing_agent.cc b/components/ui_devtools/tracing_agent.cc index 09daaf10..e3cf37a6 100644 --- a/components/ui_devtools/tracing_agent.cc +++ b/components/ui_devtools/tracing_agent.cc
@@ -358,7 +358,7 @@ return; } - if (!categories.isJust() && !options.isJust()) { + if (!categories.has_value() && !options.has_value()) { callback->sendFailure( Response::InvalidParams("categories+options should be specified.")); return; @@ -366,7 +366,7 @@ did_initiate_recording_ = true; buffer_usage_reporting_interval_ = - buffer_usage_reporting_interval.fromMaybe(0); + buffer_usage_reporting_interval.value_or(0); // Since we want minimum changes to the devtools frontend, enable the // tracing categories for ui_devtools here. @@ -375,7 +375,7 @@ "timeline.frame,views,latency,toplevel," "benchmark,cc,viz,input,latency,gpu,rail,viz,ui"; trace_config_ = base::trace_event::TraceConfig(ui_devtools_categories, - options.fromMaybe("")); + options.value_or("")); StartTracing(std::move(callback)); }
diff --git a/components/ui_devtools/views/overlay_agent_views.cc b/components/ui_devtools/views/overlay_agent_views.cc index ce362fe9..213852e 100644 --- a/components/ui_devtools/views/overlay_agent_views.cc +++ b/components/ui_devtools/views/overlay_agent_views.cc
@@ -404,7 +404,7 @@ protocol::Response OverlayAgentViews::highlightNode( std::unique_ptr<protocol::Overlay::HighlightConfig> highlight_config, protocol::Maybe<int> node_id) { - return HighlightNode(node_id.fromJust()); + return HighlightNode(node_id.value()); } protocol::Response OverlayAgentViews::hideHighlight() {
diff --git a/components/ui_devtools/views/page_agent_views.cc b/components/ui_devtools/views/page_agent_views.cc index aedde4f..cfb8fea 100644 --- a/components/ui_devtools/views/page_agent_views.cc +++ b/components/ui_devtools/views/page_agent_views.cc
@@ -78,10 +78,11 @@ } protocol::Response PageAgentViews::reload(protocol::Maybe<bool> bypass_cache) { - if (!bypass_cache.isJust()) + if (!bypass_cache.has_value()) { return protocol::Response::Success(); + } - bool shift_pressed = bypass_cache.fromMaybe(false); + bool shift_pressed = bypass_cache.value_or(false); // Ctrl+Shift+R called to toggle widget lock. if (shift_pressed) {
diff --git a/components/viz/common/debugger/viz_debugger.gni b/components/viz/common/debugger/viz_debugger.gni index dffb933..3b8302d 100644 --- a/components/viz/common/debugger/viz_debugger.gni +++ b/components/viz/common/debugger/viz_debugger.gni
@@ -4,6 +4,8 @@ declare_args() { # Indicates if the Viz Debugger is enabled. This is disabled by default on - # official builds due to security and performance reasons. - use_viz_debugger = !is_official_build + # official builds due to security and performance reasons. test + # crbug/1466891 Fuchia threading model does not play well with the + # visual debugger multithreaded submission mechanism. + use_viz_debugger = !is_official_build && !is_fuchsia }
diff --git a/components/webapps/browser/installable/ml_installability_promoter.cc b/components/webapps/browser/installable/ml_installability_promoter.cc index 3e2cccb..237ec45f 100644 --- a/components/webapps/browser/installable/ml_installability_promoter.cc +++ b/components/webapps/browser/installable/ml_installability_promoter.cc
@@ -210,11 +210,14 @@ } GURL manifest_id; if (blink::IsEmptyManifest(manifest_)) { - manifest_id = web_contents()->GetLastCommittedURL().GetWithoutRef(); + manifest_id = site_url_.GetWithoutRef(); } else { - manifest_id = manifest_->id; + manifest_id = blink::GetIdFromManifest(*manifest_); + if (!manifest_id.is_valid()) { + manifest_id = site_url_.GetWithoutRef(); + } } - CHECK(manifest_id.is_valid()); + CHECK(manifest_id.is_valid()) << " invalid manifest_id: " << manifest_id; return manifest_id; }
diff --git a/content/architecture.dot b/content/architecture.dot deleted file mode 100644 index 4711d60e..0000000 --- a/content/architecture.dot +++ /dev/null
@@ -1,70 +0,0 @@ -digraph { - graph[bgcolor=transparent] - node[shape=plaintext] - - Embedder[label=< - <table border="1" cellborder="0"> - <tr> - <td port="left1" width="25"></td> - <td port="left2" width="25"></td> - <td port="center" width="200">Embedder</td> - <td port="right" width="50"></td> - </tr> - </table> - >] - Content[label=< - <table border="1" cellborder="0"> - <tr> - <td port="left1" width="30"></td> - <td port="left2" width="30"></td> - <td port="center" width="60">Content</td> - <td port="right" width="60"></td> - </tr> - </table> - >] - Embedder:center->Content:center[label="Content\nPublic API"] - - Blink[label=< - <table border="1" cellborder="0"> - <tr> - <td port="left" width="50"></td> - <td width="50">Blink</td> - <td port="right" width="50"></td> - </tr> - </table> - >] - - {rank=same net, V8} - net[label=< - <table border="1" cellborder="0"> - <tr><td>//net</td></tr> - </table> - >] - V8[label=< - <table border="1" cellborder="0"> - <tr><td>V8</td></tr> - </table> - >] - base[label=< - <table border="1" cellborder="0"> - <tr> - <td port="left1" width="25"></td> - <td port="left2" width="25"></td> - <td port="center" width="200">//base</td> - <td port="right" width="50"></td> - </tr> - </table> - >] - - Embedder:left1->base:left1 - Embedder:right->Blink:right[dir=both, label="Blink\nPublic API"] - Embedder:left2->net[dir=both] - - Content->base:center - Content:left1->net[dir=both] - Content:left2->V8[dir=both] - Content:right->Blink:left[dir=both] - Blink:left->V8[dir=both] - Blink->base:right - net->base:left2 -}
diff --git a/content/architecture.png b/content/architecture.png index 53e089d..4711da9 100644 --- a/content/architecture.png +++ b/content/architecture.png Binary files differ
diff --git a/content/browser/browsing_data/browsing_data_remover_impl.cc b/content/browser/browsing_data/browsing_data_remover_impl.cc index d1725fd..9f09090 100644 --- a/content/browser/browsing_data/browsing_data_remover_impl.cc +++ b/content/browser/browsing_data/browsing_data_remover_impl.cc
@@ -121,6 +121,7 @@ : browser_context_(browser_context), remove_mask_(0xffffffffffffffffull), origin_type_mask_(0xffffffffffffffffull), + storage_partition_config_(absl::nullopt), is_removing_(false) { DCHECK(browser_context_); } @@ -349,6 +350,7 @@ delete_end_ = delete_end; remove_mask_ = remove_mask; origin_type_mask_ = origin_type_mask; + storage_partition_config_ = filter_builder->GetStoragePartitionConfig(); failed_data_types_ = 0; // Record the combined deletion of cookies and cache. @@ -702,6 +704,15 @@ return origin_type_mask_; } +absl::optional<StoragePartitionConfig> +BrowsingDataRemoverImpl::GetLastUsedStoragePartitionConfigForTesting() { + return storage_partition_config_; +} + +uint64_t BrowsingDataRemoverImpl::GetPendingTaskCountForTesting() { + return task_queue_.size(); +} + BrowsingDataRemoverImpl::RemovalTask::RemovalTask( const base::Time& delete_begin, const base::Time& delete_end,
diff --git a/content/browser/browsing_data/browsing_data_remover_impl.h b/content/browser/browsing_data/browsing_data_remover_impl.h index b226e06..5d80a41 100644 --- a/content/browser/browsing_data/browsing_data_remover_impl.h +++ b/content/browser/browsing_data/browsing_data_remover_impl.h
@@ -92,6 +92,9 @@ const base::Time& GetLastUsedBeginTimeForTesting() override; uint64_t GetLastUsedRemovalMaskForTesting() override; uint64_t GetLastUsedOriginTypeMaskForTesting() override; + absl::optional<StoragePartitionConfig> + GetLastUsedStoragePartitionConfigForTesting() override; + uint64_t GetPendingTaskCountForTesting() override; void ClearClientHintCacheAndReply(const url::Origin& origin, base::OnceClosure callback); @@ -251,6 +254,11 @@ // From which types of origins should we remove data? uint64_t origin_type_mask_ = 0; + // The StoragePartition from which data should be removed, or the default + // if absent. + absl::optional<StoragePartitionConfig> storage_partition_config_ = + absl::nullopt; + std::vector<std::string> domains_for_deferred_cookie_deletion_; // True if Remove has been invoked.
diff --git a/content/browser/renderer_host/navigation_controller_impl.cc b/content/browser/renderer_host/navigation_controller_impl.cc index d140fb9f..af9f3a07 100644 --- a/content/browser/renderer_host/navigation_controller_impl.cc +++ b/content/browser/renderer_host/navigation_controller_impl.cc
@@ -1195,14 +1195,9 @@ RenderFrameHostImpl* initiator_rfh, absl::optional<blink::scheduler::TaskAttributionId> soft_navigation_heuristics_task_id) { - // If the renderer sent an out-of-bounds offset, cancel and notify the - // renderer. - if (!CanGoToOffset(offset)) { - initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled( - /*navigation_api_key=*/std::string(), - blink::mojom::TraverseCancelledReason::kNotFound); + // Note: This is actually reached in unit tests. + if (!CanGoToOffset(offset)) return; - } GoToIndex(GetIndexForOffset(offset), initiator_rfh, soft_navigation_heuristics_task_id,
diff --git a/content/browser/web_contents/web_contents_view_aura.cc b/content/browser/web_contents/web_contents_view_aura.cc index 18ad2b55..8a6fd2e 100644 --- a/content/browser/web_contents/web_contents_view_aura.cc +++ b/content/browser/web_contents/web_contents_view_aura.cc
@@ -374,12 +374,14 @@ WebContentsViewAura::OnPerformDropContext::OnPerformDropContext( RenderWidgetHostImpl* target_rwh, + std::unique_ptr<DropData> drop_data, DropMetadata drop_metadata, std::unique_ptr<ui::OSExchangeData> data, base::ScopedClosureRunner end_drag_runner, absl::optional<gfx::PointF> transformed_pt, gfx::PointF screen_pt) : target_rwh(target_rwh->GetWeakPtr()), + drop_data(std::move(drop_data)), drop_metadata(drop_metadata), data(std::move(data)), end_drag_runner(std::move(end_drag_runner)), @@ -394,21 +396,11 @@ #if BUILDFLAG(IS_WIN) // A web contents observer that watches for navigations while an async drop // operation is in progress during virtual file data retrieval and temp file -// creation. Navigations may cause completion of the drop to be disallowed. The -// class also serves to cache the drop parameters as they were at the beginning -// of the drop. This is needed for checking that the drop target is still valid -// when the async operation completes, and if so, passing the parameters on to -// the render widget host to complete the drop. +// creation. Navigations may cause completion of the drop to be disallowed. class WebContentsViewAura::AsyncDropNavigationObserver : public WebContentsObserver { public: - AsyncDropNavigationObserver(WebContents* watched_contents, - std::unique_ptr<DropData> drop_data, - base::ScopedClosureRunner end_drag_runner, - RenderWidgetHostImpl* target_rwh, - const gfx::PointF& client_pt, - const gfx::PointF& screen_pt, - int key_modifiers); + explicit AsyncDropNavigationObserver(WebContents* watched_contents); AsyncDropNavigationObserver(const AsyncDropNavigationObserver&) = delete; AsyncDropNavigationObserver& operator=(const AsyncDropNavigationObserver&) = @@ -421,41 +413,13 @@ // should disallow the drop? bool drop_allowed() const { return drop_allowed_; } - DropData* drop_data() const { return drop_data_.get(); } - RenderWidgetHostImpl* target_rwh() const { return target_rwh_.get(); } - const gfx::PointF& client_pt() const { return client_pt_; } - const gfx::PointF& screen_pt() const { return screen_pt_; } - int key_modifiers() const { return key_modifiers_; } - private: - bool drop_allowed_; - - // Data cached at the start of the drop operation and needed to complete the - // drop. - std::unique_ptr<DropData> drop_data_; - base::ScopedClosureRunner end_drag_runner_; - base::WeakPtr<RenderWidgetHostImpl> target_rwh_; - const gfx::PointF client_pt_; - const gfx::PointF screen_pt_; - const int key_modifiers_; + bool drop_allowed_ = true; }; WebContentsViewAura::AsyncDropNavigationObserver::AsyncDropNavigationObserver( - WebContents* watched_contents, - std::unique_ptr<DropData> drop_data, - base::ScopedClosureRunner end_drag_runner, - RenderWidgetHostImpl* target_rwh, - const gfx::PointF& client_pt, - const gfx::PointF& screen_pt, - int key_modifiers) - : WebContentsObserver(watched_contents), - drop_allowed_(true), - drop_data_(std::move(drop_data)), - end_drag_runner_(std::move(end_drag_runner)), - target_rwh_(target_rwh->GetWeakPtr()), - client_pt_(client_pt), - screen_pt_(screen_pt), - key_modifiers_(key_modifiers) {} + WebContents* watched_contents) + : WebContentsObserver(watched_contents) {} void WebContentsViewAura::AsyncDropNavigationObserver::DidFinishNavigation( NavigationHandle* navigation_handle) { @@ -792,8 +756,9 @@ // Get a list of virtual files for later retrieval when a drop is performed // (will return empty vector if there are any non-virtual files in the data // store). - if (ShouldIncludeVirtualFiles(*drop_data)) + if (ShouldIncludeVirtualFiles(*drop_data)) { data.GetVirtualFilenames(&drop_data->filenames); + } #endif base::Pickle pickle; @@ -991,7 +956,7 @@ } DropData* WebContentsViewAura::GetDropData() const { - return current_drop_data_.get(); + return current_drag_data_.get(); } gfx::Rect WebContentsViewAura::GetViewBounds() const { @@ -1406,8 +1371,8 @@ current_rwh_for_drag_ = target_rwh->GetWeakPtr(); current_rvh_for_drag_ = GetRenderViewHostID(web_contents_->GetRenderViewHost()); - current_drop_data_ = std::move(drop_data); - current_rwh_for_drag_->FilterDropData(current_drop_data_.get()); + current_drag_data_ = std::move(drop_data); + current_rwh_for_drag_->FilterDropData(current_drag_data_.get()); blink::DragOperationsMask op_mask = ConvertToDragOperationsMask(drop_metadata.source_operations); @@ -1419,27 +1384,28 @@ // another privileged WebContents. // Do not allow dragging privileged WebContents to // non-priviledged WebContents or vice versa. - if (current_drop_data_->is_from_privileged != + if (current_drag_data_->is_from_privileged != (delegate && delegate->IsPrivileged())) { return false; } // Give the delegate an opportunity to cancel the drag - if (delegate && !delegate->CanDragEnter(web_contents_, - *current_drop_data_.get(), op_mask)) + if (delegate && !delegate->CanDragEnter( + web_contents_, *current_drag_data_.get(), op_mask)) { return false; + } return true; }; if (!allow_drag()) { - current_drop_data_ = nullptr; + current_drag_data_ = nullptr; return; } DCHECK(transformed_pt.has_value()); gfx::PointF screen_pt(display::Screen::GetScreen()->GetCursorScreenPoint()); current_rwh_for_drag_->DragTargetDragEnter( - *current_drop_data_, transformed_pt.value(), screen_pt, op_mask, + *current_drag_data_, transformed_pt.value(), screen_pt, op_mask, ui::EventFlagsToWebEventModifiers(drop_metadata.flags), base::DoNothing()); @@ -1518,7 +1484,7 @@ transformed_pt); } - if (!current_drop_data_) { + if (!current_drag_data_) { return; } @@ -1570,24 +1536,69 @@ void WebContentsViewAura::CompleteDragExit() { drag_in_progress_ = false; - if (web_contents_->IsBeingDestroyed() || - current_rvh_for_drag_ != - GetRenderViewHostID(web_contents_->GetRenderViewHost()) || - !current_drop_data_) { - return; + if (current_rwh_for_drag_ && !web_contents_->IsBeingDestroyed() && + current_rvh_for_drag_ == + GetRenderViewHostID(web_contents_->GetRenderViewHost())) { + current_rwh_for_drag_->DragTargetDragLeave(gfx::PointF(), gfx::PointF()); } if (current_rwh_for_drag_) { - current_rwh_for_drag_->DragTargetDragLeave(gfx::PointF(), gfx::PointF()); current_rwh_for_drag_.reset(); } - if (drag_dest_delegate_) + if (drag_dest_delegate_) { drag_dest_delegate_->OnDragLeave(); + } - current_drop_data_.reset(); + current_drag_data_.reset(); } +// PerformDropCallback() is called once the user releases the mouse button +// over this window. This function completes the drop if possible. A drop +// may not be possible for example if the RWH has changed since the user's drag +// entered this view. +// +// Performing the drop is an asynchronous operation that involves the RWH and +// the web contents delegate. A drop is not considered done by this view until +// all the asynchronous operations complete. +// +// Assuming that a drop is allowed, an instance of OnPerformDropContext is +// created to keep track of the drop state during the various async operations. +// This context is saved in the `drop_context` argument passed around to the +// various methods. The data being dropped, stored in `current_drag_data_`, is +// moved into the context. +// +// On the Windows platform, if the drop includes virtuals files (for example, +// dropping an email attachment dragged out of the native Outlook application) +// these are first converted into temp real files using the async function +// GetVirtualFilesAsTempFiles(). The callback OnGotVirtualFilesAsTempFiles() +// uses AsyncDropTempFileDeleter to make sure the temp files are deleted once +// the drop completes. Other platform don't have handling of virtual files. +// +// Next, the delegate is given a chance to handle the dropped data in an async +// manner. The delegate may perform additional checks on the dropped data, +// may filter that data according to specific criteria, and may even block the +// drop altogether. For example, some enterprise policies may block +// sensitive data from being dropped on unsanctioned web pages. This step is +// kicked off by calling DelegateOnPerformDrop() and the async response is +// handled by GotModifiedDropDataFromDelegate(). In tests it's possible that +// no delegate exists, in which case FinishOnPerformDrop() is called directly. +// +// GotModifiedDropDataFromDelegate() is called only when a delegate exists and +// processes the result of the delegate's handling of the dropped data. +// Assuming the delegate allows the drop, the dropped data in `drop_context` +// is updated and FinishOnPerformDrop() is called. +// +// FinishOnPerformDrop() calls CompleteDrop() to send the dropped data to +// the RWH. At this point the drop is considered completed from this view's +// point of view. +// +// Note that many of the methods above are callback to async operations, +// like this method itself, OnGotVirtualFilesAsTempFiles(), +// GotModifiedDropDataFromDelegate(). Therefore these methods begin with +// similar checks to make sure the drop is still allowed. For example, checks +// to make sure the target RWH has not changed. See IsValidDragTarget() for +// details. void WebContentsViewAura::PerformDropCallback( DropMetadata drop_metadata, std::unique_ptr<ui::OSExchangeData> data, @@ -1617,37 +1628,73 @@ transformed_pt); } - if (!current_drop_data_) + // `current_drag_data_` is set in DragEnteredCallback() when the user begins + // to drag over this view and the drag is allowed. It's possible after the + // call to DragEnteredCallback() above that this member becomes null + // indicating that the drop should not happen. + if (!current_drag_data_) { return; + } - OnPerformDropContext context(target_rwh, drop_metadata, std::move(data), - std::move(end_drag_runner), transformed_pt, - screen_pt); + OnPerformDropContext drop_context = OnPerformDropContext( + target_rwh, std::move(current_drag_data_), drop_metadata, std::move(data), + std::move(end_drag_runner), transformed_pt, screen_pt); + +#if BUILDFLAG(IS_WIN) + if (ShouldIncludeVirtualFiles(*drop_context.drop_data) && + drop_context.data->HasVirtualFilenames()) { + // Asynchronously retrieve the actual content of any virtual files now (this + // step is not needed for "real" files already on the file system, e.g. + // those dropped on Chromium from the desktop). When all content has been + // written to temporary files, the OnGotVirtualFilesAsTempFiles + // callback will be invoked and the drop communicated to the renderer + // process. + async_drop_navigation_observer_ = + std::make_unique<AsyncDropNavigationObserver>(web_contents_); + ui::OSExchangeData* data_ptr = drop_context.data.get(); + data_ptr->GetVirtualFilesAsTempFiles(base::BindOnce( + &WebContentsViewAura::OnGotVirtualFilesAsTempFiles, + weak_ptr_factory_.GetWeakPtr(), std::move(drop_context))); + return; + } +#endif + + DelegateOnPerformDrop(std::move(drop_context)); +} + +void WebContentsViewAura::DelegateOnPerformDrop( + OnPerformDropContext drop_context) { // |delegate_| may be null in unit tests. + // TODO(crbug.com/1459352): Tests should use a delegate. if (delegate_) { + auto* drop_data_ptr = drop_context.drop_data.get(); delegate_->OnPerformDrop( - *current_drop_data_, - base::BindOnce(&WebContentsViewAura::FinishOnPerformDropCallback, - weak_ptr_factory_.GetWeakPtr(), std::move(context))); + *drop_data_ptr, + base::BindOnce(&WebContentsViewAura::GotModifiedDropDataFromDelegate, + weak_ptr_factory_.GetWeakPtr(), + std::move(drop_context))); } else { - FinishOnPerformDrop(std::move(context)); + FinishOnPerformDrop(std::move(drop_context)); } } -void WebContentsViewAura::FinishOnPerformDropCallback( - OnPerformDropContext context, +void WebContentsViewAura::GotModifiedDropDataFromDelegate( + OnPerformDropContext drop_context, absl::optional<DropData> drop_data) { // This is possibly an async callback. Make sure the RWH is still valid. - if (!context.target_rwh || !IsValidDragTarget(context.target_rwh.get())) + if (!drop_context.target_rwh || + !IsValidDragTarget(drop_context.target_rwh.get())) { return; + } if (!drop_data.has_value()) { if (!drop_callback_for_testing_.is_null()) { const int key_modifiers = - ui::EventFlagsToWebEventModifiers(context.drop_metadata.flags); + ui::EventFlagsToWebEventModifiers(drop_context.drop_metadata.flags); std::move(drop_callback_for_testing_) - .Run(context.target_rwh.get(), *current_drop_data_, - context.transformed_pt.value(), context.screen_pt, key_modifiers, + .Run(drop_context.target_rwh.get(), *drop_context.drop_data, + drop_context.transformed_pt.value(), drop_context.screen_pt, + key_modifiers, /*drop_allowed=*/false); } @@ -1657,51 +1704,17 @@ return; } - *current_drop_data_ = std::move(drop_data.value()); - FinishOnPerformDrop(std::move(context)); + *drop_context.drop_data = std::move(drop_data.value()); + FinishOnPerformDrop(std::move(drop_context)); } -void WebContentsViewAura::FinishOnPerformDrop(OnPerformDropContext context) { +void WebContentsViewAura::FinishOnPerformDrop( + OnPerformDropContext drop_context) { const int key_modifiers = - ui::EventFlagsToWebEventModifiers(context.drop_metadata.flags); - // This is possibly an async callback. Make sure the RWH is still valid. - if (!context.target_rwh || !IsValidDragTarget(context.target_rwh.get())) - return; - -#if BUILDFLAG(IS_WIN) - if (ShouldIncludeVirtualFiles(*current_drop_data_) && - context.data->HasVirtualFilenames()) { - // Asynchronously retrieve the actual content of any virtual files now (this - // step is not needed for "real" files already on the file system, e.g. - // those dropped on Chromium from the desktop). When all content has been - // written to temporary files, the OnGotVirtualFilesAsTempFiles - // callback will be invoked and the drop communicated to the renderer - // process. - auto callback = - base::BindOnce(&WebContentsViewAura::OnGotVirtualFilesAsTempFiles, - weak_ptr_factory_.GetWeakPtr()); - - // GetVirtualFilesAsTempFiles will immediately return false if there are no - // virtual files to retrieve (all items are folders e.g.) and no callback - // will be received. - if (context.data->GetVirtualFilesAsTempFiles(std::move(callback))) { - // Cache the parameters as they were at the time of the drop. This is - // needed for checking that the drop target is still valid when the async - // operation completes. - async_drop_navigation_observer_ = - std::make_unique<AsyncDropNavigationObserver>( - web_contents_, std::move(current_drop_data_), - std::move(context.end_drag_runner), context.target_rwh.get(), - context.transformed_pt.value(), context.screen_pt, key_modifiers); - return; - } - } - -#endif - CompleteDrop(context.target_rwh.get(), *current_drop_data_, - context.transformed_pt.value(), context.screen_pt, + ui::EventFlagsToWebEventModifiers(drop_context.drop_metadata.flags); + CompleteDrop(drop_context.target_rwh.get(), *drop_context.drop_data, + drop_context.transformed_pt.value(), drop_context.screen_pt, key_modifiers); - current_drop_data_.reset(); } aura::client::DragDropDelegate::DropCallback @@ -1725,8 +1738,9 @@ target_rwh->DragTargetDrop(drop_data, client_pt, screen_pt, key_modifiers, base::DoNothing()); - if (drag_dest_delegate_) + if (drag_dest_delegate_) { drag_dest_delegate_->OnDrop(); + } if (!drop_callback_for_testing_.is_null()) { std::move(drop_callback_for_testing_) @@ -1759,60 +1773,62 @@ #if BUILDFLAG(IS_WIN) void WebContentsViewAura::OnGotVirtualFilesAsTempFiles( + OnPerformDropContext drop_context, const std::vector<std::pair<base::FilePath, base::FilePath>>& filepaths_and_names) { - DCHECK(!filepaths_and_names.empty()); - - if (!async_drop_navigation_observer_) + if (!async_drop_navigation_observer_) { return; + } - std::unique_ptr<AsyncDropNavigationObserver> drop_observer( - std::move(async_drop_navigation_observer_)); + if (!filepaths_and_names.empty()) { + std::unique_ptr<AsyncDropNavigationObserver> drop_observer( + std::move(async_drop_navigation_observer_)); - RenderWidgetHostImpl* target_rwh = drop_observer->target_rwh(); - DropData* drop_data = drop_observer->drop_data(); + RenderWidgetHostImpl* target_rwh = drop_context.target_rwh.get(); - // Security check--don't allow the drop if a navigation occurred since the - // drop was initiated or the render widget host has changed or it is not a - // valid target. - if (!drop_observer->drop_allowed() || - !(target_rwh && target_rwh == current_rwh_for_drag_.get() && - IsValidDragTarget(target_rwh))) { - // Signal test code that the drop is disallowed - if (!drop_callback_for_testing_.is_null()) { - std::move(drop_callback_for_testing_) - .Run(target_rwh, *drop_data, drop_observer->client_pt(), - drop_observer->screen_pt(), drop_observer->key_modifiers(), - drop_observer->drop_allowed()); + // Security check--don't allow the drop if a navigation occurred since the + // drop was initiated or the render widget host has changed or it is not a + // valid target. + if (!drop_observer->drop_allowed() || + !(target_rwh && target_rwh == current_rwh_for_drag_.get() && + IsValidDragTarget(target_rwh))) { + // Signal test code that the drop is disallowed. + if (!drop_callback_for_testing_.is_null()) { + std::move(drop_callback_for_testing_) + .Run(target_rwh, *drop_context.drop_data, + drop_context.transformed_pt.value(), drop_context.screen_pt, + drop_context.drop_metadata.flags, + drop_observer->drop_allowed()); + } + + CompleteDragExit(); + return; } - return; + // The vector of filenames will still have items added during dragenter + // (script is allowed to enumerate the files in the data store but not + // retrieve the file contents in dragenter). But the temp file path in the + // FileInfo structs will just be a placeholder. Clear out the vector before + // replacing it with FileInfo structs that have the paths to the retrieved + // file contents. + drop_context.drop_data->filenames.clear(); + + // Ensure we have temp file deleter. + if (!async_drop_temp_file_deleter_) { + async_drop_temp_file_deleter_ = + std::make_unique<AsyncDropTempFileDeleter>(); + } + + for (const auto& filepath_and_name : filepaths_and_names) { + drop_context.drop_data->filenames.push_back( + ui::FileInfo(filepath_and_name.first, filepath_and_name.second)); + + // Make sure the temp file eventually gets cleaned up. + async_drop_temp_file_deleter_->RegisterFile(filepath_and_name.first); + } } - // The vector of filenames will still have items added during dragenter - // (script is allowed to enumerate the files in the data store but not - // retrieve the file contents in dragenter). But the temp file path in the - // FileInfo structs will just be a placeholder. Clear out the vector before - // replacing it with FileInfo structs that have the paths to the retrieved - // file contents. - drop_data->filenames.clear(); - - // Ensure we have temp file deleter. - if (!async_drop_temp_file_deleter_) { - async_drop_temp_file_deleter_ = - std::make_unique<AsyncDropTempFileDeleter>(); - } - - for (const auto& filepath_and_name : filepaths_and_names) { - drop_data->filenames.push_back( - ui::FileInfo(filepath_and_name.first, filepath_and_name.second)); - - // Make sure the temp file eventually gets cleaned up. - async_drop_temp_file_deleter_->RegisterFile(filepath_and_name.first); - } - - CompleteDrop(target_rwh, *drop_data, drop_observer->client_pt(), - drop_observer->screen_pt(), drop_observer->key_modifiers()); + DelegateOnPerformDrop(std::move(drop_context)); } #endif
diff --git a/content/browser/web_contents/web_contents_view_aura.h b/content/browser/web_contents/web_contents_view_aura.h index 145559f8..71d6c593 100644 --- a/content/browser/web_contents/web_contents_view_aura.h +++ b/content/browser/web_contents/web_contents_view_aura.h
@@ -100,15 +100,19 @@ // cleared out once PerformDropCallback() returns. struct CONTENT_EXPORT OnPerformDropContext { OnPerformDropContext(RenderWidgetHostImpl* target_rwh, + std::unique_ptr<DropData> drop_data, DropMetadata drop_metadata, std::unique_ptr<ui::OSExchangeData> data, base::ScopedClosureRunner end_drag_runner, absl::optional<gfx::PointF> transformed_pt, gfx::PointF screen_pt); + OnPerformDropContext(const OnPerformDropContext& other) = delete; OnPerformDropContext(OnPerformDropContext&& other); + OnPerformDropContext& operator=(const OnPerformDropContext& other) = delete; ~OnPerformDropContext(); base::WeakPtr<RenderWidgetHostImpl> target_rwh; + std::unique_ptr<DropData> drop_data; DropMetadata drop_metadata; std::unique_ptr<ui::OSExchangeData> data; base::ScopedClosureRunner end_drag_runner; @@ -284,11 +288,11 @@ void CompleteDragExit(); // Called from PerformDropCallback() to finish processing the drop. - // The override with `drop_data` updates `current_drop_data_` before + // The override with `drop_data` updates `current_drag_data_` before // completing the drop. - void FinishOnPerformDrop(OnPerformDropContext context); - void FinishOnPerformDropCallback(OnPerformDropContext context, - absl::optional<DropData> drop_data); + void FinishOnPerformDrop(OnPerformDropContext drop_context); + void GotModifiedDropDataFromDelegate(OnPerformDropContext drop_context, + absl::optional<DropData> drop_data); // Completes a drop operation by communicating the drop data to the renderer // process. @@ -325,6 +329,7 @@ #if BUILDFLAG(IS_WIN) // Callback for asynchronous retrieval of virtual files. void OnGotVirtualFilesAsTempFiles( + OnPerformDropContext drop_context, const std::vector<std::pair</*temp path*/ base::FilePath, /*display name*/ base::FilePath>>& filepaths_and_names); @@ -337,6 +342,10 @@ #endif DropCallbackForTesting drop_callback_for_testing_; + // Calls the delegate's OnPerformDrop() if a delegate is present, otherwise + // finishes performing the drop by calling FinishOnPerformDrop(). + void DelegateOnPerformDrop(OnPerformDropContext drop_context); + // If this callback is initialized it must be run after the drop operation is // done to send dragend event in EndDrag function. base::ScopedClosureRunner end_drag_runner_; @@ -352,7 +361,11 @@ ui::mojom::DragOperation current_drag_op_; - std::unique_ptr<DropData> current_drop_data_; + // This member holds the dropped data from the drag enter phase to the end + // of the drop. A drop may end if the user releases the mouse button over + // the view, if the cursor moves off the view, or some other events occurs + // like a change in the RWH. This member is null when no drop is happening. + std::unique_ptr<DropData> current_drag_data_; raw_ptr<WebDragDestDelegate> drag_dest_delegate_;
diff --git a/content/browser/web_contents/web_contents_view_aura_unittest.cc b/content/browser/web_contents/web_contents_view_aura_unittest.cc index f70ef71..161e937 100644 --- a/content/browser/web_contents/web_contents_view_aura_unittest.cc +++ b/content/browser/web_contents/web_contents_view_aura_unittest.cc
@@ -165,7 +165,7 @@ aura::Window* GetNativeView() { return web_contents()->GetNativeView(); } void CheckDropData(WebContentsViewAura* view) const { - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); ASSERT_NE(nullptr, drop_complete_data_); EXPECT_TRUE(drop_complete_data_->drop_allowed); EXPECT_EQ(view->current_rwh_for_drag_.get(), @@ -295,26 +295,26 @@ ui::DragDropTypes::DRAG_COPY); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // By design, Linux implementations return an empty string if file data // is also present. - EXPECT_TRUE(!view->current_drop_data_->text || - view->current_drop_data_->text->empty()); + EXPECT_TRUE(!view->current_drag_data_->text || + view->current_drag_data_->text->empty()); #else - EXPECT_EQ(string_data, view->current_drop_data_->text); + EXPECT_EQ(string_data, view->current_drag_data_->text); #endif // FileContents should be ignored when Filenames exists // (https://crbug.com/1251482). - EXPECT_FALSE(view->current_drop_data_->file_contents_source_url.is_valid()); - EXPECT_TRUE(view->current_drop_data_->file_contents.empty()); + EXPECT_FALSE(view->current_drag_data_->file_contents_source_url.is_valid()); + EXPECT_TRUE(view->current_drag_data_->file_contents.empty()); std::vector<ui::FileInfo> retrieved_file_infos = - view->current_drop_data_->filenames; + view->current_drag_data_->filenames; ASSERT_EQ(test_file_infos.size(), retrieved_file_infos.size()); for (size_t i = 0; i < retrieved_file_infos.size(); i++) { EXPECT_EQ(test_file_infos[i].path, retrieved_file_infos[i].path); @@ -393,24 +393,24 @@ ui::DragDropTypes::DRAG_COPY); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // By design, Linux implementations return an empty string if file data // is also present. - EXPECT_TRUE(!view->current_drop_data_->text || - view->current_drop_data_->text->empty()); + EXPECT_TRUE(!view->current_drag_data_->text || + view->current_drag_data_->text->empty()); #else - EXPECT_EQ(string_data, view->current_drop_data_->text); + EXPECT_EQ(string_data, view->current_drag_data_->text); #endif #if BUILDFLAG(IS_CHROMEOS_ASH) // CHROMEOS_ASH always returns false for DidOriginateFromRenderer(). - ASSERT_FALSE(view->current_drop_data_->filenames.empty()); + ASSERT_FALSE(view->current_drag_data_->filenames.empty()); #else - ASSERT_TRUE(view->current_drop_data_->filenames.empty()); + ASSERT_TRUE(view->current_drag_data_->filenames.empty()); #endif // Simulate drop. @@ -489,20 +489,20 @@ ui::DragDropTypes::DRAG_COPY); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); - EXPECT_EQ(base::ASCIIToUTF16(url_spec), *view->current_drop_data_->text); - EXPECT_EQ(url_spec, view->current_drop_data_->url); - EXPECT_EQ(url_title, view->current_drop_data_->url_title); - EXPECT_TRUE(view->current_drop_data_->filenames.empty()); - EXPECT_EQ(file_contents, view->current_drop_data_->file_contents); - EXPECT_TRUE(view->current_drop_data_->file_contents_image_accessible); - EXPECT_EQ(source_url, view->current_drop_data_->file_contents_source_url); + EXPECT_EQ(base::ASCIIToUTF16(url_spec), *view->current_drag_data_->text); + EXPECT_EQ(url_spec, view->current_drag_data_->url); + EXPECT_EQ(url_title, view->current_drag_data_->url_title); + EXPECT_TRUE(view->current_drag_data_->filenames.empty()); + EXPECT_EQ(file_contents, view->current_drag_data_->file_contents); + EXPECT_TRUE(view->current_drag_data_->file_contents_image_accessible); + EXPECT_EQ(source_url, view->current_drag_data_->file_contents_source_url); EXPECT_EQ(FILE_PATH_LITERAL("jpg"), - view->current_drop_data_->file_contents_filename_extension); - EXPECT_EQ("", view->current_drop_data_->file_contents_content_disposition); + view->current_drag_data_->file_contents_filename_extension); + EXPECT_EQ("", view->current_drag_data_->file_contents_content_disposition); // Simulate drop. auto callback = base::BindOnce(&WebContentsViewAuraTest::OnDropComplete, @@ -561,15 +561,15 @@ ui::DragDropTypes::DRAG_COPY); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); - EXPECT_EQ(string_data, view->current_drop_data_->text); + EXPECT_EQ(string_data, view->current_drag_data_->text); const base::FilePath path_placeholder(FILE_PATH_LITERAL("temp.tmp")); std::vector<ui::FileInfo> retrieved_file_infos = - view->current_drop_data_->filenames; + view->current_drag_data_->filenames; ASSERT_EQ(test_filenames_and_contents.size(), retrieved_file_infos.size()); for (size_t i = 0; i < retrieved_file_infos.size(); i++) { EXPECT_EQ(test_filenames_and_contents[i].first, @@ -648,13 +648,13 @@ ui::DragDropTypes::DRAG_COPY); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); - EXPECT_EQ(string_data, view->current_drop_data_->text); + EXPECT_EQ(string_data, view->current_drag_data_->text); - ASSERT_TRUE(view->current_drop_data_->filenames.empty()); + ASSERT_TRUE(view->current_drag_data_->filenames.empty()); // Simulate drop (completes asynchronously since virtual file data is // present). @@ -700,19 +700,19 @@ ui::DragDropTypes::DRAG_COPY); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); - EXPECT_EQ(url_spec, view->current_drop_data_->url); - EXPECT_EQ(url_title, view->current_drop_data_->url_title); + EXPECT_EQ(url_spec, view->current_drag_data_->url); + EXPECT_EQ(url_title, view->current_drag_data_->url_title); // Virtual files should not have been retrieved if url data present. - EXPECT_TRUE(view->current_drop_data_->filenames.empty()); + EXPECT_TRUE(view->current_drag_data_->filenames.empty()); // Shortcut *.url file contents created by SetURL() should be ignored // (https://crbug.com/1274395). - EXPECT_TRUE(view->current_drop_data_->file_contents_source_url.is_empty()); - EXPECT_TRUE(view->current_drop_data_->file_contents.empty()); + EXPECT_TRUE(view->current_drag_data_->file_contents_source_url.is_empty()); + EXPECT_TRUE(view->current_drag_data_->file_contents.empty()); // Simulate drop (completes asynchronously since virtual file data is // present). @@ -783,9 +783,9 @@ ui::DropTargetEvent event(*data.get(), kClientPt, kScreenPt, ui::DragDropTypes::DRAG_MOVE); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_EQ(nullptr, view->current_drop_data_); + ASSERT_EQ(nullptr, view->current_drag_data_); } TEST_F(WebContentsViewAuraTest, @@ -798,9 +798,9 @@ ui::DropTargetEvent event(*data.get(), kClientPt, kScreenPt, ui::DragDropTypes::DRAG_MOVE); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_NE(nullptr, view->current_drop_data_); + ASSERT_NE(nullptr, view->current_drag_data_); } TEST_F(WebContentsViewAuraTest, @@ -812,9 +812,9 @@ ui::DropTargetEvent event(*data.get(), kClientPt, kScreenPt, ui::DragDropTypes::DRAG_MOVE); // Simulate drag enter. - EXPECT_EQ(nullptr, view->current_drop_data_); + EXPECT_EQ(nullptr, view->current_drag_data_); view->OnDragEntered(event); - ASSERT_EQ(nullptr, view->current_drop_data_); + ASSERT_EQ(nullptr, view->current_drag_data_); } TEST_F(WebContentsViewAuraTest, StartDragFromPrivilegedWebContents) {
diff --git a/content/public/browser/browsing_data_remover.h b/content/public/browser/browsing_data_remover.h index 5110512..067e45f 100644 --- a/content/public/browser/browsing_data_remover.h +++ b/content/public/browser/browsing_data_remover.h
@@ -10,6 +10,7 @@ #include "base/functional/callback_forward.h" #include "base/time/time.h" #include "build/build_config.h" +#include "third_party/abseil-cpp/absl/types/optional.h" namespace storage { class SpecialStoragePolicy; @@ -23,6 +24,7 @@ class BrowsingDataFilterBuilder; class BrowsingDataRemoverDelegate; +class StoragePartitionConfig; //////////////////////////////////////////////////////////////////////////////// // BrowsingDataRemover is responsible for removing data related to browsing: @@ -285,6 +287,9 @@ virtual const base::Time& GetLastUsedBeginTimeForTesting() = 0; virtual uint64_t GetLastUsedRemovalMaskForTesting() = 0; virtual uint64_t GetLastUsedOriginTypeMaskForTesting() = 0; + virtual absl::optional<StoragePartitionConfig> + GetLastUsedStoragePartitionConfigForTesting() = 0; + virtual uint64_t GetPendingTaskCountForTesting() = 0; }; } // namespace content
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 754e5329d..6df5a24a 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -51,6 +51,13 @@ owner_whitelist_group: "project-chromium-robot-committers" } builders { + name: "chrome/try/chromeos-betty-pi-arc-cfi-thin-lto-chrome" + includable_only: true + result_visibility: COMMENT_LEVEL_RESTRICTED + owner_whitelist_group: "googlers" + owner_whitelist_group: "project-chromium-robot-committers" + } + builders { name: "chrome/try/chromeos-betty-pi-arc-chrome" includable_only: true result_visibility: COMMENT_LEVEL_RESTRICTED
diff --git a/infra/config/subprojects/chrome/try.star b/infra/config/subprojects/chrome/try.star index a89c1fb..cd708a24 100644 --- a/infra/config/subprojects/chrome/try.star +++ b/infra/config/subprojects/chrome/try.star
@@ -85,6 +85,10 @@ ) chrome_internal_verifier( + builder = "chromeos-betty-pi-arc-cfi-thin-lto-chrome", +) + +chrome_internal_verifier( builder = "chromeos-betty-pi-arc-chrome", )
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm index ca1a7753..7249020 100644 --- a/ios/chrome/browser/flags/about_flags.mm +++ b/ios/chrome/browser/flags/about_flags.mm
@@ -963,9 +963,6 @@ FEATURE_WITH_PARAMS_VALUE_TYPE(commerce::kCommercePriceTracking, commerce::kCommercePriceTrackingVariations, "CommercePriceTracking")}, - {"web-feed-ios", flag_descriptions::kEnableWebChannelsName, - flag_descriptions::kEnableWebChannelsDescription, flags_ui::kOsIos, - FEATURE_VALUE_TYPE(kEnableWebChannels)}, {"ntp-view-hierarchy-repair", flag_descriptions::kNTPViewHierarchyRepairName, flag_descriptions::kNTPViewHierarchyRepairDescription, flags_ui::kOsIos, @@ -1593,6 +1590,13 @@ flag_descriptions::kIOSLensUseDirectUploadName, flag_descriptions::kIOSLensUseDirectUploadDescription, flags_ui::kOsIos, FEATURE_VALUE_TYPE(kIOSLensUseDirectUpload)}, + {"autofill-enable-payments-mandatory-reauth-on-bling", + flag_descriptions::kAutofillEnablePaymentsMandatoryReauthOnBlingName, + flag_descriptions:: + kAutofillEnablePaymentsMandatoryReauthOnBlingDescription, + flags_ui::kOsIos, + FEATURE_VALUE_TYPE( + autofill::features::kAutofillEnablePaymentsMandatoryReauthOnBling)}, }; bool SkipConditionalFeatureEntry(const flags_ui::FeatureEntry& entry) {
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc index eeb58962..fa1d10a5 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.cc
@@ -61,6 +61,14 @@ "When enabled, card product images (instead of network icons) will be " "shown in Payments Autofill UI."; +const char kAutofillEnablePaymentsMandatoryReauthOnBlingName[] = + "Enable mandatory re-auth for payments autofill on Bling"; +const char kAutofillEnablePaymentsMandatoryReauthOnBlingDescription[] = + "When this and the kAutofillEnablePaymentsMandatoryReauth are both " + "enabled, in use-cases where we would not have triggered any user-visible " + "authentication to autofill payment methods, we will trigger a device " + "authentication a device authentication on Bling."; + const char kAutofillEnableRankingFormulaAddressProfilesName[] = "Enable new Autofill suggestion ranking formula for address profiles"; const char kAutofillEnableRankingFormulaAddressProfilesDescription[] = @@ -475,11 +483,6 @@ "is experimental and is used only for dogfooding, and only for users who " "are signed in and have Chrome Sync enabled."; -const char kEnableWebChannelsName[] = "Enable WebFeed"; -const char kEnableWebChannelsDescription[] = - "Enable folowing content from web and display Following feed on NTP based " - "on sites that users followed."; - const char kTailoredSecurityIntegrationName[] = "Enable Tailored Security Integration"; const char kTailoredSecurityIntegrationDescription[] =
diff --git a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h index 3cffaaa..7be806502 100644 --- a/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h +++ b/ios/chrome/browser/flags/ios_chrome_flag_descriptions.h
@@ -55,6 +55,11 @@ extern const char kAutofillEnableCardArtImageName[]; extern const char kAutofillEnableCardArtImageDescription[]; +// Title and description for the flag to control whether the autofill payments +// mandatory reauth feature is enabled on Bling. +extern const char kAutofillEnablePaymentsMandatoryReauthOnBlingName[]; +extern const char kAutofillEnablePaymentsMandatoryReauthOnBlingDescription[]; + // Title and description for the flag to control the new autofill suggestion // ranking formula for address profiles. extern const char kAutofillEnableRankingFormulaAddressProfilesName[]; @@ -406,11 +411,6 @@ extern const char kEnableVariationsGoogleGroupFilteringName[]; extern const char kEnableVariationsGoogleGroupFilteringDescription[]; -// Title and description for the flag to introduce following web channels on -// Chrome iOS. -extern const char kEnableWebChannelsName[]; -extern const char kEnableWebChannelsDescription[]; - // Title and description for the flag to enable feed background refresh. extern const char kFeedBackgroundRefreshName[]; extern const char kFeedBackgroundRefreshDescription[];
diff --git a/ios/chrome/browser/ntp/features.mm b/ios/chrome/browser/ntp/features.mm index f00269f2..6f5ec314 100644 --- a/ios/chrome/browser/ntp/features.mm +++ b/ios/chrome/browser/ntp/features.mm
@@ -48,7 +48,7 @@ BASE_FEATURE(kEnableWebChannels, "EnableWebChannels", - base::FEATURE_DISABLED_BY_DEFAULT); + base::FEATURE_ENABLED_BY_DEFAULT); BASE_FEATURE(kEnableFeedBackgroundRefresh, "EnableFeedBackgroundRefresh",
diff --git a/ios/chrome/browser/ui/ntp/feed_menu_coordinator_unittest.mm b/ios/chrome/browser/ui/ntp/feed_menu_coordinator_unittest.mm index b830b41..2338f7b 100644 --- a/ios/chrome/browser/ui/ntp/feed_menu_coordinator_unittest.mm +++ b/ios/chrome/browser/ui/ntp/feed_menu_coordinator_unittest.mm
@@ -158,20 +158,6 @@ OpenFeedMenu(); ExpectActions({{IDS_IOS_DISCOVER_FEED_MENU_TURN_OFF_ITEM, UIAlertActionStyleDestructive}, - {IDS_IOS_DISCOVER_FEED_MENU_MANAGE_ACTIVITY_ITEM}, - {IDS_IOS_DISCOVER_FEED_MENU_MANAGE_INTERESTS_ITEM}, - {IDS_IOS_DISCOVER_FEED_MENU_LEARN_MORE_ITEM}, - {IDS_APP_CANCEL, UIAlertActionStyleCancel}}); -} - -// Tests the menu actions when the user is signed-in. -TEST_F(FeedMenuCoordinatorTest, SignedInFollowFeedEnabled) { - scoped_feature_list_.InitWithFeatures({kEnableWebChannels}, {}); - SetFeedEnabled(true); - SignInFakeIdentity(); - OpenFeedMenu(); - ExpectActions({{IDS_IOS_DISCOVER_FEED_MENU_TURN_OFF_ITEM, - UIAlertActionStyleDestructive}, {IDS_IOS_DISCOVER_FEED_MENU_MANAGE_ITEM}, {IDS_IOS_DISCOVER_FEED_MENU_LEARN_MORE_ITEM}, {IDS_APP_CANCEL, UIAlertActionStyleCancel}});
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 5fecc49b..52d52fa 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
@@ -164,6 +164,7 @@ std::make_unique<web::FakeWebState>(); test_web_state->SetNavigationManager(std::move(navigation_manager)); test_web_state->SetLoading(true); + test_web_state->SetBrowserState(browser_state_.get()); web_state_ = test_web_state.get(); auto frames_manager = std::make_unique<web::FakeWebFramesManager>();
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 9be3280..4acb98df 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
@@ -149,6 +149,7 @@ std::make_unique<web::FakeWebState>(); test_web_state->SetNavigationManager(std::move(navigation_manager)); test_web_state->SetLoading(true); + test_web_state->SetBrowserState(browser_state_.get()); web_state_ = test_web_state.get(); auto frames_manager = std::make_unique<web::FakeWebFramesManager>();
diff --git a/ios/chrome/browser/ui/settings/privacy/privacy_coordinator.mm b/ios/chrome/browser/ui/settings/privacy/privacy_coordinator.mm index 031f467..4f0c6bc7 100644 --- a/ios/chrome/browser/ui/settings/privacy/privacy_coordinator.mm +++ b/ios/chrome/browser/ui/settings/privacy/privacy_coordinator.mm
@@ -87,6 +87,7 @@ [self.clearBrowsingDataCoordinator stop]; self.clearBrowsingDataCoordinator = nil; [self stopLockdownModeCoordinator]; + [self stopSafeBrowsingCoordinator]; self.viewController = nil; } @@ -150,9 +151,7 @@ - (void)privacySafeBrowsingCoordinatorDidRemove: (PrivacySafeBrowsingCoordinator*)coordinator { DCHECK_EQ(self.safeBrowsingCoordinator, coordinator); - [self.safeBrowsingCoordinator stop]; - self.safeBrowsingCoordinator.delegate = nil; - self.safeBrowsingCoordinator = nil; + [self stopSafeBrowsingCoordinator]; } #pragma mark - LockdownModeCoordinatorDelegate @@ -170,4 +169,12 @@ self.lockdownModeCoordinator = nil; } +#pragma mark - Private + +- (void)stopSafeBrowsingCoordinator { + [self.safeBrowsingCoordinator stop]; + self.safeBrowsingCoordinator.delegate = nil; + self.safeBrowsingCoordinator = nil; +} + @end
diff --git a/ios/chrome/browser/ui/toolbar/buttons/toolbar_button_factory.mm b/ios/chrome/browser/ui/toolbar/buttons/toolbar_button_factory.mm index 9da35853..f954c45 100644 --- a/ios/chrome/browser/ui/toolbar/buttons/toolbar_button_factory.mm +++ b/ios/chrome/browser/ui/toolbar/buttons/toolbar_button_factory.mm
@@ -194,28 +194,31 @@ - (UIButton*)cancelButton { UIButton* cancelButton = [UIButton buttonWithType:UIButtonTypeSystem]; - cancelButton.titleLabel.font = [UIFont systemFontOfSize:kLocationBarFontSize]; cancelButton.tintColor = [UIColor colorNamed:kBlueColor]; - [cancelButton setTitle:l10n_util::GetNSString(IDS_CANCEL) - forState:UIControlStateNormal]; [cancelButton setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal]; [cancelButton setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal]; - // TODO(crbug.com/1418068): Simplify after minimum version required is >= - // iOS 15. - if (base::ios::IsRunningOnIOS15OrLater() && - IsUIButtonConfigurationEnabled()) { - if (@available(iOS 15, *)) { - UIButtonConfiguration* buttonConfiguration = - [UIButtonConfiguration plainButtonConfiguration]; - buttonConfiguration.contentInsets = NSDirectionalEdgeInsetsMake( - 0, kCancelButtonHorizontalInset, 0, kCancelButtonHorizontalInset); - cancelButton.configuration = buttonConfiguration; - } + if (IsUIButtonConfigurationEnabled()) { + UIButtonConfiguration* buttonConfiguration = + [UIButtonConfiguration plainButtonConfiguration]; + buttonConfiguration.contentInsets = NSDirectionalEdgeInsetsMake( + 0, kCancelButtonHorizontalInset, 0, kCancelButtonHorizontalInset); + UIFont* font = [UIFont systemFontOfSize:kLocationBarFontSize]; + NSDictionary* attributes = @{NSFontAttributeName : font}; + NSMutableAttributedString* attributedString = + [[NSMutableAttributedString alloc] + initWithString:l10n_util::GetNSString(IDS_CANCEL) + attributes:attributes]; + buttonConfiguration.attributedTitle = attributedString; + cancelButton.configuration = buttonConfiguration; } else { + cancelButton.titleLabel.font = + [UIFont systemFontOfSize:kLocationBarFontSize]; + [cancelButton setTitle:l10n_util::GetNSString(IDS_CANCEL) + forState:UIControlStateNormal]; UIEdgeInsets contentInsets = UIEdgeInsetsMake( 0, kCancelButtonHorizontalInset, 0, kCancelButtonHorizontalInset); SetContentEdgeInsets(cancelButton, contentInsets);
diff --git a/ios/chrome/browser/ui/toolbar/public/toolbar_constants.h b/ios/chrome/browser/ui/toolbar/public/toolbar_constants.h index 2dd1dcd..31a35119 100644 --- a/ios/chrome/browser/ui/toolbar/public/toolbar_constants.h +++ b/ios/chrome/browser/ui/toolbar/public/toolbar_constants.h
@@ -72,12 +72,12 @@ // Top margin of the top toolbar when the adaptive toolbar is unsplit. extern const CGFloat kTopToolbarUnsplitMargin; +// Height of the omnibox in the toolbar. Used for both toolbars. +extern const CGFloat kToolbarOmniboxHeight; // Height of the primary toolbar with default font size. extern const CGFloat kPrimaryToolbarHeight; // Height of the secondary toolbar with default font size. extern const CGFloat kSecondaryToolbarHeight; -// Additional height in the secondary toolbar when it has the omnibox. -extern const CGFloat kSecondaryToolbarOmniboxHeight; // Height of the part of the toolbar not scaling up when the user changes the // preferred font size. extern const CGFloat kNonDynamicToolbarHeight;
diff --git a/ios/chrome/browser/ui/toolbar/public/toolbar_constants.mm b/ios/chrome/browser/ui/toolbar/public/toolbar_constants.mm index c5f7fab3..67d8405c 100644 --- a/ios/chrome/browser/ui/toolbar/public/toolbar_constants.mm +++ b/ios/chrome/browser/ui/toolbar/public/toolbar_constants.mm
@@ -50,9 +50,10 @@ const CGFloat kLocationBarVerticalMarginDynamicType = -1.0f; const CGFloat kTopToolbarUnsplitMargin = 6; -const CGFloat kPrimaryToolbarHeight = 50; +const CGFloat kToolbarOmniboxHeight = 50; +// Remember to update ToolbarExpandedHeight if kPrimaryToolbarHeight is updated. +const CGFloat kPrimaryToolbarHeight = kToolbarOmniboxHeight; const CGFloat kSecondaryToolbarHeight = 44; -const CGFloat kSecondaryToolbarOmniboxHeight = 50; const CGFloat kNonDynamicToolbarHeight = 14; const CGFloat kToolbarHeightFullscreen = 20; const CGFloat kNonDynamicToolbarHeightFullscreen = 3;
diff --git a/ios/chrome/browser/ui/toolbar/public/toolbar_utils.mm b/ios/chrome/browser/ui/toolbar/public/toolbar_utils.mm index ad3aee6..4b5cd3c2 100644 --- a/ios/chrome/browser/ui/toolbar/public/toolbar_utils.mm +++ b/ios/chrome/browser/ui/toolbar/public/toolbar_utils.mm
@@ -51,7 +51,7 @@ CGFloat ToolbarExpandedHeight(UIContentSizeCategory category) { category = NormalizedCategory(category); - return Interpolate(category, kPrimaryToolbarHeight, kNonDynamicToolbarHeight); + return Interpolate(category, kToolbarOmniboxHeight, kNonDynamicToolbarHeight); } CGFloat LocationBarHeight(UIContentSizeCategory category) {
diff --git a/ios/chrome/browser/ui/toolbar/toolbar_coordinator.mm b/ios/chrome/browser/ui/toolbar/toolbar_coordinator.mm index f5cf6d5..2198ef74 100644 --- a/ios/chrome/browser/ui/toolbar/toolbar_coordinator.mm +++ b/ios/chrome/browser/ui/toolbar/toolbar_coordinator.mm
@@ -321,7 +321,8 @@ self.secondaryToolbarViewController.view.intrinsicContentSize.height; if (_omniboxPosition == ToolbarType::kSecondary) { CHECK(IsBottomOmniboxSteadyStateEnabled()); - height += kSecondaryToolbarOmniboxHeight; + height += ToolbarExpandedHeight( + self.traitEnvironment.traitCollection.preferredContentSizeCategory); } return height; }
diff --git a/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1 b/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1 index b9be6d34..71f0c68 100644 --- a/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1 +++ b/ios/google_internal/frameworks/ChromeInternal.framework.dSYM.ios.zip.sha1
@@ -1 +1 @@ -79177b41f5df8d2bec16351f032ee18b1a04c802 \ No newline at end of file +c6c64a7eefe88a7d8be30d2923a2be4a36e81cfa \ No newline at end of file
diff --git a/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1 b/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1 index 612b111..d9fc772e 100644 --- a/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1 +++ b/ios/google_internal/frameworks/ChromeSSOInternal.framework.dSYM.ios.zip.sha1
@@ -1 +1 @@ -6d573916233fbb81dd97e340f6046501daf2b275 \ No newline at end of file +d2e66537f9d49d79b38a706351d0db12c2657105 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 index 349721d..dc0080e6 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -b4b0cd9ef1487ae1278e46e13b804cc761dabb28 \ No newline at end of file +4de959a777523f2bd74255f15e2abce0869de8d0 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 index f7e2cd90..f00fef9 100644 --- a/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -ffcb2a6260a6115ea2fd528d1ed4fcc84db35805 \ No newline at end of file +92db0f39acd8c5666ed2856d17b2668f608a20a7 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 index 69eb852..c1e480b 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -730f1f828d4de199e33d40f986ef2d236ec166fc \ No newline at end of file +c4f46df3d0905c693fd4a9cfc751f7b885f73349 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 index af55971..ddefcb9 100644 --- a/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_sso_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -14940362662abb0b4d141c5870c2bf9691264f44 \ No newline at end of file +f3659aa965685dda4c2c182e090d771849024528 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 index f63b81fc..cb80d15 100644 --- a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -69bc57d8f0436209d34b56758c17cea2abff4618 \ No newline at end of file +c576404376ece65c954bf8f1da8d24faeb7d41c4 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 index 94fa899..f1a5d5e2 100644 --- a/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/chrome_test_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -ed9ce7fb0789c4b02d95e739acc199cabfe5246e \ No newline at end of file +65b4e592a98c872d69e42886337f7223a3554483 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 index ac60687..831f4c9f 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -cd8b5e2e901c8735d2351e400228cee1c778879a \ No newline at end of file +169bb02df9fd376e530320e216429bc8d5334f29 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 index 646ae82..c91d5c42 100644 --- a/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/remoting_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -c3bdbc5e1e52be0426edf1a4c1e420a9ac564f8b \ No newline at end of file +956b1ba2a16cf77d82d10ae5aac681a8343ba349 \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 index deaf8f9..4fce798 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.ios.zip.sha1
@@ -1 +1 @@ -53ff04f67c70f16211120d62d1ec4f85af48a252 \ No newline at end of file +25735b063e2e3bcbd50446665af4418a494344be \ No newline at end of file
diff --git a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 index 468d337..51329d24 100644 --- a/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1 +++ b/ios/google_internal/frameworks/web_view_shell_internal_dynamic_framework.iossimulator.zip.sha1
@@ -1 +1 @@ -584297ed2fe1648af1529889a4134fb31faff493 \ No newline at end of file +7bc2f0d1441b4011897e8e042e4db53ffd0c6a9c \ No newline at end of file
diff --git a/media/formats/mp4/writable_box_definitions.h b/media/formats/mp4/writable_box_definitions.h index a79935c7..cecc40c3 100644 --- a/media/formats/mp4/writable_box_definitions.h +++ b/media/formats/mp4/writable_box_definitions.h
@@ -300,7 +300,7 @@ // Optional fields, presence is indicated in `flags`. If not present, the // default value established in the `TrackFragmentHeader` is used. - std::vector<base::TimeDelta> sample_durations; + std::vector<base::TimeTicks> sample_timestamps; std::vector<uint32_t> sample_sizes; std::vector<uint32_t> sample_flags; // We don't support sample_composition_time_offsets as we don't know
diff --git a/media/gpu/vaapi/BUILD.gn b/media/gpu/vaapi/BUILD.gn index b9b78908..18ecf9c 100644 --- a/media/gpu/vaapi/BUILD.gn +++ b/media/gpu/vaapi/BUILD.gn
@@ -9,6 +9,7 @@ import("//media/media_options.gni") import("//testing/test.gni") import("//tools/generate_stubs/rules.gni") +import("//ui/gl/features.gni") assert(is_linux || is_chromeos) assert(use_vaapi) @@ -16,6 +17,9 @@ generate_stubs("libva_stubs") { extra_header = "va_stub_header.fragment" sigs = [ "va.sigs" ] + if (use_vaapi_x11) { + sigs += [ "va_x11.sigs" ] + } if (is_chromeos_ash) { sigs += [ "va_prot.sigs" ] } @@ -107,6 +111,7 @@ public_deps = [ "//media", "//skia", + "//ui/gl", ] if (is_chromeos_ash) { @@ -166,6 +171,7 @@ "//ui/base:features", "//ui/gfx:memory_buffer", "//ui/gfx/linux:drm", + "//ui/gl", ] if (use_ozone) { deps += [ "//ui/ozone" ]
diff --git a/media/gpu/vaapi/va_x11.sigs b/media/gpu/vaapi/va_x11.sigs new file mode 100644 index 0000000..748e11c --- /dev/null +++ b/media/gpu/vaapi/va_x11.sigs
@@ -0,0 +1,9 @@ +// Copyright 2014 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +//------------------------------------------------ +// Functions from libva-x11 used in chromium code. +//------------------------------------------------ +VADisplay vaGetDisplay(Display *dpy); +VAStatus vaPutSurface(VADisplay dpy, VASurfaceID surface, Drawable draw, short srcx, short srcy, unsigned short srcw, unsigned short srch, short destx, short desty, unsigned short destw, unsigned short desth, VARectangle *cliprects, unsigned int number_cliprects, unsigned int flags);
diff --git a/media/gpu/vaapi/vaapi_wrapper.cc b/media/gpu/vaapi/vaapi_wrapper.cc index f8cd69e4..883848b 100644 --- a/media/gpu/vaapi/vaapi_wrapper.cc +++ b/media/gpu/vaapi/vaapi_wrapper.cc
@@ -59,6 +59,18 @@ #include "ui/gfx/linux/native_pixmap_dmabuf.h" #include "ui/gfx/native_pixmap.h" #include "ui/gfx/native_pixmap_handle.h" +#include "ui/gl/gl_bindings.h" +#include "ui/gl/gl_implementation.h" + +#if BUILDFLAG(USE_VAAPI_X11) +typedef XID Drawable; + +extern "C" { +#include "media/gpu/vaapi/va_x11.sigs" +} + +#include "ui/gfx/x/connection.h" // nogncheck +#endif // BUILDFLAG(USE_VAAPI_X11) #if BUILDFLAG(IS_OZONE) #include "ui/ozone/public/ozone_platform.h" @@ -70,11 +82,17 @@ using media_gpu_vaapi::kModuleVa_prot; #endif -using media_gpu_vaapi::InitializeStubs; -using media_gpu_vaapi::IsVa_drmInitialized; -using media_gpu_vaapi::IsVaInitialized; using media_gpu_vaapi::kModuleVa; using media_gpu_vaapi::kModuleVa_drm; +#if BUILDFLAG(USE_VAAPI_X11) +using media_gpu_vaapi::kModuleVa_x11; +#endif // BUILDFLAG(USE_VAAPI_X11) +using media_gpu_vaapi::InitializeStubs; +using media_gpu_vaapi::IsVaInitialized; +#if BUILDFLAG(USE_VAAPI_X11) +using media_gpu_vaapi::IsVa_x11Initialized; +#endif // BUILDFLAG(USE_VAAPI_X11) +using media_gpu_vaapi::IsVa_drmInitialized; using media_gpu_vaapi::StubPathMap; namespace media { @@ -98,7 +116,7 @@ kVAExportSurfaceHandle = 12, kVAGetConfigAttributes = 13, kVAPutImage = 14, - // kVAPutSurface = 15, // UNUSED. + kVAPutSurface = 15, kVAQueryConfigAttributes = 16, kVAQueryImageFormats = 17, kVAQuerySurfaceAttributes = 18, @@ -142,7 +160,7 @@ "vaExportSurfaceHandle", "vaGetConfigAttributes", "vaPutImage", - "", // UNUSED (used to be vaPutSurface). + "vaPutSurface", "vaQueryConfigAttributes", "vaQueryImageFormats", "vaQuerySurfaceAttributes", @@ -766,6 +784,50 @@ return false; } +#if BUILDFLAG(USE_VAAPI_X11) + +absl::optional<VADisplay> GetVADisplayStateX11(const base::ScopedFD& drm_fd) { + switch (gl::GetGLImplementation()) { + case gl::kGLImplementationEGLGLES2: + return vaGetDisplayDRM(drm_fd.get()); + + case gl::kGLImplementationNone: { + VADisplay display = + vaGetDisplay(x11::Connection::Get()->GetXlibDisplay()); + if (vaDisplayIsValid(display)) + return display; + return vaGetDisplayDRM(drm_fd.get()); + } + + case gl::kGLImplementationEGLANGLE: + return vaGetDisplay(x11::Connection::Get()->GetXlibDisplay()); + + default: + LOG(WARNING) << "VAAPI video acceleration not available for " + << gl::GetGLImplementationGLName( + gl::GetGLImplementationParts()); + return absl::nullopt; + } +} + +#else + +absl::optional<VADisplay> GetVADisplayState(const base::ScopedFD& drm_fd) { + switch (gl::GetGLImplementation()) { + case gl::kGLImplementationEGLGLES2: + case gl::kGLImplementationEGLANGLE: + case gl::kGLImplementationNone: + return vaGetDisplayDRM(drm_fd.get()); + default: + LOG(WARNING) << "VAAPI video acceleration not available for " + << gl::GetGLImplementationGLName( + gl::GetGLImplementationParts()); + return absl::nullopt; + } +} + +#endif // BUILDFLAG(USE_VAAPI_X11) + // Returns all the VAProfiles that the driver lists as supported, regardless of // what Chrome supports or not. std::vector<VAProfile> GetSupportedVAProfiles(const base::Lock* va_lock, @@ -1561,7 +1623,10 @@ } #endif - const bool libraries_initialized = IsVaInitialized() && IsVa_drmInitialized(); + bool libraries_initialized = IsVaInitialized() && IsVa_drmInitialized(); +#if BUILDFLAG(USE_VAAPI_X11) + libraries_initialized = libraries_initialized && IsVa_x11Initialized(); +#endif if (!libraries_initialized) { return {}; } @@ -1584,7 +1649,17 @@ env->SetVar(libva_log_level_env, "1"); } - const VADisplay va_display = vaGetDisplayDRM(drm_fd_.get()); + absl::optional<VADisplay> display = +#if BUILDFLAG(USE_VAAPI_X11) + GetVADisplayStateX11(drm_fd_); +#else + GetVADisplayState(drm_fd_); +#endif + + if (!display) { + return false; + } + VADisplay va_display = *display; base::ScopedClosureRunner va_display_cleaner_cb(base::BindOnce( [](VADisplay va_display) { if (vaDisplayIsValid(va_display)) { @@ -2733,6 +2808,27 @@ return Execute_Locked(va_surface_id, va_buffer_ids); } +#if BUILDFLAG(USE_VAAPI_X11) +bool VaapiWrapper::PutSurfaceIntoPixmap(VASurfaceID va_surface_id, + x11::Pixmap x_pixmap, + gfx::Size dest_size) { + CHECK(!enforce_sequence_affinity_ || + sequence_checker_.CalledOnValidSequence()); + base::AutoLockMaybe auto_lock(va_lock_.get()); + + VAStatus va_res = vaSyncSurface(va_display_, va_surface_id); + VA_SUCCESS_OR_RETURN(va_res, VaapiFunctions::kVASyncSurface, false); + + // Put the data into an X Pixmap. + va_res = + vaPutSurface(va_display_, va_surface_id, static_cast<uint32_t>(x_pixmap), + 0, 0, dest_size.width(), dest_size.height(), 0, 0, + dest_size.width(), dest_size.height(), nullptr, 0, 0); + VA_SUCCESS_OR_RETURN(va_res, VaapiFunctions::kVAPutSurface, false); + return true; +} +#endif // BUILDFLAG(USE_VAAPI_X11) + std::unique_ptr<ScopedVAImage> VaapiWrapper::CreateVaImage( VASurfaceID va_surface_id, VAImageFormat* format, @@ -3136,11 +3232,17 @@ paths[kModuleVa].push_back(std::string("libva.so.") + va_suffix); paths[kModuleVa_drm].push_back(std::string("libva-drm.so.") + va_suffix); +#if BUILDFLAG(USE_VAAPI_X11) + paths[kModuleVa_x11].push_back(std::string("libva-x11.so.") + va_suffix); +#endif #if BUILDFLAG(IS_CHROMEOS_ASH) paths[kModuleVa_prot].push_back(std::string("libva.so.") + va_suffix); #endif - // InitializeStubs dlopen()s VA-API libraries and loads the required symbols. + // InitializeStubs dlopen() VA-API libraries + // libva.so + // libva-x11.so (X11) + // libva-drm.so (X11 and Ozone). static bool result = InitializeStubs(paths); if (!result) { static const char kErrorMsg[] = "Failed to initialize VAAPI libs";
diff --git a/media/gpu/vaapi/vaapi_wrapper.h b/media/gpu/vaapi/vaapi_wrapper.h index e3f2534..c093cf8 100644 --- a/media/gpu/vaapi/vaapi_wrapper.h +++ b/media/gpu/vaapi/vaapi_wrapper.h
@@ -36,6 +36,10 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gfx/geometry/size.h" +#if BUILDFLAG(USE_VAAPI_X11) +#include "ui/gfx/x/xproto.h" // nogncheck +#endif // BUILDFLAG(USE_VAAPI_X11) + namespace gfx { enum class BufferFormat : uint8_t; class NativePixmap; @@ -477,6 +481,14 @@ VASurfaceID va_surface_id, const std::vector<std::pair<VABufferID, VABufferDescriptor>>& va_buffers); +#if BUILDFLAG(USE_VAAPI_X11) + // Put data from |va_surface_id| into |x_pixmap| of size + // |dest_size|, converting/scaling to it. + [[nodiscard]] bool PutSurfaceIntoPixmap(VASurfaceID va_surface_id, + x11::Pixmap x_pixmap, + gfx::Size dest_size); +#endif // BUILDFLAG(USE_VAAPI_X11) + // Creates a ScopedVAImage from a VASurface |va_surface_id| and map it into // memory with the given |format| and |size|. If |format| is not equal to the // internal format, the underlying implementation will do format conversion if
diff --git a/media/muxers/BUILD.gn b/media/muxers/BUILD.gn index 15722d30..3dc1a55 100644 --- a/media/muxers/BUILD.gn +++ b/media/muxers/BUILD.gn
@@ -41,6 +41,7 @@ deps = [ "//base", + "//components/version_info:version_info", "//media/base", "//media/formats", "//third_party/libwebm",
diff --git a/media/muxers/DEPS b/media/muxers/DEPS index dd27068..96cdb66 100644 --- a/media/muxers/DEPS +++ b/media/muxers/DEPS
@@ -1,3 +1,4 @@ include_rules = [ "+third_party/libwebm", + "+components/version_info/version_info.h", ]
diff --git a/media/muxers/mp4_fragment_box_writer.cc b/media/muxers/mp4_fragment_box_writer.cc index dcb92bce..30be38d 100644 --- a/media/muxers/mp4_fragment_box_writer.cc +++ b/media/muxers/mp4_fragment_box_writer.cc
@@ -223,7 +223,9 @@ mp4::writable_boxes::TrackFragmentRunFlags::kSampleFlagsPresent)); if (duration_exists) { - CHECK_EQ(box_.sample_count, box_.sample_durations.size()); + // fragment, if not last, has an additional timestamp entry for last + // item duration calculation. + CHECK_EQ(box_.sample_count + 1, box_.sample_timestamps.size()); } if (size_exists) { @@ -236,7 +238,11 @@ for (uint32_t i = 0; i < box_.sample_count; ++i) { if (duration_exists) { - writer.WriteU32(box_.sample_durations[i].InMilliseconds()); + // TODO(crbug.com://1465031): sample_timestamps will be converted to + // per sample duration with timescale. + writer.WriteU32( + (box_.sample_timestamps[i + 1] - box_.sample_timestamps[i]) + .InMilliseconds()); } if (size_exists) {
diff --git a/media/muxers/mp4_movie_box_writer.cc b/media/muxers/mp4_movie_box_writer.cc index 44630d27..f572caef 100644 --- a/media/muxers/mp4_movie_box_writer.cc +++ b/media/muxers/mp4_movie_box_writer.cc
@@ -104,6 +104,9 @@ WriteIsoTime(writer, box_.creation_time); WriteIsoTime(writer, box_.modification_time); writer.WriteU32(box_.timescale); + + // TODO(crbug.com://1465031): The conversion to timescale will be made in + // the box writer with its duration calculation. writer.WriteU64(box_.duration.InMilliseconds()); writer.WriteU32(0x00010000); // normal rate.
diff --git a/media/muxers/mp4_muxer_box_writer_unittest.cc b/media/muxers/mp4_muxer_box_writer_unittest.cc index fc96569..3434e7c 100644 --- a/media/muxers/mp4_muxer_box_writer_unittest.cc +++ b/media/muxers/mp4_muxer_box_writer_unittest.cc
@@ -725,6 +725,8 @@ std::vector<uint8_t> written_data; CreateContext(written_data); + // TODO(crbug.com://1465031): The client passes the timestamp. + // Duration conversion will be done in the box writer. constexpr uint32_t kSampleDurations[] = {960, 960, 960}; constexpr uint32_t kSampleSizes[] = {6400, 333, 333}; constexpr uint32_t kSampleCount = 3u; @@ -779,12 +781,16 @@ static_cast<S>(mp4::writable_boxes::FragmentSampleFlags:: kSampleFlagDependsYes)); - std::vector<base::TimeDelta> durations; + std::vector<base::TimeTicks> time_ticks; + base::TimeTicks base_time_ticks = base::TimeTicks::Now(); + time_ticks.push_back(base_time_ticks); + base::TimeDelta delta; for (auto* iter = std::begin(kSampleDurations); iter != std::end(kSampleDurations); ++iter) { - durations.push_back(base::Milliseconds(*iter)); + delta += base::Milliseconds(*iter); + time_ticks.push_back(base_time_ticks + delta); } - video_trun.sample_durations = std::move(durations); + video_trun.sample_timestamps = std::move(time_ticks); video_fragment.run = std::move(video_trun); } moof.track_fragments.push_back(std::move(video_fragment)); @@ -828,12 +834,16 @@ static_cast<S>(mp4::writable_boxes::FragmentSampleFlags:: kSampleFlagDependsYes)); - std::vector<base::TimeDelta> durations; + std::vector<base::TimeTicks> time_ticks; + base::TimeTicks base_time_ticks = base::TimeTicks::Now(); + time_ticks.push_back(base_time_ticks); + base::TimeDelta delta = base::Milliseconds(0); for (auto* iter = std::begin(kSampleDurations); iter != std::end(kSampleDurations); ++iter) { - durations.push_back(base::Milliseconds(*iter)); + delta += base::Milliseconds(*iter); + time_ticks.push_back(base_time_ticks + delta); } - audio_trun.sample_durations = std::move(durations); + audio_trun.sample_timestamps = std::move(time_ticks); std::vector<uint32_t> sizes(std::begin(kSampleSizes), std::end(kSampleSizes));
diff --git a/media/muxers/mp4_muxer_delegate.cc b/media/muxers/mp4_muxer_delegate.cc index f4e63b1..282a175 100644 --- a/media/muxers/mp4_muxer_delegate.cc +++ b/media/muxers/mp4_muxer_delegate.cc
@@ -4,12 +4,49 @@ #include "media/muxers/mp4_muxer_delegate.h" +#include "components/version_info/version_info.h" #include "media/base/audio_parameters.h" +#include "media/formats/mp4/avc.h" #include "media/formats/mp4/box_definitions.h" +#include "media/muxers/box_byte_stream.h" +#include "media/muxers/mp4_box_writer.h" +#include "media/muxers/mp4_fragment_box_writer.h" +#include "media/muxers/mp4_movie_box_writer.h" +#include "media/muxers/output_position_tracker.h" + +#if BUILDFLAG(USE_PROPRIETARY_CODECS) +#include "media/formats/mp4/h264_annex_b_to_avc_bitstream_converter.h" +#endif namespace media { -Mp4MuxerDelegate::Mp4MuxerDelegate(Muxer::WriteDataCB write_callback) {} +namespace { + +using mp4::writable_boxes::FragmentSampleFlags; +using mp4::writable_boxes::TrackFragmentHeaderFlags; +using mp4::writable_boxes::TrackFragmentRunFlags; + +constexpr char kVideoHandlerName[] = "VideoHandler"; +constexpr char kUndefinedLanguageName[] = "und"; + +// Milliseconds time scale is set in the Movie header and it will +// be the base for the duration. +constexpr uint32_t kMillisecondsTimeScale = 1000u; + +template <typename T> +uint32_t BuildFlags(const std::vector<T>& build_flags) { + uint32_t flags = 0; + for (auto flag : build_flags) { + flags |= static_cast<uint32_t>(flag); + } + + return flags; +} + +} // namespace + +Mp4MuxerDelegate::Mp4MuxerDelegate(Muxer::WriteDataCB write_callback) + : write_callback_(std::move(write_callback)) {} Mp4MuxerDelegate::~Mp4MuxerDelegate() = default; @@ -17,56 +54,331 @@ const Muxer::VideoParameters& params, base::StringPiece encoded_data, absl::optional<VideoEncoder::CodecDescription> codec_description, - base::TimeTicks timestamp) { - if (video_track_index_ == -1) { - video_track_index_ = GetNextTrackIndex(); - PopulateInitialVideoTrack(params, encoded_data, video_track_index_); - } + base::TimeTicks timestamp, + bool is_key_frame) { + if (!video_track_index_.has_value()) { + CHECK(codec_description.has_value()); + CHECK(is_key_frame); + CHECK(start_video_time_.is_null()); - PopulateVideoFragment(params, encoded_data, timestamp); + EnsureInitialized(); + last_video_time_ = start_video_time_ = timestamp; + + CHECK_GT(params.frame_rate, 0); + video_frame_rate_ = params.frame_rate; + + video_track_index_ = GetNextTrackIndex(); + context_->SetVideoIndex(video_track_index_.value()); + + mp4::writable_boxes::Track track; + moov_->tracks.emplace_back(std::move(track)); + + mp4::writable_boxes::TrackExtends trex; + moov_->extends.track_extends.emplace_back(std::move(trex)); + + BuildVideoTrackWithKeyframe(params, encoded_data, + codec_description.value()); + } + last_video_time_ = timestamp; + + BuildVideoFragment(params, encoded_data, timestamp, is_key_frame); } void Mp4MuxerDelegate::AddAudioFrame( const AudioParameters& params, base::StringPiece encoded_data, - const AudioEncoder::CodecDescription& codec_description, + absl::optional<AudioEncoder::CodecDescription> codec_description, base::TimeTicks timestamp) { NOTIMPLEMENTED(); } void Mp4MuxerDelegate::Flush() { - NOTIMPLEMENTED(); - PopulateMovieHeader(); + BuildMovieBox(); + + // Write `moov` box and its children. + Mp4MovieBoxWriter box_writer(*context_, *moov_); + box_writer.WriteAndFlush(); + + AddLastVideoSampleTimestamp(); + + // Write `moof` box and its children as well as `mdat` box. + for (auto& fragment : fragments_) { + // `moof` and `mdat` should use same `BoxByteStream` as `moof` + // has a dependency of `mdat` offset. + Mp4MovieFragmentBoxWriter fragment_box_writer(*context_, fragment->moof); + BoxByteStream box_byte_stream; + fragment_box_writer.Write(box_byte_stream); + + // Write `mdat` box with `moof` boxes writer object. + Mp4MediaDataBoxWriter mdat_box_writer(*context_, fragment->mdat); + + mdat_box_writer.WriteAndFlush(box_byte_stream); + } + + Reset(); } -void Mp4MuxerDelegate::PopulateMovieHeader() { - NOTIMPLEMENTED(); +void Mp4MuxerDelegate::EnsureInitialized() { + if (context_) { + return; + } + + // `write_callback_` continue to be used even after `Reset`. + auto output_position_tracker = + std::make_unique<OutputPositionTracker>(write_callback_); + + context_ = + std::make_unique<Mp4MuxerContext>(std::move(output_position_tracker)); + + moov_ = std::make_unique<mp4::writable_boxes::Movie>(); } -void Mp4MuxerDelegate::PopulateInitialVideoTrack( +void Mp4MuxerDelegate::Reset() { + context_.reset(); + moov_.reset(); + fragments_.clear(); + + video_track_index_.reset(); + next_track_index_ = 0; + start_video_time_ = base::TimeTicks(); + last_video_time_ = base::TimeTicks(); +} + +void Mp4MuxerDelegate::BuildMovieBox() { + // It will be called during Flush time. + moov_->header.creation_time = base::Time::Now(); + moov_->header.modification_time = moov_->header.creation_time; + + // Milliseconds timescale for movie header. + moov_->header.timescale = kMillisecondsTimeScale; + + base::TimeDelta longest_track_duration; + if (video_track_index_.has_value()) { + auto& track = moov_->tracks[*video_track_index_]; + track.header.creation_time = moov_->header.creation_time; + track.header.modification_time = moov_->header.modification_time; + + track.media.header.creation_time = moov_->header.creation_time; + track.media.header.modification_time = moov_->header.modification_time; + + // video track duration on the `tkhd` and `mdhd`. + + // Use inverse frame_rate just in case when it has a single frame. + longest_track_duration = std::max(base::Seconds(1 / video_frame_rate_), + last_video_time_ - start_video_time_); + track.header.duration = longest_track_duration; + track.media.header.duration = longest_track_duration; + } + + // Update the track's duration that the longest duration on the track + // whether it is video or audio. + moov_->header.duration = longest_track_duration; + + // next_track_id indicates a value to use for the track ID of the next + // track to be added to this presentation. + moov_->header.next_track_id = GetNextTrackIndex() + 1; +} + +void Mp4MuxerDelegate::BuildVideoTrackWithKeyframe( const Muxer::VideoParameters& params, base::StringPiece encoded_data, - int index) { - NOTIMPLEMENTED(); + VideoEncoder::CodecDescription codec_description) { + DCHECK(video_track_index_.has_value()); + + mp4::writable_boxes::Track& video_track = moov_->tracks[*video_track_index_]; + + // `tkhd`. + video_track.header.track_id = static_cast<uint32_t>(*video_track_index_ + 1); + video_track.header.is_audio = false; + + video_track.header.natural_size = params.visible_rect_size; + + // `mdhd` + video_track.media.header.timescale = + video_frame_rate_ * kMillisecondsTimeScale; + video_track.media.header.language = + kUndefinedLanguageName; // use 'und' as default at this time. + + // `hdlr` + video_track.media.handler.handler_type = media::mp4::FOURCC_VIDE; + video_track.media.handler.name = kVideoHandlerName; + + // `minf` + + // `vmhd` + mp4::writable_boxes::VideoMediaHeader video_header = {}; + video_track.media.information.video_header = std::move(video_header); + + // `dinf`, `dref`, `url`. + mp4::writable_boxes::DataInformation data_info; + mp4::writable_boxes::DataUrlEntry url; + data_info.data_reference.entries.emplace_back(std::move(url)); + video_track.media.information.data_information = std::move(data_info); + + // `stbl`, `stco`, `stsz`, `stts`, `stsc'. + mp4::writable_boxes::SampleTable sample_table = {}; + sample_table.sample_to_chunk = mp4::writable_boxes::SampleToChunk{}; + sample_table.decoding_time_to_sample = + mp4::writable_boxes::DecodingTimeToSample(); + sample_table.sample_size = mp4::writable_boxes::SampleSize(); + sample_table.sample_chunk_offset = mp4::writable_boxes::SampleChunkOffset(); + + // `stsd`, `avc1`, `avcC`. + mp4::writable_boxes::SampleDescription description = {}; + +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + mp4::writable_boxes::VisualSampleEntry visual_entry = {}; + + visual_entry.coded_size = params.visible_rect_size; + + visual_entry.compressor_name = version_info::GetProductName(); + + mp4::AVCDecoderConfigurationRecord avc_config; + bool result = + avc_config.Parse(codec_description.data(), codec_description.size()); + DCHECK(result); + + visual_entry.avc_decoder_configuration.avc_config_record = + std::move(avc_config); + visual_entry.pixel_aspect_ratio = mp4::writable_boxes::PixelAspectRatioBox(); + description.visual_sample_entry = std::move(visual_entry); +#endif + + sample_table.sample_description = std::move(description); + video_track.media.information.sample_table = std::move(sample_table); + + // `trex`. + mp4::writable_boxes::TrackExtends& video_extends = + moov_->extends.track_extends[*video_track_index_]; + video_extends.track_id = *video_track_index_ + 1; + + // TODO(crbug.com/1464063): Various MP4 samples doesn't need + // default_sample_duration, default_sample_size, default_sample_flags. We need + // to investigate it further though whether we need to set these fields. + video_extends.default_sample_description_index = 1; + video_extends.default_sample_size = 0; + video_extends.default_sample_duration = base::Milliseconds(0); + video_extends.default_sample_flags = 0; } -void Mp4MuxerDelegate::PopulateVideoFragment( - const Muxer::VideoParameters& params, - base::StringPiece encoded_data, - base::TimeTicks timestamp) { - NOTIMPLEMENTED(); +void Mp4MuxerDelegate::BuildVideoFragment(const Muxer::VideoParameters& params, + base::StringPiece encoded_data, + base::TimeTicks timestamp, + bool is_key_frame) { + DCHECK(video_track_index_.has_value()); + bool add_new_fragment = false; + + // Create new fragment only when it is key frame && no fragment exists + // && the previous fragment has an entry. + if (is_key_frame && ((fragments_.size() == 0 || + (fragments_.back() + ->moof.track_fragments[*video_track_index_] + .header.track_id != -1u)))) { + auto fragment = std::make_unique<Fragment>(); + + mp4::writable_boxes::TrackFragment track_frag; + fragment->moof.track_fragments.emplace_back( + std::move(track_frag)); // video track. + + fragment->mdat.track_data.emplace_back(); + + if (!fragments_.empty()) { + mp4::writable_boxes::TrackFragmentRun& prior_video_trun = + fragments_.back()->moof.track_fragments[*video_track_index_].run; + + // Add additional timestamp on the previous fragment so that it can + // get sample duration during box writer for last sample. + prior_video_trun.sample_timestamps.emplace_back(timestamp); + } + + fragments_.emplace_back(std::move(fragment)); + add_new_fragment = true; + } + + Fragment* fragment = fragments_.back().get(); + if (!fragment) { + // Don't add if the first frame does not have SPS/PPS. + return; + } + + if (add_new_fragment) { + AddNewVideoFragment(*fragment); + } + + // Add sample. + mp4::writable_boxes::TrackFragmentRun& video_trun = + fragment->moof.track_fragments[*video_track_index_].run; + + // Additional entries may exist in various sample vectors, such as durations, + // hence the use of 'sample_count' to ensure an accurate count of valid + // samples. + video_trun.sample_count += 1; + + // Add sample size, which is required. + video_trun.sample_sizes.emplace_back(encoded_data.size()); + + // Add sample timestamp. + video_trun.sample_timestamps.emplace_back(last_video_time_); + + // Add sample data to the data box. + AddDataToMdat(*fragment, encoded_data); } -void Mp4MuxerDelegate::AddSampleDataToTrunAndMdat( - mp4::writable_boxes::TrackFragmentRun& trun, - Mp4MuxerDelegate::Fragment* fragment, - Mp4MuxerNaluReader& nalu_reader, - base::StringPiece encoded_data, - base::TimeTicks timestamp, - uint32_t timescale) { - DCHECK_NE(video_track_index_, -1); +void Mp4MuxerDelegate::AddNewVideoFragment( + Mp4MuxerDelegate::Fragment& fragment) { + // `tfhd` fields. + fragment.moof.header.sequence_number = fragments_.size(); - AddSampleDuration(trun, timestamp, timescale); + mp4::writable_boxes::TrackFragment& video_track_fragment = + fragment.moof.track_fragments[*video_track_index_]; + + // `traf`. + video_track_fragment.header.track_id = *video_track_index_ + 1; + + std::vector<mp4::writable_boxes::FragmentSampleFlags> sample_flags = { + FragmentSampleFlags::kSampleFlagIsNonSync, + FragmentSampleFlags::kSampleFlagDependsYes}; + video_track_fragment.header.default_sample_flags = + BuildFlags<mp4::writable_boxes::FragmentSampleFlags>(sample_flags); + + video_track_fragment.header.default_sample_duration = base::TimeDelta(); + video_track_fragment.header.default_sample_size = 0; + + std::vector<mp4::writable_boxes::TrackFragmentHeaderFlags> + fragment_header_flags = { + TrackFragmentHeaderFlags::kDefaultBaseIsMoof, + TrackFragmentHeaderFlags::kDefaultSampleDurationPresent, + TrackFragmentHeaderFlags::kkDefaultSampleFlagsPresent}; + video_track_fragment.header.flags = + BuildFlags<mp4::writable_boxes::TrackFragmentHeaderFlags>( + fragment_header_flags); + + // `trun`. + video_track_fragment.run = {}; + video_track_fragment.run.sample_count = 0; + + std::vector<mp4::writable_boxes::TrackFragmentRunFlags> fragment_run_flags = { + TrackFragmentRunFlags::kDataOffsetPresent, + TrackFragmentRunFlags::kFirstSampleFlagsPresent, + TrackFragmentRunFlags::kSampleDurationPresent, + TrackFragmentRunFlags::kSampleSizePresent}; + video_track_fragment.run.flags = + BuildFlags<mp4::writable_boxes::TrackFragmentRunFlags>( + fragment_run_flags); + + // The first sample in the `trun` uses the `first_sample_flags` and + // other sample will use `default_sample_flags`. + video_track_fragment.run.first_sample_flags = static_cast<uint32_t>( + mp4::writable_boxes::FragmentSampleFlags::kSampleFlagDependsNo); + + // `tfdt`. + video_track_fragment.decode_time.base_media_decode_time = + last_video_time_ - start_video_time_; +} + +void Mp4MuxerDelegate::AddDataToMdat(Mp4MuxerDelegate::Fragment& fragment, + base::StringPiece encoded_data) { + DCHECK(video_track_index_.has_value()); // The parameter sets are supplied in-band at the sync samples. // It is a default on encoded stream, see @@ -78,7 +390,7 @@ // a giant blob of memory to hold them all. We should only have one // copy into the final muxed output buffer in an ideal world. std::vector<uint8_t>& video_data = - fragment->mdat.track_data[video_track_index_]; + fragment.mdat.track_data[*video_track_index_]; size_t current_size = video_data.size(); if (current_size + encoded_data.size() > video_data.capacity()) { video_data.reserve((current_size + encoded_data.size()) * 1.5); @@ -89,11 +401,21 @@ memcpy(&video_data[current_size], encoded_data.data(), encoded_data.size()); } -void Mp4MuxerDelegate::AddSampleDuration( - mp4::writable_boxes::TrackFragmentRun& trun, - base::TimeTicks timestamp, - uint32_t timescale) { - NOTIMPLEMENTED(); +void Mp4MuxerDelegate::AddLastVideoSampleTimestamp() { + CHECK(!fragments_.empty()); + + // Add last timestamp to the sample_timestamps on the last fragment. + mp4::writable_boxes::TrackFragmentRun& last_video_trun = + fragments_.back()->moof.track_fragments[*video_track_index_].run; + + // Use duration based on the frame rate for the last duration of the + // last fragment. + base::TimeTicks last_video_timestamp = + last_video_trun.sample_timestamps.back(); + + last_video_trun.sample_timestamps.emplace_back( + last_video_timestamp + + base::Milliseconds(kMillisecondsTimeScale / video_frame_rate_)); } int Mp4MuxerDelegate::GetNextTrackIndex() {
diff --git a/media/muxers/mp4_muxer_delegate.h b/media/muxers/mp4_muxer_delegate.h index 327ffb9..a288d666 100644 --- a/media/muxers/mp4_muxer_delegate.h +++ b/media/muxers/mp4_muxer_delegate.h
@@ -5,6 +5,10 @@ #ifndef MEDIA_MUXERS_MP4_MUXER_DELEGATE_H_ #define MEDIA_MUXERS_MP4_MUXER_DELEGATE_H_ +#include <memory> +#include <string> +#include <vector> + #include "base/sequence_checker.h" #include "base/strings/string_piece.h" #include "base/thread_annotations.h" @@ -13,13 +17,13 @@ #include "media/base/video_encoder.h" #include "media/formats/mp4/box_definitions.h" #include "media/formats/mp4/writable_box_definitions.h" +#include "media/muxers/mp4_muxer_context.h" #include "media/muxers/muxer.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace media { class AudioParameters; -class Mp4MuxerNaluReader; // Mp4MuxerDelegate builds the MP4 boxes from the encoded stream. // The boxes fields will start to be populated from the first stream and @@ -36,12 +40,14 @@ const Muxer::VideoParameters& params, base::StringPiece encoded_data, absl::optional<VideoEncoder::CodecDescription> codec_description, - base::TimeTicks timestamp); + base::TimeTicks timestamp, + bool is_key_frame); - void AddAudioFrame(const AudioParameters& params, - base::StringPiece encoded_data, - const AudioEncoder::CodecDescription& codec_description, - base::TimeTicks timestamp); + void AddAudioFrame( + const AudioParameters& params, + base::StringPiece encoded_data, + absl::optional<AudioEncoder::CodecDescription> codec_description, + base::TimeTicks timestamp); // Write to the big endian ISO-BMFF boxes and call `write_callback`. void Flush(); @@ -56,26 +62,28 @@ mp4::writable_boxes::MediaData mdat; }; - void PopulateMovieHeader(); - void PopulateInitialVideoTrack(const Muxer::VideoParameters& params, - base::StringPiece encoded_data, - int index); - void PopulateVideoFragment(const Muxer::VideoParameters& params, - base::StringPiece encoded_data, - base::TimeTicks timestamp); - void AddSampleDataToTrunAndMdat(mp4::writable_boxes::TrackFragmentRun& trun, - Mp4MuxerDelegate::Fragment* fragment, - Mp4MuxerNaluReader& nalu_reader, - base::StringPiece encoded_data, - base::TimeTicks timestamp, - uint32_t timescale); - void AddSampleDuration(mp4::writable_boxes::TrackFragmentRun& trun, - base::TimeTicks timestamp, - uint32_t timescale); + void BuildMovieBox(); + void BuildVideoTrackWithKeyframe( + const Muxer::VideoParameters& params, + base::StringPiece encoded_data, + VideoEncoder::CodecDescription codec_description); + void BuildVideoFragment(const Muxer::VideoParameters& params, + base::StringPiece encoded_data, + base::TimeTicks timestamp, + bool is_key_frame); + void AddNewVideoFragment(Mp4MuxerDelegate::Fragment& fragment); + void AddDataToMdat(Mp4MuxerDelegate::Fragment& fragment, + base::StringPiece encoded_data); + void AddLastVideoSampleTimestamp(); int GetNextTrackIndex(); + void EnsureInitialized(); + void Reset(); + + std::unique_ptr<Mp4MuxerContext> context_; + Muxer::WriteDataCB write_callback_; // The MP4 has single movie box and multiple fragment boxes. - mp4::writable_boxes::Movie movie_box_; + std::unique_ptr<mp4::writable_boxes::Movie> moov_; // Only key video frame has `SPS` and `PPS` and it will be a // signal of new fragment. In Windows, key frame is every 100th frame. @@ -83,10 +91,14 @@ // video and audio index is a 0 based index that is an item of the container. // The track id would be plus one on this index value. - int video_track_index_ = -1; + absl::optional<int> video_track_index_; int next_track_index_ = 0; - std::vector<base::TimeTicks> video_captured_time_; + // Duration time delta for the video track. + base::TimeTicks start_video_time_; + base::TimeTicks last_video_time_; + + double video_frame_rate_; Muxer::WriteDataCB write_data_callback_ GUARDED_BY_CONTEXT(sequence_checker_); SEQUENCE_CHECKER(sequence_checker_);
diff --git a/media/muxers/mp4_muxer_delegate_unittest.cc b/media/muxers/mp4_muxer_delegate_unittest.cc index 9833023..80c9ffa6 100644 --- a/media/muxers/mp4_muxer_delegate_unittest.cc +++ b/media/muxers/mp4_muxer_delegate_unittest.cc
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "media/formats/mp4/mp4_stream_parser.h" + +#include <algorithm> #include <cstddef> #include <vector> @@ -10,27 +13,95 @@ #include "base/path_service.h" #include "base/strings/string_piece.h" #include "base/test/task_environment.h" +#include "media/base/media_tracks.h" +#include "media/base/mock_media_log.h" +#include "media/base/stream_parser.h" +#include "media/formats/mp4/es_descriptor.h" +#include "media/formats/mp4/mp4_stream_parser.h" #include "media/muxers/mp4_muxer_delegate.h" +#include "media/muxers/mp4_type_conversion.h" +#include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { +namespace { +#if BUILDFLAG(USE_PROPRIETARY_CODECS) +constexpr uint32_t kWidth = 1024u; +constexpr uint32_t kHeight = 780u; +constexpr uint32_t kMovieHeaderTimescale = 1000u; +constexpr uint32_t kVideoTimescale = 30000u; +constexpr char kVideoHandlerName[] = "VideoHandler"; +constexpr uint32_t kBoxHeaderSize = 8u; +#endif +} // namespace class Mp4MuxerDelegateTest : public testing::Test { public: Mp4MuxerDelegateTest() = default; + void InitF(const StreamParser::InitParameters& expected_params) {} + + bool NewConfigCB(std::unique_ptr<MediaTracks> tracks, + const StreamParser::TextTrackConfigMap& text_track_map) { + return true; + } + bool NewConfigF(std::unique_ptr<MediaTracks> tracks, + const StreamParser::TextTrackConfigMap& tc) { + return true; + } + + bool NewBuffersF(const StreamParser::BufferQueueMap& buffer_queue_map) { + return true; + } + + void KeyNeededF(EmeInitDataType type, const std::vector<uint8_t>& init_data) { + } + + void NewSegmentF() {} + + void EndOfSegmentF() {} + protected: - void LoadVideo(base::StringPiece filename) { + void LoadVideo(base::StringPiece filename, + base::MemoryMappedFile& video_stream) { base::FilePath file_path = GetTestDataFilePath(filename); - ASSERT_TRUE(video_stream_.Initialize(file_path)) + + ASSERT_TRUE(video_stream.Initialize(file_path)) << "Couldn't open stream file: " << file_path.MaybeAsASCII(); } - base::StringPiece GetStreamData() const { - return base::StringPiece( - reinterpret_cast<const char*>(video_stream_.data()), - video_stream_.length()); +#if BUILDFLAG(USE_PROPRIETARY_CODECS) + void PopulateAVCDecoderConfiguration(std::vector<uint8_t>& code_description) { + // copied from box_reader_unittest.cc. + std::vector<uint8_t> test_data{ + 0x1, // configurationVersion = 1 + 0x64, // AVCProfileIndication = 100 + 0x0, // profile_compatibility = 0 + 0xc, // AVCLevelIndication = 10 + 0xff, // lengthSizeMinusOne = 3 + 0xe1, // numOfSequenceParameterSets = 1 + 0x0, 0x19, // sequenceParameterSetLength = 25 + + // sequenceParameterSet + 0x67, 0x64, 0x0, 0xc, 0xac, 0xd9, 0x41, 0x41, 0xfb, 0x1, 0x10, 0x0, 0x0, + 0x3, 0x0, 0x10, 0x0, 0x0, 0x3, 0x1, 0x40, 0xf1, 0x42, 0x99, 0x60, + + 0x1, // numOfPictureParameterSets + 0x0, 0x6, // pictureParameterSetLength = 6 + 0x68, 0xeb, 0xe3, 0xcb, 0x22, 0xc0, + + 0xfd, // chroma_format = 1 + 0xf8, // bit_depth_luma_minus8 = 0 + 0xf8, // bit_depth_chroma_minus8 = 0 + 0x0, // numOfSequanceParameterSetExt = 0 + }; + mp4::AVCDecoderConfigurationRecord avc_config; + ASSERT_TRUE(avc_config.Parse(test_data.data(), test_data.size())); + ASSERT_TRUE(avc_config.Serialize(code_description)); } +#endif + + testing::StrictMock<MockMediaLog> media_log_; private: base::FilePath GetTestDataFilePath(base::StringPiece name) { @@ -44,11 +115,326 @@ } base::test::TaskEnvironment task_environment; - base::MemoryMappedFile video_stream_; }; +#if BUILDFLAG(USE_PROPRIETARY_CODECS) TEST_F(Mp4MuxerDelegateTest, AddVideoFrame) { - // TODO: Add test. + media::Muxer::VideoParameters params(gfx::Size(kWidth, kHeight), 30, + media::VideoCodec::kH264, + gfx::ColorSpace()); + + base::MemoryMappedFile mapped_file_1; + LoadVideo("avc-bitstream-format-0.h264", mapped_file_1); + base::StringPiece video_stream_1( + reinterpret_cast<const char*>(mapped_file_1.data()), + mapped_file_1.length()); + + base::MemoryMappedFile mapped_file_2; + LoadVideo("avc-bitstream-format-1.h264", mapped_file_2); + base::StringPiece video_stream_2( + reinterpret_cast<const char*>(mapped_file_2.data()), + mapped_file_2.length()); + + base::RunLoop run_loop; + + std::vector<uint8_t> total_written_data; + std::vector<uint8_t> moov_written_data; + std::vector<uint8_t> first_moof_written_data; + std::vector<uint8_t> second_moof_written_data; + + int callback_count = 0; + Mp4MuxerDelegate delegate(base::BindRepeating( + [](base::OnceClosure run_loop_quit, + std::vector<uint8_t>* total_written_data, + std::vector<uint8_t>* moov_written_data, + std::vector<uint8_t>* first_moof_written_data, + std::vector<uint8_t>* second_moof_written_data, int* callback_count, + base::StringPiece mp4_data_string) { + std::copy(mp4_data_string.begin(), mp4_data_string.end(), + std::back_inserter(*total_written_data)); + + ++(*callback_count); + switch (*callback_count) { + case 1: + std::copy(mp4_data_string.begin(), mp4_data_string.end(), + std::back_inserter(*moov_written_data)); + break; + case 2: + std::copy(mp4_data_string.begin(), mp4_data_string.end(), + std::back_inserter(*first_moof_written_data)); + break; + case 3: + std::copy(mp4_data_string.begin(), mp4_data_string.end(), + std::back_inserter(*second_moof_written_data)); + + // Quit. + std::move(run_loop_quit).Run(); + } + }, + run_loop.QuitClosure(), &total_written_data, &moov_written_data, + &first_moof_written_data, &second_moof_written_data, &callback_count)); + + std::vector<uint8_t> code_description; + PopulateAVCDecoderConfiguration(code_description); + + base::TimeTicks base_time_ticks = base::TimeTicks::Now(); + + constexpr uint32_t kSampleDurations[] = {1020, 960, 900, 950}; + base::TimeDelta delta; + + delegate.AddVideoFrame(params, video_stream_1, code_description, + base_time_ticks, true); + for (int i = 0; i < 3; ++i) { + delta += base::Milliseconds(kSampleDurations[i]); + delegate.AddVideoFrame(params, video_stream_2, absl::nullopt, + base_time_ticks + delta, false); + } + + delta += base::Milliseconds(kSampleDurations[3]); + delegate.AddVideoFrame(params, video_stream_1, code_description, + base_time_ticks + delta, true); + for (int i = 0; i < 2; ++i) { + delta += base::Milliseconds(kSampleDurations[i]); + delegate.AddVideoFrame(params, video_stream_2, absl::nullopt, + base_time_ticks + delta, false); + } + + // Write box data to the callback. + delegate.Flush(); + + run_loop.Run(); + + { + // Validate MP4 format. + std::set<int> audio_object_types; + audio_object_types.insert(mp4::kISO_14496_3); + mp4::MP4StreamParser mp4_stream_parser(audio_object_types, false, false); + StreamParser::InitParameters stream_params(base::TimeDelta::Max()); + stream_params.detected_video_track_count = 1; + mp4_stream_parser.Init( + base::BindOnce(&Mp4MuxerDelegateTest::InitF, base::Unretained(this)), + base::BindRepeating(&Mp4MuxerDelegateTest::NewConfigCB, + base::Unretained(this)), + base::BindRepeating(&Mp4MuxerDelegateTest::NewBuffersF, + base::Unretained(this)), + true, + base::BindRepeating(&Mp4MuxerDelegateTest::KeyNeededF, + base::Unretained(this)), + base::BindRepeating(&Mp4MuxerDelegateTest::NewSegmentF, + base::Unretained(this)), + base::BindRepeating(&Mp4MuxerDelegateTest::EndOfSegmentF, + base::Unretained(this)), + &media_log_); + + bool result = mp4_stream_parser.AppendToParseBuffer( + total_written_data.data(), total_written_data.size()); + EXPECT_TRUE(result); + + // `MP4StreamParser::Parse` validates the MP4 format. + StreamParser::ParseStatus parse_result = + mp4_stream_parser.Parse(total_written_data.size()); + EXPECT_EQ(StreamParser::ParseStatus::kSuccess, parse_result); + } + + // Validates the MP4 boxes. + { + // `moov` validation. + std::unique_ptr<mp4::BoxReader> reader; + mp4::ParseResult result = mp4::BoxReader::ReadTopLevelBox( + moov_written_data.data(), moov_written_data.size(), nullptr, &reader); + + EXPECT_EQ(result, mp4::ParseResult::kOk); + EXPECT_TRUE(reader); + EXPECT_EQ(mp4::FOURCC_MOOV, reader->type()); + EXPECT_TRUE(reader->ScanChildren()); + + // `mvhd` test. + mp4::MovieHeader mvhd_box; + EXPECT_TRUE(reader->ReadChild(&mvhd_box)); + EXPECT_EQ(mvhd_box.version, 1); + + EXPECT_NE(mvhd_box.creation_time, 0u); + EXPECT_NE(mvhd_box.modification_time, 0u); + EXPECT_EQ(mvhd_box.timescale, kMovieHeaderTimescale); + EXPECT_NE(mvhd_box.duration, 0u); + EXPECT_EQ(mvhd_box.next_track_id, 2u); + + // `mvex` test. + mp4::MovieExtends mvex_box; + EXPECT_TRUE(reader->ReadChild(&mvex_box)); + + // mp4::MovieExtends mvex_box = mvex_boxes[0]; + EXPECT_EQ(mvex_box.tracks.size(), 1u); + + EXPECT_EQ(mvex_box.tracks[0].track_id, 1u); + EXPECT_EQ(mvex_box.tracks[0].default_sample_description_index, 1u); + EXPECT_EQ(mvex_box.tracks[0].default_sample_duration, 0u); + EXPECT_EQ(mvex_box.tracks[0].default_sample_size, 0u); + EXPECT_EQ(mvex_box.tracks[0].default_sample_flags, 0u); + + // Track header validation. + std::vector<mp4::Track> track_boxes; + EXPECT_TRUE(reader->ReadChildren(&track_boxes)); + EXPECT_EQ(track_boxes.size(), 1u); + + EXPECT_EQ(track_boxes[0].header.track_id, 1u); + EXPECT_NE(track_boxes[0].header.creation_time, 0u); + EXPECT_NE(track_boxes[0].header.modification_time, 0u); + EXPECT_NE(track_boxes[0].header.duration, 0u); + EXPECT_EQ(track_boxes[0].header.volume, 0); + EXPECT_EQ(track_boxes[0].header.width, kWidth); + EXPECT_EQ(track_boxes[0].header.height, kHeight); + + // Media Header validation. + EXPECT_NE(track_boxes[0].media.header.creation_time, 0u); + EXPECT_NE(track_boxes[0].media.header.modification_time, 0u); + EXPECT_NE(track_boxes[0].media.header.duration, 0u); + EXPECT_EQ(track_boxes[0].media.header.timescale, kVideoTimescale); + EXPECT_EQ(track_boxes[0].media.header.language_code, + kUndefinedLanguageCode); + + // Media Handler validation. + EXPECT_EQ(track_boxes[0].media.handler.type, mp4::TrackType::kVideo); + EXPECT_EQ(track_boxes[0].media.handler.name, kVideoHandlerName); + } + + { + // The first `moof` and `mdat` validation. + std::unique_ptr<mp4::BoxReader> moof_reader; + mp4::ParseResult result = mp4::BoxReader::ReadTopLevelBox( + first_moof_written_data.data(), first_moof_written_data.size(), nullptr, + &moof_reader); + + EXPECT_EQ(result, mp4::ParseResult::kOk); + EXPECT_TRUE(moof_reader); + + // `moof` test. + EXPECT_EQ(mp4::FOURCC_MOOF, moof_reader->type()); + EXPECT_TRUE(moof_reader->ScanChildren()); + + // `mfhd` test. + mp4::MovieFragmentHeader mfhd_box; + EXPECT_TRUE(moof_reader->ReadChild(&mfhd_box)); + EXPECT_EQ(1u, mfhd_box.sequence_number); + + // `traf` test. + std::vector<mp4::TrackFragment> traf_boxes; + EXPECT_TRUE(moof_reader->ReadChildren(&traf_boxes)); + ASSERT_EQ(traf_boxes.size(), 1u); + + // `tfhd` test of video. + EXPECT_EQ(1u, traf_boxes[0].header.track_id); + EXPECT_EQ(0u, traf_boxes[0].header.default_sample_duration); + EXPECT_EQ(0u, traf_boxes[0].header.default_sample_size); + EXPECT_EQ(true, traf_boxes[0].header.has_default_sample_flags); + EXPECT_EQ(0x1010000u, traf_boxes[0].header.default_sample_flags); + + // `tfdt` test of video. + EXPECT_EQ(0u, traf_boxes[0].decode_time.decode_time); + + // `trun` test of video. + uint32_t mdat_video_data_offset; + + ASSERT_EQ(1u, traf_boxes[0].runs.size()); + EXPECT_EQ(4u, traf_boxes[0].runs[0].sample_count); + EXPECT_EQ(136u, traf_boxes[0].runs[0].data_offset); + mdat_video_data_offset = traf_boxes[0].runs[0].data_offset; + + ASSERT_EQ(4u, traf_boxes[0].runs[0].sample_durations.size()); + EXPECT_EQ(std::vector<uint32_t>(std::begin(kSampleDurations), + std::end(kSampleDurations)), + traf_boxes[0].runs[0].sample_durations); + + ASSERT_EQ(4u, traf_boxes[0].runs[0].sample_sizes.size()); + // kFirstSampleFlagsPresent enabled and no sample_flags entry, + // then sample_flags will have a value of the first sample flags. + ASSERT_EQ(1u, traf_boxes[0].runs[0].sample_flags.size()); + ASSERT_EQ(0u, traf_boxes[0].runs[0].sample_composition_time_offsets.size()); + + // `mdat` test. + std::unique_ptr<mp4::BoxReader> mdat_reader; + // first_moof_written_data.data() is `moof` box start address. + mp4::ParseResult result1 = mp4::BoxReader::ReadTopLevelBox( + first_moof_written_data.data() + mdat_video_data_offset - + kBoxHeaderSize, + first_moof_written_data.size() - mdat_video_data_offset + + kBoxHeaderSize, + nullptr, &mdat_reader); + + EXPECT_EQ(result1, mp4::ParseResult::kOk); + EXPECT_TRUE(mdat_reader); + EXPECT_EQ(mp4::FOURCC_MDAT, mdat_reader->type()); + } + + { + // The second `moof` and `mdat` validation. + std::unique_ptr<mp4::BoxReader> moof_reader; + mp4::ParseResult result = mp4::BoxReader::ReadTopLevelBox( + second_moof_written_data.data(), second_moof_written_data.size(), + nullptr, &moof_reader); + + EXPECT_EQ(result, mp4::ParseResult::kOk); + EXPECT_TRUE(moof_reader); + + // `moof` test. + EXPECT_EQ(mp4::FOURCC_MOOF, moof_reader->type()); + EXPECT_TRUE(moof_reader->ScanChildren()); + + // `mfhd` test. + mp4::MovieFragmentHeader mfhd_box; + EXPECT_TRUE(moof_reader->ReadChild(&mfhd_box)); + EXPECT_EQ(2u, mfhd_box.sequence_number); + + // `traf` test. + std::vector<mp4::TrackFragment> traf_boxes; + EXPECT_TRUE(moof_reader->ReadChildren(&traf_boxes)); + ASSERT_EQ(traf_boxes.size(), 1u); + + // `tfhd` test of video. + EXPECT_EQ(1u, traf_boxes[0].header.track_id); + EXPECT_EQ(0u, traf_boxes[0].header.default_sample_duration); + EXPECT_EQ(0u, traf_boxes[0].header.default_sample_size); + EXPECT_EQ(true, traf_boxes[0].header.has_default_sample_flags); + EXPECT_EQ(0x1010000u, traf_boxes[0].header.default_sample_flags); + + // `tfdt` test of video. + EXPECT_NE(0u, traf_boxes[0].decode_time.decode_time); + + // `trun` test of video. + uint32_t mdat_video_data_offset; + + ASSERT_EQ(1u, traf_boxes[0].runs.size()); + EXPECT_EQ(3u, traf_boxes[0].runs[0].sample_count); + EXPECT_EQ(128u, traf_boxes[0].runs[0].data_offset); + mdat_video_data_offset = traf_boxes[0].runs[0].data_offset; + + ASSERT_EQ(3u, traf_boxes[0].runs[0].sample_durations.size()); + EXPECT_EQ(kSampleDurations[0], traf_boxes[0].runs[0].sample_durations[0]); + EXPECT_EQ(kSampleDurations[1], traf_boxes[0].runs[0].sample_durations[1]); + // The last sample duration of the last fragment will 1/frame_rate. + EXPECT_EQ(33u, traf_boxes[0].runs[0].sample_durations[2]); + + ASSERT_EQ(3u, traf_boxes[0].runs[0].sample_sizes.size()); + // kFirstSampleFlagsPresent enabled and no sample_flags entry, + // then sample_flags will have a value of the first sample flags. + ASSERT_EQ(1u, traf_boxes[0].runs[0].sample_flags.size()); + ASSERT_EQ(0u, traf_boxes[0].runs[0].sample_composition_time_offsets.size()); + + // `mdat` test. + std::unique_ptr<mp4::BoxReader> mdat_reader; + // second_moof_written_data.data() is `moof` box start address. + mp4::ParseResult result1 = mp4::BoxReader::ReadTopLevelBox( + second_moof_written_data.data() + mdat_video_data_offset - + kBoxHeaderSize, + second_moof_written_data.size() - mdat_video_data_offset + + kBoxHeaderSize, + nullptr, &mdat_reader); + + EXPECT_EQ(result1, mp4::ParseResult::kOk); + EXPECT_TRUE(mdat_reader); + EXPECT_EQ(mp4::FOURCC_MDAT, mdat_reader->type()); + } } +#endif } // namespace media
diff --git a/media/test/data/README.md b/media/test/data/README.md index cdb7a87..ed47f174 100644 --- a/media/test/data/README.md +++ b/media/test/data/README.md
@@ -1576,3 +1576,14 @@ ``` ### one_frame_1280x720.mjpeg It's a single frame mjpeg data. Resolution: 1280x720, color primary: sRGB, transfer function: BT.709, color matrix: BT.601, color range: full-range. + +### avc-bitstream-format-0.h264 +The first 2 frames of the H.264 with bitstream format (NALU length) + +avc-bitstream-format-0.h264: IDR +- ffmpeg -y -i bear-1280x720.mp4 -vcodec copy -f m4v avc-bitstream-format-0.h264 +avc-bitstream-format-1.h264: Non-IDR +- split bear-1280x720.mp4 to annexb files by command of + ffmpeg -i %1 -f image2 -vcodec copy -bsf h264_mp4toannexb "%d.h264" +- manually convert one of created Non-IDR annexb file to avc bitstream. + (replace annexb start code with length)
diff --git a/media/test/data/avc-bitstream-format-0.h264 b/media/test/data/avc-bitstream-format-0.h264 new file mode 100644 index 0000000..46c589d --- /dev/null +++ b/media/test/data/avc-bitstream-format-0.h264 Binary files differ
diff --git a/media/test/data/avc-bitstream-format-1.h264 b/media/test/data/avc-bitstream-format-1.h264 new file mode 100644 index 0000000..6b0f8ca --- /dev/null +++ b/media/test/data/avc-bitstream-format-1.h264 Binary files differ
diff --git a/media/test/media_bundle_data.filelist b/media/test/media_bundle_data.filelist index 92d929b7..4d855a2d 100644 --- a/media/test/media_bundle_data.filelist +++ b/media/test/media_bundle_data.filelist
@@ -32,6 +32,8 @@ data/av1-monochrome-I-frame-320x240-8bpp data/av1-show_existing_frame.ivf data/av1-svc-L2T2.ivf +data/avc-bitstream-format-0.h264 +data/avc-bitstream-format-1.h264 data/bali_640x360_P420.yuv data/basketball_2_layers.vvc data/bbb-320x240-2video-2audio.mp4
diff --git a/media/unit_tests_bundle_data.filelist b/media/unit_tests_bundle_data.filelist index 0ad4ed81..7584dccd 100644 --- a/media/unit_tests_bundle_data.filelist +++ b/media/unit_tests_bundle_data.filelist
@@ -44,6 +44,8 @@ //media/test/data/av1-monochrome-I-frame-320x240-8bpp //media/test/data/av1-show_existing_frame.ivf //media/test/data/av1-svc-L2T2.ivf +//media/test/data/avc-bitstream-format-0.h264 +//media/test/data/avc-bitstream-format-1.h264 //media/test/data/bali_640x360_P420.yuv //media/test/data/basketball_2_layers.vvc //media/test/data/bbb-320x240-2video-2audio.mp4
diff --git a/net/first_party_sets/global_first_party_sets.cc b/net/first_party_sets/global_first_party_sets.cc index bdb45ac..07c2de9 100644 --- a/net/first_party_sets/global_first_party_sets.cc +++ b/net/first_party_sets/global_first_party_sets.cc
@@ -11,9 +11,7 @@ #include "base/containers/flat_map.h" #include "base/containers/flat_set.h" #include "base/functional/function_ref.h" -#include "base/metrics/histogram_macros.h" #include "base/ranges/algorithm.h" -#include "base/timer/elapsed_timer.h" #include "base/types/optional_util.h" #include "net/base/schemeful_site.h" #include "net/first_party_sets/addition_overlaps_union_find.h" @@ -176,13 +174,6 @@ const SchemefulSite* top_frame_site, const std::set<SchemefulSite>& party_context, const FirstPartySetsContextConfig& fps_context_config) const { - const base::ElapsedTimer timer; - - // TODO(https://crbug.com/1348588): Remove this histogram. - UMA_HISTOGRAM_CUSTOM_MICROSECONDS_TIMES( - "Cookie.FirstPartySets.ComputeContext.Latency", timer.Elapsed(), - base::Microseconds(1), base::Milliseconds(100), 50); - absl::optional<FirstPartySetEntry> top_frame_entry = top_frame_site ? FindEntry(*top_frame_site, fps_context_config) : absl::nullopt;
diff --git a/net/quic/quic_connection_logger.cc b/net/quic/quic_connection_logger.cc index 412dbed3..ac521dd 100644 --- a/net/quic/quic_connection_logger.cc +++ b/net/quic/quic_connection_logger.cc
@@ -160,7 +160,8 @@ quic::EncryptionLevel encryption_level, const quic::QuicFrames& retransmittable_frames, const quic::QuicFrames& nonretransmittable_frames, - quic::QuicTime sent_time) { + quic::QuicTime sent_time, + uint32_t batch_id) { // 4.4.1.4. Minimum Packet Size // The payload of a UDP datagram carrying the Initial packet MUST be // expanded to at least 1200 octets @@ -197,7 +198,7 @@ event_logger_.OnPacketSent(packet_number, packet_length, has_crypto_handshake, transmission_type, encryption_level, retransmittable_frames, nonretransmittable_frames, - sent_time); + sent_time, batch_id); } void QuicConnectionLogger::OnPacketLoss(
diff --git a/net/quic/quic_connection_logger.h b/net/quic/quic_connection_logger.h index 255f2e9..04295ed6 100644 --- a/net/quic/quic_connection_logger.h +++ b/net/quic/quic_connection_logger.h
@@ -51,7 +51,8 @@ quic::EncryptionLevel encryption_level, const quic::QuicFrames& retransmittable_frames, const quic::QuicFrames& nonretransmittable_frames, - quic::QuicTime sent_time) override; + quic::QuicTime sent_time, + uint32_t batch_id) override; void OnIncomingAck(quic::QuicPacketNumber ack_packet_number, quic::EncryptionLevel ack_decrypted_level, const quic::QuicAckFrame& frame,
diff --git a/net/quic/quic_event_logger.cc b/net/quic/quic_event_logger.cc index 62e564f..cff25b1 100644 --- a/net/quic/quic_event_logger.cc +++ b/net/quic/quic_event_logger.cc
@@ -32,7 +32,8 @@ quic::QuicPacketLength packet_length, quic::TransmissionType transmission_type, quic::EncryptionLevel encryption_level, - quic::QuicTime sent_time) { + quic::QuicTime sent_time, + uint32_t batch_id) { base::Value::Dict dict; dict.Set("transmission_type", quic::TransmissionTypeToString(transmission_type)); @@ -40,6 +41,7 @@ dict.Set("size", packet_length); dict.Set("sent_time_us", NetLogNumberValue(sent_time.ToDebuggingValue())); dict.Set("encryption_level", quic::EncryptionLevelToString(encryption_level)); + dict.Set("batch_id", NetLogNumberValue(batch_id)); return dict; } @@ -516,11 +518,12 @@ quic::EncryptionLevel encryption_level, const quic::QuicFrames& /*retransmittable_frames*/, const quic::QuicFrames& /*nonretransmittable_frames*/, - quic::QuicTime sent_time) { + quic::QuicTime sent_time, + uint32_t batch_id) { net_log_.AddEvent(NetLogEventType::QUIC_SESSION_PACKET_SENT, [&] { return NetLogQuicPacketSentParams(packet_number, packet_length, transmission_type, encryption_level, - sent_time); + sent_time, batch_id); }); }
diff --git a/net/quic/quic_event_logger.h b/net/quic/quic_event_logger.h index cb9b921..ce7a0c5 100644 --- a/net/quic/quic_event_logger.h +++ b/net/quic/quic_event_logger.h
@@ -37,7 +37,8 @@ quic::EncryptionLevel encryption_level, const quic::QuicFrames& retransmittable_frames, const quic::QuicFrames& nonretransmittable_frames, - quic::QuicTime sent_time) override; + quic::QuicTime sent_time, + uint32_t batch_id) override; void OnIncomingAck(quic::QuicPacketNumber ack_packet_number, quic::EncryptionLevel ack_decrypted_level, const quic::QuicAckFrame& frame,
diff --git a/printing/metafile_skia.cc b/printing/metafile_skia.cc index d0328e3..75b26b4 100644 --- a/printing/metafile_skia.cc +++ b/printing/metafile_skia.cc
@@ -272,8 +272,8 @@ } gfx::Rect MetafileSkia::GetPageBounds(unsigned int page_number) const { - if (page_number < data_->pages.size()) { - SkSize size = data_->pages[page_number].size; + if (page_number > 0 && page_number - 1 < data_->pages.size()) { + SkSize size = data_->pages[page_number - 1].size; return gfx::Rect(base::ClampRound(size.width()), base::ClampRound(size.height())); }
diff --git a/printing/metafile_skia.h b/printing/metafile_skia.h index a0cad537..5f885543 100644 --- a/printing/metafile_skia.h +++ b/printing/metafile_skia.h
@@ -126,8 +126,9 @@ ui::AXTreeUpdate& accessibility_tree() { return accessibility_tree_; } private: - FRIEND_TEST_ALL_PREFIXES(MetafileSkiaTest, TestFrameContent); - FRIEND_TEST_ALL_PREFIXES(MetafileSkiaTest, TestMultiPictureDocumentTypefaces); + FRIEND_TEST_ALL_PREFIXES(MetafileSkiaTest, FrameContent); + FRIEND_TEST_ALL_PREFIXES(MetafileSkiaTest, GetPageBounds); + FRIEND_TEST_ALL_PREFIXES(MetafileSkiaTest, MultiPictureDocumentTypefaces); // The following three functions are used for tests only. void AppendPage(const SkSize& page_size, cc::PaintRecord record);
diff --git a/printing/metafile_skia_unittest.cc b/printing/metafile_skia_unittest.cc index e1dec65..539045b 100644 --- a/printing/metafile_skia_unittest.cc +++ b/printing/metafile_skia_unittest.cc
@@ -27,7 +27,7 @@ namespace printing { -TEST(MetafileSkiaTest, TestFrameContent) { +TEST(MetafileSkiaTest, FrameContent) { constexpr int kPictureSideLen = 100; constexpr int kPageSideLen = 150; @@ -94,7 +94,47 @@ EXPECT_EQ(bitmap.getColor(kPictureSideLen, kPictureSideLen), SK_ColorWHITE); } -TEST(MetafileSkiaTest, TestMultiPictureDocumentTypefaces) { +TEST(MetafileSkiaTest, GetPageBounds) { + constexpr int kPictureSideLen = 100; + constexpr int kPageSideWidth = 150; + constexpr int kPageSideHeight = 120; + + // Create a placeholder picture. + sk_sp<SkPicture> pic_holder = SkPicture::MakePlaceholder( + SkRect::MakeXYWH(0, 0, kPictureSideLen, kPictureSideLen)); + + // Create the page with nested content which is the placeholder and will be + // replaced later. + cc::PaintOpBuffer buffer; + cc::PaintFlags flags; + flags.setColor(SK_ColorWHITE); + const SkRect page_rect = + SkRect::MakeXYWH(0, 0, kPageSideWidth, kPageSideHeight); + buffer.push<cc::DrawRectOp>(page_rect, flags); + const uint32_t content_id = pic_holder->uniqueID(); + buffer.push<cc::CustomDataOp>(content_id); + SkSize page_size = SkSize::Make(kPageSideWidth, kPageSideHeight); + + // Finish creating the entire metafile. + MetafileSkia metafile(mojom::SkiaDocumentType::kMSKP, 1); + metafile.AppendPage(page_size, buffer.ReleaseAsRecord()); + metafile.AppendSubframeInfo(content_id, base::UnguessableToken::Create(), + std::move(pic_holder)); + metafile.FinishFrameContent(); + + // Confirm there is 1 page in the doc. + EXPECT_EQ(1u, metafile.GetPageCount()); + + // Test in bound case. + EXPECT_EQ(gfx::Rect(kPageSideWidth, kPageSideHeight), + metafile.GetPageBounds(/*page_number=*/1)); + + // Test out of bounds cases. + EXPECT_EQ(gfx::Rect(), metafile.GetPageBounds(/*page_number=*/0)); + EXPECT_EQ(gfx::Rect(), metafile.GetPageBounds(/*page_number=*/2)); +} + +TEST(MetafileSkiaTest, MultiPictureDocumentTypefaces) { constexpr int kPictureSideLen = 100; constexpr int kPageSideLen = 150; constexpr int kDocumentCookie = 1;
diff --git a/sandbox/policy/features.cc b/sandbox/policy/features.cc index 35be129..b273d2fd 100644 --- a/sandbox/policy/features.cc +++ b/sandbox/policy/features.cc
@@ -83,6 +83,13 @@ BASE_FEATURE(kWinSboxWarmupProcessPrng, "WinSboxWarmupProcessPrng", base::FEATURE_DISABLED_BY_DEFAULT); + +// If enabled, launch the network service within an LPAC sandbox. If disabled, +// the network service will run inside an App Container. +BASE_FEATURE(kWinSboxNetworkServiceSandboxIsLPAC, + "WinSboxNetworkServiceSandboxIsLPAC", + base::FEATURE_DISABLED_BY_DEFAULT); + #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/sandbox/policy/features.h b/sandbox/policy/features.h index ef9d2cc..2c6150e 100644 --- a/sandbox/policy/features.h +++ b/sandbox/policy/features.h
@@ -34,6 +34,7 @@ SANDBOX_POLICY_EXPORT BASE_DECLARE_FEATURE(kWinSboxHighRendererJobMemoryLimits); SANDBOX_POLICY_EXPORT BASE_DECLARE_FEATURE(kWinSboxRendererCloseKsecDD); SANDBOX_POLICY_EXPORT BASE_DECLARE_FEATURE(kWinSboxWarmupProcessPrng); +SANDBOX_POLICY_EXPORT BASE_DECLARE_FEATURE(kWinSboxNetworkServiceSandboxIsLPAC); #endif // BUILDFLAG(IS_WIN) #if BUILDFLAG(IS_CHROMEOS_ASH)
diff --git a/sandbox/policy/win/sandbox_win.cc b/sandbox/policy/win/sandbox_win.cc index 8a13045..ced003a 100644 --- a/sandbox/policy/win/sandbox_win.cc +++ b/sandbox/policy/win/sandbox_win.cc
@@ -542,6 +542,8 @@ base::win::WellKnownCapability::kEnterpriseAuthentication); container->AddCapability(kLpacIdentityServices); container->AddCapability(kLpacCryptoServices); + container->SetEnableLowPrivilegeAppContainer(base::FeatureList::IsEnabled( + features::kWinSboxNetworkServiceSandboxIsLPAC)); } if (sandbox_type == Sandbox::kWindowsSystemProxyResolver) { @@ -555,7 +557,6 @@ if ((sandbox_type == Sandbox::kGpu && base::FeatureList::IsEnabled(features::kGpuLPAC)) || sandbox_type == Sandbox::kMediaFoundationCdm || - sandbox_type == Sandbox::kNetwork || sandbox_type == Sandbox::kWindowsSystemProxyResolver) { container->SetEnableLowPrivilegeAppContainer(true); }
diff --git a/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.cc b/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.cc index 34a80a5..a0ea7d5 100644 --- a/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.cc +++ b/services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.cc
@@ -537,7 +537,7 @@ trace_packet->set_streaming_profile_packet(); streaming_profile_packet->add_callstack_iid(callstack_id); - int32_t current_process_priority = base::Process::Current().GetPriority(); + int32_t current_process_priority = base::Process::Current().GetOSPriority(); if (current_process_priority != 0) { streaming_profile_packet->set_process_priority(current_process_priority); }
diff --git a/testing/scripts/run_finch_smoke_tests_android.py b/testing/scripts/run_finch_smoke_tests_android.py index 0c165e7..462a10b 100755 --- a/testing/scripts/run_finch_smoke_tests_android.py +++ b/testing/scripts/run_finch_smoke_tests_android.py
@@ -267,20 +267,22 @@ return True def enable_internet(self): + # Commands here need root permission. self._device.RunShellCommand( - ['settings', 'put', 'global', 'airplane_mode_on', '0']) + ['settings', 'put', 'global', 'airplane_mode_on', '0'], as_root=True) self._device.RunShellCommand( ['am', 'broadcast', '-a', - 'android.intent.action.AIRPLANE_MODE']) - self._device.RunShellCommand(['svc', 'wifi', 'enable']) - self._device.RunShellCommand(['svc', 'data', 'enable']) + 'android.intent.action.AIRPLANE_MODE'], as_root=True) + self._device.RunShellCommand(['svc', 'wifi', 'enable'], as_root=True) + self._device.RunShellCommand(['svc', 'data', 'enable'], as_root=True) def disable_internet(self): + # Commands here need root permission. self._device.RunShellCommand( - ['settings', 'put', 'global', 'airplane_mode_on', '1']) + ['settings', 'put', 'global', 'airplane_mode_on', '1'], as_root=True) self._device.RunShellCommand( ['am', 'broadcast', '-a', - 'android.intent.action.AIRPLANE_MODE']) + 'android.intent.action.AIRPLANE_MODE'], as_root=True) @contextlib.contextmanager def _archive_logcat(self, filename, endpoint_name):
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index f6e2e1c..a3ce44d 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -4711,6 +4711,23 @@ ] } ], + "DesktopPWAInstallPromotionML": [ + { + "platforms": [ + "linux", + "mac", + "windows" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "WebAppsEnableMLModelForPromotion" + ] + } + ] + } + ], "DesktopReadingListAddFromDialog": [ { "platforms": [ @@ -6437,6 +6454,63 @@ ] } ], + "GridTabSwitcherTablet": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "TabStripRedesign.FolioWithoutButtonStyleOnly.Enabled_20230718", + "params": { + "disable_btn_style": "true", + "enable_folio": "true" + }, + "enable_features": [ + "TabStripRedesign" + ] + }, + { + "name": "TabStripRedesign.DetachedWithoutButtonStyleOnly.Enabled_20230718", + "params": { + "disable_btn_style": "true", + "enable_detached": "true" + }, + "enable_features": [ + "TabStripRedesign" + ] + }, + { + "name": "TabStripRedesign.FolioWithoutNtbAnchorAndWithoutBtnStyle.Enabled_20230718", + "params": { + "disable_btn_style": "true", + "disable_ntb_anchor": "true", + "enable_folio": "true" + }, + "enable_features": [ + "TabStripRedesign" + ] + }, + { + "name": "TabStripRedesign.DetachedWithoutNtbAnchorAndWithoutBtnStyle.Enabled_20230718", + "params": { + "disable_btn_style": "true", + "disable_ntb_anchor": "true", + "enable_detached": "true" + }, + "enable_features": [ + "TabStripRedesign" + ] + }, + { + "name": "TabletToolbarReorderingEnabled_20230718", + "enable_features": [ + "TabletToolbarReordering" + ] + } + ] + } + ], "GwpAsanAndroid": [ { "platforms": [ @@ -7663,21 +7737,6 @@ ] } ], - "IOSWebChannels": [ - { - "platforms": [ - "ios" - ], - "experiments": [ - { - "name": "EnabledWebChannels", - "enable_features": [ - "EnableWebChannels" - ] - } - ] - } - ], "IOSWhatsNew": [ { "platforms": [
diff --git a/third_party/blink/common/rust_crash/src/lib.rs b/third_party/blink/common/rust_crash/src/lib.rs index 1b002538..4089cb6 100644 --- a/third_party/blink/common/rust_crash/src/lib.rs +++ b/third_party/blink/common/rust_crash/src/lib.rs
@@ -5,7 +5,7 @@ //! Code to generate an artificial Rust panic to exercise our crash handling //! logic and ensure it works for Rust crashes. -#[cxx::bridge] +#[cxx::bridge(namespace = "blink")] mod ffi { extern "Rust" { fn crash_in_rust(); // step 1 of main crash trigger. We bounce back to C++
diff --git a/third_party/blink/public/mojom/manifest/manifest.mojom b/third_party/blink/public/mojom/manifest/manifest.mojom index dfba6635..9574ab8 100644 --- a/third_party/blink/public/mojom/manifest/manifest.mojom +++ b/third_party/blink/public/mojom/manifest/manifest.mojom
@@ -32,6 +32,11 @@ // This is empty if the start_url is empty. url.mojom.Url id; + // TODO(crbug.com/1466730): Investigate if this should return the + // document_url_ if ManifestParser fails to parse the start_url as per + // the spec. This can sometimes be an empty KURL, which can be + // intentional so that the non existence of a start URL can be handled + // further down the callstack. url.mojom.Url start_url; DisplayMode display;
diff --git a/third_party/blink/renderer/core/frame/history.cc b/third_party/blink/renderer/core/frame/history.cc index af1a92c..f4119ca 100644 --- a/third_party/blink/renderer/core/frame/history.cc +++ b/third_party/blink/renderer/core/frame/history.cc
@@ -229,8 +229,10 @@ task_id = tracker->RunningTaskAttributionId(script_state); } DCHECK(frame->Client()); - frame->Client()->NavigateBackForward(delta, task_id); - frame->GetPage()->HistoryNavigationVirtualTimePauser().PauseVirtualTime(); + if (frame->Client()->NavigateBackForward(delta, task_id)) { + if (Page* page = frame->GetPage()) + page->HistoryNavigationVirtualTimePauser().PauseVirtualTime(); + } } else { // We intentionally call reload() for the current frame if delta is zero. // Otherwise, navigation happens on the root frame.
diff --git a/third_party/blink/renderer/core/frame/local_frame_client.h b/third_party/blink/renderer/core/frame/local_frame_client.h index fb229297..62e611e 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client.h +++ b/third_party/blink/renderer/core/frame/local_frame_client.h
@@ -199,7 +199,7 @@ virtual void DidStartLoading() = 0; virtual void DidStopLoading() = 0; - virtual void NavigateBackForward( + virtual bool NavigateBackForward( int offset, absl::optional<scheduler::TaskAttributionId> soft_navigation_heuristics_task_id) const = 0;
diff --git a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc index fa8c26e..dbf7fd7 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client_impl.cc +++ b/third_party/blink/renderer/core/frame/local_frame_client_impl.cc
@@ -708,18 +708,25 @@ web_frame_->Client()->DidStopLoading(); } -void LocalFrameClientImpl::NavigateBackForward( +bool LocalFrameClientImpl::NavigateBackForward( int offset, absl::optional<scheduler::TaskAttributionId> soft_navigation_heuristics_task_id) const { WebViewImpl* webview = web_frame_->ViewImpl(); DCHECK(webview->Client()); DCHECK(web_frame_->Client()); + DCHECK(offset); + if (offset > webview->HistoryForwardListCount()) + return false; + if (offset < -webview->HistoryBackListCount()) + return false; + bool has_user_gesture = LocalFrame::HasTransientUserActivation(web_frame_->GetFrame()); web_frame_->GetFrame()->GetLocalFrameHostRemote().GoToEntryAtOffset( offset, has_user_gesture, soft_navigation_heuristics_task_id); + return true; } void LocalFrameClientImpl::DidDispatchPingLoader(const KURL& url) {
diff --git a/third_party/blink/renderer/core/frame/local_frame_client_impl.h b/third_party/blink/renderer/core/frame/local_frame_client_impl.h index 9f6a7e83..28e1c00 100644 --- a/third_party/blink/renderer/core/frame/local_frame_client_impl.h +++ b/third_party/blink/renderer/core/frame/local_frame_client_impl.h
@@ -146,7 +146,7 @@ void DispatchWillSendSubmitEvent(HTMLFormElement*) override; void DidStartLoading() override; void DidStopLoading() override; - void NavigateBackForward( + bool NavigateBackForward( int offset, absl::optional<scheduler::TaskAttributionId> soft_navigation_heuristics_task_id) const override;
diff --git a/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc b/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc index 4a40473c..57e1e45 100644 --- a/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc +++ b/third_party/blink/renderer/core/frame/local_frame_mojo_handler.cc
@@ -1142,7 +1142,6 @@ void LocalFrameMojoHandler::TraverseCancelled( const String& navigation_api_key, mojom::blink::TraverseCancelledReason reason) { - frame_->GetPage()->HistoryNavigationVirtualTimePauser().UnpauseVirtualTime(); frame_->DomWindow()->navigation()->TraverseCancelled(navigation_api_key, reason); }
diff --git a/third_party/blink/renderer/core/loader/empty_clients.h b/third_party/blink/renderer/core/loader/empty_clients.h index 6b695ab..1934ca8 100644 --- a/third_party/blink/renderer/core/loader/empty_clients.h +++ b/third_party/blink/renderer/core/loader/empty_clients.h
@@ -359,9 +359,11 @@ void TransitionToCommittedForNewPage() override {} - void NavigateBackForward( + bool NavigateBackForward( int offset, - absl::optional<scheduler::TaskAttributionId>) const override {} + absl::optional<scheduler::TaskAttributionId>) const override { + return false; + } void DidDispatchPingLoader(const KURL&) override {} void SelectorMatchChanged(const Vector<String>&, const Vector<String>&) override {}
diff --git a/third_party/blink/renderer/modules/file_system_access/BUILD.gn b/third_party/blink/renderer/modules/file_system_access/BUILD.gn index bf58b81e..390c34f 100644 --- a/third_party/blink/renderer/modules/file_system_access/BUILD.gn +++ b/third_party/blink/renderer/modules/file_system_access/BUILD.gn
@@ -15,6 +15,8 @@ "file_system_access_file_delegate.h", "file_system_access_incognito_file_delegate.cc", "file_system_access_incognito_file_delegate.h", + "file_system_access_manager.cc", + "file_system_access_manager.h", "file_system_access_regular_file_delegate.cc", "file_system_access_regular_file_delegate.h", "file_system_directory_handle.cc",
diff --git a/third_party/blink/renderer/modules/file_system_access/data_transfer_item_file_system_access.cc b/third_party/blink/renderer/modules/file_system_access/data_transfer_item_file_system_access.cc index 755d3ef3..c59e52f 100644 --- a/third_party/blink/renderer/modules/file_system_access/data_transfer_item_file_system_access.cc +++ b/third_party/blink/renderer/modules/file_system_access/data_transfer_item_file_system_access.cc
@@ -4,12 +4,9 @@ #include "third_party/blink/renderer/modules/file_system_access/data_transfer_item_file_system_access.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_data_transfer_token.mojom-blink.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom-blink.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_error.mojom-blink.h" -#include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-blink.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/core/clipboard/data_object_item.h" @@ -17,6 +14,7 @@ #include "third_party/blink/renderer/core/clipboard/data_transfer_item.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_access_error.h" +#include "third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" @@ -39,11 +37,6 @@ return ScriptPromise::CastUndefined(script_state); } - mojo::Remote<mojom::blink::FileSystemAccessManager> fsa_manager; - ExecutionContext* execution_context = ExecutionContext::From(script_state); - execution_context->GetBrowserInterfaceBroker().GetInterface( - fsa_manager.BindNewPipeAndPassReceiver()); - const DataObjectItem& data_object_item = *data_transfer_item.GetDataObjectItem(); @@ -56,32 +49,30 @@ script_state, exception_state.GetContext()); ScriptPromise result = resolver->Promise(); - // We need to move `fsa_manager` into GetEntryFromDataTransferToken in order - // to keep it in scope long enough for the callback to be executed. To do this - // we extract `raw_fsa_manager` from `fsa_manager` and move `fsa_manager` into - // the GetEntryFromDataTransferToken callback. - auto* raw_fsa_manager = fsa_manager.get(); - raw_fsa_manager->GetEntryFromDataTransferToken( - std::move(token_remote), - WTF::BindOnce( - [](mojo::Remote<mojom::blink::FileSystemAccessManager>, - ScriptPromiseResolver* resolver, - mojom::blink::FileSystemAccessErrorPtr result, - mojom::blink::FileSystemAccessEntryPtr entry) { - ScriptState* script_state = resolver->GetScriptState(); - if (!script_state) - return; + auto* execution_context = ExecutionContext::From(script_state); + FileSystemAccessManager::From(execution_context) + ->GetEntryFromDataTransferToken( + std::move(token_remote), + WTF::BindOnce( + [](ScriptPromiseResolver* resolver, + mojom::blink::FileSystemAccessErrorPtr result, + mojom::blink::FileSystemAccessEntryPtr entry) { + ScriptState* script_state = resolver->GetScriptState(); + if (!script_state) { + return; + } - if (result->status != mojom::blink::FileSystemAccessStatus::kOk) { - DCHECK(entry.is_null()); - file_system_access_error::Reject(resolver, *result); - return; - } + if (result->status != + mojom::blink::FileSystemAccessStatus::kOk) { + DCHECK(entry.is_null()); + file_system_access_error::Reject(resolver, *result); + return; + } - resolver->Resolve(FileSystemHandle::CreateFromMojoEntry( - std::move(entry), ExecutionContext::From(script_state))); - }, - std::move(fsa_manager), WrapPersistent(resolver))); + resolver->Resolve(FileSystemHandle::CreateFromMojoEntry( + std::move(entry), ExecutionContext::From(script_state))); + }, + WrapPersistent(resolver))); return result; }
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_access_manager.cc b/third_party/blink/renderer/modules/file_system_access/file_system_access_manager.cc new file mode 100644 index 0000000..1939a917 --- /dev/null +++ b/third_party/blink/renderer/modules/file_system_access/file_system_access_manager.cc
@@ -0,0 +1,51 @@ +// 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 "third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h" +#include "third_party/blink/public/platform/task_type.h" +#include "third_party/blink/renderer/core/execution_context/execution_context.h" + +namespace blink { + +// static +const char FileSystemAccessManager::kSupplementName[] = + "FileSystemAccessManager"; + +// static +FileSystemAccessManager& FileSystemAccessManager::From( + ExecutionContext* context) { + FileSystemAccessManager* manager = + Supplement<ExecutionContext>::From<FileSystemAccessManager>(context); + if (!manager) { + manager = MakeGarbageCollected<FileSystemAccessManager>(context); + Supplement<ExecutionContext>::ProvideTo(*context, manager); + } + manager->EnsureConnection(); + return *manager; +} + +FileSystemAccessManager::FileSystemAccessManager(ExecutionContext* context) + : Supplement<ExecutionContext>(*context), + ExecutionContextClient(context), + remote_(context) {} + +void FileSystemAccessManager::Trace(Visitor* visitor) const { + visitor->Trace(remote_); + Supplement<ExecutionContext>::Trace(visitor); + ExecutionContextClient::Trace(visitor); +} + +void FileSystemAccessManager::EnsureConnection() { + CHECK(GetExecutionContext()); + + if (remote_.is_bound()) { + return; + } + + auto task_runner = GetExecutionContext()->GetTaskRunner(TaskType::kStorage); + GetExecutionContext()->GetBrowserInterfaceBroker().GetInterface( + remote_.BindNewPipeAndPassReceiver(std::move(task_runner))); +} + +} // namespace blink
diff --git a/third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h b/third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h new file mode 100644 index 0000000..90b67c95 --- /dev/null +++ b/third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h
@@ -0,0 +1,53 @@ +// 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 THIRD_PARTY_BLINK_RENDERER_MODULES_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_MANAGER_H_ +#define THIRD_PARTY_BLINK_RENDERER_MODULES_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_MANAGER_H_ + +#include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-blink.h" +#include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" +#include "third_party/blink/renderer/modules/modules_export.h" +#include "third_party/blink/renderer/platform/heap/garbage_collected.h" +#include "third_party/blink/renderer/platform/mojo/heap_mojo_remote.h" +#include "third_party/blink/renderer/platform/supplementable.h" + +namespace blink { + +class ExecutionContext; + +// This class maintains a connection to the FileSystemAccessManager remote. +class MODULES_EXPORT FileSystemAccessManager final + : public GarbageCollected<FileSystemAccessManager>, + public Supplement<ExecutionContext>, + public ExecutionContextClient { + public: + static const char kSupplementName[]; + + static FileSystemAccessManager& From(ExecutionContext*); + + explicit FileSystemAccessManager(ExecutionContext*); + + FileSystemAccessManager(const FileSystemAccessManager&) = delete; + FileSystemAccessManager& operator=(const FileSystemAccessManager&) = delete; + + HeapMojoRemote<mojom::blink::FileSystemAccessManager>::Proxy* operator->() { + return remote_.get(); + } + + // GarbageCollected + void Trace(Visitor*) const override; + + private: + // TODO(https://crbug.com/1241174): Extend ExecutionContextLifecycleObserver + // and override ContextEnteredBackForwardCache() to respond gracefully when a + // page enters the BFCache (e.g. by releasing locks). + + void EnsureConnection(); + + HeapMojoRemote<mojom::blink::FileSystemAccessManager> remote_; +}; + +} // namespace blink + +#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_FILE_SYSTEM_ACCESS_FILE_SYSTEM_ACCESS_MANAGER_H_
diff --git a/third_party/blink/renderer/modules/file_system_access/global_file_system_access.cc b/third_party/blink/renderer/modules/file_system_access/global_file_system_access.cc index 8dd6d829..3fd97881c 100644 --- a/third_party/blink/renderer/modules/file_system_access/global_file_system_access.cc +++ b/third_party/blink/renderer/modules/file_system_access/global_file_system_access.cc
@@ -8,8 +8,6 @@ #include "base/notreached.h" #include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_error.mojom-blink.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-blink-forward.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-blink.h" @@ -28,6 +26,7 @@ #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/probe/core_probes.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_access_error.h" +#include "third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_file_handle.h" #include "third_party/blink/renderer/platform/bindings/enumeration_base.h" @@ -247,60 +246,52 @@ script_state, exception_state.GetContext()); ScriptPromise resolver_result = resolver->Promise(); - // TODO(mek): Cache mojo::Remote<mojom::blink::FileSystemAccessManager> - // associated with an ExecutionContext, so we don't have to request a new one - // for each operation, and can avoid code duplication between here and other - // uses. - mojo::Remote<mojom::blink::FileSystemAccessManager> manager; - window.GetBrowserInterfaceBroker().GetInterface( - manager.BindNewPipeAndPassReceiver()); + FileSystemAccessManager::From(resolver->GetExecutionContext()) + ->ChooseEntries( + std::move(options), std::move(common_options), + WTF::BindOnce( + [](ScriptPromiseResolver* resolver, bool return_as_sequence, + LocalFrame* local_frame, + mojom::blink::FileSystemAccessErrorPtr file_operation_result, + Vector<mojom::blink::FileSystemAccessEntryPtr> entries) { + ExecutionContext* context = resolver->GetExecutionContext(); + if (!context) { + return; + } + if (file_operation_result->status != + mojom::blink::FileSystemAccessStatus::kOk) { + file_system_access_error::Reject(resolver, + *file_operation_result); + return; + } - auto* raw_manager = manager.get(); - raw_manager->ChooseEntries( - std::move(options), std::move(common_options), - WTF::BindOnce( - [](ScriptPromiseResolver* resolver, - mojo::Remote<mojom::blink::FileSystemAccessManager>, - bool return_as_sequence, LocalFrame* local_frame, - mojom::blink::FileSystemAccessErrorPtr file_operation_result, - Vector<mojom::blink::FileSystemAccessEntryPtr> entries) { - ExecutionContext* context = resolver->GetExecutionContext(); - if (!context) - return; - if (file_operation_result->status != - mojom::blink::FileSystemAccessStatus::kOk) { - file_system_access_error::Reject(resolver, - *file_operation_result); - return; - } + // While it would be better to not trust the renderer process, + // we're doing this here to avoid potential mojo message pipe + // ordering problems, where the frame activation state + // reconciliation messages would compete with concurrent File + // System Access messages to the browser. + // TODO(https://crbug.com/1017270): Remove this after spec + // change, or when activation moves to browser. + LocalFrame::NotifyUserActivation( + local_frame, mojom::blink::UserActivationNotificationType:: + kFileSystemAccess); - // While it would be better to not trust the renderer process, - // we're doing this here to avoid potential mojo message pipe - // ordering problems, where the frame activation state - // reconciliation messages would compete with concurrent File - // System Access messages to the browser. - // TODO(https://crbug.com/1017270): Remove this after spec change, - // or when activation moves to browser. - LocalFrame::NotifyUserActivation( - local_frame, mojom::blink::UserActivationNotificationType:: - kFileSystemAccess); - - if (return_as_sequence) { - HeapVector<Member<FileSystemHandle>> results; - results.ReserveInitialCapacity(entries.size()); - for (auto& entry : entries) { - results.push_back(FileSystemHandle::CreateFromMojoEntry( - std::move(entry), context)); - } - resolver->Resolve(results); - } else { - DCHECK_EQ(1u, entries.size()); - resolver->Resolve(FileSystemHandle::CreateFromMojoEntry( - std::move(entries[0]), context)); - } - }, - WrapPersistent(resolver), std::move(manager), return_as_sequence, - WrapPersistent(window.GetFrame()))); + if (return_as_sequence) { + HeapVector<Member<FileSystemHandle>> results; + results.ReserveInitialCapacity(entries.size()); + for (auto& entry : entries) { + results.push_back(FileSystemHandle::CreateFromMojoEntry( + std::move(entry), context)); + } + resolver->Resolve(results); + } else { + DCHECK_EQ(1u, entries.size()); + resolver->Resolve(FileSystemHandle::CreateFromMojoEntry( + std::move(entries[0]), context)); + } + }, + WrapPersistent(resolver), return_as_sequence, + WrapPersistent(window.GetFrame()))); return resolver_result; }
diff --git a/third_party/blink/renderer/modules/file_system_access/storage_manager_file_system_access.cc b/third_party/blink/renderer/modules/file_system_access/storage_manager_file_system_access.cc index 09db2bc..fa097de 100644 --- a/third_party/blink/renderer/modules/file_system_access/storage_manager_file_system_access.cc +++ b/third_party/blink/renderer/modules/file_system_access/storage_manager_file_system_access.cc
@@ -7,10 +7,7 @@ #include <utility> #include "mojo/public/cpp/bindings/pending_remote.h" -#include "mojo/public/cpp/bindings/remote.h" -#include "third_party/blink/public/common/browser_interface_broker_proxy.h" #include "third_party/blink/public/mojom/file_system_access/file_system_access_error.mojom-blink.h" -#include "third_party/blink/public/mojom/file_system_access/file_system_access_manager.mojom-blink.h" #include "third_party/blink/public/platform/web_content_settings_client.h" #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" #include "third_party/blink/renderer/bindings/core/v8/v8_throw_dom_exception.h" @@ -18,6 +15,7 @@ #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_access_error.h" +#include "third_party/blink/renderer/modules/file_system_access/file_system_access_manager.h" #include "third_party/blink/renderer/modules/file_system_access/file_system_directory_handle.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/garbage_collected.h" @@ -33,21 +31,16 @@ // Gets the OPFS for the default bucket. void GetSandboxedFileSystemForDefaultBucket(ScriptPromiseResolver* resolver) { - mojo::Remote<mojom::blink::FileSystemAccessManager> manager; - resolver->GetExecutionContext()->GetBrowserInterfaceBroker().GetInterface( - manager.BindNewPipeAndPassReceiver()); - - auto* raw_manager = manager.get(); - raw_manager->GetSandboxedFileSystem(WTF::BindOnce( - [](ScriptPromiseResolver* resolver, - mojo::Remote<mojom::blink::FileSystemAccessManager>, - mojom::blink::FileSystemAccessErrorPtr result, - mojo::PendingRemote<mojom::blink::FileSystemAccessDirectoryHandle> - handle) { - StorageManagerFileSystemAccess::DidGetSandboxedFileSystem( - resolver, std::move(result), std::move(handle)); - }, - WrapPersistent(resolver), std::move(manager))); + FileSystemAccessManager::From(resolver->GetExecutionContext()) + ->GetSandboxedFileSystem(WTF::BindOnce( + [](ScriptPromiseResolver* resolver, + mojom::blink::FileSystemAccessErrorPtr result, + mojo::PendingRemote<mojom::blink::FileSystemAccessDirectoryHandle> + handle) { + StorageManagerFileSystemAccess::DidGetSandboxedFileSystem( + resolver, std::move(result), std::move(handle)); + }, + WrapPersistent(resolver))); } // Called with the result of browser-side permissions checks.
diff --git a/third_party/blink/web_tests/SlowTests b/third_party/blink/web_tests/SlowTests index 74cfb79..2dbeae0 100644 --- a/third_party/blink/web_tests/SlowTests +++ b/third_party/blink/web_tests/SlowTests
@@ -575,7 +575,6 @@ crbug.com/874695 fast/forms/color-scheme/* [ Slow ] crbug.com/874695 [ Release ] fast/forms/number/number-spinbutton-gets-disabled-or-readonly.html [ Slow ] crbug.com/874695 fast/forms/select/input-select-after-resize.html [ Slow ] -crbug.com/874695 fast/history/history-back-twice-with-subframes-assert.html [ Slow ] crbug.com/874695 fast/media/mq-color-gamut-picture.html [ Slow ] crbug.com/874695 [ Linux ] fast/peerconnection/RTCPeerConnection-many.html [ Slow ] crbug.com/874695 [ Mac10.15 Release ] fast/peerconnection/RTCPeerConnection-many.html [ Slow ]
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index 66ec993a..ae2f508 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -6565,3 +6565,6 @@ # Gardener 2023-07-21 crbug.com/1180274 http/tests/inspector-protocol/network/navigate-iframe-out2in.js [ Crash Failure Pass Timeout ] + +# This test is unreliable because of delayed update of history.length during cross-document navigation. +crbug.com/1466474 fast/history/history-back-twice-with-subframes-assert.html [ Pass Timeout ]
diff --git a/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/overlapping-navigations-and-traversals/cross-document-traversal-cross-document-traversal-expected.txt b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/overlapping-navigations-and-traversals/cross-document-traversal-cross-document-traversal-expected.txt new file mode 100644 index 0000000..bc974a7 --- /dev/null +++ b/third_party/blink/web_tests/external/wpt/html/browsers/browsing-the-web/overlapping-navigations-and-traversals/cross-document-traversal-cross-document-traversal-expected.txt
@@ -0,0 +1,7 @@ +This is a testharness.js-based test. +PASS cross-document traversals in opposite directions: the result is going nowhere +FAIL cross-document traversals in opposite directions, second traversal invalid at queuing time but valid at the time it is run: the result is going nowhere assert_unreached: second load event Reached unreachable code +PASS cross-document traversals in the same (back) direction: the result is going -2 with only one load event +PASS cross-document traversals in the same (forward) direction: the result is going +2 with only one load event +Harness: the test ran to completion. +
diff --git a/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect-expected.txt b/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect-expected.txt index c8829d6..91a5677 100644 --- a/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect-expected.txt +++ b/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect-expected.txt
@@ -3,6 +3,7 @@ --prefers-color-scheme: nomatch; --prefers-reduced-motion: nomatch; --prefers-reduced-data: nomatch; + --prefers-reduced-transparency: nomatch; --prefers-contrast: nomatch; --color-gamut: nomatch; --forced-colors: nomatch @@ -10,6 +11,7 @@ --prefers-color-scheme: dark; --prefers-reduced-motion: reduce; --prefers-reduced-data: reduce; + --prefers-reduced-transparency: reduce; --prefers-contrast: more; --color-gamut: p3; --forced-colors: active @@ -17,6 +19,7 @@ --prefers-color-scheme: nomatch; --prefers-reduced-motion: nomatch; --prefers-reduced-data: nomatch; + --prefers-reduced-transparency: nomatch; --prefers-contrast: nomatch; --color-gamut: nomatch; --forced-colors: nomatch
diff --git a/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect.js b/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect.js index cbde8ccb..6e0100f7 100644 --- a/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect.js +++ b/third_party/blink/web_tests/inspector-protocol/emulation/restore-emulated-media-on-disconnect.js
@@ -17,6 +17,10 @@ value: 'reduce', }, { + name: 'prefers-reduced-transparency', + value: 'reduce', + }, + { name: 'prefers-contrast', value: 'more', },
diff --git a/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt index ced2fcb..ed3e9de 100644 --- a/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt +++ b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override-expected.txt
@@ -25,6 +25,14 @@ matchMedia("(prefers-reduced-data: reduce)").matches applied: reduce matchMedia("(prefers-reduced-data: __invalid__)").matches: false matchMedia("(prefers-reduced-data: __invalid__)").matches applied: no-preference +matchMedia("(prefers-reduced-transparency: __invalid__)").matches: false +matchMedia("(prefers-reduced-transparency: __invalid__)").matches applied: no-preference +matchMedia("(prefers-reduced-transparency: no-preference)").matches: true +matchMedia("(prefers-reduced-transparency: no-preference)").matches applied: no-preference +matchMedia("(prefers-reduced-transparency: reduce)").matches: true +matchMedia("(prefers-reduced-transparency: reduce)").matches applied: reduce +matchMedia("(prefers-reduced-transparency: __invalid__)").matches: false +matchMedia("(prefers-reduced-transparency: __invalid__)").matches applied: no-preference matchMedia("(prefers-contrast: __invalid__)").matches: false matchMedia("(prefers-contrast: __invalid__)").matches applied: no-preference matchMedia("(prefers-contrast: no-preference)").matches: true
diff --git a/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js index be6ac2f..69b8068 100644 --- a/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js +++ b/third_party/blink/web_tests/inspector-protocol/emulation/set-css-media-feature-override.js
@@ -64,6 +64,13 @@ await setEmulatedMediaFeature('prefers-reduced-data', 'reduce'); await setEmulatedMediaFeature('prefers-reduced-data', '__invalid__'); + // Test `prefers-reduced-transparency`. + // https://drafts.csswg.org/mediaqueries-5/#prefers-reduced-transparency + await setEmulatedMediaFeature('prefers-reduced-transparency', '__invalid__'); + await setEmulatedMediaFeature('prefers-reduced-transparency', 'no-preference'); + await setEmulatedMediaFeature('prefers-reduced-transparency', 'reduce'); + await setEmulatedMediaFeature('prefers-reduced-transparency', '__invalid__'); + // Test `prefers-contrast`. // https://drafts.csswg.org/mediaqueries-5/#prefers-contrast await setEmulatedMediaFeature('prefers-contrast', '__invalid__');
diff --git a/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html b/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html index a61ae3c..0ff0bd7 100644 --- a/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html +++ b/third_party/blink/web_tests/inspector-protocol/resources/css-media-features.html
@@ -4,6 +4,7 @@ --prefers-color-scheme:invalid; --prefers-reduced-motion:invalid; --prefers-reduced-data:invalid; + --prefers-reduced-transparency:invalid; --prefers-contrast:invalid; --color-gamut:invalid; --forced-colors:invalid; @@ -15,6 +16,8 @@ @media (prefers-reduced-motion: reduce) { p { --prefers-reduced-motion:reduce; } } @media (prefers-reduced-data: no-preference) { p { --prefers-reduced-data:no-preference; } } @media (prefers-reduced-data: reduce) { p { --prefers-reduced-data:reduce; } } + @media (prefers-reduced-transparency: no-preference) { p { --prefers-reduced-transparency:no-preference; } } + @media (prefers-reduced-transparency: reduce) { p { --prefers-reduced-transparency:reduce; } } @media (prefers-contrast: no-preference) { p { --prefers-contrast:no-preference; } } @media (prefers-contrast: more) { p { --prefers-contrast:more; } } @media (prefers-contrast: less) { p { --prefers-contrast:less; } }
diff --git a/third_party/blink/web_tests/inspector-protocol/resources/restore-emulated-media-on-disconnect.html b/third_party/blink/web_tests/inspector-protocol/resources/restore-emulated-media-on-disconnect.html index 9b80086..5e092a3 100644 --- a/third_party/blink/web_tests/inspector-protocol/resources/restore-emulated-media-on-disconnect.html +++ b/third_party/blink/web_tests/inspector-protocol/resources/restore-emulated-media-on-disconnect.html
@@ -4,6 +4,7 @@ --prefers-color-scheme:nomatch; --prefers-reduced-motion:nomatch; --prefers-reduced-data:nomatch; + --prefers-reduced-transparency:nomatch; --prefers-contrast:nomatch; --color-gamut:nomatch; --forced-colors:nomatch; @@ -11,6 +12,7 @@ @media (prefers-color-scheme: dark) { p { --prefers-color-scheme:dark; } } @media (prefers-reduced-motion: reduce) { p { --prefers-reduced-motion:reduce; } } @media (prefers-reduced-data: reduce) { p { --prefers-reduced-data:reduce; } } + @media (prefers-reduced-transparency: reduce) { p { --prefers-reduced-transparency:reduce; } } @media (prefers-contrast: more) { p { --prefers-contrast:more; } } @media (color-gamut: p3) { p { --color-gamut:p3; } } @media (forced-colors: active) { p { --forced-colors:active; } }
diff --git a/third_party/mediapipe/patches/update-checks.patch b/third_party/mediapipe/patches/update-checks.patch new file mode 100644 index 0000000..7a591d9 --- /dev/null +++ b/third_party/mediapipe/patches/update-checks.patch
@@ -0,0 +1,5672 @@ +diff --git a/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc +index 60ec405372e01..b9e2fe4abdf20 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc +@@ -200,15 +200,15 @@ PacketResamplerCalculator::GetSamplingStrategy( + + Timestamp PacketResamplerCalculator::PeriodIndexToTimestamp( + int64_t index) const { +- CHECK_EQ(jitter_, 0.0); +- CHECK_NE(first_timestamp_, Timestamp::Unset()); ++ ABSL_CHECK_EQ(jitter_, 0.0); ++ ABSL_CHECK_NE(first_timestamp_, Timestamp::Unset()); + return first_timestamp_ + TimestampDiffFromSeconds(index / frame_rate_); + } + + int64_t PacketResamplerCalculator::TimestampToPeriodIndex( + Timestamp timestamp) const { +- CHECK_EQ(jitter_, 0.0); +- CHECK_NE(first_timestamp_, Timestamp::Unset()); ++ ABSL_CHECK_EQ(jitter_, 0.0); ++ ABSL_CHECK_NE(first_timestamp_, Timestamp::Unset()); + return MathUtil::SafeRound<int64_t, double>( + (timestamp - first_timestamp_).Seconds() * frame_rate_); + } +@@ -340,8 +340,8 @@ void LegacyJitterWithReflectionStrategy::UpdateNextOutputTimestampWithJitter() { + next_output_timestamp_ = Timestamp(ReflectBetween( + next_output_timestamp_.Value(), next_output_timestamp_min_.Value(), + next_output_timestamp_max_.Value())); +- CHECK_GE(next_output_timestamp_, next_output_timestamp_min_); +- CHECK_LT(next_output_timestamp_, next_output_timestamp_max_); ++ ABSL_CHECK_GE(next_output_timestamp_, next_output_timestamp_min_); ++ ABSL_CHECK_LT(next_output_timestamp_, next_output_timestamp_max_); + } + + absl::Status ReproducibleJitterWithReflectionStrategy::Open( +diff --git a/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc +index 35cd966ea3173..ecb6ca57f0b3b 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc +@@ -17,6 +17,7 @@ + #include <cmath> // for ceil + #include <memory> + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/core/packet_thinner_calculator.pb.h" + #include "mediapipe/framework/calculator_context.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -177,7 +178,8 @@ absl::Status PacketThinnerCalculator::Open(CalculatorContext* cc) { + } else { + period_ = TimestampDiff(options.period()); + } +- CHECK_LT(TimestampDiff(0), period_) << "Specified period must be positive."; ++ ABSL_CHECK_LT(TimestampDiff(0), period_) ++ << "Specified period must be positive."; + + if (options.has_start_time()) { + start_time_ = Timestamp(options.start_time()); +@@ -189,7 +191,7 @@ absl::Status PacketThinnerCalculator::Open(CalculatorContext* cc) { + + end_time_ = + options.has_end_time() ? Timestamp(options.end_time()) : Timestamp::Max(); +- CHECK_LT(start_time_, end_time_) ++ ABSL_CHECK_LT(start_time_, end_time_) + << "Invalid PacketThinner: start_time must be earlier than end_time"; + + sync_output_timestamps_ = options.sync_output_timestamps(); +@@ -232,7 +234,7 @@ absl::Status PacketThinnerCalculator::Close(CalculatorContext* cc) { + // Emit any saved packets before quitting. + if (!saved_packet_.IsEmpty()) { + // Only sync thinner should have saved packets. +- CHECK_EQ(PacketThinnerCalculatorOptions::SYNC, thinner_type_); ++ ABSL_CHECK_EQ(PacketThinnerCalculatorOptions::SYNC, thinner_type_); + if (sync_output_timestamps_) { + cc->Outputs().Index(0).AddPacket( + saved_packet_.At(NearestSyncTimestamp(saved_packet_.Timestamp()))); +@@ -269,7 +271,7 @@ absl::Status PacketThinnerCalculator::SyncThinnerProcess( + const Timestamp saved_sync = NearestSyncTimestamp(saved); + const Timestamp now = cc->InputTimestamp(); + const Timestamp now_sync = NearestSyncTimestamp(now); +- CHECK_LE(saved_sync, now_sync); ++ ABSL_CHECK_LE(saved_sync, now_sync); + if (saved_sync == now_sync) { + // Saved Packet is in same interval as current packet. + // Replace saved packet with current if it is at least as +@@ -295,7 +297,7 @@ absl::Status PacketThinnerCalculator::SyncThinnerProcess( + } + + Timestamp PacketThinnerCalculator::NearestSyncTimestamp(Timestamp now) const { +- CHECK_NE(start_time_, Timestamp::Unset()) ++ ABSL_CHECK_NE(start_time_, Timestamp::Unset()) + << "Method only valid for sync thinner calculator."; + + // Computation is done using int64 arithmetic. No easy way to avoid +@@ -303,12 +305,12 @@ Timestamp PacketThinnerCalculator::NearestSyncTimestamp(Timestamp now) const { + const int64_t now64 = now.Value(); + const int64_t start64 = start_time_.Value(); + const int64_t period64 = period_.Value(); +- CHECK_LE(0, period64); ++ ABSL_CHECK_LE(0, period64); + + // Round now64 to its closest interval (units of period64). + int64_t sync64 = + (now64 - start64 + period64 / 2) / period64 * period64 + start64; +- CHECK_LE(abs(now64 - sync64), period64 / 2) ++ ABSL_CHECK_LE(abs(now64 - sync64), period64 / 2) + << "start64: " << start64 << "; now64: " << now64 + << "; sync64: " << sync64; + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc +index 6bb43dc00ee05..5eac351d2582b 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc +@@ -15,6 +15,7 @@ + #include <memory> + #include <string> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_replace.h" + #include "mediapipe/calculators/image/bilateral_filter_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -112,7 +113,7 @@ class BilateralFilterCalculator : public CalculatorBase { + REGISTER_CALCULATOR(BilateralFilterCalculator); + + absl::Status BilateralFilterCalculator::GetContract(CalculatorContract* cc) { +- CHECK_GE(cc->Inputs().NumEntries(), 1); ++ ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); + + if (cc->Inputs().HasTag(kInputFrameTag) && + cc->Inputs().HasTag(kInputFrameTagGpu)) { +@@ -183,8 +184,8 @@ absl::Status BilateralFilterCalculator::Open(CalculatorContext* cc) { + + sigma_color_ = options_.sigma_color(); + sigma_space_ = options_.sigma_space(); +- CHECK_GE(sigma_color_, 0.0); +- CHECK_GE(sigma_space_, 0.0); ++ ABSL_CHECK_GE(sigma_color_, 0.0); ++ ABSL_CHECK_GE(sigma_space_, 0.0); + if (!use_gpu_) sigma_color_ *= 255.0; + + if (use_gpu_) { +diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc +index 93ec9435f1af4..0308b9b8c4af8 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc +@@ -12,6 +12,7 @@ + // See the License for the specific language governing permissions and + // limitations under the License. + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/image/opencv_image_encoder_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/image_frame_opencv.h" +@@ -61,7 +62,7 @@ absl::Status OpenCvImageEncoderCalculator::Open(CalculatorContext* cc) { + + absl::Status OpenCvImageEncoderCalculator::Process(CalculatorContext* cc) { + const ImageFrame& image_frame = cc->Inputs().Index(0).Get<ImageFrame>(); +- CHECK_EQ(1, image_frame.ByteDepth()); ++ ABSL_CHECK_EQ(1, image_frame.ByteDepth()); + + std::unique_ptr<OpenCvImageEncoderCalculatorResults> encoded_result = + absl::make_unique<OpenCvImageEncoderCalculatorResults>(); +diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc +index d8a3cb93ba583..128aa424fbe1a 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc +@@ -18,6 +18,7 @@ + #include <memory> + #include <string> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/substitute.h" + #include "libyuv/scale.h" +@@ -507,7 +508,7 @@ absl::Status ScaleImageCalculator::ValidateImageFrame( + + absl::Status ScaleImageCalculator::ValidateYUVImage(CalculatorContext* cc, + const YUVImage& yuv_image) { +- CHECK_EQ(input_format_, ImageFormat::YCBCR420P); ++ ABSL_CHECK_EQ(input_format_, ImageFormat::YCBCR420P); + if (!has_header_) { + if (input_width_ != yuv_image.width() || + input_height_ != yuv_image.height()) { +diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc +index 86a53ffc5eb65..e119a876a89d4 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc +@@ -18,6 +18,7 @@ + + #include <string> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_split.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/ret_check.h" +@@ -83,8 +84,8 @@ absl::Status FindCropDimensions(int input_width, int input_height, // + } + } + +- CHECK_LE(*crop_width, input_width); +- CHECK_LE(*crop_height, input_height); ++ ABSL_CHECK_LE(*crop_width, input_width); ++ ABSL_CHECK_LE(*crop_height, input_height); + return absl::OkStatus(); + } + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc +index 81732f9044f38..9b4a262913215 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc +@@ -32,6 +32,7 @@ + #endif // !MEDIAPIPE_DISABLE_GPU + + #if !MEDIAPIPE_DISABLE_OPENCV ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/formats/image_frame_opencv.h" + #include "mediapipe/framework/formats/image_opencv.h" + #include "mediapipe/framework/port/opencv_core_inc.h" +@@ -110,7 +111,7 @@ REGISTER_CALCULATOR(SegmentationSmoothingCalculator); + + absl::Status SegmentationSmoothingCalculator::GetContract( + CalculatorContract* cc) { +- CHECK_GE(cc->Inputs().NumEntries(), 1); ++ ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); + + cc->Inputs().Tag(kCurrentMaskTag).Set<Image>(); + cc->Inputs().Tag(kPreviousMaskTag).Set<Image>(); +diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc +index e20621e8d7489..211c2840100e2 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc +@@ -14,6 +14,7 @@ + + #include <memory> + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/image/set_alpha_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/calculator_options.pb.h" +@@ -142,7 +143,7 @@ class SetAlphaCalculator : public CalculatorBase { + REGISTER_CALCULATOR(SetAlphaCalculator); + + absl::Status SetAlphaCalculator::GetContract(CalculatorContract* cc) { +- CHECK_GE(cc->Inputs().NumEntries(), 1); ++ ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); + + bool use_gpu = false; + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc +index 01cc60a154439..e8c9a6c65f753 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc +@@ -20,6 +20,7 @@ + #include <utility> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/status/status.h" + #include "absl/status/statusor.h" +@@ -457,7 +458,7 @@ absl::Status AudioToTensorCalculator::SetupStreamingResampler( + } + + void AudioToTensorCalculator::AppendZerosToSampleBuffer(int num_samples) { +- CHECK_GE(num_samples, 0); // Ensured by `UpdateContract`. ++ ABSL_CHECK_GE(num_samples, 0); // Ensured by `UpdateContract`. + if (num_samples == 0) { + return; + } +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc +index c1bd92968eb2f..a9606e653f1a0 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc +@@ -15,6 +15,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/tensor/tensor_converter_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/image_frame.h" +@@ -582,7 +583,7 @@ absl::Status TensorConverterCalculator::LoadOptions(CalculatorContext* cc) { + if (options.has_output_tensor_float_range()) { + output_range_.emplace(options.output_tensor_float_range().min(), + options.output_tensor_float_range().max()); +- CHECK_GT(output_range_->second, output_range_->first); ++ ABSL_CHECK_GT(output_range_->second, output_range_->first); + } + + // Custom div and sub values. +@@ -600,9 +601,9 @@ absl::Status TensorConverterCalculator::LoadOptions(CalculatorContext* cc) { + + // Get desired way to handle input channels. + max_num_channels_ = options.max_num_channels(); +- CHECK_GE(max_num_channels_, 1); +- CHECK_LE(max_num_channels_, 4); +- CHECK_NE(max_num_channels_, 2); ++ ABSL_CHECK_GE(max_num_channels_, 1); ++ ABSL_CHECK_LE(max_num_channels_, 4); ++ ABSL_CHECK_NE(max_num_channels_, 2); + return absl::OkStatus(); + } + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc +index 246269de10efa..3e19ae5bee365 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc +@@ -15,6 +15,7 @@ + #include <unordered_map> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + #include "absl/types/span.h" + #include "mediapipe/calculators/tensor/tensors_to_detections_calculator.pb.h" +@@ -83,7 +84,7 @@ void ConvertRawValuesToAnchors(const float* raw_anchors, int num_boxes, + + void ConvertAnchorsToRawValues(const std::vector<Anchor>& anchors, + int num_boxes, float* raw_anchors) { +- CHECK_EQ(anchors.size(), num_boxes); ++ ABSL_CHECK_EQ(anchors.size(), num_boxes); + int box = 0; + for (const auto& anchor : anchors) { + raw_anchors[box * kNumCoordsPerBox + 0] = anchor.y_center(); +@@ -703,18 +704,18 @@ absl::Status TensorsToDetectionsCalculator::LoadOptions(CalculatorContext* cc) { + num_boxes_ = options_.num_boxes(); + num_coords_ = options_.num_coords(); + box_output_format_ = GetBoxFormat(options_); +- CHECK_NE(options_.max_results(), 0) ++ ABSL_CHECK_NE(options_.max_results(), 0) + << "The maximum number of the top-scored detection results must be " + "non-zero."; + max_results_ = options_.max_results(); + + // Currently only support 2D when num_values_per_keypoint equals to 2. +- CHECK_EQ(options_.num_values_per_keypoint(), 2); ++ ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); + + // Check if the output size is equal to the requested boxes and keypoints. +- CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + +- kNumCoordsPerBox, +- num_coords_); ++ ABSL_CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + ++ kNumCoordsPerBox, ++ num_coords_); + + if (kSideInIgnoreClasses(cc).IsConnected()) { + RET_CHECK(!kSideInIgnoreClasses(cc).IsEmpty()); +@@ -1154,11 +1155,12 @@ void main() { + } + // TODO support better filtering. + if (class_index_set_.is_allowlist) { +- CHECK_EQ(class_index_set_.values.size(), +- IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) ++ ABSL_CHECK_EQ(class_index_set_.values.size(), ++ IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) + << "Only all classes >= class 0 or >= class 1"; + } else { +- CHECK_EQ(class_index_set_.values.size(), IsClassIndexAllowed(0) ? 0 : 1) ++ ABSL_CHECK_EQ(class_index_set_.values.size(), ++ IsClassIndexAllowed(0) ? 0 : 1) + << "Only ignore class 0 is allowed"; + } + +@@ -1379,11 +1381,12 @@ kernel void scoreKernel( + + // TODO support better filtering. + if (class_index_set_.is_allowlist) { +- CHECK_EQ(class_index_set_.values.size(), +- IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) ++ ABSL_CHECK_EQ(class_index_set_.values.size(), ++ IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) + << "Only all classes >= class 0 or >= class 1"; + } else { +- CHECK_EQ(class_index_set_.values.size(), IsClassIndexAllowed(0) ? 0 : 1) ++ ABSL_CHECK_EQ(class_index_set_.values.size(), ++ IsClassIndexAllowed(0) ? 0 : 1) + << "Only ignore class 0 is allowed"; + } + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc +index a1cc4e202a49f..cfee6bad0a535 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc +@@ -12,6 +12,7 @@ + // See the License for the specific language governing permissions and + // limitations under the License. + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/tensor/tensors_to_landmarks_calculator.pb.h" + #include "mediapipe/framework/api2/node.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -142,7 +143,7 @@ absl::Status TensorsToLandmarksCalculator::Process(CalculatorContext* cc) { + RET_CHECK(input_tensors[0].element_type() == Tensor::ElementType::kFloat32); + int num_values = input_tensors[0].shape().num_elements(); + const int num_dimensions = num_values / num_landmarks_; +- CHECK_GT(num_dimensions, 0); ++ ABSL_CHECK_GT(num_dimensions, 0); + + auto view = input_tensors[0].GetCpuReadView(); + auto raw_landmarks = view.buffer<float>(); +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc +index cb90276aee6cd..04c3ba117979e 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc +@@ -15,6 +15,7 @@ + // Converts a single int or vector<int> or vector<vector<int>> to 1D (or 2D) + // tf::Tensor. + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator_options.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/port/ret_check.h" +@@ -113,11 +114,11 @@ absl::Status VectorIntToTensorCalculator::Process(CalculatorContext* cc) { + .Get<std::vector<std::vector<int>>>(); + + const int32_t rows = input.size(); +- CHECK_GE(rows, 1); ++ ABSL_CHECK_GE(rows, 1); + const int32_t cols = input[0].size(); +- CHECK_GE(cols, 1); ++ ABSL_CHECK_GE(cols, 1); + for (int i = 1; i < rows; ++i) { +- CHECK_EQ(input[i].size(), cols); ++ ABSL_CHECK_EQ(input[i].size(), cols); + } + if (options_.transpose()) { + tensor_shape = tf::TensorShape({cols, rows}); +@@ -171,7 +172,7 @@ absl::Status VectorIntToTensorCalculator::Process(CalculatorContext* cc) { + } else { + input = cc->Inputs().Tag(kVectorInt).Value().Get<std::vector<int>>(); + } +- CHECK_GE(input.size(), 1); ++ ABSL_CHECK_GE(input.size(), 1); + const int32_t length = input.size(); + tensor_shape = tf::TensorShape({length}); + auto output = ::absl::make_unique<tf::Tensor>(options_.tensor_data_type(), +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc +index 5ed5a95dcaecd..e56765d94d784 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc +@@ -16,6 +16,7 @@ + #include <utility> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/tflite/ssd_anchors_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/object_detection/anchor.pb.h" +@@ -274,11 +275,11 @@ absl::Status SsdAnchorsCalculator::GenerateAnchors( + if (options.strides_size()) { + LOG(ERROR) << "Found feature map shapes. Strides will be ignored."; + } +- CHECK_EQ(options.feature_map_height_size(), kNumLayers); +- CHECK_EQ(options.feature_map_height_size(), +- options.feature_map_width_size()); ++ ABSL_CHECK_EQ(options.feature_map_height_size(), kNumLayers); ++ ABSL_CHECK_EQ(options.feature_map_height_size(), ++ options.feature_map_width_size()); + } else { +- CHECK_EQ(options.strides_size(), kNumLayers); ++ ABSL_CHECK_EQ(options.strides_size(), kNumLayers); + } + + if (options.multiscale_anchor_generation()) { +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc +index ff6b2ff91b2ee..7188cbc591c8f 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc +@@ -15,6 +15,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/tflite/tflite_converter_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/image_frame.h" +@@ -643,7 +644,7 @@ absl::Status TfLiteConverterCalculator::LoadOptions(CalculatorContext* cc) { + if (options.has_output_tensor_float_range()) { + output_range_.emplace(options.output_tensor_float_range().min(), + options.output_tensor_float_range().max()); +- CHECK_GT(output_range_->second, output_range_->first); ++ ABSL_CHECK_GT(output_range_->second, output_range_->first); + } + + // Custom div and sub values. +@@ -661,9 +662,9 @@ absl::Status TfLiteConverterCalculator::LoadOptions(CalculatorContext* cc) { + + // Get desired way to handle input channels. + max_num_channels_ = options.max_num_channels(); +- CHECK_GE(max_num_channels_, 1); +- CHECK_LE(max_num_channels_, 4); +- CHECK_NE(max_num_channels_, 2); ++ ABSL_CHECK_GE(max_num_channels_, 1); ++ ABSL_CHECK_LE(max_num_channels_, 4); ++ ABSL_CHECK_NE(max_num_channels_, 2); + #if defined(MEDIAPIPE_IOS) + if (cc->Inputs().HasTag(kGpuBufferTag)) + // Currently on iOS, tflite gpu input tensor must be 4 channels, +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc +index add9bb1a81668..4b89133236b54 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc +@@ -17,6 +17,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "mediapipe/calculators/tflite/tflite_inference_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -109,8 +110,8 @@ std::unique_ptr<tflite::Interpreter> BuildEdgeTpuInterpreter( + edgetpu::EdgeTpuContext* edgetpu_context) { + resolver->AddCustom(edgetpu::kCustomOp, edgetpu::RegisterCustomOp()); + std::unique_ptr<tflite::Interpreter> interpreter; +- CHECK_EQ(tflite::InterpreterBuilder(model, *resolver)(&interpreter), +- kTfLiteOk); ++ ABSL_CHECK_EQ(tflite::InterpreterBuilder(model, *resolver)(&interpreter), ++ kTfLiteOk); + interpreter->SetExternalContext(kTfLiteEdgeTpuContext, edgetpu_context); + return interpreter; + } +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc +index 4d28b91e9263c..98ab4b1da12d1 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc +@@ -17,6 +17,7 @@ + #include <vector> + + #include "absl/container/node_hash_map.h" ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + #include "absl/types/span.h" + #include "mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.pb.h" +@@ -172,7 +173,7 @@ absl::Status TfLiteTensorsToClassificationCalculator::Process( + + // Note that partial_sort will raise error when top_k_ > + // classification_list->classification_size(). +- CHECK_GE(classification_list->classification_size(), top_k_); ++ ABSL_CHECK_GE(classification_list->classification_size(), top_k_); + auto raw_classification_list = classification_list->mutable_classification(); + if (top_k_ > 0 && classification_list->classification_size() >= top_k_) { + std::partial_sort(raw_classification_list->begin(), +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc +index 2ed62c46d4505..2d91f54252ecb 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc +@@ -15,6 +15,7 @@ + #include <unordered_map> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + #include "absl/types/span.h" + #include "mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.pb.h" +@@ -93,7 +94,7 @@ void ConvertRawValuesToAnchors(const float* raw_anchors, int num_boxes, + + void ConvertAnchorsToRawValues(const std::vector<Anchor>& anchors, + int num_boxes, float* raw_anchors) { +- CHECK_EQ(anchors.size(), num_boxes); ++ ABSL_CHECK_EQ(anchors.size(), num_boxes); + int box = 0; + for (const auto& anchor : anchors) { + raw_anchors[box * kNumCoordsPerBox + 0] = anchor.y_center(); +@@ -288,14 +289,14 @@ absl::Status TfLiteTensorsToDetectionsCalculator::ProcessCPU( + const TfLiteTensor* raw_score_tensor = &input_tensors[1]; + + // TODO: Add flexible input tensor size handling. +- CHECK_EQ(raw_box_tensor->dims->size, 3); +- CHECK_EQ(raw_box_tensor->dims->data[0], 1); +- CHECK_EQ(raw_box_tensor->dims->data[1], num_boxes_); +- CHECK_EQ(raw_box_tensor->dims->data[2], num_coords_); +- CHECK_EQ(raw_score_tensor->dims->size, 3); +- CHECK_EQ(raw_score_tensor->dims->data[0], 1); +- CHECK_EQ(raw_score_tensor->dims->data[1], num_boxes_); +- CHECK_EQ(raw_score_tensor->dims->data[2], num_classes_); ++ ABSL_CHECK_EQ(raw_box_tensor->dims->size, 3); ++ ABSL_CHECK_EQ(raw_box_tensor->dims->data[0], 1); ++ ABSL_CHECK_EQ(raw_box_tensor->dims->data[1], num_boxes_); ++ ABSL_CHECK_EQ(raw_box_tensor->dims->data[2], num_coords_); ++ ABSL_CHECK_EQ(raw_score_tensor->dims->size, 3); ++ ABSL_CHECK_EQ(raw_score_tensor->dims->data[0], 1); ++ ABSL_CHECK_EQ(raw_score_tensor->dims->data[1], num_boxes_); ++ ABSL_CHECK_EQ(raw_score_tensor->dims->data[2], num_classes_); + const float* raw_boxes = raw_box_tensor->data.f; + const float* raw_scores = raw_score_tensor->data.f; + +@@ -303,9 +304,9 @@ absl::Status TfLiteTensorsToDetectionsCalculator::ProcessCPU( + if (!anchors_init_) { + if (input_tensors.size() == kNumInputTensorsWithAnchors) { + const TfLiteTensor* anchor_tensor = &input_tensors[2]; +- CHECK_EQ(anchor_tensor->dims->size, 2); +- CHECK_EQ(anchor_tensor->dims->data[0], num_boxes_); +- CHECK_EQ(anchor_tensor->dims->data[1], kNumCoordsPerBox); ++ ABSL_CHECK_EQ(anchor_tensor->dims->size, 2); ++ ABSL_CHECK_EQ(anchor_tensor->dims->data[0], num_boxes_); ++ ABSL_CHECK_EQ(anchor_tensor->dims->data[1], kNumCoordsPerBox); + const float* raw_anchors = anchor_tensor->data.f; + ConvertRawValuesToAnchors(raw_anchors, num_boxes_, &anchors_); + } else if (side_packet_anchors_) { +@@ -417,7 +418,7 @@ absl::Status TfLiteTensorsToDetectionsCalculator::ProcessGPU( + MP_RETURN_IF_ERROR(gpu_data_->raw_anchors_buffer.Write<float>( + absl::MakeSpan(raw_anchors))); + } else { +- CHECK_EQ(input_tensors.size(), kNumInputTensorsWithAnchors); ++ ABSL_CHECK_EQ(input_tensors.size(), kNumInputTensorsWithAnchors); + MP_RETURN_IF_ERROR( + CopyBuffer(input_tensors[2], gpu_data_->raw_anchors_buffer)); + } +@@ -567,12 +568,12 @@ absl::Status TfLiteTensorsToDetectionsCalculator::LoadOptions( + num_coords_ = options_.num_coords(); + + // Currently only support 2D when num_values_per_keypoint equals to 2. +- CHECK_EQ(options_.num_values_per_keypoint(), 2); ++ ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); + + // Check if the output size is equal to the requested boxes and keypoints. +- CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + +- kNumCoordsPerBox, +- num_coords_); ++ ABSL_CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + ++ kNumCoordsPerBox, ++ num_coords_); + + for (int i = 0; i < options_.ignore_classes_size(); ++i) { + ignore_classes_.insert(options_.ignore_classes(i)); +@@ -897,10 +898,11 @@ void main() { + int max_wg_size; // typically <= 1024 + glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, + &max_wg_size); // y-dim +- CHECK_LT(num_classes_, max_wg_size) ++ ABSL_CHECK_LT(num_classes_, max_wg_size) + << "# classes must be < " << max_wg_size; + // TODO support better filtering. +- CHECK_LE(ignore_classes_.size(), 1) << "Only ignore class 0 is allowed"; ++ ABSL_CHECK_LE(ignore_classes_.size(), 1) ++ << "Only ignore class 0 is allowed"; + + // Shader program + GlShader score_shader; +@@ -1115,7 +1117,7 @@ kernel void scoreKernel( + ignore_classes_.size() ? 1 : 0); + + // TODO support better filtering. +- CHECK_LE(ignore_classes_.size(), 1) << "Only ignore class 0 is allowed"; ++ ABSL_CHECK_LE(ignore_classes_.size(), 1) << "Only ignore class 0 is allowed"; + + { + // Shader program +@@ -1147,7 +1149,8 @@ kernel void scoreKernel( + options:MTLResourceStorageModeShared]; + // # filter classes supported is hardware dependent. + int max_wg_size = gpu_data_->score_program.maxTotalThreadsPerThreadgroup; +- CHECK_LT(num_classes_, max_wg_size) << "# classes must be <" << max_wg_size; ++ ABSL_CHECK_LT(num_classes_, max_wg_size) ++ << "# classes must be <" << max_wg_size; + } + + #endif // MEDIAPIPE_TFLITE_GL_INFERENCE +diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc +index 1be83bbe14d30..6740f0afa5989 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc +@@ -12,6 +12,7 @@ + // See the License for the specific language governing permissions and + // limitations under the License. + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/landmark.pb.h" +@@ -199,7 +200,7 @@ absl::Status TfLiteTensorsToLandmarksCalculator::Process( + num_values *= raw_tensor->dims->data[i]; + } + const int num_dimensions = num_values / num_landmarks_; +- CHECK_GT(num_dimensions, 0); ++ ABSL_CHECK_GT(num_dimensions, 0); + + const float* raw_landmarks = raw_tensor->data.f; + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc +index 34093702ca789..fbd24ee3b95af 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc +@@ -14,6 +14,7 @@ + + #include <memory> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/calculators/util/annotation_overlay_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -172,7 +173,7 @@ class AnnotationOverlayCalculator : public CalculatorBase { + REGISTER_CALCULATOR(AnnotationOverlayCalculator); + + absl::Status AnnotationOverlayCalculator::GetContract(CalculatorContract* cc) { +- CHECK_GE(cc->Inputs().NumEntries(), 1); ++ ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); + + bool use_gpu = false; + +diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h b/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h +index 037ea838c7688..1cec63c80c31e 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h ++++ b/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h +@@ -18,6 +18,7 @@ + #include <memory> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "mediapipe/calculators/util/association_calculator.pb.h" + #include "mediapipe/framework/calculator_context.h" +@@ -72,7 +73,7 @@ class AssociationCalculator : public CalculatorBase { + prev_input_stream_id_ = cc->Inputs().GetId("PREV", 0); + } + options_ = cc->Options<::mediapipe::AssociationCalculatorOptions>(); +- CHECK_GE(options_.min_similarity_threshold(), 0); ++ ABSL_CHECK_GE(options_.min_similarity_threshold(), 0); + + return absl::OkStatus(); + } +diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc +index 25d74ba68e236..73430093b6f3d 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc +@@ -12,6 +12,7 @@ + // See the License for the specific language governing permissions and + // limitations under the License. + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/str_join.h" +@@ -239,7 +240,7 @@ void DetectionsToRenderDataCalculator::AddLabels( + "is present."; + const auto num_labels = + std::max(detection.label_size(), detection.label_id_size()); +- CHECK_EQ(detection.score_size(), num_labels) ++ ABSL_CHECK_EQ(detection.score_size(), num_labels) + << "Number of scores and labels should match for detection."; + + // Extracts all "label(_id),score" for the detection. +diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc +index dcd76d47b2836..314640ed736bc 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc +@@ -19,6 +19,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/calculators/util/labels_to_render_data_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -114,7 +115,8 @@ absl::Status LabelsToRenderDataCalculator::Process(CalculatorContext* cc) { + video_height_ = video_header.height; + return absl::OkStatus(); + } else { +- CHECK_EQ(options_.location(), LabelsToRenderDataCalculatorOptions::TOP_LEFT) ++ ABSL_CHECK_EQ(options_.location(), ++ LabelsToRenderDataCalculatorOptions::TOP_LEFT) + << "Only TOP_LEFT is supported without VIDEO_PRESTREAM."; + } + +@@ -144,7 +146,7 @@ absl::Status LabelsToRenderDataCalculator::Process(CalculatorContext* cc) { + if (cc->Inputs().HasTag(kScoresTag)) { + std::vector<float> score_vector = + cc->Inputs().Tag(kScoresTag).Get<std::vector<float>>(); +- CHECK_EQ(label_vector.size(), score_vector.size()); ++ ABSL_CHECK_EQ(label_vector.size(), score_vector.size()); + scores.resize(label_vector.size()); + for (int i = 0; i < label_vector.size(); ++i) { + scores[i] = score_vector[i]; +diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc +index 535e2a719015c..1bab7af878ea5 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc +@@ -18,6 +18,7 @@ + #include <utility> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/calculators/util/non_max_suppression_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/detection.pb.h" +@@ -171,9 +172,9 @@ class NonMaxSuppressionCalculator : public CalculatorBase { + cc->SetOffset(TimestampDiff(0)); + + options_ = cc->Options<NonMaxSuppressionCalculatorOptions>(); +- CHECK_GT(options_.num_detection_streams(), 0) ++ ABSL_CHECK_GT(options_.num_detection_streams(), 0) + << "At least one detection stream need to be specified."; +- CHECK_NE(options_.max_num_detections(), 0) ++ ABSL_CHECK_NE(options_.max_num_detections(), 0) + << "max_num_detections=0 is not a valid value. Please choose a " + << "positive number of you want to limit the number of output " + << "detections, or set -1 if you do not want any limit."; +diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc +index 14ac12e5edd9e..4767d4d632fce 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc +@@ -17,6 +17,7 @@ + #include <memory> + #include <unordered_set> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/numbers.h" + #include "mediapipe/calculators/video/box_detector_calculator.pb.h" +@@ -359,7 +360,7 @@ absl::Status BoxDetectorCalculator::Process(CalculatorContext* cc) { + + const auto& descriptors = descriptor_stream->Get<std::vector<float>>(); + const int dims = options_.detector_options().descriptor_dims(); +- CHECK_GE(descriptors.size(), feature_size * dims); ++ ABSL_CHECK_GE(descriptors.size(), feature_size * dims); + cv::Mat descriptors_mat(feature_size, dims, CV_32F); + for (int j = 0; j < feature_size; ++j) { + features_vec[j].Set(features[j].pt.x * inv_scale, +diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc +index b5f3b5b0b3a16..c71e6857debd2 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc +@@ -22,6 +22,7 @@ + #include "absl/container/flat_hash_set.h" + #include "absl/container/node_hash_map.h" + #include "absl/container/node_hash_set.h" ++#include "absl/log/absl_check.h" + #include "absl/strings/numbers.h" + #include "mediapipe/calculators/video/box_tracker_calculator.pb.h" + #include "mediapipe/framework/calculator_framework.h" +@@ -323,8 +324,8 @@ void ConvertCoordinateForRotation(float in_top, float in_left, float in_bottom, + const float in_center_y = (in_top + in_bottom) * 0.5f; + const float in_width = in_right - in_left; + const float in_height = in_bottom - in_top; +- CHECK_GT(in_width, 0); +- CHECK_GT(in_height, 0); ++ ABSL_CHECK_GT(in_width, 0); ++ ABSL_CHECK_GT(in_height, 0); + float out_center_x; + float out_center_y; + float out_width; +@@ -999,7 +1000,7 @@ void BoxTrackerCalculator::OutputRandomAccessTrack( + + const int init_frame = timestamp_pos - track_timestamps_.begin() + + track_timestamps_base_index_; +- CHECK_GE(init_frame, 0); ++ ABSL_CHECK_GE(init_frame, 0); + + MotionBoxMap single_map = + PrepareRandomAccessTrack(start, init_frame, forward_track, start_data); +@@ -1233,7 +1234,7 @@ void BoxTrackerCalculator::FastForwardStartPos( + // Start at previous frame. + const int init_frame = timestamp_pos - track_timestamps_.begin() + + track_timestamps_base_index_; +- CHECK_GE(init_frame, 0); ++ ABSL_CHECK_GE(init_frame, 0); + + // Locate corresponding tracking data. + auto start_data = std::find_if( +diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc +index 2965cd8e66d77..f30fed88baa18 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc +@@ -17,6 +17,7 @@ + #include <fstream> + #include <memory> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + #include "absl/strings/string_view.h" + #include "mediapipe/calculators/video/flow_packager_calculator.pb.h" +@@ -160,7 +161,7 @@ absl::Status FlowPackagerCalculator::Process(CalculatorContext* cc) { + timestamp.Value() / 1000 / options_.caching_chunk_size_msec(); + tracking_chunk_.set_first_chunk(true); + } +- CHECK_GE(chunk_idx_, 0); ++ ABSL_CHECK_GE(chunk_idx_, 0); + + TrackingDataChunk::Item* item = tracking_chunk_.add_item(); + item->set_frame_idx(frame_idx_); +diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc +index 544439ae82f7d..fe320b1aefb53 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc +@@ -17,6 +17,7 @@ + #include <memory> + #include <string> + ++#include "absl/log/absl_check.h" + #include "absl/strings/numbers.h" + #include "absl/strings/str_split.h" + #include "absl/strings/string_view.h" +@@ -620,7 +621,7 @@ void MotionAnalysisCalculator::OutputMotionAnalyzedFrames( + const int num_results = motion_analysis_->GetResults( + flush, &features, &camera_motions, with_saliency_ ? &saliency : nullptr); + +- CHECK_LE(num_results, buffer_size); ++ ABSL_CHECK_LE(num_results, buffer_size); + + if (num_results == 0) { + return; +@@ -695,7 +696,7 @@ void MotionAnalysisCalculator::OutputMotionAnalyzedFrames( + + if (hybrid_meta_analysis_) { + hybrid_meta_offset_ -= num_results; +- CHECK_GE(hybrid_meta_offset_, 0); ++ ABSL_CHECK_GE(hybrid_meta_offset_, 0); + } + + timestamp_buffer_.erase(timestamp_buffer_.begin(), +@@ -901,7 +902,7 @@ void MotionAnalysisCalculator::AddMetaMotion( + const CameraMotion& meta_motion, const RegionFlowFeatureList& meta_features, + RegionFlowFeatureList* features, CameraMotion* motion) { + // Restore old feature location. +- CHECK_EQ(meta_features.feature_size(), features->feature_size()); ++ ABSL_CHECK_EQ(meta_features.feature_size(), features->feature_size()); + for (int k = 0; k < meta_features.feature_size(); ++k) { + auto feature = features->mutable_feature(k); + const auto& meta_feature = meta_features.feature(k); +@@ -947,8 +948,9 @@ void MotionAnalysisCalculator::AppendCameraMotionsFromHomographies( + } + + const int models_per_frame = options_.meta_models_per_frame(); +- CHECK_GT(models_per_frame, 0) << "At least one model per frame is needed"; +- CHECK_EQ(0, homographies.size() % models_per_frame); ++ ABSL_CHECK_GT(models_per_frame, 0) ++ << "At least one model per frame is needed"; ++ ABSL_CHECK_EQ(0, homographies.size() % models_per_frame); + const int num_frames = homographies.size() / models_per_frame; + + // Heuristic sigma, similar to what we use for rolling shutter removal. +diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc b/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc +index f0b00063fd9d9..146dc4a7031ce 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/calculators/video/tool/flow_quantizer_model.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/ret_check.h" + #include "mediapipe/framework/type_map.h" + +@@ -21,7 +22,7 @@ namespace mediapipe { + + // Uniform normalization to 0-255. + uint8_t FlowQuantizerModel::Apply(const float val, const int channel) const { +- CHECK_LT(channel, model_.min_value_size()); ++ ABSL_CHECK_LT(channel, model_.min_value_size()); + const auto& min_value = model_.min_value(channel); + const auto& max_value = model_.max_value(channel); + QCHECK_GT(max_value, min_value); +@@ -51,7 +52,7 @@ const QuantizerModelData& FlowQuantizerModel::GetModelData() const { + // TODO: Taking the min and max over all training flow fields might be + // sensitive to noise. We should use more robust statistics. + void FlowQuantizerModel::AddSampleFlowField(const OpticalFlowField& flow) { +- CHECK_EQ(model_.min_value_size(), 2); ++ ABSL_CHECK_EQ(model_.min_value_size(), 2); + const cv::Mat_<cv::Point2f>& flow_mat = flow.flow_data(); + for (int i = 0; i != flow.width(); ++i) { + for (int j = 0; j != flow.height(); ++j) { +diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc +index 56f3253e29763..dd87ae644b739 100644 +--- a/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc +@@ -13,6 +13,7 @@ + // limitations under the License. + + #include "absl/base/macros.h" ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/image_frame.h" +@@ -182,7 +183,7 @@ absl::Status Tvl1OpticalFlowCalculator::CalculateOpticalFlow( + flow->Allocate(first.cols, first.rows); + cv::Mat cv_flow(flow->mutable_flow_data()); + tvl1_computer->calc(first, second, cv_flow); +- CHECK_EQ(flow->mutable_flow_data().data, cv_flow.data); ++ ABSL_CHECK_EQ(flow->mutable_flow_data().data, cv_flow.data); + // Inserts the idle DenseOpticalFlow object back to the cache for reuse. + { + absl::MutexLock lock(&mutex_); +diff --git a/third_party/mediapipe/src/mediapipe/framework/api2/builder.h b/third_party/mediapipe/src/mediapipe/framework/api2/builder.h +index 0c4c82f3708c1..89f25c7b52a4e 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/api2/builder.h ++++ b/third_party/mediapipe/src/mediapipe/framework/api2/builder.h +@@ -11,6 +11,7 @@ + #include <vector> + + #include "absl/container/btree_map.h" ++#include "absl/log/absl_check.h" + #include "absl/strings/string_view.h" + #include "google/protobuf/message_lite.h" + #include "mediapipe/framework/api2/port.h" +@@ -109,7 +110,7 @@ class MultiPort : public Single { + : Single(vec), vec_(*vec) {} + + Single operator[](int index) { +- CHECK_GE(index, 0); ++ ABSL_CHECK_GE(index, 0); + return Single{&GetWithAutoGrow(&vec_, index)}; + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/api2/packet.h b/third_party/mediapipe/src/mediapipe/framework/api2/packet.h +index c059a988b4315..f231f4c80b312 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/api2/packet.h ++++ b/third_party/mediapipe/src/mediapipe/framework/api2/packet.h +@@ -13,6 +13,7 @@ + #include <functional> + #include <type_traits> + ++#include "absl/log/absl_check.h" + #include "absl/meta/type_traits.h" + #include "mediapipe/framework/api2/tuple.h" + #include "mediapipe/framework/packet.h" +@@ -102,9 +103,9 @@ mediapipe::Packet ToOldPacket(PacketBase&& p); + + template <typename T> + inline const T& PacketBase::Get() const { +- CHECK(payload_); ++ ABSL_CHECK(payload_); + packet_internal::Holder<T>* typed_payload = payload_->As<T>(); +- CHECK(typed_payload) << absl::StrCat( ++ ABSL_CHECK(typed_payload) << absl::StrCat( + "The Packet stores \"", payload_->DebugTypeName(), "\", but \"", + MediaPipeTypeStringOrDemangled<T>(), "\" was requested."); + return typed_payload->data(); +@@ -134,17 +135,17 @@ namespace internal { + template <class T> + inline void CheckCompatibleType(const HolderBase& holder, internal::Wrap<T>) { + const packet_internal::Holder<T>* typed_payload = holder.As<T>(); +- CHECK(typed_payload) << absl::StrCat( ++ ABSL_CHECK(typed_payload) << absl::StrCat( + "The Packet stores \"", holder.DebugTypeName(), "\", but \"", + MediaPipeTypeStringOrDemangled<T>(), "\" was requested."); +- // CHECK(payload_->has_type<T>()); ++ // ABSL_CHECK(payload_->has_type<T>()); + } + + template <class... T> + inline void CheckCompatibleType(const HolderBase& holder, + internal::Wrap<OneOf<T...>>) { + bool compatible = (holder.As<T>() || ...); +- CHECK(compatible) ++ ABSL_CHECK(compatible) + << "The Packet stores \"" << holder.DebugTypeName() << "\", but one of " + << absl::StrJoin( + {absl::StrCat("\"", MediaPipeTypeStringOrDemangled<T>(), "\"")...}, +@@ -211,9 +212,9 @@ class Packet : public Packet<internal::Generic> { + Packet<T> At(Timestamp timestamp) &&; + + const T& Get() const { +- CHECK(payload_); ++ ABSL_CHECK(payload_); + packet_internal::Holder<T>* typed_payload = payload_->As<T>(); +- CHECK(typed_payload); ++ ABSL_CHECK(typed_payload); + return typed_payload->data(); + } + const T& operator*() const { return Get(); } +@@ -330,9 +331,9 @@ class Packet<OneOf<T...>> : public PacketBase { + + template <class U, class = AllowedType<U>> + const U& Get() const { +- CHECK(payload_); ++ ABSL_CHECK(payload_); + packet_internal::Holder<U>* typed_payload = payload_->As<U>(); +- CHECK(typed_payload); ++ ABSL_CHECK(typed_payload); + return typed_payload->data(); + } + +@@ -343,7 +344,7 @@ class Packet<OneOf<T...>> : public PacketBase { + + template <class... F> + auto Visit(const F&... args) const { +- CHECK(payload_); ++ ABSL_CHECK(payload_); + auto f = internal::Overload{args...}; + using FirstT = typename internal::First<T...>::type; + using ResultType = absl::result_of_t<decltype(f)(const FirstT&)>; +@@ -364,7 +365,7 @@ class Packet<OneOf<T...>> : public PacketBase { + + template <class... F> + auto ConsumeAndVisit(const F&... args) { +- CHECK(payload_); ++ ABSL_CHECK(payload_); + auto f = internal::Overload{args...}; + using FirstT = typename internal::First<T...>::type; + using VisitorResultType = +diff --git a/third_party/mediapipe/src/mediapipe/framework/api2/port.h b/third_party/mediapipe/src/mediapipe/framework/api2/port.h +index 18a786075980c..075e88437a8f6 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/api2/port.h ++++ b/third_party/mediapipe/src/mediapipe/framework/api2/port.h +@@ -20,6 +20,7 @@ + #include <type_traits> + #include <utility> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/string_view.h" + #include "mediapipe/framework/api2/const_str.h" +@@ -243,8 +244,8 @@ class MultiplePortAccess { + // container? + int Count() { return count_; } + AccessT operator[](int pos) { +- CHECK_GE(pos, 0); +- CHECK_LT(pos, count_); ++ ABSL_CHECK_GE(pos, 0); ++ ABSL_CHECK_LT(pos, count_); + return SinglePortAccess<ValueT>(cc_, &first_[pos]); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_context.h b/third_party/mediapipe/src/mediapipe/framework/calculator_context.h +index 9568ba7455392..315d265118550 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/calculator_context.h ++++ b/third_party/mediapipe/src/mediapipe/framework/calculator_context.h +@@ -20,6 +20,7 @@ + #include <string> + #include <utility> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/calculator_state.h" + #include "mediapipe/framework/counter.h" + #include "mediapipe/framework/graph_service.h" +@@ -147,7 +148,7 @@ class CalculatorContext { + } + + void PopInputTimestamp() { +- CHECK(!input_timestamps_.empty()); ++ ABSL_CHECK(!input_timestamps_.empty()); + input_timestamps_.pop(); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h b/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h +index 6b988b03d9685..ae697e12f2d23 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h ++++ b/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h +@@ -21,6 +21,7 @@ + #include <memory> + + #include "absl/base/thread_annotations.h" ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/calculator_context.h" + #include "mediapipe/framework/calculator_state.h" +@@ -97,18 +98,18 @@ class CalculatorContextManager { + + void PushInputTimestampToContext(CalculatorContext* calculator_context, + Timestamp input_timestamp) { +- CHECK(calculator_context); ++ ABSL_CHECK(calculator_context); + calculator_context->PushInputTimestamp(input_timestamp); + } + + void PopInputTimestampFromContext(CalculatorContext* calculator_context) { +- CHECK(calculator_context); ++ ABSL_CHECK(calculator_context); + calculator_context->PopInputTimestamp(); + } + + void SetGraphStatusInContext(CalculatorContext* calculator_context, + const absl::Status& status) { +- CHECK(calculator_context); ++ ABSL_CHECK(calculator_context); + calculator_context->SetGraphStatus(status); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc b/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc +index 33ca41fb872ad..770f8337b1fba 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc +@@ -25,6 +25,7 @@ + + #include "absl/container/fixed_array.h" + #include "absl/container/flat_hash_set.h" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/status/status.h" + #include "absl/strings/str_cat.h" +@@ -904,7 +905,7 @@ absl::Status CalculatorGraph::AddPacketToInputStreamInternal( + "graph input stream.", + stream_name); + int node_id = mediapipe::FindOrDie(graph_input_stream_node_ids_, stream_name); +- CHECK_GE(node_id, validated_graph_->CalculatorInfos().size()); ++ ABSL_CHECK_GE(node_id, validated_graph_->CalculatorInfos().size()); + { + absl::MutexLock lock(&full_input_streams_mutex_); + if (full_input_streams_.empty()) { +@@ -1155,10 +1156,10 @@ void CalculatorGraph::UpdateThrottledNodes(InputStreamManager* stream, + .set_stream_id(&stream->Name())); + bool was_throttled = !full_input_streams_[node_id].empty(); + if (stream_is_full) { +- DCHECK_EQ(full_input_streams_[node_id].count(stream), 0); ++ ABSL_DCHECK_EQ(full_input_streams_[node_id].count(stream), 0); + full_input_streams_[node_id].insert(stream); + } else { +- DCHECK_EQ(full_input_streams_[node_id].count(stream), 1); ++ ABSL_DCHECK_EQ(full_input_streams_[node_id].count(stream), 1); + full_input_streams_[node_id].erase(stream); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc b/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc +index f6a1c7dbfcdcb..5618038e25c5f 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc +@@ -19,6 +19,7 @@ + #include <unordered_map> + #include <utility> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/status/status.h" + #include "absl/strings/str_cat.h" +@@ -341,7 +342,7 @@ absl::Status CalculatorNode::ConnectShardsToStreams( + + void CalculatorNode::SetExecutor(const std::string& executor) { + absl::MutexLock status_lock(&status_mutex_); +- CHECK_LT(status_, kStateOpened); ++ ABSL_CHECK_LT(status_, kStateOpened); + executor_ = executor; + } + +@@ -539,7 +540,7 @@ absl::Status CalculatorNode::OpenNode() { + + void CalculatorNode::ActivateNode() { + absl::MutexLock status_lock(&status_mutex_); +- CHECK_EQ(status_, kStateOpened) << DebugName(); ++ ABSL_CHECK_EQ(status_, kStateOpened) << DebugName(); + status_ = kStateActive; + } + +@@ -694,7 +695,7 @@ void CalculatorNode::InputStreamHeadersReady() { + bool ready_for_open = false; + { + absl::MutexLock lock(&status_mutex_); +- CHECK_EQ(status_, kStatePrepared) << DebugName(); ++ ABSL_CHECK_EQ(status_, kStatePrepared) << DebugName(); + CHECK(!input_stream_headers_ready_called_); + input_stream_headers_ready_called_ = true; + input_stream_headers_ready_ = true; +@@ -709,7 +710,7 @@ void CalculatorNode::InputSidePacketsReady() { + bool ready_for_open = false; + { + absl::MutexLock lock(&status_mutex_); +- CHECK_EQ(status_, kStatePrepared) << DebugName(); ++ ABSL_CHECK_EQ(status_, kStatePrepared) << DebugName(); + CHECK(!input_side_packets_ready_called_); + input_side_packets_ready_called_ = true; + input_side_packets_ready_ = true; +@@ -760,7 +761,7 @@ void CalculatorNode::EndScheduling() { + return; + } + --current_in_flight_; +- CHECK_GE(current_in_flight_, 0); ++ ABSL_CHECK_GE(current_in_flight_, 0); + + if (scheduling_state_ == kScheduling) { + // Changes the state to scheduling pending if another thread is doing the +@@ -893,9 +894,9 @@ absl::Status CalculatorNode::ProcessNode( + // open input streams for Process(). So this node needs to be closed + // too. + // If the streams are closed, there shouldn't be more input. +- CHECK_EQ(calculator_context_manager_.NumberOfContextTimestamps( +- *calculator_context), +- 1); ++ ABSL_CHECK_EQ(calculator_context_manager_.NumberOfContextTimestamps( ++ *calculator_context), ++ 1); + return CloseNode(absl::OkStatus(), /*graph_run_ended=*/false); + } else { + RET_CHECK_FAIL() +diff --git a/third_party/mediapipe/src/mediapipe/framework/collection.h b/third_party/mediapipe/src/mediapipe/framework/collection.h +index c7b6fb0de333a..a2ab39fa49ae6 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/collection.h ++++ b/third_party/mediapipe/src/mediapipe/framework/collection.h +@@ -24,6 +24,7 @@ + #include <vector> + + #include "absl/base/macros.h" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/string_view.h" +@@ -413,16 +414,16 @@ bool Collection<T, storage, ErrorHandler>::UsesTags() const { + template <typename T, CollectionStorage storage, typename ErrorHandler> + typename Collection<T, storage, ErrorHandler>::value_type& + Collection<T, storage, ErrorHandler>::Get(CollectionItemId id) { +- CHECK_LE(BeginId(), id); +- CHECK_LT(id, EndId()); ++ ABSL_CHECK_LE(BeginId(), id); ++ ABSL_CHECK_LT(id, EndId()); + return begin()[id.value()]; + } + + template <typename T, CollectionStorage storage, typename ErrorHandler> + const typename Collection<T, storage, ErrorHandler>::value_type& + Collection<T, storage, ErrorHandler>::Get(CollectionItemId id) const { +- CHECK_LE(BeginId(), id); +- CHECK_LT(id, EndId()); ++ ABSL_CHECK_LE(BeginId(), id); ++ ABSL_CHECK_LT(id, EndId()); + return begin()[id.value()]; + } + +@@ -433,8 +434,8 @@ Collection<T, storage, ErrorHandler>::GetPtr(CollectionItemId id) { + "mediapipe::internal::Collection<T>::GetPtr() is only " + "available for collections that were defined with template " + "argument storage == CollectionStorage::kStorePointer."); +- CHECK_LE(BeginId(), id); +- CHECK_LT(id, EndId()); ++ ABSL_CHECK_LE(BeginId(), id); ++ ABSL_CHECK_LT(id, EndId()); + return data_[id.value()]; + } + +@@ -445,8 +446,8 @@ Collection<T, storage, ErrorHandler>::GetPtr(CollectionItemId id) const { + "mediapipe::internal::Collection<T>::GetPtr() is only " + "available for collections that were defined with template " + "argument storage == CollectionStorage::kStorePointer."); +- CHECK_LE(BeginId(), id); +- CHECK_LT(id, EndId()); ++ ABSL_CHECK_LE(BeginId(), id); ++ ABSL_CHECK_LT(id, EndId()); + return data_[id.value()]; + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h b/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h +index 315b78c42fcdf..24543d4c3476f 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h +@@ -23,6 +23,7 @@ + #include <limits> + #include <type_traits> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" + +@@ -364,7 +365,7 @@ class MathUtil { + // absolute margin of error. + template <typename T> + static bool WithinMargin(const T x, const T y, const T margin) { +- DCHECK_GE(margin, 0); ++ ABSL_DCHECK_GE(margin, 0); + return (std::abs(x) <= std::abs(y) + margin) && + (std::abs(x) >= std::abs(y) - margin); + } +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc b/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc +index 503ef5cfdd019..e3cc9de231cd7 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc +@@ -16,6 +16,7 @@ + + #include "absl/base/macros.h" + #include "absl/base/thread_annotations.h" ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "absl/time/time.h" + #include "mediapipe/framework/port/logging.h" +@@ -80,7 +81,7 @@ class MonotonicClockImpl : public MonotonicClock { + absl::MutexLock m(&state_->lock); + + // Check consistency of internal data with state_. +- CHECK_LE(last_raw_time_, state_->max_time) ++ ABSL_CHECK_LE(last_raw_time_, state_->max_time) + << "non-monotonic behavior: last_raw_time_=" << last_raw_time_ + << ", max_time=" << state_->max_time; + +@@ -107,7 +108,7 @@ class MonotonicClockImpl : public MonotonicClock { + // First, update correction metrics. + ++correction_count_; + absl::Duration delta = state_->max_time - raw_time; +- CHECK_LT(absl::ZeroDuration(), delta); ++ ABSL_CHECK_LT(absl::ZeroDuration(), delta); + if (delta > max_correction_) { + max_correction_ = delta; + } +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/registration.h b/third_party/mediapipe/src/mediapipe/framework/deps/registration.h +index c67f07305a5f3..9abc30ee4f280 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/registration.h ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/registration.h +@@ -28,6 +28,7 @@ + #include "absl/base/thread_annotations.h" + #include "absl/container/flat_hash_map.h" + #include "absl/container/flat_hash_set.h" ++#include "absl/log/absl_check.h" + #include "absl/meta/type_traits.h" + #include "absl/strings/str_join.h" + #include "absl/strings/str_split.h" +@@ -270,7 +271,7 @@ class FunctionRegistry { + if (names[0].empty()) { + names.erase(names.begin()); + } else { +- CHECK_EQ(1u, names.size()) ++ ABSL_CHECK_EQ(1u, names.size()) + << "A registered class name must be either fully qualified " + << "with a leading :: or unqualified, got: " << name << "."; + } +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h b/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h +index f6dbb931d23c6..8b717cb9700d3 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h +@@ -44,6 +44,7 @@ + #include <limits> + #include <type_traits> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/deps/strong_int.h" + #include "mediapipe/framework/port/logging.h" + +@@ -67,17 +68,17 @@ class SafeIntStrongIntValidator { + // Check that the underlying integral type provides a range that is + // compatible with two's complement. + if (std::numeric_limits<T>::is_signed) { +- CHECK_EQ(-1, +- std::numeric_limits<T>::min() + std::numeric_limits<T>::max()) ++ ABSL_CHECK_EQ( ++ -1, std::numeric_limits<T>::min() + std::numeric_limits<T>::max()) + << "unexpected integral bounds"; + } + + // Check that division truncates towards 0 (implementation defined in + // C++'03, but standard in C++'11). +- CHECK_EQ(12, 127 / 10) << "division does not truncate towards 0"; +- CHECK_EQ(-12, -127 / 10) << "division does not truncate towards 0"; +- CHECK_EQ(-12, 127 / -10) << "division does not truncate towards 0"; +- CHECK_EQ(12, -127 / -10) << "division does not truncate towards 0"; ++ ABSL_CHECK_EQ(12, 127 / 10) << "division does not truncate towards 0"; ++ ABSL_CHECK_EQ(-12, -127 / 10) << "division does not truncate towards 0"; ++ ABSL_CHECK_EQ(-12, 127 / -10) << "division does not truncate towards 0"; ++ ABSL_CHECK_EQ(12, -127 / -10) << "division does not truncate towards 0"; + } + + public: +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc b/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc +index d9c32d35e1f01..9610f3745dab3 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc +@@ -18,6 +18,7 @@ + #include <sys/syscall.h> + #include <unistd.h> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/str_join.h" + #include "mediapipe/framework/deps/threadpool.h" +@@ -48,7 +49,7 @@ ThreadPool::WorkerThread::WorkerThread(ThreadPool* pool, + const std::string& name_prefix) + : pool_(pool), name_prefix_(name_prefix) { + int res = pthread_create(&thread_, nullptr, ThreadBody, this); +- CHECK_EQ(res, 0) << "pthread_create failed"; ++ ABSL_CHECK_EQ(res, 0) << "pthread_create failed"; + } + + ThreadPool::WorkerThread::~WorkerThread() {} +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc b/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc +index 67fc6adc4e582..65cd825b135d6 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc +@@ -16,12 +16,13 @@ + + #include <algorithm> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + + namespace mediapipe { + + TopologicalSorter::TopologicalSorter(int num_nodes) : num_nodes_(num_nodes) { +- CHECK_GE(num_nodes_, 0); ++ ABSL_CHECK_GE(num_nodes_, 0); + adjacency_lists_.resize(num_nodes_); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/vector.h b/third_party/mediapipe/src/mediapipe/framework/deps/vector.h +index 2d4de82f314c3..577575321a423 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/deps/vector.h ++++ b/third_party/mediapipe/src/mediapipe/framework/deps/vector.h +@@ -24,6 +24,7 @@ + #include <limits> + #include <type_traits> + ++#include "absl/log/absl_check.h" + #include "absl/utility/utility.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" +@@ -78,13 +79,13 @@ class BasicVector { + void Clear() { AsD() = D(); } + + T& operator[](int b) { +- DCHECK_GE(b, 0); +- DCHECK_LT(b, SIZE); ++ ABSL_DCHECK_GE(b, 0); ++ ABSL_DCHECK_LT(b, SIZE); + return static_cast<D&>(*this).Data()[b]; + } + T operator[](int b) const { +- DCHECK_GE(b, 0); +- DCHECK_LT(b, SIZE); ++ ABSL_DCHECK_GE(b, 0); ++ ABSL_DCHECK_LT(b, SIZE); + return static_cast<const D&>(*this).Data()[b]; + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h b/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h +index 21a5f537f95fe..4ebf3c607e189 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h +@@ -18,6 +18,7 @@ limitations under the License. + + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/log/check.h" + #include "absl/status/statusor.h" + #include "mediapipe/framework/port/integral_types.h" +@@ -147,15 +148,15 @@ class FrameBuffer { + + // Returns plane indexed by the input `index`. + const Plane& plane(int index) const { +- CHECK_GE(index, 0); +- CHECK_LT(static_cast<size_t>(index), planes_.size()); ++ ABSL_CHECK_GE(index, 0); ++ ABSL_CHECK_LT(static_cast<size_t>(index), planes_.size()); + return planes_[index]; + } + + // Returns mutable plane indexed by the input `index`. + Plane mutable_plane(int index) { +- CHECK_GE(index, 0); +- CHECK_LT(static_cast<size_t>(index), planes_.size()); ++ ABSL_CHECK_GE(index, 0); ++ ABSL_CHECK_LT(static_cast<size_t>(index), planes_.size()); + return planes_[index]; + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc b/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc +index 2de819a35bf60..458d1308c17ac 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc +@@ -23,6 +23,7 @@ + #include <algorithm> + #include <utility> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/framework/formats/image_format.pb.h" + #include "mediapipe/framework/port/aligned_malloc_and_free.h" +@@ -98,7 +99,7 @@ void ImageFrame::Reset(ImageFormat::Format format, int width, int height, + format_ = format; + width_ = width; + height_ = height; +- CHECK_NE(ImageFormat::UNKNOWN, format_); ++ ABSL_CHECK_NE(ImageFormat::UNKNOWN, format_); + CHECK(IsValidAlignmentNumber(alignment_boundary)); + width_step_ = width * NumberOfChannels() * ByteDepth(); + if (alignment_boundary == 1) { +@@ -124,8 +125,8 @@ void ImageFrame::AdoptPixelData(ImageFormat::Format format, int width, + height_ = height; + width_step_ = width_step; + +- CHECK_NE(ImageFormat::UNKNOWN, format_); +- CHECK_GE(width_step_, width * NumberOfChannels() * ByteDepth()); ++ ABSL_CHECK_NE(ImageFormat::UNKNOWN, format_); ++ ABSL_CHECK_GE(width_step_, width * NumberOfChannels() * ByteDepth()); + + pixel_data_ = {pixel_data, deleter}; + } +@@ -136,8 +137,8 @@ std::unique_ptr<uint8_t[], ImageFrame::Deleter> ImageFrame::Release() { + + void ImageFrame::InternalCopyFrom(int width, int height, int width_step, + int channel_size, const uint8_t* pixel_data) { +- CHECK_EQ(width_, width); +- CHECK_EQ(height_, height); ++ ABSL_CHECK_EQ(width_, width); ++ ABSL_CHECK_EQ(height_, height); + // row_bytes = channel_size * num_channels * width + const int row_bytes = channel_size * NumberOfChannels() * width; + if (width_step == 0) { +@@ -187,8 +188,8 @@ void ImageFrame::SetAlignmentPaddingAreas() { + if (!pixel_data_) { + return; + } +- CHECK_GE(width_, 1); +- CHECK_GE(height_, 1); ++ ABSL_CHECK_GE(width_, 1); ++ ABSL_CHECK_GE(height_, 1); + + const int pixel_size = ByteDepth() * NumberOfChannels(); + const int padding_size = width_step_ - width_ * pixel_size; +@@ -359,7 +360,7 @@ void ImageFrame::CopyFrom(const ImageFrame& image_frame, + Reset(image_frame.Format(), image_frame.Width(), image_frame.Height(), + alignment_boundary); + +- CHECK_EQ(format_, image_frame.Format()); ++ ABSL_CHECK_EQ(format_, image_frame.Format()); + InternalCopyFrom(image_frame.Width(), image_frame.Height(), + image_frame.WidthStep(), image_frame.ChannelSize(), + image_frame.PixelData()); +@@ -383,9 +384,9 @@ void ImageFrame::CopyPixelData(ImageFormat::Format format, int width, + + void ImageFrame::CopyToBuffer(uint8_t* buffer, int buffer_size) const { + CHECK(buffer); +- CHECK_EQ(1, ByteDepth()); ++ ABSL_CHECK_EQ(1, ByteDepth()); + const int data_size = width_ * height_ * NumberOfChannels(); +- CHECK_LE(data_size, buffer_size); ++ ABSL_CHECK_LE(data_size, buffer_size); + if (IsContiguous()) { + // The data is stored contiguously, we can just copy. + const uint8_t* src = reinterpret_cast<const uint8_t*>(pixel_data_.get()); +@@ -398,9 +399,9 @@ void ImageFrame::CopyToBuffer(uint8_t* buffer, int buffer_size) const { + + void ImageFrame::CopyToBuffer(uint16_t* buffer, int buffer_size) const { + CHECK(buffer); +- CHECK_EQ(2, ByteDepth()); ++ ABSL_CHECK_EQ(2, ByteDepth()); + const int data_size = width_ * height_ * NumberOfChannels(); +- CHECK_LE(data_size, buffer_size); ++ ABSL_CHECK_LE(data_size, buffer_size); + if (IsContiguous()) { + // The data is stored contiguously, we can just copy. + const uint16_t* src = reinterpret_cast<const uint16_t*>(pixel_data_.get()); +@@ -413,9 +414,9 @@ void ImageFrame::CopyToBuffer(uint16_t* buffer, int buffer_size) const { + + void ImageFrame::CopyToBuffer(float* buffer, int buffer_size) const { + CHECK(buffer); +- CHECK_EQ(4, ByteDepth()); ++ ABSL_CHECK_EQ(4, ByteDepth()); + const int data_size = width_ * height_ * NumberOfChannels(); +- CHECK_LE(data_size, buffer_size); ++ ABSL_CHECK_LE(data_size, buffer_size); + if (IsContiguous()) { + // The data is stored contiguously, we can just copy. + const float* src = reinterpret_cast<float*>(pixel_data_.get()); +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc b/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc +index 655064d36eba2..5953d0fd933ab 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc +@@ -16,6 +16,7 @@ + + #include <tuple> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/port/logging.h" +@@ -43,7 +44,7 @@ ImageMultiPool::SimplePoolGpu ImageMultiPool::MakeSimplePoolGpu( + IBufferSpec spec) { + OSType cv_format = mediapipe::CVPixelFormatForGpuBufferFormat( + GpuBufferFormatForImageFormat(spec.format)); +- CHECK_NE(cv_format, -1) << "unsupported pixel format"; ++ ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; + return MakeCFHolderAdopting(mediapipe::CreateCVPixelBufferPool( + spec.width, spec.height, cv_format, kKeepCount, + 0.1 /* max age in seconds */)); +@@ -61,7 +62,7 @@ Image ImageMultiPool::GetBufferFromSimplePool( + // pool to give us contiguous data. + OSType cv_format = mediapipe::CVPixelFormatForGpuBufferFormat( + mediapipe::GpuBufferFormatForImageFormat(spec.format)); +- CHECK_NE(cv_format, -1) << "unsupported pixel format"; ++ ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; + CVPixelBufferRef buffer; + CVReturn err = mediapipe::CreateCVPixelBufferWithoutPool( + spec.width, spec.height, cv_format, &buffer); +@@ -188,7 +189,7 @@ Image ImageMultiPool::GetBuffer(int width, int height, bool use_gpu, + ImageMultiPool::~ImageMultiPool() { + #if !MEDIAPIPE_DISABLE_GPU + #ifdef __APPLE__ +- CHECK_EQ(texture_caches_.size(), 0) ++ ABSL_CHECK_EQ(texture_caches_.size(), 0) + << "Failed to unregister texture caches before deleting pool"; + #endif // defined(__APPLE__) + #endif // !MEDIAPIPE_DISABLE_GPU +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/location.cc b/third_party/mediapipe/src/mediapipe/framework/formats/location.cc +index 205edf191418b..f2d7be0f3fce6 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/location.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/location.cc +@@ -18,6 +18,7 @@ + #include <cmath> + #include <memory> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/substitute.h" + #include "mediapipe/framework/formats/annotation/locus.pb.h" +@@ -152,7 +153,7 @@ bool Location::IsValidLocationData(const LocationData& location_data) { + + template <> + Rectangle_i Location::GetBBox<Rectangle_i>() const { +- CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); ++ ABSL_CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); + const auto& box = location_data_.bounding_box(); + return Rectangle_i(box.xmin(), box.ymin(), box.width(), box.height()); + } +@@ -160,7 +161,7 @@ Rectangle_i Location::GetBBox<Rectangle_i>() const { + Location& Location::Scale(const float scale) { + CHECK(!location_data_.has_mask()) + << "Location mask scaling is not implemented."; +- CHECK_GT(scale, 0.0f); ++ ABSL_CHECK_GT(scale, 0.0f); + switch (location_data_.format()) { + case LocationData::GLOBAL: { + // Do nothing. +@@ -247,7 +248,7 @@ namespace { + // This function is inteded to shift boundaries of intervals such that they + // best fit within an image. + float BestShift(float min_value, float max_value, float range) { +- CHECK_LE(min_value, max_value); ++ ABSL_CHECK_LE(min_value, max_value); + const float value_range = max_value - min_value; + if (value_range > range) { + return 0.5f * (range - min_value - max_value); +@@ -294,8 +295,8 @@ Location& Location::ShiftToFitBestIntoImage(int image_width, int image_height) { + const float y_shift = BestShift(mask_bounding_box.xmin(), + mask_bounding_box.xmax(), image_height); + auto* mask = location_data_.mutable_mask(); +- CHECK_EQ(image_width, mask->width()); +- CHECK_EQ(image_height, mask->height()); ++ ABSL_CHECK_EQ(image_width, mask->width()); ++ ABSL_CHECK_EQ(image_height, mask->height()); + for (auto& interval : + *mask->mutable_rasterization()->mutable_interval()) { + interval.set_y(interval.y() + y_shift); +@@ -418,7 +419,7 @@ Rectangle_i Location::ConvertToBBox<Rectangle_i>(int image_width, + } + + Rectangle_f Location::GetRelativeBBox() const { +- CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); ++ ABSL_CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); + const auto& box = location_data_.relative_bounding_box(); + return Rectangle_f(box.xmin(), box.ymin(), box.width(), box.height()); + } +@@ -457,7 +458,7 @@ Rectangle_f Location::ConvertToRelativeBBox(int image_width, + + template <> + ::mediapipe::BoundingBox Location::GetBBox<::mediapipe::BoundingBox>() const { +- CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); ++ ABSL_CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); + const auto& box = location_data_.bounding_box(); + ::mediapipe::BoundingBox bounding_box; + bounding_box.set_left_x(box.xmin()); +@@ -480,7 +481,7 @@ template <> + } + + std::vector<Point2_f> Location::GetRelativeKeypoints() const { +- CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); ++ ABSL_CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); + std::vector<Point2_f> keypoints; + for (const auto& keypoint : location_data_.relative_keypoints()) { + keypoints.emplace_back(Point2_f(keypoint.x(), keypoint.y())); +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc b/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc +index 6e15b299a1a26..90cd2bb574940 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/framework/formats/location_opencv.h" + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/substitute.h" + #include "mediapipe/framework/formats/annotation/rasterization.pb.h" +@@ -85,7 +86,7 @@ Location CreateBBoxLocation(const cv::Rect& rect) { + + std::unique_ptr<cv::Mat> GetCvMask(const Location& location) { + const auto location_data = location.ConvertToProto(); +- CHECK_EQ(LocationData::MASK, location_data.format()); ++ ABSL_CHECK_EQ(LocationData::MASK, location_data.format()); + const auto& mask = location_data.mask(); + std::unique_ptr<cv::Mat> mat( + new cv::Mat(mask.height(), mask.width(), CV_8UC1, cv::Scalar(0))); +@@ -128,7 +129,7 @@ std::unique_ptr<cv::Mat> ConvertToCvMask(const Location& location, + } + + void EnlargeLocation(Location& location, const float factor) { +- CHECK_GT(factor, 0.0f); ++ ABSL_CHECK_GT(factor, 0.0f); + if (factor == 1.0f) return; + auto location_data = location.ConvertToProto(); + switch (location_data.format()) { +@@ -183,7 +184,7 @@ void EnlargeLocation(Location& location, const float factor) { + + template <typename T> + Location CreateCvMaskLocation(const cv::Mat_<T>& mask) { +- CHECK_EQ(1, mask.channels()) ++ ABSL_CHECK_EQ(1, mask.channels()) + << "The specified cv::Mat mask should be single-channel."; + + LocationData location_data; +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc b/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc +index 42f2df5f8915a..daad9c0d2cb02 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc +@@ -15,6 +15,7 @@ + + #include <algorithm> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/core_proto_inc.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/proto_ns.h" +@@ -33,8 +34,8 @@ void MatrixDataProtoFromMatrix(const Matrix& matrix, MatrixData* matrix_data) { + } + + void MatrixFromMatrixDataProto(const MatrixData& matrix_data, Matrix* matrix) { +- CHECK_EQ(matrix_data.rows() * matrix_data.cols(), +- matrix_data.packed_data_size()); ++ ABSL_CHECK_EQ(matrix_data.rows() * matrix_data.cols(), ++ matrix_data.packed_data_size()); + if (matrix_data.layout() == MatrixData::ROW_MAJOR) { + matrix->resize(matrix_data.cols(), matrix_data.rows()); + } else { +diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc b/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc +index a96504192d3aa..8b3dd3f71452a 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc +@@ -18,6 +18,7 @@ + + #include <cmath> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/string_view.h" + #include "mediapipe/framework/deps/mathutil.h" +@@ -105,7 +106,7 @@ cv::Mat OpticalFlowField::GetVisualizationInternal( + std::max(std::numeric_limits<float>::epsilon(), + MaxAbsoluteValueIgnoringHuge(magnitudes, kHugeToIgnore)); + } +- CHECK_LT(0, max_magnitude); ++ ABSL_CHECK_LT(0, max_magnitude); + cv::Mat hsv = MakeVisualizationHsv(angles, magnitudes, max_magnitude); + cv::Mat viz; + cv::cvtColor(hsv, viz, 71 /*cv::COLOR_HSV2RGB_FULL*/); +@@ -119,7 +120,7 @@ cv::Mat OpticalFlowField::GetVisualization() const { + + cv::Mat OpticalFlowField::GetVisualizationSaturatedAt( + float max_magnitude) const { +- CHECK_LT(0, max_magnitude) ++ ABSL_CHECK_LT(0, max_magnitude) + << "Specified saturation magnitude must be positive."; + return GetVisualizationInternal(max_magnitude, true); + } +@@ -147,9 +148,9 @@ void OpticalFlowField::Resize(int new_width, int new_height) { + } + + void OpticalFlowField::CopyFromTensor(const tensorflow::Tensor& tensor) { +- CHECK_EQ(tensorflow::DT_FLOAT, tensor.dtype()); +- CHECK_EQ(3, tensor.dims()) << "Tensor must be height x width x 2."; +- CHECK_EQ(2, tensor.dim_size(2)) << "Tensor must be height x width x 2."; ++ ABSL_CHECK_EQ(tensorflow::DT_FLOAT, tensor.dtype()); ++ ABSL_CHECK_EQ(3, tensor.dims()) << "Tensor must be height x width x 2."; ++ ABSL_CHECK_EQ(2, tensor.dim_size(2)) << "Tensor must be height x width x 2."; + const int height = tensor.dim_size(0); + const int width = tensor.dim_size(1); + Allocate(width, height); +@@ -163,8 +164,8 @@ void OpticalFlowField::CopyFromTensor(const tensorflow::Tensor& tensor) { + } + + void OpticalFlowField::SetFromProto(const OpticalFlowFieldData& proto) { +- CHECK_EQ(proto.width() * proto.height(), proto.dx_size()); +- CHECK_EQ(proto.width() * proto.height(), proto.dy_size()); ++ ABSL_CHECK_EQ(proto.width() * proto.height(), proto.dx_size()); ++ ABSL_CHECK_EQ(proto.width() * proto.height(), proto.dy_size()); + flow_data_.create(proto.height(), proto.width()); + int i = 0; + for (int r = 0; r < flow_data_.rows; ++r) { +@@ -205,10 +206,10 @@ bool OpticalFlowField::FollowFlow(float x, float y, float* new_x, + + cv::Point2f OpticalFlowField::InterpolatedFlowAt(float x, float y) const { + // Sanity bounds checks. +- CHECK_GE(x, 0); +- CHECK_GE(y, 0); +- CHECK_LE(x, flow_data_.cols - 1); +- CHECK_LE(y, flow_data_.rows - 1); ++ ABSL_CHECK_GE(x, 0); ++ ABSL_CHECK_GE(y, 0); ++ ABSL_CHECK_LE(x, flow_data_.cols - 1); ++ ABSL_CHECK_LE(y, flow_data_.rows - 1); + + const int x0 = static_cast<int>(std::floor(x)); + const int y0 = static_cast<int>(std::floor(y)); +@@ -265,9 +266,9 @@ void OpticalFlowField::EstimateMotionConsistencyOcclusions( + const OpticalFlowField& forward, const OpticalFlowField& backward, + double spatial_distance_threshold, Location* occluded_mask, + Location* disoccluded_mask) { +- CHECK_EQ(forward.width(), backward.width()) ++ ABSL_CHECK_EQ(forward.width(), backward.width()) + << "Flow fields have different widths."; +- CHECK_EQ(forward.height(), backward.height()) ++ ABSL_CHECK_EQ(forward.height(), backward.height()) + << "Flow fields have different heights."; + if (occluded_mask != nullptr) { + *occluded_mask = FindMotionInconsistentPixels(forward, backward, +diff --git a/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc b/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc +index de024dfe5120f..34b4ffea978ac 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/framework/graph_output_stream.h" + ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/port/status.h" + +@@ -212,7 +213,7 @@ bool OutputStreamPollerImpl::Next(Packet* packet) { + bool stream_is_done = false; + *packet = input_stream_->PopPacketAtTimestamp( + min_timestamp, &num_packets_dropped, &stream_is_done); +- CHECK_EQ(num_packets_dropped, 0) ++ ABSL_CHECK_EQ(num_packets_dropped, 0) + << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, input_stream_->Name()); + } else if (timestamp_bound_changed) { +diff --git a/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc +index a7bd9ef439a8e..428305103da9f 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/framework/input_stream_handler.h" + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_join.h" + #include "absl/strings/substitute.h" + #include "mediapipe/framework/collection_item_id.h" +@@ -102,7 +103,7 @@ void InputStreamHandler::SetHeader(CollectionItemId id, const Packet& header) { + return; + } + if (!input_stream_managers_.Get(id)->BackEdge()) { +- CHECK_GT(unset_header_count_, 0); ++ ABSL_CHECK_GT(unset_header_count_, 0); + if (unset_header_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) { + headers_ready_callback_(); + } +@@ -321,9 +322,11 @@ void InputStreamHandler::SetBatchSize(int batch_size) { + << "Batching cannot be combined with parallel execution."; + CHECK(!late_preparation_ || batch_size == 1) + << "Batching cannot be combined with late preparation."; +- CHECK_GE(batch_size, 1) << "Batch size has to be greater than or equal to 1."; ++ ABSL_CHECK_GE(batch_size, 1) ++ << "Batch size has to be greater than or equal to 1."; + // Source nodes shouldn't specify batch_size even if it's set to 1. +- CHECK_GE(NumInputStreams(), 0) << "Source nodes cannot batch input packets."; ++ ABSL_CHECK_GE(NumInputStreams(), 0) ++ << "Source nodes cannot batch input packets."; + batch_size_ = batch_size; + } + +@@ -412,7 +415,7 @@ void SyncSet::FillInputSet(Timestamp input_timestamp, + bool stream_is_done = false; + Packet current_packet = stream->PopPacketAtTimestamp( + input_timestamp, &num_packets_dropped, &stream_is_done); +- CHECK_EQ(num_packets_dropped, 0) ++ ABSL_CHECK_EQ(num_packets_dropped, 0) + << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, stream->Name()); + input_stream_handler_->AddPacketToShard( +diff --git a/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc b/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc +index 1af2e2cc8b261..d38f3c61f2b46 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc +@@ -17,6 +17,7 @@ + #include <type_traits> + #include <utility> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/packet.h" +@@ -252,7 +253,7 @@ Packet InputStreamManager::PopPacketAtTimestamp(Timestamp timestamp, + { + absl::MutexLock stream_lock(&stream_mutex_); + // Make sure timestamp didn't decrease from last time. +- CHECK_LE(last_select_timestamp_, timestamp); ++ ABSL_CHECK_LE(last_select_timestamp_, timestamp); + last_select_timestamp_ = timestamp; + + // Make sure AddPacket and SetNextTimestampBound are not called with +diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc +index ba8f4671838f6..74138cd7f8a4f 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/framework/output_stream_handler.h" + ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/collection_item_id.h" + #include "mediapipe/framework/output_stream_shard.h" +@@ -79,7 +80,7 @@ void OutputStreamHandler::UpdateTaskTimestampBound(Timestamp timestamp) { + if (task_timestamp_bound_ == timestamp) { + return; + } +- CHECK_GT(timestamp, task_timestamp_bound_); ++ ABSL_CHECK_GT(timestamp, task_timestamp_bound_); + task_timestamp_bound_ = timestamp; + if (propagation_state_ == kPropagatingBound) { + propagation_state_ = kPropagationPending; +diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h +index 0b8dbed2c64c6..cb6b2d6e10e91 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h ++++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h +@@ -25,6 +25,7 @@ + + // TODO: Move protos in another CL after the C++ code migration. + #include "absl/base/thread_annotations.h" ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/calculator_context_manager.h" + #include "mediapipe/framework/collection.h" +@@ -63,7 +64,7 @@ class OutputStreamHandler { + calculator_context_manager_(calculator_context_manager), + options_(options), + calculator_run_in_parallel_(calculator_run_in_parallel) { +- CHECK(calculator_context_manager_); ++ ABSL_CHECK(calculator_context_manager_); + } + + virtual ~OutputStreamHandler() = default; +diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h b/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h +index 26c0e72b25b40..98ebda313eb07 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h ++++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h +@@ -17,6 +17,7 @@ + + #include <memory> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/graph_output_stream.h" + + namespace mediapipe { +@@ -34,7 +35,7 @@ class OutputStreamPoller { + // Resets OutputStramPollerImpl and cleans the internal packet queue. + void Reset() { + auto poller = internal_poller_impl_.lock(); +- CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; ++ ABSL_CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; + poller->Reset(); + } + +@@ -50,14 +51,14 @@ class OutputStreamPoller { + + void SetMaxQueueSize(int queue_size) { + auto poller = internal_poller_impl_.lock(); +- CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; ++ ABSL_CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; + return poller->SetMaxQueueSize(queue_size); + } + + // Returns the number of packets in the queue. + int QueueSize() { + auto poller = internal_poller_impl_.lock(); +- CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; ++ ABSL_CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; + return poller->QueueSize(); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h b/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h +index 718174c452f35..81a897591adba 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h ++++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h +@@ -18,6 +18,7 @@ + #include <list> + #include <string> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/output_stream.h" + #include "mediapipe/framework/packet.h" + #include "mediapipe/framework/packet_type.h" +@@ -34,7 +35,7 @@ struct OutputStreamSpec { + // Triggers the error callback with absl::Status info when an error + // occurs. + void TriggerErrorCallback(const absl::Status& status) const { +- CHECK(error_callback); ++ ABSL_CHECK(error_callback); + error_callback(status); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/packet.h b/third_party/mediapipe/src/mediapipe/framework/packet.h +index 1024cbc15450c..2739b09594db0 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/packet.h ++++ b/third_party/mediapipe/src/mediapipe/framework/packet.h +@@ -23,6 +23,7 @@ + #include <type_traits> + + #include "absl/base/macros.h" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/str_cat.h" + #include "absl/synchronization/mutex.h" +@@ -742,7 +743,7 @@ inline Packet& Packet::operator=(Packet&& packet) { + inline bool Packet::IsEmpty() const { return holder_ == nullptr; } + + inline TypeId Packet::GetTypeId() const { +- CHECK(holder_); ++ ABSL_CHECK(holder_); + return holder_->GetTypeId(); + } + +@@ -761,13 +762,13 @@ inline Timestamp Packet::Timestamp() const { return timestamp_; } + + template <typename T> + Packet Adopt(const T* ptr) { +- CHECK(ptr != nullptr); ++ ABSL_CHECK(ptr != nullptr); + return packet_internal::Create(new packet_internal::Holder<T>(ptr)); + } + + template <typename T> + Packet PointToForeign(const T* ptr) { +- CHECK(ptr != nullptr); ++ ABSL_CHECK(ptr != nullptr); + return packet_internal::Create(new packet_internal::ForeignHolder<T>(ptr)); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/packet_type.h b/third_party/mediapipe/src/mediapipe/framework/packet_type.h +index 9b4bbd36cf2b7..d4a0438216539 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/packet_type.h ++++ b/third_party/mediapipe/src/mediapipe/framework/packet_type.h +@@ -23,6 +23,7 @@ + #include <vector> + + #include "absl/base/macros.h" ++#include "absl/log/absl_check.h" + #include "absl/status/status.h" + #include "absl/strings/str_split.h" + #include "absl/strings/string_view.h" +@@ -162,7 +163,7 @@ class PacketTypeSetErrorHandler { + if (!missing_) { + missing_ = absl::make_unique<Missing>(); + } +- CHECK(!missing_->initialized_errors); ++ ABSL_CHECK(!missing_->initialized_errors); + std::string key = absl::StrCat(tag, ":", index); + return missing_->entries[key]; + } +@@ -181,9 +182,9 @@ class PacketTypeSetErrorHandler { + // Get the error messages that have been deferred. + // This function can only be called if HasError() is true. + const std::vector<std::string>& ErrorMessages() const { +- CHECK(missing_) << "ErrorMessages() can only be called if errors have " +- "occurred. Call HasError() before calling this " +- "function."; ++ ABSL_CHECK(missing_) << "ErrorMessages() can only be called if errors have " ++ "occurred. Call HasError() before calling this " ++ "function."; + if (!missing_->initialized_errors) { + for (const auto& entry : missing_->entries) { + // Optional entries that were missing are not considered errors. +diff --git a/third_party/mediapipe/src/mediapipe/framework/scheduler.cc b/third_party/mediapipe/src/mediapipe/framework/scheduler.cc +index ceadce7876e3a..f281ce448f7df 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/scheduler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/scheduler.cc +@@ -19,6 +19,7 @@ + #include <utility> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/calculator_graph.h" +@@ -77,7 +78,7 @@ void Scheduler::Reset() { + void Scheduler::CloseAllSourceNodes() { shared_.stopping = true; } + + void Scheduler::SetExecutor(Executor* executor) { +- CHECK_EQ(state_, STATE_NOT_STARTED) ++ ABSL_CHECK_EQ(state_, STATE_NOT_STARTED) + << "SetExecutor must not be called after the scheduler has started"; + default_queue_.SetExecutor(executor); + } +@@ -198,7 +199,7 @@ void Scheduler::Start() { + shared_.timer.StartRun(); + { + absl::MutexLock lock(&state_mutex_); +- CHECK_EQ(state_, STATE_NOT_STARTED); ++ ABSL_CHECK_EQ(state_, STATE_NOT_STARTED); + state_ = STATE_RUNNING; + SetQueuesRunning(true); + +@@ -427,8 +428,9 @@ bool Scheduler::TryToScheduleNextSourceLayer() { + } + + void Scheduler::AddUnopenedSourceNode(CalculatorNode* node) { +- CHECK_EQ(state_, STATE_NOT_STARTED) << "AddUnopenedSourceNode can only be " +- "called before starting the scheduler"; ++ ABSL_CHECK_EQ(state_, STATE_NOT_STARTED) ++ << "AddUnopenedSourceNode can only be " ++ "called before starting the scheduler"; + unopened_sources_.insert(node); + } + +@@ -539,7 +541,7 @@ void Scheduler::CleanupAfterRun() { + } + + internal::SchedulerTimes Scheduler::GetSchedulerTimes() { +- CHECK_EQ(state_, STATE_TERMINATED); ++ ABSL_CHECK_EQ(state_, STATE_TERMINATED); + return shared_.timer.GetSchedulerTimes(); + } + +diff --git a/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc b/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc +index 33214cf642ffb..08360ec429132 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc +@@ -18,6 +18,7 @@ + #include <queue> + #include <utility> + ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/calculator_node.h" + #include "mediapipe/framework/executor.h" +@@ -104,7 +105,7 @@ bool SchedulerQueue::IsIdle() { + void SchedulerQueue::SetRunning(bool running) { + absl::MutexLock lock(&mutex_); + running_count_ += running ? 1 : -1; +- DCHECK_LE(running_count_, 1); ++ ABSL_DCHECK_LE(running_count_, 1); + } + + void SchedulerQueue::AddNode(CalculatorNode* node, CalculatorContext* cc) { +@@ -221,7 +222,7 @@ void SchedulerQueue::RunNextTask() { + bool is_idle; + { + absl::MutexLock lock(&mutex_); +- DCHECK_GT(num_pending_tasks_, 0); ++ ABSL_DCHECK_GT(num_pending_tasks_, 0); + --num_pending_tasks_; + is_idle = IsIdle(); + } +@@ -299,8 +300,8 @@ void SchedulerQueue::CleanupAfterRun() { + { + absl::MutexLock lock(&mutex_); + was_idle = IsIdle(); +- CHECK_EQ(num_pending_tasks_, 0); +- CHECK_EQ(num_tasks_to_add_, queue_.size()); ++ ABSL_CHECK_EQ(num_pending_tasks_, 0); ++ ABSL_CHECK_EQ(num_tasks_to_add_, queue_.size()); + num_tasks_to_add_ = 0; + while (!queue_.empty()) { + queue_.pop(); +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc +index ece873b1eaceb..250d3da27071b 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc +@@ -16,6 +16,7 @@ + #include <memory> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/input_stream_handler.h" + + namespace mediapipe { +@@ -67,7 +68,7 @@ class BarrierInputStreamHandler : public InputStreamHandler { + *min_stream_timestamp = std::min(*min_stream_timestamp, stream_timestamp); + } + +- CHECK_NE(*min_stream_timestamp, Timestamp::Done()); ++ ABSL_CHECK_NE(*min_stream_timestamp, Timestamp::Done()); + if (all_available) { + return NodeReadiness::kReadyForProcess; + } +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc +index 983b986c39334..c0ec0b676a3a9 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc +@@ -16,6 +16,7 @@ + #include <memory> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/strings/substitute.h" + #include "mediapipe/framework/input_stream_handler.h" + +@@ -56,13 +57,13 @@ class EarlyCloseInputStreamHandler : public InputStreamHandler { + *min_stream_timestamp = std::min(*min_stream_timestamp, stream_timestamp); + } + +- CHECK_NE(*min_stream_timestamp, Timestamp::Done()); ++ ABSL_CHECK_NE(*min_stream_timestamp, Timestamp::Done()); + + if (min_bound > *min_stream_timestamp) { + return NodeReadiness::kReadyForProcess; + } + +- CHECK_EQ(min_bound, *min_stream_timestamp); ++ ABSL_CHECK_EQ(min_bound, *min_stream_timestamp); + return NodeReadiness::kNotReady; + } + +@@ -78,7 +79,7 @@ class EarlyCloseInputStreamHandler : public InputStreamHandler { + bool stream_is_done = false; + Packet current_packet = stream->PopPacketAtTimestamp( + input_timestamp, &num_packets_dropped, &stream_is_done); +- CHECK_EQ(num_packets_dropped, 0) ++ ABSL_CHECK_EQ(num_packets_dropped, 0) + << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, stream->Name()); + AddPacketToShard(&input_set->Get(id), std::move(current_packet), +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc +index c34fc96b3cc18..2951c833d28a7 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc +@@ -15,6 +15,7 @@ + #include <memory> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/input_stream_handler.h" + + namespace mediapipe { +@@ -115,7 +116,7 @@ NodeReadiness ImmediateInputStreamHandler::GetNodeReadiness( + ready_timestamps_[i] = stream_ts; + input_timestamp = std::min(input_timestamp, stream_ts); + } else if (readiness == NodeReadiness::kReadyForClose) { +- CHECK_EQ(stream_ts, Timestamp::Done()); ++ ABSL_CHECK_EQ(stream_ts, Timestamp::Done()); + if (ProcessTimestampBounds()) { + // With kReadyForClose, the timestamp-bound Done is returned. + // TODO: Make all InputStreamHandlers process Done() like this. +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc +index 9af38ecdd6531..8faaacebec27f 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/framework/stream_handler/in_order_output_stream_handler.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/collection.h" + #include "mediapipe/framework/collection_item_id.h" + #include "mediapipe/framework/output_stream_shard.h" +@@ -23,7 +24,7 @@ namespace mediapipe { + REGISTER_OUTPUT_STREAM_HANDLER(InOrderOutputStreamHandler); + + void InOrderOutputStreamHandler::PropagationLoop() { +- CHECK_EQ(propagation_state_, kIdle); ++ ABSL_CHECK_EQ(propagation_state_, kIdle); + Timestamp context_timestamp; + CalculatorContext* calculator_context; + if (!calculator_context_manager_->HasActiveContexts()) { +@@ -34,7 +35,7 @@ void InOrderOutputStreamHandler::PropagationLoop() { + if (!completed_input_timestamps_.empty()) { + Timestamp completed_timestamp = *completed_input_timestamps_.begin(); + if (context_timestamp != completed_timestamp) { +- CHECK_LT(context_timestamp, completed_timestamp); ++ ABSL_CHECK_LT(context_timestamp, completed_timestamp); + return; + } + propagation_state_ = kPropagatingPackets; +@@ -45,7 +46,7 @@ void InOrderOutputStreamHandler::PropagationLoop() { + if (propagation_state_ == kPropagatingPackets) { + PropagatePackets(&calculator_context, &context_timestamp); + } else { +- CHECK_EQ(kPropagatingBound, propagation_state_); ++ ABSL_CHECK_EQ(kPropagatingBound, propagation_state_); + PropagationBound(&calculator_context, &context_timestamp); + } + } +@@ -105,12 +106,12 @@ void InOrderOutputStreamHandler::PropagationBound( + } + // Some recent changes require the propagation thread to recheck if any + // new packets can be propagated. +- CHECK_EQ(propagation_state_, kPropagationPending); ++ ABSL_CHECK_EQ(propagation_state_, kPropagationPending); + // task_timestamp_bound_ was updated while the propagation thread was + // doing timestamp propagation. This thread will redo timestamp + // propagation for the new task_timestamp_bound_. + if (!calculator_context_manager_->HasActiveContexts()) { +- CHECK_LT(bound_to_propagate, task_timestamp_bound_); ++ ABSL_CHECK_LT(bound_to_propagate, task_timestamp_bound_); + propagation_state_ = kPropagatingBound; + return; + } +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc +index 0303a5778cb42..699aa91e3766a 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc +@@ -12,6 +12,7 @@ + // See the License for the specific language governing permissions and + // limitations under the License. + ++#include "absl/log/absl_check.h" + #include "absl/strings/substitute.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/collection_item_id.h" +@@ -73,8 +74,8 @@ class MuxInputStreamHandler : public InputStreamHandler { + Packet control_packet = control_stream->QueueHead(); + CHECK(!control_packet.IsEmpty()); + int control_value = control_packet.Get<int>(); +- CHECK_LE(0, control_value); +- CHECK_LT(control_value, input_stream_managers_.NumEntries() - 1); ++ ABSL_CHECK_LE(0, control_value); ++ ABSL_CHECK_LT(control_value, input_stream_managers_.NumEntries() - 1); + const auto& data_stream = input_stream_managers_.Get( + input_stream_managers_.BeginId() + control_value); + +@@ -100,7 +101,7 @@ class MuxInputStreamHandler : public InputStreamHandler { + // indicated as timestamp boun update. + return NodeReadiness::kReadyForProcess; + } +- CHECK_EQ(stream_timestamp, *min_stream_timestamp); ++ ABSL_CHECK_EQ(stream_timestamp, *min_stream_timestamp); + return NodeReadiness::kReadyForProcess; + } + +@@ -118,7 +119,7 @@ class MuxInputStreamHandler : public InputStreamHandler { + bool stream_is_done = false; + Packet control_packet = control_stream->PopPacketAtTimestamp( + input_timestamp, &num_packets_dropped, &stream_is_done); +- CHECK_EQ(num_packets_dropped, 0) ++ ABSL_CHECK_EQ(num_packets_dropped, 0) + << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, control_stream->Name()); + CHECK(!control_packet.IsEmpty()); +@@ -128,13 +129,13 @@ class MuxInputStreamHandler : public InputStreamHandler { + + const CollectionItemId data_stream_id = + input_stream_managers_.BeginId() + control_value; +- CHECK_LE(input_stream_managers_.BeginId(), data_stream_id); +- CHECK_LT(data_stream_id, control_stream_id); ++ ABSL_CHECK_LE(input_stream_managers_.BeginId(), data_stream_id); ++ ABSL_CHECK_LT(data_stream_id, control_stream_id); + auto& data_stream = input_stream_managers_.Get(data_stream_id); + stream_is_done = false; + Packet data_packet = data_stream->PopPacketAtTimestamp( + input_timestamp, &num_packets_dropped, &stream_is_done); +- CHECK_EQ(num_packets_dropped, 0) ++ ABSL_CHECK_EQ(num_packets_dropped, 0) + << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, data_stream->Name()); + AddPacketToShard(&input_set->Get(data_stream_id), std::move(data_packet), +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc +index 1001d64f73e36..adb4c05b3b74e 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc +@@ -15,6 +15,7 @@ + #include <algorithm> + + // TODO: Move protos in another CL after the C++ code migration. ++#include "absl/log/absl_check.h" + #include "absl/strings/substitute.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/collection_item_id.h" +@@ -102,7 +103,7 @@ void SyncSetInputStreamHandler::PrepareForRun( + std::set<CollectionItemId> used_ids; + for (const auto& sync_set : handler_options.sync_set()) { + std::vector<CollectionItemId> stream_ids; +- CHECK_LT(0, sync_set.tag_index_size()); ++ ABSL_CHECK_LT(0, sync_set.tag_index_size()); + for (const auto& tag_index : sync_set.tag_index()) { + std::string tag; + int index; +@@ -185,7 +186,7 @@ void SyncSetInputStreamHandler::FillInputSet(Timestamp input_timestamp, + InputStreamShardSet* input_set) { + // Assume that all current packets are already cleared. + absl::MutexLock lock(&mutex_); +- CHECK_LE(0, ready_sync_set_index_); ++ ABSL_CHECK_LE(0, ready_sync_set_index_); + sync_sets_[ready_sync_set_index_].FillInputSet(input_timestamp, input_set); + for (int i = 0; i < sync_sets_.size(); ++i) { + if (i != ready_sync_set_index_) { +diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc +index ae075d788552b..cb78618cbc3a2 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc ++++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc +@@ -17,6 +17,7 @@ + #include <utility> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/strings/substitute.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/collection_item_id.h" +@@ -178,7 +179,7 @@ NodeReadiness TimestampAlignInputStreamHandler::GetNodeReadiness( + return NodeReadiness::kReadyForProcess; + } + +- CHECK_EQ(min_bound, *min_stream_timestamp); ++ ABSL_CHECK_EQ(min_bound, *min_stream_timestamp); + return NodeReadiness::kNotReady; + } + +@@ -198,7 +199,7 @@ void TimestampAlignInputStreamHandler::FillInputSet( + if (id == timestamp_base_stream_id_) { + current_packet = stream->PopPacketAtTimestamp( + input_timestamp, &num_packets_dropped, &stream_is_done); +- CHECK_EQ(num_packets_dropped, 0) << absl::Substitute( ++ ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute( + "Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, stream->Name()); + } +@@ -218,10 +219,10 @@ void TimestampAlignInputStreamHandler::FillInputSet( + Packet current_packet = stream->PopPacketAtTimestamp( + stream_timestamp, &num_packets_dropped, &stream_is_done); + if (!current_packet.IsEmpty()) { +- CHECK_EQ(current_packet.Timestamp(), stream_timestamp); ++ ABSL_CHECK_EQ(current_packet.Timestamp(), stream_timestamp); + current_packet = current_packet.At(input_timestamp); + } +- CHECK_EQ(num_packets_dropped, 0) ++ ABSL_CHECK_EQ(num_packets_dropped, 0) + << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", + num_packets_dropped, stream->Name()); + AddPacketToShard(&input_set->Get(id), std::move(current_packet), +diff --git a/third_party/mediapipe/src/mediapipe/framework/timestamp.h b/third_party/mediapipe/src/mediapipe/framework/timestamp.h +index d125d28bb58d8..8949dcc807dcd 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/timestamp.h ++++ b/third_party/mediapipe/src/mediapipe/framework/timestamp.h +@@ -47,6 +47,7 @@ + #include <cmath> + #include <string> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/deps/safe_int.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" +@@ -270,14 +271,14 @@ std::ostream& operator<<(std::ostream& os, TimestampDiff arg); + inline Timestamp::Timestamp() : timestamp_(kint64min) {} + + inline Timestamp::Timestamp(int64 timestamp) : timestamp_(timestamp) { +- CHECK(!IsSpecialValue()) ++ ABSL_CHECK(!IsSpecialValue()) + << "Cannot directly create a Timestamp with a special value: " + << CreateNoErrorChecking(timestamp); + } + + inline Timestamp::Timestamp(TimestampBaseType timestamp) + : timestamp_(timestamp) { +- CHECK(!IsSpecialValue()) ++ ABSL_CHECK(!IsSpecialValue()) + << "Cannot directly create a Timestamp with a special value: " + << CreateNoErrorChecking(timestamp.value()); + } +diff --git a/third_party/mediapipe/src/mediapipe/framework/type_map.h b/third_party/mediapipe/src/mediapipe/framework/type_map.h +index 42f6fe6bf2fb9..f958a658f82f2 100644 +--- a/third_party/mediapipe/src/mediapipe/framework/type_map.h ++++ b/third_party/mediapipe/src/mediapipe/framework/type_map.h +@@ -64,6 +64,7 @@ + #include <vector> + + #include "absl/base/macros.h" ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/demangle.h" + #include "mediapipe/framework/port/status.h" +@@ -127,7 +128,7 @@ class StaticMap { + } + + static void GetKeys(std::vector<KeyType>* keys) { +- CHECK(keys); ++ ABSL_CHECK(keys); + keys->clear(); + const MapType& internal_map = GetMap()->internal_map_; + for (typename MapType::const_iterator i = internal_map.begin(); +@@ -158,12 +159,12 @@ class StaticMap { + + // Type has been already registered. + const MediaPipeTypeData& existing_data = it->second.second; +- CHECK_EQ(existing_data.type_id, value.type_id) ++ ABSL_CHECK_EQ(existing_data.type_id, value.type_id) + << "Found inconsistent type ids (" << existing_data.type_id << " vs " + << value.type_id + << ") during mediapipe type registration. Previous definition at " + << it->second.first << " and current definition at " << file_and_line; +- CHECK_EQ(existing_data.type_string, value.type_string) ++ ABSL_CHECK_EQ(existing_data.type_string, value.type_string) + << "Found inconsistent type strings (" << existing_data.type_string + << " vs " << value.type_string + << ") during mediapipe type registration. Previous registration at " +@@ -171,7 +172,7 @@ class StaticMap { + << file_and_line; + if (value.serialize_fn && value.deserialize_fn) { + // Doesn't allow to redefine the existing type serialization functions. +- CHECK(!existing_data.serialize_fn && !existing_data.deserialize_fn) ++ ABSL_CHECK(!existing_data.serialize_fn && !existing_data.deserialize_fn) + << "Attempting to redefine serialization functions of type " + << value.type_string << ", that have been defined at " + << it->second.first << ", at " << file_and_line; +diff --git a/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm b/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm +index c0703e6ee6533..db8bb0a5399e0 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm ++++ b/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm +@@ -20,6 +20,7 @@ + #import "mediapipe/gpu/metal_shared_resources.h" + #import "GTMDefines.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/ret_check.h" + + @interface MPPMetalHelper () { +@@ -78,7 +79,7 @@ class MetalHelperLegacySupport { + - (instancetype)initWithSidePackets:(const mediapipe::PacketSet&)inputSidePackets { + auto cc = mediapipe::MetalHelperLegacySupport::GetCalculatorContext(); + if (cc) { +- CHECK_EQ(&inputSidePackets, &cc->InputSidePackets()); ++ ABSL_CHECK_EQ(&inputSidePackets, &cc->InputSidePackets()); + return [self initWithCalculatorContext:cc]; + } + +@@ -96,7 +97,7 @@ class MetalHelperLegacySupport { + + (absl::Status)setupInputSidePackets:(mediapipe::PacketTypeSet*)inputSidePackets { + auto cc = mediapipe::MetalHelperLegacySupport::GetCalculatorContract(); + if (cc) { +- CHECK_EQ(inputSidePackets, &cc->InputSidePackets()); ++ ABSL_CHECK_EQ(inputSidePackets, &cc->InputSidePackets()); + return [self updateContract:cc]; + } + +@@ -180,7 +181,7 @@ class MetalHelperLegacySupport { + NULL, _gpuResources->metal_shared().resources().mtlTextureCache, + mediapipe::GetCVPixelBufferRef(gpuBuffer), NULL, metalPixelFormat, width, height, plane, + &texture); +- CHECK_EQ(err, kCVReturnSuccess); ++ ABSL_CHECK_EQ(err, kCVReturnSuccess); + return texture; + } + +diff --git a/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc b/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc +index 6e077ae6ebb9e..b0689cd6a9a67 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc +@@ -17,6 +17,7 @@ + #include <tuple> + + #include "CoreFoundation/CFBase.h" ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/objc/CFHolder.h" + #include "mediapipe/objc/util.h" +@@ -27,7 +28,7 @@ CvPixelBufferPoolWrapper::CvPixelBufferPoolWrapper( + int width, int height, GpuBufferFormat format, CFTimeInterval maxAge, + CvTextureCacheManager* texture_caches) { + OSType cv_format = CVPixelFormatForGpuBufferFormat(format); +- CHECK_NE(cv_format, -1) << "unsupported pixel format"; ++ ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; + pool_ = MakeCFHolderAdopting( + /* keep count is 0 because the age param keeps buffers around anyway */ + CreateCVPixelBufferPool(width, height, cv_format, 0, maxAge)); +@@ -73,7 +74,7 @@ void CvPixelBufferPoolWrapper::Flush() { CVPixelBufferPoolFlush(*pool_, 0); } + CFHolder<CVPixelBufferRef> CvPixelBufferPoolWrapper::CreateBufferWithoutPool( + const internal::GpuBufferSpec& spec) { + OSType cv_format = CVPixelFormatForGpuBufferFormat(spec.format); +- CHECK_NE(cv_format, -1) << "unsupported pixel format"; ++ ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; + CVPixelBufferRef buffer; + CVReturn err = CreateCVPixelBufferWithoutPool(spec.width, spec.height, + cv_format, &buffer); +diff --git a/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc b/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc +index b977a8993c4a8..5e06ab6dfc19b 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/gpu/cv_texture_cache_manager.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + + namespace mediapipe { +@@ -48,7 +49,7 @@ void CvTextureCacheManager::UnregisterTextureCache(CVTextureCacheType cache) { + } + + CvTextureCacheManager::~CvTextureCacheManager() { +- CHECK_EQ(texture_caches_.size(), 0) ++ ABSL_CHECK_EQ(texture_caches_.size(), 0) + << "Failed to unregister texture caches before deleting manager"; + } + +diff --git a/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc b/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc +index 974525a91387f..0a422f308ec54 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/gpu/gl_calculator_helper.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/formats/image.h" + #include "mediapipe/framework/formats/image_frame.h" + #include "mediapipe/framework/legacy_calculator_support.h" +@@ -71,7 +72,7 @@ absl::Status GlCalculatorHelper::SetupInputSidePackets( + PacketTypeSet* input_side_packets) { + auto cc = LegacyCalculatorSupport::Scoped<CalculatorContract>::current(); + if (cc) { +- CHECK_EQ(input_side_packets, &cc->InputSidePackets()); ++ ABSL_CHECK_EQ(input_side_packets, &cc->InputSidePackets()); + return UpdateContract(cc); + } + +diff --git a/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc b/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc +index d7381babddd16..c596430bc1948 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc +@@ -34,6 +34,7 @@ + + #ifndef __EMSCRIPTEN__ + #include "absl/debugging/leak_check.h" ++#include "absl/log/absl_check.h" + #include "mediapipe/gpu/gl_thread_collector.h" + #endif + +@@ -69,17 +70,17 @@ static void SetThreadName(const char* name) { + } + + GlContext::DedicatedThread::DedicatedThread() { +- CHECK_EQ(pthread_create(&gl_thread_id_, nullptr, ThreadBody, this), 0); ++ ABSL_CHECK_EQ(pthread_create(&gl_thread_id_, nullptr, ThreadBody, this), 0); + } + + GlContext::DedicatedThread::~DedicatedThread() { + if (IsCurrentThread()) { + CHECK(self_destruct_); +- CHECK_EQ(pthread_detach(gl_thread_id_), 0); ++ ABSL_CHECK_EQ(pthread_detach(gl_thread_id_), 0); + } else { + // Give an invalid job to signal termination. + PutJob({}); +- CHECK_EQ(pthread_join(gl_thread_id_, nullptr), 0); ++ ABSL_CHECK_EQ(pthread_join(gl_thread_id_, nullptr), 0); + } + } + +diff --git a/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc b/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc +index 4e5ce4ee4002c..8c7df3a0bc1d9 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc +@@ -20,6 +20,7 @@ + #include "mediapipe/gpu/gpu_buffer_storage_image_frame.h" + + #if MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER ++#include "absl/log/absl_check.h" + #include "mediapipe/gpu/gl_texture_util.h" + #include "mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.h" + #endif // MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER +@@ -152,7 +153,7 @@ bool GlTextureBuffer::CreateInternal(const void* data, int alignment) { + CHECK(!deletion_callback_); + deletion_callback_ = [this, + context](std::shared_ptr<GlSyncPoint> sync_token) { +- CHECK_NE(name_, 0); ++ ABSL_CHECK_NE(name_, 0); + GLuint name_to_delete = name_; + context->RunWithoutWaiting([name_to_delete]() { + // Note that we do not wait for consumers to be done before deleting the +@@ -264,7 +265,7 @@ GlTextureView GlTextureBuffer::GetReadView(internal::types<GlTextureView>, + int plane) const { + auto gl_context = GlContext::GetCurrent(); + CHECK(gl_context); +- CHECK_EQ(plane, 0); ++ ABSL_CHECK_EQ(plane, 0); + // Note that this method is only supposed to be called by GpuBuffer, which + // ensures this condition is satisfied. + DCHECK(!weak_from_this().expired()) +@@ -285,7 +286,7 @@ GlTextureView GlTextureBuffer::GetWriteView(internal::types<GlTextureView>, + int plane) { + auto gl_context = GlContext::GetCurrent(); + CHECK(gl_context); +- CHECK_EQ(plane, 0); ++ ABSL_CHECK_EQ(plane, 0); + // Note that this method is only supposed to be called by GpuBuffer, which + // ensures this condition is satisfied. + DCHECK(!weak_from_this().expired()) +diff --git a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc +index e88aa602ed9a6..e9f8d0b9fcdd2 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc +@@ -15,6 +15,7 @@ + #include "mediapipe/gpu/gpu_buffer_format.h" + + #include "absl/container/flat_hash_map.h" ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/deps/no_destructor.h" + #include "mediapipe/framework/port/logging.h" + +@@ -194,11 +195,11 @@ const GlTextureInfo& GlTextureInfoForGpuBufferFormat(GpuBufferFormat format, + << static_cast<std::underlying_type_t<decltype(format)>>(format); + const auto& planes = iter->second; + #ifndef __APPLE__ +- CHECK_EQ(planes.size(), 1) ++ ABSL_CHECK_EQ(planes.size(), 1) + << "multiplanar formats are not supported on this platform"; + #endif +- CHECK_GE(plane, 0) << "invalid plane number"; +- CHECK_LT(plane, planes.size()) << "invalid plane number"; ++ ABSL_CHECK_GE(plane, 0) << "invalid plane number"; ++ ABSL_CHECK_LT(plane, planes.size()) << "invalid plane number"; + return planes[plane]; + } + #endif // MEDIAPIPE_DISABLE_GPU +diff --git a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc +index 7cac32b7f1903..642ce23b56846 100644 +--- a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc ++++ b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc +@@ -2,6 +2,7 @@ + + #include <memory> + ++#include "absl/log/absl_check.h" + #include "mediapipe/gpu/gl_context.h" + #include "mediapipe/gpu/gpu_buffer_storage_image_frame.h" + #include "mediapipe/objc/util.h" +@@ -17,7 +18,7 @@ typedef CVOpenGLESTextureRef CVTextureType; + GpuBufferStorageCvPixelBuffer::GpuBufferStorageCvPixelBuffer( + int width, int height, GpuBufferFormat format) { + OSType cv_format = CVPixelFormatForGpuBufferFormat(format); +- CHECK_NE(cv_format, -1) << "unsupported pixel format"; ++ ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; + CVPixelBufferRef buffer; + CVReturn err = + CreateCVPixelBufferWithoutPool(width, height, cv_format, &buffer); +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc +index bd2ce57f95273..9b3e434840cb9 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc +@@ -15,6 +15,7 @@ + #include "mediapipe/modules/objectron/calculators/box.h" + + #include "Eigen/Core" ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + + namespace mediapipe { +@@ -107,12 +108,12 @@ void Box::Adjust(const std::vector<float>& variables) { + } + + float* Box::GetVertex(size_t vertex_id) { +- CHECK_LT(vertex_id, kNumKeypoints); ++ ABSL_CHECK_LT(vertex_id, kNumKeypoints); + return bounding_box_[vertex_id].data(); + } + + const float* Box::GetVertex(size_t vertex_id) const { +- CHECK_LT(vertex_id, kNumKeypoints); ++ ABSL_CHECK_LT(vertex_id, kNumKeypoints); + return bounding_box_[vertex_id].data(); + } + +@@ -135,7 +136,7 @@ bool Box::InsideTest(const Eigen::Vector3f& point, int check_axis) const { + } + + void Box::Deserialize(const Object& obj) { +- CHECK_EQ(obj.keypoints_size(), kNumKeypoints); ++ ABSL_CHECK_EQ(obj.keypoints_size(), kNumKeypoints); + Model::Deserialize(obj); + } + +@@ -222,7 +223,7 @@ std::pair<Vector3f, Vector3f> Box::GetGroundPlane() const { + + template <typename T> + void Box::Fit(const std::vector<T>& vertices) { +- CHECK_EQ(vertices.size(), kNumKeypoints); ++ ABSL_CHECK_EQ(vertices.size(), kNumKeypoints); + scale_.setZero(); + // The scale would remain invariant under rotation and translation. + // We can safely estimate the scale from the oriented box. +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc +index 0af34585b2470..ba6e98a5d22b1 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc +@@ -19,6 +19,7 @@ + + #include "Eigen/Core" + #include "Eigen/Dense" ++#include "absl/log/absl_check.h" + #include "absl/status/status.h" + #include "mediapipe/framework/port/canonical_errors.h" + #include "mediapipe/framework/port/logging.h" +@@ -46,10 +47,10 @@ inline void SetPoint3d(const Eigen::Vector3f& point_vec, Point3D* point_3d) { + + FrameAnnotation Decoder::DecodeBoundingBoxKeypoints( + const cv::Mat& heatmap, const cv::Mat& offsetmap) const { +- CHECK_EQ(1, heatmap.channels()); +- CHECK_EQ(kNumOffsetmaps, offsetmap.channels()); +- CHECK_EQ(heatmap.cols, offsetmap.cols); +- CHECK_EQ(heatmap.rows, offsetmap.rows); ++ ABSL_CHECK_EQ(1, heatmap.channels()); ++ ABSL_CHECK_EQ(kNumOffsetmaps, offsetmap.channels()); ++ ABSL_CHECK_EQ(heatmap.cols, offsetmap.cols); ++ ABSL_CHECK_EQ(heatmap.rows, offsetmap.rows); + + const float offset_scale = std::min(offsetmap.cols, offsetmap.rows); + const std::vector<cv::Point> center_points = ExtractCenterKeypoints(heatmap); +@@ -204,7 +205,7 @@ absl::Status Decoder::Lift2DTo3D( + CHECK(estimated_box != nullptr); + + for (auto& annotation : *estimated_box->mutable_annotations()) { +- CHECK_EQ(kNumKeypoints, annotation.keypoints_size()); ++ ABSL_CHECK_EQ(kNumKeypoints, annotation.keypoints_size()); + + // Fill input 2D Points; + std::vector<Vector2f> input_points_2d; +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc +index 8bd7151fad955..03b78c728484b 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc +@@ -14,6 +14,8 @@ + + #include "mediapipe/modules/objectron/calculators/epnp.h" + ++#include "absl/log/absl_check.h" ++ + namespace mediapipe { + + namespace { +@@ -126,7 +128,7 @@ absl::Status SolveEpnp(const float focal_x, const float focal_y, + if (eigen_solver.info() != Eigen::Success) { + return absl::AbortedError("Eigen decomposition failed."); + } +- CHECK_EQ(12, eigen_solver.eigenvalues().size()); ++ ABSL_CHECK_EQ(12, eigen_solver.eigenvalues().size()); + + // Eigenvalues are sorted in increasing order for SelfAdjointEigenSolver + // only! If you use other Eigen Solvers, it's not guaranteed to be in +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc +index 40aca39d9edc1..d6fe9ed6c5f9a 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/modules/objectron/calculators/model.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + + namespace mediapipe { +@@ -66,9 +67,9 @@ const Eigen::Ref<const Eigen::Matrix3f> Model::GetRotation() const { + const std::string& Model::GetCategory() const { return category_; } + + void Model::Deserialize(const Object& obj) { +- CHECK_EQ(obj.rotation_size(), 9); +- CHECK_EQ(obj.translation_size(), 3); +- CHECK_EQ(obj.scale_size(), 3); ++ ABSL_CHECK_EQ(obj.rotation_size(), 9); ++ ABSL_CHECK_EQ(obj.translation_size(), 3); ++ ABSL_CHECK_EQ(obj.scale_size(), 3); + category_ = obj.category(); + + using RotationMatrix = Eigen::Matrix<float, 3, 3, Eigen::RowMajor>; +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc +index 0004edd800fc5..e48256575304c 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/modules/objectron/calculators/tensor_util.h" + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + + namespace mediapipe { +@@ -21,7 +22,8 @@ namespace mediapipe { + cv::Mat ConvertTfliteTensorToCvMat(const TfLiteTensor& tensor) { + // Check tensor is BxCxWxH (size = 4) and the batch size is one(data[0] = 1) + CHECK(tensor.dims->size == 4 && tensor.dims->data[0] == 1); +- CHECK_EQ(kTfLiteFloat32, tensor.type) << "tflite_tensor type is not float"; ++ ABSL_CHECK_EQ(kTfLiteFloat32, tensor.type) ++ << "tflite_tensor type is not float"; + + const size_t num_output_channels = tensor.dims->data[3]; + const int dims = 2; +@@ -33,8 +35,8 @@ cv::Mat ConvertTfliteTensorToCvMat(const TfLiteTensor& tensor) { + cv::Mat ConvertTensorToCvMat(const mediapipe::Tensor& tensor) { + // Check tensor is BxCxWxH (size = 4) and the batch size is one(data[0] = 1) + CHECK(tensor.shape().dims.size() == 4 && tensor.shape().dims[0] == 1); +- CHECK_EQ(mediapipe::Tensor::ElementType::kFloat32 == tensor.element_type(), +- true) ++ ABSL_CHECK_EQ( ++ mediapipe::Tensor::ElementType::kFloat32 == tensor.element_type(), true) + << "tensor type is not float"; + + const size_t num_output_channels = tensor.shape().dims[3]; +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc +index 6989c34ce88ae..d0fc612318d61 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc +@@ -17,6 +17,7 @@ + #include <vector> + + #include "Eigen/Dense" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/str_format.h" + #include "absl/types/span.h" +@@ -170,7 +171,7 @@ absl::Status TensorsToObjectsCalculator::LoadOptions(CalculatorContext* cc) { + num_keypoints_ = options_.num_keypoints(); + + // Currently only support 2D when num_values_per_keypoint equals to 2. +- CHECK_EQ(options_.num_values_per_keypoint(), 2); ++ ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); + + return absl::OkStatus(); + } +diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc +index d74b59a254658..98aeb7362fa06 100644 +--- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc ++++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc +@@ -17,6 +17,7 @@ + #include <vector> + + #include "Eigen/Dense" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "absl/strings/str_format.h" + #include "absl/types/span.h" +@@ -178,7 +179,7 @@ absl::Status TfLiteTensorsToObjectsCalculator::LoadOptions( + num_keypoints_ = options_.num_keypoints(); + + // Currently only support 2D when num_values_per_keypoint equals to 2. +- CHECK_EQ(options_.num_values_per_keypoint(), 2); ++ ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); + + return absl::OkStatus(); + } +diff --git a/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc b/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc +index a0eadd7154634..3f0ed01a1df38 100644 +--- a/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc ++++ b/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc +@@ -18,6 +18,7 @@ limitations under the License. + #include <cstdint> + #include <memory> + ++#include "absl/log/absl_check.h" + #include "flatbuffers/flexbuffers.h" + #include "tensorflow/core/util/ragged_to_dense_util_common.h" + #include "tensorflow/lite/c/common.h" +@@ -357,7 +358,7 @@ void CalculateOutputIndexValueRowID(const TfLiteTensor& value_rowids, + }; + int current_output_column = 0; + int current_value_rowid = value_rowids_val(0); +- // DCHECK_LT(current_value_rowid, parent_output_index.size()); ++ // ABSL_DCHECK_LT(current_value_rowid, parent_output_index.size()); + int current_output_index = parent_output_index[current_value_rowid]; + result->push_back(current_output_index); + for (int i = 1; i < index_size; ++i) { +@@ -374,12 +375,12 @@ void CalculateOutputIndexValueRowID(const TfLiteTensor& value_rowids, + } else { + current_output_column = 0; + current_value_rowid = next_value_rowid; +- // DCHECK_LT(next_value_rowid, parent_output_index.size()); ++ // ABSL_DCHECK_LT(next_value_rowid, parent_output_index.size()); + current_output_index = parent_output_index[next_value_rowid]; + } + result->push_back(current_output_index); + } +- // DCHECK_EQ(result->size(), value_rowids.size()); ++ // ABSL_DCHECK_EQ(result->size(), value_rowids.size()); + } + + void CalculateOutputIndexRowSplit(const TfLiteTensor& row_split, +@@ -420,7 +421,7 @@ void CalculateOutputIndexRowSplit(const TfLiteTensor& row_split, + } + } + // if (row_split_size > 0) { +- // DCHECK_EQ(result->size(), row_split(row_split_size - 1)); ++ // ABSL_DCHECK_EQ(result->size(), row_split(row_split_size - 1)); + //} + } + +diff --git a/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc b/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc +index d8516f9bc36c7..e1aa4846792b4 100644 +--- a/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc ++++ b/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc +@@ -19,6 +19,7 @@ + #include <algorithm> + #include <cmath> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/vector.h" + #include "mediapipe/util/color.pb.h" +@@ -49,8 +50,8 @@ bool NormalizedtoPixelCoordinates(double normalized_x, double normalized_y, + int* y_px) { + CHECK(x_px != nullptr); + CHECK(y_px != nullptr); +- CHECK_GT(image_width, 0); +- CHECK_GT(image_height, 0); ++ ABSL_CHECK_GT(image_width, 0); ++ ABSL_CHECK_GT(image_height, 0); + + if (normalized_x < 0 || normalized_x > 1.0 || normalized_y < 0 || + normalized_y > 1.0) { +diff --git a/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc b/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc +index bf2773fdc7152..d2769427e626b 100644 +--- a/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc ++++ b/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc +@@ -20,6 +20,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/str_join.h" + #include "absl/strings/string_view.h" +@@ -47,7 +48,7 @@ void RescaleImageFrame(const ImageFrame& source_frame, const int width, + const int open_cv_interpolation_algorithm, + ImageFrame* destination_frame) { + CHECK(destination_frame); +- CHECK_EQ(ImageFormat::SRGB, source_frame.Format()); ++ ABSL_CHECK_EQ(ImageFormat::SRGB, source_frame.Format()); + + cv::Mat source_mat = ::mediapipe::formats::MatView(&source_frame); + destination_frame->Reset(source_frame.Format(), width, height, +@@ -106,7 +107,7 @@ void ImageFrameToYUVImage(const ImageFrame& image_frame, YUVImage* yuv_image) { + u, uv_stride, // + v, uv_stride, // + width, height); +- CHECK_EQ(0, rv); ++ ABSL_CHECK_EQ(0, rv); + } + + void ImageFrameToYUVNV12Image(const ImageFrame& image_frame, +@@ -136,7 +137,7 @@ void ImageFrameToYUVNV12Image(const ImageFrame& image_frame, + yuv_i420_image.stride(2), yuv_nv12_image->mutable_data(0), + yuv_nv12_image->stride(0), yuv_nv12_image->mutable_data(1), + yuv_nv12_image->stride(1), width, height); +- CHECK_EQ(0, rv); ++ ABSL_CHECK_EQ(0, rv); + } + + void YUVImageToImageFrame(const YUVImage& yuv_image, ImageFrame* image_frame, +@@ -161,7 +162,7 @@ void YUVImageToImageFrame(const YUVImage& yuv_image, ImageFrame* image_frame, + image_frame->MutablePixelData(), + image_frame->WidthStep(), width, height); + } +- CHECK_EQ(0, rv); ++ ABSL_CHECK_EQ(0, rv); + } + + void YUVImageToImageFrameFromFormat(const YUVImage& yuv_image, +diff --git a/third_party/mediapipe/src/mediapipe/util/resource_cache.h b/third_party/mediapipe/src/mediapipe/util/resource_cache.h +index 2b3ccbc7d6749..da0e4adfb0bf9 100644 +--- a/third_party/mediapipe/src/mediapipe/util/resource_cache.h ++++ b/third_party/mediapipe/src/mediapipe/util/resource_cache.h +@@ -19,6 +19,7 @@ + + #include "absl/container/flat_hash_map.h" + #include "absl/functional/function_ref.h" ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + + namespace mediapipe { +@@ -40,10 +41,12 @@ class ResourceCache { + std::tie(map_it, std::ignore) = + map_.try_emplace(key, std::make_unique<Entry>(key)); + entry = map_it->second.get(); +- CHECK_EQ(entry->request_count, 0); ++ ABSL_CHECK_EQ(entry->request_count, 0); + entry->request_count = 1; + entry_list_.Append(entry); +- if (entry->prev != nullptr) CHECK_GE(entry->prev->request_count, 1); ++ if (entry->prev != nullptr) { ++ ABSL_CHECK_GE(entry->prev->request_count, 1); ++ } + } else { + entry = map_it->second.get(); + ++entry->request_count; +diff --git a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc +index 21d030fffd72a..372a2c6115d88 100644 +--- a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc ++++ b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc +@@ -17,6 +17,7 @@ + #include <cmath> + #include <limits> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_split.h" + #include "mediapipe/framework/port/opencv_imgcodecs_inc.h" + #include "mediapipe/framework/port/ret_check.h" +@@ -534,7 +535,7 @@ std::unique_ptr<mediapipe::Matrix> GetAudioFromFeatureAt( + << "GetAudioAt requires num_channels context to be specified as key: " + << merge_prefix(prefix, kFeatureNumChannelsKey); + int num_channels = GetFeatureNumChannels(prefix, sequence); +- CHECK_EQ(flat_data.size() % num_channels, 0) ++ ABSL_CHECK_EQ(flat_data.size() % num_channels, 0) + << "The data size is not a multiple of the number of channels: " + << flat_data.size() << " % " << num_channels << " = " + << flat_data.size() % num_channels << " for sequence index " << index; +diff --git a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h +index 1737f91a0e701..2e738281b2cde 100644 +--- a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h ++++ b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h +@@ -92,6 +92,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/proto_ns.h" +@@ -220,7 +221,7 @@ inline const proto_ns::RepeatedField<float>& GetFloatsAt( + const tensorflow::SequenceExample& sequence, const std::string& key, + const int index) { + const tensorflow::FeatureList& fl = GetFeatureList(sequence, key); +- CHECK_LT(index, fl.feature_size()) ++ ABSL_CHECK_LT(index, fl.feature_size()) + << "Sequence: \n " << sequence.DebugString(); + return fl.feature().Get(index).float_list().value(); + } +@@ -231,7 +232,7 @@ inline const proto_ns::RepeatedField<int64>& GetInt64sAt( + const tensorflow::SequenceExample& sequence, const std::string& key, + const int index) { + const tensorflow::FeatureList& fl = GetFeatureList(sequence, key); +- CHECK_LT(index, fl.feature_size()) ++ ABSL_CHECK_LT(index, fl.feature_size()) + << "Sequence: \n " << sequence.DebugString(); + return fl.feature().Get(index).int64_list().value(); + } +@@ -242,7 +243,7 @@ inline const proto_ns::RepeatedPtrField<std::string>& GetBytesAt( + const tensorflow::SequenceExample& sequence, const std::string& key, + const int index) { + const tensorflow::FeatureList& fl = GetFeatureList(sequence, key); +- CHECK_LT(index, fl.feature_size()) ++ ABSL_CHECK_LT(index, fl.feature_size()) + << "Sequence: \n " << sequence.DebugString(); + return fl.feature().Get(index).bytes_list().value(); + } +diff --git a/third_party/mediapipe/src/mediapipe/util/time_series_util.cc b/third_party/mediapipe/src/mediapipe/util/time_series_util.cc +index 87f69475a2ccf..128cc11756fda 100644 +--- a/third_party/mediapipe/src/mediapipe/util/time_series_util.cc ++++ b/third_party/mediapipe/src/mediapipe/util/time_series_util.cc +@@ -19,6 +19,7 @@ + #include <iostream> + #include <string> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/framework/calculator_framework.h" + #include "mediapipe/framework/formats/time_series_header.pb.h" +@@ -127,7 +128,7 @@ int64_t SecondsToSamples(double time_in_seconds, double sample_rate) { + } + + double SamplesToSeconds(int64_t num_samples, double sample_rate) { +- DCHECK_NE(sample_rate, 0.0); ++ ABSL_DCHECK_NE(sample_rate, 0.0); + return (num_samples / sample_rate); + } + +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc b/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc +index 58d855537c8d1..44567d7941744 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc +@@ -16,6 +16,7 @@ + + #include <vector> + ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "mediapipe/framework/port/opencv_calib3d_inc.h" + #include "mediapipe/framework/port/opencv_imgproc_inc.h" +@@ -46,7 +47,7 @@ cv::Mat ConvertDescriptorsToMat(const std::vector<std::string> &descriptors) { + CHECK(!descriptors.empty()) << "empty descriptors."; + + const int descriptors_dims = descriptors[0].size(); +- CHECK_GT(descriptors_dims, 0); ++ ABSL_CHECK_GT(descriptors_dims, 0); + + cv::Mat mat(descriptors.size(), descriptors_dims, CV_8U); + +@@ -59,13 +60,13 @@ cv::Mat ConvertDescriptorsToMat(const std::vector<std::string> &descriptors) { + + cv::Mat GetDescriptorsWithIndices(const cv::Mat &frame_descriptors, + const std::vector<int> &indices) { +- CHECK_GT(frame_descriptors.rows, 0); ++ ABSL_CHECK_GT(frame_descriptors.rows, 0); + + const int num_inlier_descriptors = indices.size(); +- CHECK_GT(num_inlier_descriptors, 0); ++ ABSL_CHECK_GT(num_inlier_descriptors, 0); + + const int descriptors_dims = frame_descriptors.cols; +- CHECK_GT(descriptors_dims, 0); ++ ABSL_CHECK_GT(descriptors_dims, 0); + + cv::Mat mat(num_inlier_descriptors, descriptors_dims, CV_32F); + +@@ -301,7 +302,7 @@ void BoxDetectorInterface::DetectAndAddBox( + orb_extractor_->detect(resize_image, keypoints); + orb_extractor_->compute(resize_image, keypoints, descriptors); + +- CHECK_EQ(keypoints.size(), descriptors.rows); ++ ABSL_CHECK_EQ(keypoints.size(), descriptors.rows); + + float inv_scale = 1.0f / std::max(resize_image.cols, resize_image.rows); + std::vector<Vector2_f> v_keypoints(keypoints.size()); +@@ -681,15 +682,15 @@ void BoxDetectorInterface::AddBoxDetectorIndex(const BoxDetectorIndex &index) { + continue; + } + +- CHECK_EQ(frame_entry.keypoints_size(), +- frame_entry.descriptors_size() * 2); ++ ABSL_CHECK_EQ(frame_entry.keypoints_size(), ++ frame_entry.descriptors_size() * 2); + + const int num_features = frame_entry.descriptors_size(); +- CHECK_GT(num_features, 0); ++ ABSL_CHECK_GT(num_features, 0); + std::vector<Vector2_f> features(num_features); + + const int descriptors_dims = frame_entry.descriptors(0).data().size(); +- CHECK_GT(descriptors_dims, 0); ++ ABSL_CHECK_GT(descriptors_dims, 0); + + cv::Mat descriptors_mat(num_features, descriptors_dims / sizeof(float), + CV_32F); +@@ -713,7 +714,7 @@ std::vector<FeatureCorrespondence> + BoxDetectorOpencvBfImpl::MatchFeatureDescriptors( + const std::vector<Vector2_f> &features, const cv::Mat &descriptors, + int box_idx) { +- CHECK_EQ(features.size(), descriptors.rows); ++ ABSL_CHECK_EQ(features.size(), descriptors.rows); + + std::vector<FeatureCorrespondence> correspondence_result( + frame_box_[box_idx].size()); +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc b/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc +index 2d1af779ee50e..61a9437b7e61f 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc +@@ -19,6 +19,7 @@ + #include <fstream> + #include <limits> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/synchronization/mutex.h" + #include "absl/time/clock.h" +@@ -36,7 +37,7 @@ static constexpr int kInitCheckpoint = -1; + + void MotionBoxStateQuadToVertices(const MotionBoxState::Quad& quad, + std::vector<Vector2_f>* vertices) { +- CHECK_EQ(TimedBox::kNumQuadVertices * 2, quad.vertices_size()); ++ ABSL_CHECK_EQ(TimedBox::kNumQuadVertices * 2, quad.vertices_size()); + CHECK(vertices != nullptr); + vertices->clear(); + for (int i = 0; i < TimedBox::kNumQuadVertices; ++i) { +@@ -47,7 +48,7 @@ void MotionBoxStateQuadToVertices(const MotionBoxState::Quad& quad, + + void VerticesToMotionBoxStateQuad(const std::vector<Vector2_f>& vertices, + MotionBoxState::Quad* quad) { +- CHECK_EQ(TimedBox::kNumQuadVertices, vertices.size()); ++ ABSL_CHECK_EQ(TimedBox::kNumQuadVertices, vertices.size()); + CHECK(quad != nullptr); + for (const Vector2_f& vertex : vertices) { + quad->add_vertices(vertex.x()); +@@ -113,7 +114,7 @@ namespace { + + TimedBox BlendTimedBoxes(const TimedBox& lhs, const TimedBox& rhs, + int64_t time_msec) { +- CHECK_LT(lhs.time_msec, rhs.time_msec); ++ ABSL_CHECK_LT(lhs.time_msec, rhs.time_msec); + const double alpha = + (time_msec - lhs.time_msec) * 1.0 / (rhs.time_msec - lhs.time_msec); + return TimedBox::Blend(lhs, rhs, alpha); +@@ -245,10 +246,10 @@ BoxTracker::BoxTracker( + + void BoxTracker::AddTrackingDataChunk(const TrackingDataChunk* chunk, + bool copy_data) { +- CHECK_GT(chunk->item_size(), 0) << "Empty chunk."; ++ ABSL_CHECK_GT(chunk->item_size(), 0) << "Empty chunk."; + int64_t chunk_time_msec = chunk->item(0).timestamp_usec() / 1000; + int chunk_idx = ChunkIdxFromTime(chunk_time_msec); +- CHECK_GE(chunk_idx, tracking_data_.size()) << "Chunk is out of order."; ++ ABSL_CHECK_GE(chunk_idx, tracking_data_.size()) << "Chunk is out of order."; + if (chunk_idx > tracking_data_.size()) { + LOG(INFO) << "Resize tracking_data_ to " << chunk_idx; + tracking_data_.resize(chunk_idx); +@@ -688,7 +689,7 @@ bool BoxTracker::WaitForChunkFile(int id, int checkpoint, + + int BoxTracker::ClosestFrameIndex(int64_t msec, + const TrackingDataChunk& chunk) const { +- CHECK_GT(chunk.item_size(), 0); ++ ABSL_CHECK_GT(chunk.item_size(), 0); + typedef TrackingDataChunk::Item Item; + Item item_to_find; + item_to_find.set_timestamp_usec(msec * 1000); +@@ -749,8 +750,8 @@ void BoxTracker::TrackingImpl(const TrackingImplArgs& a) { + MotionBox motion_box(track_step_options); + const int chunk_data_size = a.chunk_data->item_size(); + +- CHECK_GE(a.start_frame, 0); +- CHECK_LT(a.start_frame, chunk_data_size); ++ ABSL_CHECK_GE(a.start_frame, 0); ++ ABSL_CHECK_LT(a.start_frame, chunk_data_size); + + VLOG(1) << " a.start_frame = " << a.start_frame << " @" + << a.chunk_data->item(a.start_frame).timestamp_usec() << " with " +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc +index e753be71208a8..b2c137c8c0a00 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc +@@ -16,6 +16,7 @@ + + #include <numeric> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + #include "mediapipe/util/tracking/region_flow.h" + +@@ -76,8 +77,8 @@ void CameraMotionToMixtureHomography(const CameraMotion& camera_motion, + + CameraMotion ComposeCameraMotion(const CameraMotion& lhs, + const CameraMotion& rhs) { +- CHECK_EQ(lhs.frame_width(), rhs.frame_width()); +- CHECK_EQ(lhs.frame_height(), rhs.frame_height()); ++ ABSL_CHECK_EQ(lhs.frame_width(), rhs.frame_width()); ++ ABSL_CHECK_EQ(lhs.frame_height(), rhs.frame_height()); + + CameraMotion result = rhs; + if (lhs.has_translation() || rhs.has_translation()) { +@@ -185,7 +186,7 @@ void SubtractCameraMotionFromFeatures( + const std::vector<CameraMotion>& camera_motions, + std::vector<RegionFlowFeatureList*>* feature_lists) { + CHECK(feature_lists != nullptr); +- CHECK_GE(camera_motions.size(), feature_lists->size()); ++ ABSL_CHECK_GE(camera_motions.size(), feature_lists->size()); + if (feature_lists->empty()) { + return; + } +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h +index cadee78cbc1e5..379920b1ec216 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h +@@ -17,6 +17,7 @@ + + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/util/tracking/camera_motion.pb.h" + #include "mediapipe/util/tracking/motion_models.h" + #include "mediapipe/util/tracking/region_flow.pb.h" +@@ -236,7 +237,7 @@ void DownsampleMotionModels( + std::vector<Model>* downsampled_models, + std::vector<CameraMotion::Type>* downsampled_types) { + if (model_type) { +- CHECK_EQ(models.size(), model_type->size()); ++ ABSL_CHECK_EQ(models.size(), model_type->size()); + CHECK(downsampled_models) << "Expecting output models."; + } + +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc b/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc +index dceacbcd9b366..01ee6f60cef93 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc +@@ -20,6 +20,7 @@ + #include <cmath> + #include <memory> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "absl/strings/string_view.h" + #include "mediapipe/framework/port/logging.h" +@@ -36,8 +37,8 @@ namespace mediapipe { + FlowPackager::FlowPackager(const FlowPackagerOptions& options) + : options_(options) { + if (options_.binary_tracking_data_support()) { +- CHECK_LE(options.domain_width(), 256); +- CHECK_LE(options.domain_height(), 256); ++ ABSL_CHECK_LE(options.domain_width(), 256); ++ ABSL_CHECK_LE(options.domain_height(), 256); + } + } + +@@ -135,8 +136,8 @@ void FlowPackager::PackFlow(const RegionFlowFeatureList& feature_list, + const CameraMotion* camera_motion, + TrackingData* tracking_data) const { + CHECK(tracking_data); +- CHECK_GT(feature_list.frame_width(), 0); +- CHECK_GT(feature_list.frame_height(), 0); ++ ABSL_CHECK_GT(feature_list.frame_width(), 0); ++ ABSL_CHECK_GT(feature_list.frame_height(), 0); + + // Scale flow to output domain. + const float dim_x_scale = +@@ -231,12 +232,12 @@ void FlowPackager::PackFlow(const RegionFlowFeatureList& feature_list, + const int curr_col = loc.x(); + + if (curr_col != last_col) { +- CHECK_LT(last_col, curr_col); +- CHECK_EQ(-1, col_start[curr_col]); ++ ABSL_CHECK_LT(last_col, curr_col); ++ ABSL_CHECK_EQ(-1, col_start[curr_col]); + col_start[curr_col] = data->row_indices_size() - 1; + last_col = curr_col; + } else { +- CHECK_LE(last_row, loc.y()); ++ ABSL_CHECK_LE(last_row, loc.y()); + } + last_row = loc.y(); + } +@@ -247,7 +248,7 @@ void FlowPackager::PackFlow(const RegionFlowFeatureList& feature_list, + // Fill unset values with previously set value. Propagate end value. + for (int i = options_.domain_width() - 1; i > 0; --i) { + if (col_start[i] < 0) { +- DCHECK_GE(col_start[i + 1], 0); ++ ABSL_DCHECK_GE(col_start[i + 1], 0); + col_start[i] = col_start[i + 1]; + } + } +@@ -261,11 +262,11 @@ void FlowPackager::PackFlow(const RegionFlowFeatureList& feature_list, + const int r_start = data->col_starts(c); + const int r_end = data->col_starts(c + 1); + for (int r = r_start; r < r_end - 1; ++r) { +- CHECK_LE(data->row_indices(r), data->row_indices(r + 1)); ++ ABSL_CHECK_LE(data->row_indices(r), data->row_indices(r + 1)); + } + } + +- CHECK_EQ(data->vector_data_size(), 2 * data->row_indices_size()); ++ ABSL_CHECK_EQ(data->vector_data_size(), 2 * data->row_indices_size()); + + *data->mutable_actively_discarded_tracked_ids() = + feature_list.actively_discarded_tracked_ids(); +@@ -313,7 +314,7 @@ void FlowPackager::EncodeTrackingData(const TrackingData& tracking_data, + + const int32_t domain_width = tracking_data.domain_width(); + const int32_t domain_height = tracking_data.domain_height(); +- CHECK_LT(domain_height, 256) << "Only heights below 256 are supported."; ++ ABSL_CHECK_LT(domain_height, 256) << "Only heights below 256 are supported."; + const float frame_aspect = tracking_data.frame_aspect(); + + // Limit vector value from above (to 20% frame diameter) and below (small +@@ -393,7 +394,7 @@ void FlowPackager::EncodeTrackingData(const TrackingData& tracking_data, + flow_compressed_8.push_back(flow_y); + } + +- DCHECK_LT(motion_data.row_indices(r), 256); ++ ABSL_DCHECK_LT(motion_data.row_indices(r), 256); + row_idx.push_back(motion_data.row_indices(r)); + } + } +@@ -470,7 +471,7 @@ void FlowPackager::EncodeTrackingData(const TrackingData& tracking_data, + // Delta compress. + int delta_row = motion_data.row_indices(r) - + (r == r_start ? 0 : motion_data.row_indices(r - 1)); +- CHECK_GE(delta_row, 0); ++ ABSL_CHECK_GE(delta_row, 0); + + bool combined = false; + if (r > r_start) { +@@ -520,9 +521,9 @@ void FlowPackager::EncodeTrackingData(const TrackingData& tracking_data, + } + + if (options_.high_fidelity_16bit_encode()) { +- CHECK_EQ(2 * encoded, flow_compressed_16.size()); ++ ABSL_CHECK_EQ(2 * encoded, flow_compressed_16.size()); + } else { +- CHECK_EQ(2 * encoded, flow_compressed_8.size()); ++ ABSL_CHECK_EQ(2 * encoded, flow_compressed_8.size()); + } + + // Adjust column start by compressions. +@@ -530,11 +531,11 @@ void FlowPackager::EncodeTrackingData(const TrackingData& tracking_data, + for (int k = 0; k < domain_width; ++k) { + curr_adjust -= compressions_per_column[k]; + col_starts[k + 1] += curr_adjust; +- CHECK_LE(col_starts[k], col_starts[k + 1]); ++ ABSL_CHECK_LE(col_starts[k], col_starts[k + 1]); + } + +- CHECK_EQ(row_idx.size(), col_starts.back()); +- CHECK_EQ(num_vectors, row_idx.size() + compressible); ++ ABSL_CHECK_EQ(row_idx.size(), col_starts.back()); ++ ABSL_CHECK_EQ(num_vectors, row_idx.size() + compressible); + } + + // Delta compress col_starts. +@@ -542,7 +543,7 @@ void FlowPackager::EncodeTrackingData(const TrackingData& tracking_data, + col_start_delta[0] = col_starts[0]; + for (int k = 1; k < domain_width + 1; ++k) { + const int delta = col_starts[k] - col_starts[k - 1]; +- CHECK_LT(delta, 256) << "Only up to 255 items per column supported."; ++ ABSL_CHECK_LT(delta, 256) << "Only up to 255 items per column supported."; + col_start_delta[k] = delta; + } + +@@ -618,8 +619,8 @@ void FlowPackager::DecodeTrackingData(const BinaryTrackingData& container_data, + DecodeFromStringView(PopSubstring(4, &data), &domain_height); + DecodeFromStringView(PopSubstring(4, &data), &frame_aspect); + +- CHECK_LE(domain_width, 256); +- CHECK_LE(domain_height, 256); ++ ABSL_CHECK_LE(domain_width, 256); ++ ABSL_CHECK_LE(domain_height, 256); + + DecodeVectorFromStringView( + PopSubstring(4 * HomographyAdapter::NumParameters(), &data), +@@ -662,7 +663,7 @@ void FlowPackager::DecodeTrackingData(const BinaryTrackingData& container_data, + + // Should not have more row indices than vectors. (One for each in baseline + // profile, less in high profile). +- CHECK_LE(row_idx_size, num_vectors); ++ ABSL_CHECK_LE(row_idx_size, num_vectors); + DecodeVectorFromStringView(PopSubstring(row_idx_size, &data), &row_idx); + + // Records for each vector whether to advance pointer in the vector data array +@@ -707,7 +708,7 @@ void FlowPackager::DecodeTrackingData(const BinaryTrackingData& container_data, + } + } + row_idx.swap(row_idx_unpacked); +- CHECK_EQ(num_vectors, row_idx.size()); ++ ABSL_CHECK_EQ(num_vectors, row_idx.size()); + + // Adjust column start by expansions. + int curr_adjust = 0; +@@ -717,7 +718,7 @@ void FlowPackager::DecodeTrackingData(const BinaryTrackingData& container_data, + } + } + +- CHECK_EQ(num_vectors, col_starts.back()); ++ ABSL_CHECK_EQ(num_vectors, col_starts.back()); + + int vector_data_size; + DecodeFromStringView(PopSubstring(4, &data), &vector_data_size); +@@ -749,7 +750,7 @@ void FlowPackager::DecodeTrackingData(const BinaryTrackingData& container_data, + motion_data->add_vector_data(prev_flow_y * flow_denom); + } + } +- CHECK_EQ(vector_data_size, counter); ++ ABSL_CHECK_EQ(vector_data_size, counter); + } else { + std::vector<int8_t> vector_data; + DecodeVectorFromStringView( +@@ -775,7 +776,7 @@ void FlowPackager::DecodeTrackingData(const BinaryTrackingData& container_data, + motion_data->add_vector_data(prev_flow_y * flow_denom); + } + } +- CHECK_EQ(vector_data_size, counter); ++ ABSL_CHECK_EQ(vector_data_size, counter); + } + + for (auto idx : row_idx) { +@@ -799,8 +800,8 @@ void FlowPackager::BinaryTrackingDataToContainer( + + void FlowPackager::BinaryTrackingDataFromContainer( + const TrackingContainer& container, BinaryTrackingData* binary_data) const { +- CHECK_EQ("TRAK", container.header()); +- CHECK_EQ(1, container.version()) << "Unsupported version."; ++ ABSL_CHECK_EQ("TRAK", container.header()); ++ ABSL_CHECK_EQ(1, container.version()) << "Unsupported version."; + *binary_data->mutable_data() = container.data(); + } + +@@ -808,8 +809,8 @@ void FlowPackager::DecodeMetaData(const TrackingContainer& container_data, + MetaData* meta_data) const { + CHECK(meta_data != nullptr); + +- CHECK_EQ("META", container_data.header()); +- CHECK_EQ(1, container_data.version()) << "Unsupported version."; ++ ABSL_CHECK_EQ("META", container_data.header()); ++ ABSL_CHECK_EQ(1, container_data.version()) << "Unsupported version."; + + absl::string_view data(container_data.data()); + +@@ -840,7 +841,7 @@ void FlowPackager::FinalizeTrackingContainerFormat( + + std::vector<uint32_t> msecs(num_frames, 0); + if (timestamps) { +- CHECK_EQ(num_frames, timestamps->size()); ++ ABSL_CHECK_EQ(num_frames, timestamps->size()); + msecs = *timestamps; + } + std::vector<int> sizes(num_frames, 0); +@@ -884,7 +885,7 @@ void FlowPackager::FinalizeTrackingContainerProto( + + std::vector<uint32_t> msecs(num_frames, 0); + if (timestamps) { +- CHECK_EQ(num_frames, timestamps->size()); ++ ABSL_CHECK_EQ(num_frames, timestamps->size()); + msecs = *timestamps; + } + +@@ -909,8 +910,8 @@ void FlowPackager::InitializeMetaData(int num_frames, + const std::vector<int>& data_sizes, + MetaData* meta_data) const { + meta_data->set_num_frames(num_frames); +- CHECK_EQ(num_frames, msecs.size()); +- CHECK_EQ(num_frames, data_sizes.size()); ++ ABSL_CHECK_EQ(num_frames, msecs.size()); ++ ABSL_CHECK_EQ(num_frames, data_sizes.size()); + + int curr_offset = 0; + for (int f = 0; f < num_frames; ++f) { +@@ -925,7 +926,7 @@ void FlowPackager::AddContainerToString(const TrackingContainer& container, + std::string* binary_data) { + CHECK(binary_data != nullptr); + std::string header_string(container.header()); +- CHECK_EQ(4, header_string.size()); ++ ABSL_CHECK_EQ(4, header_string.size()); + + std::vector<char> header{header_string[0], header_string[1], header_string[2], + header_string[3]}; +@@ -938,8 +939,8 @@ std::string FlowPackager::SplitContainerFromString( + absl::string_view* binary_data, TrackingContainer* container) { + CHECK(binary_data != nullptr); + CHECK(container != nullptr); +- CHECK_GE(binary_data->size(), 12) << "Data does not contain " +- << "valid container"; ++ ABSL_CHECK_GE(binary_data->size(), 12) << "Data does not contain " ++ << "valid container"; + + container->set_header(PopSubstring(4, binary_data)); + +@@ -979,18 +980,18 @@ void FlowPackager::TrackingContainerFormatFromBinary( + + absl::string_view data(binary); + +- CHECK_EQ("META", SplitContainerFromString( +- &data, container_format->mutable_meta_data())); ++ ABSL_CHECK_EQ("META", SplitContainerFromString( ++ &data, container_format->mutable_meta_data())); + MetaData meta_data; + DecodeMetaData(container_format->meta_data(), &meta_data); + + for (int f = 0; f < meta_data.num_frames(); ++f) { + TrackingContainer* container = container_format->add_track_data(); +- CHECK_EQ("TRAK", SplitContainerFromString(&data, container)); ++ ABSL_CHECK_EQ("TRAK", SplitContainerFromString(&data, container)); + } + +- CHECK_EQ("TERM", SplitContainerFromString( +- &data, container_format->mutable_term_data())); ++ ABSL_CHECK_EQ("TERM", SplitContainerFromString( ++ &data, container_format->mutable_term_data())); + } + + void FlowPackager::SortRegionFlowFeatureList( +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc +index a44c00b01f4c8..a7e4a2f40f21f 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc +@@ -17,6 +17,7 @@ + #include <algorithm> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/util/tracking/motion_models.h" + #include "mediapipe/util/tracking/region_flow.h" +@@ -26,7 +27,7 @@ namespace mediapipe { + // Returns median of the L1 color distance between img_1 and img_2 + float FrameDifferenceMedian(const cv::Mat& img_1, const cv::Mat& img_2) { + CHECK(img_1.size() == img_2.size()); +- CHECK_EQ(img_1.channels(), img_2.channels()); ++ ABSL_CHECK_EQ(img_1.channels(), img_2.channels()); + + std::vector<float> color_diffs; + color_diffs.reserve(img_1.cols * img_1.rows); +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h +index ba58d343bc053..f1e7eda36169e 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h +@@ -17,6 +17,7 @@ + + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/opencv_core_inc.h" + #include "mediapipe/framework/port/opencv_imgproc_inc.h" + #include "mediapipe/framework/port/vector.h" +@@ -75,7 +76,7 @@ void CopyMatBorder(cv::Mat* mat) { + } + + // src and dst should point to same column from here. +- DCHECK_EQ(0, (src_ptr - dst_ptr) * sizeof(T) % mat->step[0]); ++ ABSL_DCHECK_EQ(0, (src_ptr - dst_ptr) * sizeof(T) % mat->step[0]); + + // Top row copy. + memcpy(dst_ptr, src_ptr, width * channels * sizeof(dst_ptr[0])); +@@ -122,7 +123,7 @@ void CopyMatBorder(cv::Mat* mat) { + } + + // src and dst should point to same column from here. +- DCHECK_EQ(0, (dst_ptr - src_ptr) * sizeof(T) % mat->step[0]); ++ ABSL_DCHECK_EQ(0, (dst_ptr - src_ptr) * sizeof(T) % mat->step[0]); + memcpy(dst_ptr, src_ptr, width * channels * sizeof(dst_ptr[0])); + src_ptr += width * channels; // Points one behind the end. + dst_ptr += width * channels; +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc +index 67973cbcf7612..d750977485b55 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc +@@ -20,6 +20,7 @@ + #include <deque> + #include <memory> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" +@@ -92,8 +93,8 @@ MotionAnalysis::MotionAnalysis(const MotionAnalysisOptions& options, + use_spatial_bias; + + if (compute_feature_descriptors_) { +- CHECK_EQ(RegionFlowComputationOptions::FORMAT_RGB, +- options_.flow_options().image_format()) ++ ABSL_CHECK_EQ(RegionFlowComputationOptions::FORMAT_RGB, ++ options_.flow_options().image_format()) + << "Feature descriptors only support RGB currently."; + prev_frame_.reset(new cv::Mat(frame_height_, frame_width_, CV_8UC3)); + } +@@ -479,7 +480,7 @@ int MotionAnalysis::GetResults( + + const int num_features_lists = buffer_->BufferSize("features"); + const int num_new_feature_lists = num_features_lists - overlap_start_; +- CHECK_GE(num_new_feature_lists, 0); ++ ABSL_CHECK_GE(num_new_feature_lists, 0); + + if (!flush && num_new_feature_lists < options_.estimation_clip_size()) { + // Nothing to compute, return. +@@ -487,7 +488,7 @@ int MotionAnalysis::GetResults( + } + + const bool compute_saliency = options_.compute_motion_saliency(); +- CHECK_EQ(compute_saliency, saliency != nullptr) ++ ABSL_CHECK_EQ(compute_saliency, saliency != nullptr) + << "Computing saliency requires saliency output and vice versa"; + + // Estimate motions for newly buffered RegionFlowFeatureLists, which also +@@ -528,7 +529,7 @@ int MotionAnalysis::OutputResults( + std::vector<std::unique_ptr<CameraMotion>>* camera_motion, + std::vector<std::unique_ptr<SalientPointFrame>>* saliency) { + const bool compute_saliency = options_.compute_motion_saliency(); +- CHECK_EQ(compute_saliency, saliency != nullptr) ++ ABSL_CHECK_EQ(compute_saliency, saliency != nullptr) + << "Computing saliency requires saliency output and vice versa"; + CHECK(buffer_->HaveEqualSize({"features", "motion"})); + +@@ -598,7 +599,7 @@ int MotionAnalysis::OutputResults( + + // Reset for next chunk. + prev_overlap_start_ = num_output_frames - new_overlap_start; +- CHECK_GE(prev_overlap_start_, 0); ++ ABSL_CHECK_GE(prev_overlap_start_, 0); + + CHECK(buffer_->TruncateBuffer(flush)); + +@@ -612,8 +613,8 @@ void MotionAnalysis::RenderResults(const RegionFlowFeatureList& feature_list, + cv::Mat* rendered_results) { + #ifndef NO_RENDERING + CHECK(rendered_results != nullptr); +- CHECK_EQ(frame_width_, rendered_results->cols); +- CHECK_EQ(frame_height_, rendered_results->rows); ++ ABSL_CHECK_EQ(frame_width_, rendered_results->cols); ++ ABSL_CHECK_EQ(frame_height_, rendered_results->rows); + + const auto viz_options = options_.visualization_options(); + +@@ -797,7 +798,7 @@ void MotionAnalysis::VisualizeBlurAnalysisRegions(cv::Mat* input_view) { + + void MotionAnalysis::ComputeSaliency() { + MEASURE_TIME << "Saliency computation."; +- CHECK_EQ(overlap_start_, buffer_->BufferSize("saliency")); ++ ABSL_CHECK_EQ(overlap_start_, buffer_->BufferSize("saliency")); + + const int num_features_lists = buffer_->BufferSize("features"); + +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc +index b608b470559d8..1da649682670f 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc +@@ -31,6 +31,7 @@ + #include "Eigen/SVD" + #include "absl/container/node_hash_map.h" + #include "absl/container/node_hash_set.h" ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/util/tracking/camera_motion.h" +@@ -175,7 +176,7 @@ class InlierMask { + std::vector<float>* motion_prior) { + CHECK(motion_prior != nullptr); + const int num_features = feature_list.feature_size(); +- CHECK_EQ(num_features, motion_prior->size()); ++ ABSL_CHECK_EQ(num_features, motion_prior->size()); + + // Return, if prior is too low. + const float kMinTranslationPrior = 0.5f; +@@ -185,7 +186,7 @@ class InlierMask { + } + const float prev_magnitude = translation_.Norm(); + +- CHECK_EQ(num_features, motion_prior->size()); ++ ABSL_CHECK_EQ(num_features, motion_prior->size()); + const float inv_prev_magnitude = + prev_magnitude < options_.min_translation_norm() + ? (1.0f / options_.min_translation_norm()) +@@ -398,21 +399,21 @@ struct MotionEstimation::SingleTrackClipData { + void CheckInitialization() const { + CHECK(feature_lists != nullptr); + CHECK(camera_motions != nullptr); +- CHECK_EQ(feature_lists->size(), camera_motions->size()); ++ ABSL_CHECK_EQ(feature_lists->size(), camera_motions->size()); + if (feature_lists->empty()) { + return; + } + +- CHECK_EQ(num_frames(), irls_weight_input.size()); +- CHECK_EQ(num_frames(), homog_irls_weight_input.size()); ++ ABSL_CHECK_EQ(num_frames(), irls_weight_input.size()); ++ ABSL_CHECK_EQ(num_frames(), homog_irls_weight_input.size()); + if (irls_weight_backup) { +- CHECK_EQ(num_frames(), irls_weight_backup->size()); ++ ABSL_CHECK_EQ(num_frames(), irls_weight_backup->size()); + } + + for (int k = 0; k < num_frames(); ++k) { + const int num_features = (*feature_lists)[k]->feature_size(); +- CHECK_EQ(num_features, irls_weight_input[k].size()); +- CHECK_EQ(num_features, homog_irls_weight_input[k].size()); ++ ABSL_CHECK_EQ(num_features, irls_weight_input[k].size()); ++ ABSL_CHECK_EQ(num_features, homog_irls_weight_input[k].size()); + } + } + +@@ -500,15 +501,15 @@ void MotionEstimation::InitializeWithOptions( + } + + // Check for deprecated options. +- CHECK_NE(options.estimate_similarity(), true) ++ ABSL_CHECK_NE(options.estimate_similarity(), true) + << "Option estimate_similarity is deprecated, use static function " + << "EstimateSimilarityModelL2 instead."; +- CHECK_NE(options.linear_similarity_estimation(), +- MotionEstimationOptions::ESTIMATION_LS_L2_RANSAC) ++ ABSL_CHECK_NE(options.linear_similarity_estimation(), ++ MotionEstimationOptions::ESTIMATION_LS_L2_RANSAC) + << "Option ESTIMATION_LS_L2_RANSAC is deprecated, use " + << "ESTIMATION_LS_IRLS instead."; +- CHECK_NE(options.linear_similarity_estimation(), +- MotionEstimationOptions::ESTIMATION_LS_L1) ++ ABSL_CHECK_NE(options.linear_similarity_estimation(), ++ MotionEstimationOptions::ESTIMATION_LS_L1) + << "Option ESTIMATION_LS_L1 is deprecated, use static function " + << "EstimateLinearSimilarityL1 instead."; + +@@ -825,7 +826,7 @@ void MotionEstimation::EstimateMotionsParallelImpl( + CHECK(camera_motions != nullptr); + + const int num_frames = feature_lists->size(); +- CHECK_EQ(num_frames, camera_motions->size()); ++ ABSL_CHECK_EQ(num_frames, camera_motions->size()); + + // Initialize camera_motions. + for (int f = 0; f < num_frames; ++f) { +@@ -866,7 +867,7 @@ void MotionEstimation::EstimateMotionsParallelImpl( + const int num_motion_models = + use_joint_tracks ? options_.joint_track_estimation().num_motion_models() + : 1; +- CHECK_GT(num_motion_models, 0); ++ ABSL_CHECK_GT(num_motion_models, 0); + + // Several single track clip datas, we seek to process. + std::vector<SingleTrackClipData> clip_datas(num_motion_models); +@@ -1080,7 +1081,8 @@ void MotionEstimation::EstimateMotionsParallelImpl( + // Estimate mixtures across a spectrum a different regularizers, from the + // weakest to the most regularized one. + const int num_mixture_levels = options_.mixture_regularizer_levels(); +- CHECK_LE(num_mixture_levels, 10) << "Only up to 10 mixtures are supported."; ++ ABSL_CHECK_LE(num_mixture_levels, 10) ++ << "Only up to 10 mixtures are supported."; + + // Initialize to weakest regularizer. + float regularizer = options_.mixture_regularizer(); +@@ -1124,8 +1126,8 @@ void MotionEstimation::EstimateMotionsParallelImpl( + // Check that mixture spectrum has sufficient entries. + for (const CameraMotion& motion : *camera_motions) { + if (motion.mixture_homography_spectrum_size() > 0) { +- CHECK_EQ(motion.mixture_homography_spectrum_size(), +- options_.mixture_regularizer_levels()); ++ ABSL_CHECK_EQ(motion.mixture_homography_spectrum_size(), ++ options_.mixture_regularizer_levels()); + } + } + +@@ -1570,7 +1572,7 @@ class IrlsInitializationInvoker { + + // Initialize priors from irls weights. + if (use_prior_weights) { +- CHECK_LT(frame, clip_data_->prior_weights.size()); ++ ABSL_CHECK_LT(frame, clip_data_->prior_weights.size()); + + if (clip_data_->prior_weights[frame].priors.empty()) { + clip_data_->prior_weights[frame].priors.resize( +@@ -1610,7 +1612,7 @@ void MotionEstimation::LongFeatureInitialization( + return; + } + +- CHECK_EQ(num_features, irls_weights->size()); ++ ABSL_CHECK_EQ(num_features, irls_weights->size()); + + // Determine actual scale to be applied to each feature. + std::vector<float> feature_scales(num_features); +@@ -1644,7 +1646,7 @@ void MotionEstimation::FeatureDensityNormalization( + std::vector<float>* irls_weights) const { + CHECK(irls_weights); + const int num_features = feature_list.feature_size(); +- CHECK_EQ(num_features, irls_weights->size()); ++ ABSL_CHECK_EQ(num_features, irls_weights->size()); + + // Compute mask index for each feature. + std::vector<int> bin_indices; +@@ -1707,13 +1709,13 @@ void MotionEstimation::FeatureDensityNormalization( + + float normalizer = 0; + int bin_idx = int_grid_y * mask_size + int_grid_x; +- CHECK_LT(bin_idx, max_bins); ++ ABSL_CHECK_LT(bin_idx, max_bins); + // See above. + normalizer += bin_normalizer[bin_idx] * (1 - dx_plus_dy + dxdy); + normalizer += bin_normalizer[bin_idx + inc_x] * (dx - dxdy); + + bin_idx += mask_size * inc_y; +- CHECK_LT(bin_idx, max_bins); ++ ABSL_CHECK_LT(bin_idx, max_bins); + normalizer += bin_normalizer[bin_idx] * (dy - dxdy); + normalizer += bin_normalizer[bin_idx + inc_x] * dxdy; + +@@ -1738,8 +1740,8 @@ void MotionEstimation::IrlsInitialization( + SingleTrackClipData* clip_data) const { + if (options_.estimation_policy() == + MotionEstimationOptions::TEMPORAL_LONG_FEATURE_BIAS) { +- CHECK_NE(frame, -1) << "Only per frame processing for this policy " +- << "supported."; ++ ABSL_CHECK_NE(frame, -1) << "Only per frame processing for this policy " ++ << "supported."; + } + + IrlsInitializationInvoker invoker(type, max_unstable_type, model_options, +@@ -1763,8 +1765,8 @@ void MotionEstimation::IrlsInitialization( + + for_function(0, clip_data->num_frames(), 1, invoker); + } else { +- CHECK_GE(frame, 0); +- CHECK_LT(frame, clip_data->num_frames()); ++ ABSL_CHECK_GE(frame, 0); ++ ABSL_CHECK_LT(frame, clip_data->num_frames()); + invoker(BlockedRange(frame, frame + 1, 1)); + } + } +@@ -1960,7 +1962,7 @@ void MotionEstimation::BiasLongFeatures( + prior_weights->priors.resize(num_features, 1.0f); + } + +- CHECK_EQ(num_features, prior_weights->priors.size()); ++ ABSL_CHECK_EQ(num_features, prior_weights->priors.size()); + for (int k = 0; k < num_features; ++k) { + prior_weights->priors[k] *= bias[k]; + auto* feature = feature_list->mutable_feature(k); +@@ -1993,7 +1995,7 @@ void MotionEstimation::ComputeSpatialBias( + BuildFeatureGrid(NormalizedDomain().x(), NormalizedDomain().y(), + bias_options.grid_size(), {feature_view}, FeatureLocation, + &feature_taps_3, nullptr, nullptr, &feature_grids); +- CHECK_EQ(1, feature_grids.size()); ++ ABSL_CHECK_EQ(1, feature_grids.size()); + const FeatureGrid<RegionFlowFeature>& single_grid = feature_grids[0]; + + const float long_track_threshold = bias_options.long_track_threshold(); +@@ -2118,7 +2120,7 @@ void MotionEstimation::UpdateLongFeatureBias( + const auto& bias_options = options_.long_feature_bias_options(); + const int num_irls_observations = bias_options.num_irls_observations(); + +- CHECK_GT(num_irls_observations, 0) << "Specify value > 0"; ++ ABSL_CHECK_GT(num_irls_observations, 0) << "Specify value > 0"; + const float inv_num_irls_observations = 1.0f / num_irls_observations; + + SpatialBiasMap spatial_bias; +@@ -2137,7 +2139,7 @@ void MotionEstimation::UpdateLongFeatureBias( + + // Scale applied to irls weight for linear interpolation between inlier and + // outlier bias. +- CHECK_GT(bias_options.inlier_irls_weight(), 0); ++ ABSL_CHECK_GT(bias_options.inlier_irls_weight(), 0); + const float irls_scale = 1.0f / bias_options.inlier_irls_weight(); + const float long_track_scale = + 1.0f / bias_options.long_track_confidence_fraction(); +@@ -2434,9 +2436,9 @@ void MotionEstimation::CheckModelStability( + CHECK(camera_motions != nullptr); + const int num_frames = feature_lists->size(); + if (reset_irls_weights) { +- DCHECK_EQ(num_frames, reset_irls_weights->size()); ++ ABSL_DCHECK_EQ(num_frames, reset_irls_weights->size()); + } +- DCHECK_EQ(num_frames, camera_motions->size()); ++ ABSL_DCHECK_EQ(num_frames, camera_motions->size()); + + for (int f = 0; f < num_frames; ++f) { + CameraMotion& camera_motion = (*camera_motions)[f]; +@@ -2470,7 +2472,7 @@ void MotionEstimation::CheckSingleModelStability( + camera_motion->translation_variance(), + *feature_list)) { + // Translation can never be singular. +- CHECK_EQ( ++ ABSL_CHECK_EQ( + 0, camera_motion->flags() & CameraMotion::FLAG_SINGULAR_ESTIMATION); + } else { + // Invalid model. +@@ -2697,7 +2699,7 @@ void MotionEstimation::DetermineShotBoundaries( + const std::vector<RegionFlowFeatureList*>& feature_lists, + std::vector<CameraMotion>* camera_motions) const { + CHECK(camera_motions != nullptr); +- CHECK_EQ(feature_lists.size(), camera_motions->size()); ++ ABSL_CHECK_EQ(feature_lists.size(), camera_motions->size()); + const auto& shot_options = options_.shot_boundary_options(); + + // Verify empty feature frames and invalid models via visual consistency. +@@ -3493,11 +3495,11 @@ void MotionEstimation::ComputeSimilarityInliers( + float threshold = std::max<float>(similarity_bounds.inlier_threshold(), + similarity_bounds.frac_inlier_threshold() * + hypot(frame_width_, frame_height_)); +- CHECK_GT(threshold, 0); ++ ABSL_CHECK_GT(threshold, 0); + + threshold = 1.0f / threshold; + float strict_threshold = similarity_bounds.strict_inlier_threshold(); +- CHECK_GT(strict_threshold, 0); ++ ABSL_CHECK_GT(strict_threshold, 0); + strict_threshold = 1.0f / strict_threshold; + + if (!options_.irls_use_l0_norm()) { +@@ -3761,12 +3763,12 @@ bool HomographyL2QRSolve( + Eigen::Matrix<T, 8, 1>* solution) { + CHECK(matrix); + CHECK(solution); +- CHECK_EQ(8, matrix->cols()); ++ ABSL_CHECK_EQ(8, matrix->cols()); + const int num_rows = + 2 * feature_list.feature_size() + (perspective_regularizer == 0 ? 0 : 1); +- CHECK_EQ(num_rows, matrix->rows()); +- CHECK_EQ(1, solution->cols()); +- CHECK_EQ(8, solution->rows()); ++ ABSL_CHECK_EQ(num_rows, matrix->rows()); ++ ABSL_CHECK_EQ(1, solution->cols()); ++ ABSL_CHECK_EQ(8, solution->rows()); + + // Compute homography from features (H * location = prev_location). + *matrix = Eigen::Matrix<T, Eigen::Dynamic, 8>::Zero(matrix->rows(), 8); +@@ -4066,11 +4068,12 @@ bool MixtureHomographyL2DLTSolve( + const int num_dof = 8 * num_models; + const int num_constraints = num_dof - 8; + +- CHECK_EQ(matrix->cols(), num_dof); ++ ABSL_CHECK_EQ(matrix->cols(), num_dof); + // 2 Rows (x,y) per feature. +- CHECK_EQ(matrix->rows(), 2 * feature_list.feature_size() + num_constraints); +- CHECK_EQ(solution->cols(), 1); +- CHECK_EQ(solution->rows(), num_dof); ++ ABSL_CHECK_EQ(matrix->rows(), ++ 2 * feature_list.feature_size() + num_constraints); ++ ABSL_CHECK_EQ(solution->cols(), 1); ++ ABSL_CHECK_EQ(solution->rows(), num_dof); + + // Compute homography from features. (H * location = prev_location) + *matrix = Eigen::MatrixXf::Zero(matrix->rows(), matrix->cols()); +@@ -4162,11 +4165,12 @@ bool TransMixtureHomographyL2DLTSolve( + const int num_dof = 6 + 2 * num_models; + const int num_constraints = 2 * (num_models - 1); + +- CHECK_EQ(matrix->cols(), num_dof); ++ ABSL_CHECK_EQ(matrix->cols(), num_dof); + // 2 Rows (x,y) per feature. +- CHECK_EQ(matrix->rows(), 2 * feature_list.feature_size() + num_constraints); +- CHECK_EQ(solution->cols(), 1); +- CHECK_EQ(solution->rows(), num_dof); ++ ABSL_CHECK_EQ(matrix->rows(), ++ 2 * feature_list.feature_size() + num_constraints); ++ ABSL_CHECK_EQ(solution->cols(), 1); ++ ABSL_CHECK_EQ(solution->rows(), num_dof); + + // Compute homography from features. (H * location = prev_location) + *matrix = Eigen::MatrixXf::Zero(matrix->rows(), matrix->cols()); +@@ -4261,11 +4265,12 @@ bool SkewRotMixtureHomographyL2DLTSolve( + const int num_dof = 4 + 4 * num_models; + const int num_constraints = 4 * (num_models - 1); + +- CHECK_EQ(matrix->cols(), num_dof); ++ ABSL_CHECK_EQ(matrix->cols(), num_dof); + // 2 Rows (x,y) per feature. +- CHECK_EQ(matrix->rows(), 2 * feature_list.feature_size() + num_constraints); +- CHECK_EQ(solution->cols(), 1); +- CHECK_EQ(solution->rows(), num_dof); ++ ABSL_CHECK_EQ(matrix->rows(), ++ 2 * feature_list.feature_size() + num_constraints); ++ ABSL_CHECK_EQ(solution->cols(), 1); ++ ABSL_CHECK_EQ(solution->rows(), num_dof); + + // Compute homography from features. (H * location = prev_location) + *matrix = Eigen::MatrixXf::Zero(matrix->rows(), matrix->cols()); +@@ -4669,7 +4674,7 @@ float MotionEstimation::GridCoverage( + + const std::vector<float>& grid_cell_weights = + thread_storage->GridCoverageInitializationWeights(); +- CHECK_EQ(mask_size, grid_cell_weights.size()); ++ ABSL_CHECK_EQ(mask_size, grid_cell_weights.size()); + + const float max_inlier_score = 1.75f * min_inlier_score; + const float mid_inlier_score = 0.5 * (min_inlier_score + max_inlier_score); +@@ -4694,7 +4699,7 @@ float MotionEstimation::GridCoverage( + normalized_domain_.x() / grid_size * overlap_x / num_overlaps; + std::vector<std::vector<float>>& irls_mask = + *thread_storage->EmptyGridCoverageIrlsMask(); +- CHECK_EQ(mask_size, irls_mask.size()); ++ ABSL_CHECK_EQ(mask_size, irls_mask.size()); + + // Bin features. + for (const auto& feature : feature_list.feature()) { +@@ -4738,7 +4743,7 @@ float MotionEstimation::GridCoverage( + + const float cell_weight_sum = + std::accumulate(grid_cell_weights.begin(), grid_cell_weights.end(), 0.0f); +- CHECK_GT(cell_weight_sum, 0); ++ ABSL_CHECK_GT(cell_weight_sum, 0); + + return std::inner_product(max_coverage.begin(), max_coverage.end(), + grid_cell_weights.begin(), 0.0f) / +@@ -5088,8 +5093,8 @@ bool MotionEstimation::MixtureHomographyFromFeature( + // Compute weights if necessary. + // Compute scale to index mixture weights from normalization. + CHECK(row_weights_.get() != nullptr); +- CHECK_EQ(row_weights_->YScale(), frame_height_ / normalized_domain_.y()); +- CHECK_EQ(row_weights_->NumModels(), num_mixtures); ++ ABSL_CHECK_EQ(row_weights_->YScale(), frame_height_ / normalized_domain_.y()); ++ ABSL_CHECK_EQ(row_weights_->NumModels(), num_mixtures); + + const MotionEstimationOptions::MixtureModelMode mixture_mode = + options_.mixture_model_mode(); +@@ -5444,7 +5449,7 @@ void MotionEstimation::DetermineOverlayIndices( + // Two stage estimation: First translation only, followed by + // overlay analysis. + const int num_frames = feature_lists->size(); +- CHECK_EQ(num_frames, camera_motions->size()); ++ ABSL_CHECK_EQ(num_frames, camera_motions->size()); + + std::vector<CameraMotion> translation_motions(num_frames); + const int irls_per_round = options_.irls_rounds(); +@@ -5521,7 +5526,7 @@ float MotionEstimation::OverlayAnalysis( + std::vector<int>* overlay_indices) const { + CHECK(feature_lists != nullptr); + CHECK(overlay_indices != nullptr); +- CHECK_EQ(feature_lists->size(), translations.size()); ++ ABSL_CHECK_EQ(feature_lists->size(), translations.size()); + overlay_indices->clear(); + + const int grid_size = +@@ -5717,7 +5722,7 @@ void TemporalIRLSPush(const FeatureGrid<RegionFlowFeature>& curr_grid, + } + + // Only zero if spatial AND feature sigma = 0. +- DCHECK_GT(weight_sum, 0); ++ ABSL_DCHECK_GT(weight_sum, 0); + feature->mutable_internal_irls()->set_weight_sum(weight_sum); + feature->mutable_internal_irls()->set_value_sum(value_sum); + } +@@ -5829,7 +5834,7 @@ void TemporalIRLSPull(const FeatureGrid<RegionFlowFeature>& curr_grid, + } + } + +- CHECK_GT(weight_sum, 0) << feature->irls_weight(); ++ ABSL_CHECK_GT(weight_sum, 0) << feature->irls_weight(); + feature->mutable_internal_irls()->set_weight_sum(weight_sum); + feature->mutable_internal_irls()->set_value_sum(value_sum); + } +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc +index eb6a8b314db6b..5d6645f9fe177 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc +@@ -22,6 +22,7 @@ + + #include "Eigen/Core" + #include "Eigen/Dense" ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + + // Set to true to use catmull rom mixture weights instead of Gaussian weights +@@ -43,10 +44,10 @@ AffineModel ModelAdapter<TranslationModel>::ToAffine( + + TranslationModel ModelAdapter<TranslationModel>::FromAffine( + const AffineModel& model) { +- DCHECK_EQ(model.a(), 1); +- DCHECK_EQ(model.b(), 0); +- DCHECK_EQ(model.c(), 0); +- DCHECK_EQ(model.d(), 1); ++ ABSL_DCHECK_EQ(model.a(), 1); ++ ABSL_DCHECK_EQ(model.b(), 0); ++ ABSL_DCHECK_EQ(model.c(), 0); ++ ABSL_DCHECK_EQ(model.d(), 1); + + return TranslationAdapter::FromArgs(model.dx(), model.dy()); + } +@@ -235,7 +236,7 @@ std::string ModelAdapter<SimilarityModel>::ToString( + SimilarityModel ModelAdapter<SimilarityModel>::NormalizationTransform( + float frame_width, float frame_height) { + const float scale = std::hypot(frame_width, frame_height); +- DCHECK_NE(scale, 0); ++ ABSL_DCHECK_NE(scale, 0); + return SimilarityAdapter::FromArgs(0, 0, 1.0 / scale, 0); + } + +@@ -262,8 +263,8 @@ AffineModel ModelAdapter<LinearSimilarityModel>::ToAffine( + + LinearSimilarityModel ModelAdapter<LinearSimilarityModel>::FromAffine( + const AffineModel& model) { +- DCHECK_EQ(model.a(), model.d()); +- DCHECK_EQ(model.b(), -model.c()); ++ ABSL_DCHECK_EQ(model.a(), model.d()); ++ ABSL_DCHECK_EQ(model.b(), -model.c()); + + return LinearSimilarityAdapter::FromArgs(model.dx(), model.dy(), model.a(), + -model.b()); +@@ -330,7 +331,7 @@ LinearSimilarityModel + ModelAdapter<LinearSimilarityModel>::NormalizationTransform( + float frame_width, float frame_height) { + const float scale = std::hypot(frame_width, frame_height); +- DCHECK_NE(scale, 0); ++ ABSL_DCHECK_NE(scale, 0); + return LinearSimilarityAdapter::FromArgs(0, 0, 1.0 / scale, 0); + } + +@@ -368,7 +369,7 @@ std::string ModelAdapter<AffineModel>::ToString(const AffineModel& model) { + AffineModel ModelAdapter<AffineModel>::NormalizationTransform( + float frame_width, float frame_height) { + const float scale = std::hypot(frame_width, frame_height); +- DCHECK_NE(scale, 0); ++ ABSL_DCHECK_NE(scale, 0); + return AffineAdapter::FromArgs(0, 0, 1.0f / scale, 0, 0, 1.0f / scale); + } + +@@ -379,8 +380,8 @@ Homography ModelAdapter<AffineModel>::ToHomography(const AffineModel& model) { + } + + AffineModel ModelAdapter<AffineModel>::FromHomography(const Homography& model) { +- DCHECK_EQ(model.h_20(), 0); +- DCHECK_EQ(model.h_21(), 0); ++ ABSL_DCHECK_EQ(model.h_20(), 0); ++ ABSL_DCHECK_EQ(model.h_21(), 0); + + float params[6] = {model.h_02(), model.h_12(), // dx, dy + model.h_00(), model.h_01(), // a, b +@@ -582,8 +583,8 @@ std::string ModelAdapter<Homography>::ToString(const Homography& model) { + } + + AffineModel ModelAdapter<Homography>::ToAffine(const Homography& model) { +- DCHECK_EQ(model.h_20(), 0); +- DCHECK_EQ(model.h_21(), 0); ++ ABSL_DCHECK_EQ(model.h_20(), 0); ++ ABSL_DCHECK_EQ(model.h_21(), 0); + AffineModel affine_model; + affine_model.set_a(model.h_00()); + affine_model.set_b(model.h_01()); +@@ -629,7 +630,7 @@ void ModelAdapter<Homography>::GetJacobianAtPoint(const Vector2_f& pt, + Homography ModelAdapter<Homography>::NormalizationTransform( + float frame_width, float frame_height) { + const float scale = std::hypot(frame_width, frame_height); +- DCHECK_NE(scale, 0); ++ ABSL_DCHECK_NE(scale, 0); + return HomographyAdapter::FromArgs(1.0f / scale, 0, 0, 0, 1.0f / scale, 0, 0, + 0); + } +@@ -860,7 +861,7 @@ MixtureRowWeights::MixtureRowWeights(int frame_height, int margin, float sigma, + weight_ptr[int_pos] += spline_weights[0]; // Double knot. + } + +- CHECK_LT(int_pos, num_models - 1); ++ ABSL_CHECK_LT(int_pos, num_models - 1); + weight_ptr[int_pos + 1] += spline_weights[2]; + if (int_pos + 1 < num_models - 1) { + weight_ptr[int_pos + 2] += spline_weights[3]; +@@ -897,7 +898,7 @@ MixtureRowWeights::MixtureRowWeights(int frame_height, int margin, float sigma, + } + + // Normalize. +- DCHECK_GT(weight_sum, 0); ++ ABSL_DCHECK_GT(weight_sum, 0); + const float inv_weight_sum = 1.0f / weight_sum; + for (int j = 0; j < num_models; ++j) { + weight_ptr[j] *= inv_weight_sum; +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h +index 567831ad5e755..4edf28abf2a7c 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h +@@ -21,6 +21,7 @@ + #include <vector> + + #include "absl/container/node_hash_map.h" ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/singleton.h" + #include "mediapipe/framework/port/vector.h" +@@ -762,8 +763,8 @@ Model UniformModelParameters(const float value) { + template <class Model> + Model BlendModels(const Model& a, const Model& b, float weight_b) { + Model blended; +- DCHECK_GE(weight_b, 0); +- DCHECK_LE(weight_b, 1); ++ ABSL_DCHECK_GE(weight_b, 0); ++ ABSL_DCHECK_LE(weight_b, 1); + const float weight_a = 1 - weight_b; + for (int p = 0; p < ModelAdapter<Model>::NumParameters(); ++p) { + const float pa = ModelAdapter<Model>::GetParameter(a, p); +@@ -822,8 +823,8 @@ class MixtureRowWeights { + + const float* RowWeights(float y) const { + int bin_y = y * y_scale_ + 0.5; +- DCHECK_LT(bin_y, frame_height_ + margin_); +- DCHECK_GE(bin_y, -margin_); ++ ABSL_DCHECK_LT(bin_y, frame_height_ + margin_); ++ ABSL_DCHECK_GE(bin_y, -margin_); + return &weights_[(bin_y + margin_) * num_models_]; + } + +@@ -1398,7 +1399,7 @@ inline Homography ModelAdapter<Homography>::Compose(const Homography& lhs, + Homography result; + const float z = + lhs.h_20() * rhs.h_02() + lhs.h_21() * rhs.h_12() + 1.0f * 1.0f; +- CHECK_NE(z, 0) << "Degenerate homography. See proto."; ++ ABSL_CHECK_NE(z, 0) << "Degenerate homography. See proto."; + const float inv_z = 1.0 / z; + + result.set_h_00((lhs.h_00() * rhs.h_00() + lhs.h_01() * rhs.h_10() + +@@ -1631,7 +1632,7 @@ MixtureModelAdapterBase<MixtureTraits>::LinearModel( + } + + const double denom = sum_xx - inv_models * sum_x * sum_x; +- CHECK_NE(denom, 0); // As num_models > 1. ++ ABSL_CHECK_NE(denom, 0); // As num_models > 1. + const double a = (sum_xy - inv_models * sum_x * sum_y) * denom; + const double b = inv_models * (sum_y - a * sum_x); + +@@ -1688,7 +1689,7 @@ Vector2_f MixtureModelAdapter<MixtureTraits>::TransformPoint( + BaseModelAdapter::TransformPoint3(model.model(i), pt3 * weights[i]); + } + +- DCHECK_NE(result.z(), 0) << "Degenerate mapping."; ++ ABSL_DCHECK_NE(result.z(), 0) << "Degenerate mapping."; + return Vector2_f(result.x() / result.z(), result.y() / result.z()); + } + +@@ -1818,7 +1819,7 @@ inline Vector2_f MixtureModelAdapter<HomographyTraits>::TransformPoint( + LOG(FATAL) << "Unknown type."; + } + +- DCHECK_NE(result.z(), 0) << "Degenerate mapping."; ++ ABSL_DCHECK_NE(result.z(), 0) << "Degenerate mapping."; + return Vector2_f(result.x() / result.z(), result.y() / result.z()); + } + +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc +index 5adafca4c579f..9e2911e4a4d95 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc +@@ -24,6 +24,7 @@ + #include <memory> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/util/tracking/camera_motion.h" + #include "mediapipe/util/tracking/measure_time.h" +@@ -45,11 +46,11 @@ void MotionSaliency::SaliencyFromFeatures( + std::vector<float>* irls_weights, // optional. + SalientPointFrame* salient_frame) { + CHECK(salient_frame); +- CHECK_EQ(frame_width_, feature_list.frame_width()); +- CHECK_EQ(frame_height_, feature_list.frame_height()); ++ ABSL_CHECK_EQ(frame_width_, feature_list.frame_width()); ++ ABSL_CHECK_EQ(frame_height_, feature_list.frame_height()); + + if (irls_weights) { +- CHECK_EQ(feature_list.feature_size(), irls_weights->size()); ++ ABSL_CHECK_EQ(feature_list.feature_size(), irls_weights->size()); + } + + if (feature_list.feature_size() < 1) { +@@ -106,7 +107,7 @@ void MotionSaliency::SaliencyFromPoints(const std::vector<Vector2_f>* points, + SalientPointFrame* salient_frame) { + // TODO: Handle vectors of size zero. + CHECK(salient_frame); +- CHECK_EQ(points->size(), weights->size()); ++ ABSL_CHECK_EQ(points->size(), weights->size()); + + float max_weight = *std::max_element(weights->begin(), weights->end()); + +@@ -477,7 +478,7 @@ void MotionSaliency::SalientModeFinding(std::vector<SalientLocation>* locations, + nullptr, &grid_dims, &feature_grids); + + // Just one frame input, expect one grid as output. +- CHECK_EQ(1, feature_grids.size()); ++ ABSL_CHECK_EQ(1, feature_grids.size()); + const auto& feature_grid = feature_grids[0]; + + // Setup Gaussian LUT for smoothing in space, using 2^10 discretization bins. +@@ -595,8 +596,8 @@ void MotionSaliency::SalientModeFinding(std::vector<SalientLocation>* locations, + if (angle < 0) { + angle += M_PI; + } +- CHECK_GE(angle, 0); +- CHECK_LE(angle, M_PI + 1e-3); ++ ABSL_CHECK_GE(angle, 0); ++ ABSL_CHECK_LE(angle, M_PI + 1e-3); + } + + SalientMode irls_mode; +@@ -665,7 +666,7 @@ void ForegroundWeightsFromFeatures(const RegionFlowFeatureList& feature_list, + + constexpr float kEpsilon = 1e-4f; + +- CHECK_GT(foreground_threshold, 0.0f); ++ ABSL_CHECK_GT(foreground_threshold, 0.0f); + if (camera_motion) { + foreground_threshold *= + std::max(kEpsilon, InlierCoverage(*camera_motion, false)); +@@ -694,7 +695,7 @@ void ForegroundWeightsFromFeatures(const RegionFlowFeatureList& feature_list, + std::max(kEpsilon, std::pow(foreground_measure, foreground_gamma))); + } + } +- CHECK_EQ(feature_list.feature_size(), weights->size()); ++ ABSL_CHECK_EQ(feature_list.feature_size(), weights->size()); + } + + } // namespace mediapipe +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h b/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h +index 823522310ba2f..734e99054cd57 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h +@@ -71,6 +71,7 @@ + + #include <memory> + ++#include "absl/log/absl_check.h" + #include "absl/synchronization/mutex.h" + #include "mediapipe/framework/port/logging.h" + +@@ -282,9 +283,10 @@ inline void CheckAndSetInvokerOptions() { + } + #endif // PARALLEL_INVOKER_ACTIVE + +- CHECK_LT(flags_parallel_invoker_mode, PARALLEL_INVOKER_MAX_VALUE) ++ ABSL_CHECK_LT(flags_parallel_invoker_mode, PARALLEL_INVOKER_MAX_VALUE) ++ << "Invalid invoker mode specified."; ++ ABSL_CHECK_GE(flags_parallel_invoker_mode, 0) + << "Invalid invoker mode specified."; +- CHECK_GE(flags_parallel_invoker_mode, 0) << "Invalid invoker mode specified."; + } + + // Performs parallel iteration from [start to end), scheduling grain_size +@@ -301,7 +303,7 @@ void ParallelFor(size_t start, size_t end, size_t grain_size, + #if defined(__APPLE__) + case PARALLEL_INVOKER_GCD: { + int iterations_remain = (end - start + grain_size - 1) / grain_size; +- CHECK_GT(iterations_remain, 0); ++ ABSL_CHECK_GT(iterations_remain, 0); + if (iterations_remain == 1) { + // Execute invoker serially. + invoker(BlockedRange(start, std::min(end, start + grain_size), 1)); +@@ -313,7 +315,7 @@ void ParallelFor(size_t start, size_t end, size_t grain_size, + dispatch_apply_f(iterations_remain, concurrent_queue, &context, + ParallelForGCDTask<Invoker>); + #if CHECK_GCD_PARALLEL_WORK_COUNT +- CHECK_EQ(iterations_remain, context.count()); ++ ABSL_CHECK_EQ(iterations_remain, context.count()); + #endif + } + break; +@@ -322,7 +324,7 @@ void ParallelFor(size_t start, size_t end, size_t grain_size, + + case PARALLEL_INVOKER_THREAD_POOL: { + int iterations_remain = (end - start + grain_size - 1) / grain_size; +- CHECK_GT(iterations_remain, 0); ++ ABSL_CHECK_GT(iterations_remain, 0); + if (iterations_remain == 1) { + // Execute invoker serially. + invoker(BlockedRange(start, std::min(end, start + grain_size), 1)); +@@ -413,7 +415,7 @@ void ParallelFor2D(size_t start_row, size_t end_row, size_t start_col, + case PARALLEL_INVOKER_GCD: { + const int iterations_remain = + (end_row - start_row + grain_size - 1) / grain_size; +- CHECK_GT(iterations_remain, 0); ++ ABSL_CHECK_GT(iterations_remain, 0); + if (iterations_remain == 1) { + // Execute invoker serially. + invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1), +@@ -427,7 +429,7 @@ void ParallelFor2D(size_t start_row, size_t end_row, size_t start_col, + dispatch_apply_f(iterations_remain, concurrent_queue, &context, + ParallelForGCDTask2D<Invoker>); + #if CHECK_GCD_PARALLEL_WORK_COUNT +- CHECK_EQ(iterations_remain, context.count()); ++ ABSL_CHECK_EQ(iterations_remain, context.count()); + #endif + } + break; +@@ -436,7 +438,7 @@ void ParallelFor2D(size_t start_row, size_t end_row, size_t start_col, + + case PARALLEL_INVOKER_THREAD_POOL: { + int iterations_remain = end_row - start_row; // Guarded by loop_mutex +- CHECK_GT(iterations_remain, 0); ++ ABSL_CHECK_GT(iterations_remain, 0); + if (iterations_remain == 1) { + // Execute invoker serially. + invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1), +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h b/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h +index f9b2c6c3cc077..cdf451f5bbbf5 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h +@@ -33,6 +33,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/opencv_core_inc.h" + #include "mediapipe/util/tracking/image_util.h" + #include "mediapipe/util/tracking/push_pull_filtering.pb.h" +@@ -148,7 +149,7 @@ class PushPullFiltering { + // Returns domain size of n-th pyramid level (including border depending on + // filter_type). + cv::Size NthPyramidDomain(int level) { +- CHECK_LT(level, PyramidLevels()); ++ ABSL_CHECK_LT(level, PyramidLevels()); + return downsample_pyramid_[level].size(); + } + +@@ -469,14 +470,14 @@ template <int C, class FilterWeightMultiplier> + void PushPullFiltering<C, FilterWeightMultiplier>::InitializeImagePyramid( + const cv::Mat& input_frame, std::vector<cv::Mat>* pyramid) { + CHECK(pyramid != nullptr); +- CHECK_GT(pyramid->size(), 0); ++ ABSL_CHECK_GT(pyramid->size(), 0); + + cv::Mat base_level((*pyramid)[0], + cv::Range(border_, (*pyramid)[0].rows - border_), + cv::Range(border_, (*pyramid)[0].cols - border_)); +- CHECK_EQ(base_level.rows, input_frame.rows); +- CHECK_EQ(base_level.cols, input_frame.cols); +- CHECK_EQ(base_level.type(), input_frame.type()); ++ ABSL_CHECK_EQ(base_level.rows, input_frame.rows); ++ ABSL_CHECK_EQ(base_level.cols, input_frame.cols); ++ ABSL_CHECK_EQ(base_level.type(), input_frame.type()); + + input_frame.copyTo(base_level); + CopyNecessaryBorder<uint8, 3>(&(*pyramid)[0]); +@@ -743,11 +744,11 @@ void PushPullFiltering<C, FilterWeightMultiplier>::PerformPushPull( + cv::Point2i origin, int readout_level, + const std::vector<float>* data_weights, const cv::Mat* input_frame, + cv::Mat* results) { +- CHECK_EQ(data_locations.size(), data_values.size()); ++ ABSL_CHECK_EQ(data_locations.size(), data_values.size()); + CHECK(results != nullptr); + + if (data_weights) { +- CHECK_EQ(data_weights->size(), data_locations.size()); ++ ABSL_CHECK_EQ(data_weights->size(), data_locations.size()); + } + + origin.x += border_; +@@ -760,13 +761,13 @@ void PushPullFiltering<C, FilterWeightMultiplier>::PerformPushPull( + mip_map[i] = &downsample_pyramid_[i]; + } + +- CHECK_GE(readout_level, 0); +- CHECK_LT(readout_level, PyramidLevels()); ++ ABSL_CHECK_GE(readout_level, 0); ++ ABSL_CHECK_LT(readout_level, PyramidLevels()); + + // CHECK if passed results matrix is compatible w.r.t. type and domain. +- CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); +- CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); +- CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); ++ ABSL_CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); ++ ABSL_CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); ++ ABSL_CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); + + // Use caller-allocated results Mat. + mip_map[readout_level] = results; +@@ -815,18 +816,18 @@ void PushPullFiltering<C, FilterWeightMultiplier>::PerformPushPullMat( + mip_map[i] = &downsample_pyramid_[i]; + } + +- CHECK_GE(readout_level, 0); +- CHECK_LT(readout_level, PyramidLevels()); ++ ABSL_CHECK_GE(readout_level, 0); ++ ABSL_CHECK_LT(readout_level, PyramidLevels()); + + // CHECK if passed mip_map at level[0] is compatible w.r.t. type and domain. +- CHECK_EQ(mip_map_level_0.cols, results->cols); +- CHECK_EQ(mip_map_level_0.rows, results->rows); +- CHECK_EQ(mip_map_level_0.type(), results->type()); ++ ABSL_CHECK_EQ(mip_map_level_0.cols, results->cols); ++ ABSL_CHECK_EQ(mip_map_level_0.rows, results->rows); ++ ABSL_CHECK_EQ(mip_map_level_0.type(), results->type()); + + // CHECK if passed results matrix is compatible w.r.t. type and domain. +- CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); +- CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); +- CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); ++ ABSL_CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); ++ ABSL_CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); ++ ABSL_CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); + + // Use caller-allocated results Mat. + mip_map[readout_level] = results; +@@ -1049,7 +1050,7 @@ void PushPullFiltering<C, FilterWeightMultiplier>::PullDownSampling( + } + } + +- DCHECK_GE(weight_sum, 0); ++ ABSL_DCHECK_GE(weight_sum, 0); + + if (weight_sum >= kBilateralEps * kBilateralEps) { + const float inv_weight_sum = 1.f / weight_sum; +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc +index cdd6bcd88d0dc..1babddde897f9 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc +@@ -22,6 +22,7 @@ + + #include "absl/container/node_hash_map.h" + #include "absl/container/node_hash_set.h" ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/util/tracking/measure_time.h" +@@ -76,8 +77,8 @@ void GetRegionFlowFeatureList(const RegionFlowFrame& region_flow_frame, + + float RegionFlowFeatureDistance(const PatchDescriptor& patch_desc_1, + const PatchDescriptor& patch_desc_2) { +- DCHECK_EQ(patch_desc_1.data_size(), patch_desc_2.data_size()); +- DCHECK_GE(patch_desc_1.data_size(), 3); ++ ABSL_DCHECK_EQ(patch_desc_1.data_size(), patch_desc_2.data_size()); ++ ABSL_DCHECK_GE(patch_desc_1.data_size(), 3); + + constexpr int kNumMeans = 3; + float sq_distance_sum = 0; +@@ -212,7 +213,7 @@ void GetRegionFlowFeatureIRLSWeights( + void SetRegionFlowFeatureIRLSWeights(const std::vector<float>& irls_weights, + RegionFlowFeatureList* flow_feature_list) { + CHECK(flow_feature_list != nullptr); +- CHECK_EQ(irls_weights.size(), flow_feature_list->feature_size()); ++ ABSL_CHECK_EQ(irls_weights.size(), flow_feature_list->feature_size()); + int idx = 0; + for (auto feature = flow_feature_list->mutable_feature()->begin(); + feature != flow_feature_list->mutable_feature()->end(); +@@ -515,7 +516,7 @@ void CopyToEmptyFeatureList(RegionFlowFeatureList* src, + src->mutable_feature()->Swap(empty_list.mutable_feature()); + + // src_features should be empty as in the beginning. +- CHECK_EQ(0, empty_list.feature_size()); ++ ABSL_CHECK_EQ(0, empty_list.feature_size()); + } + + void IntersectRegionFlowFeatureList( +@@ -607,10 +608,10 @@ void LongFeatureStream::AddFeatures(const RegionFlowFeatureList& feature_list, + if (find_pos != tracks_.end()) { + // Track is present, add to it. + if (check_connectivity) { +- CHECK_LT((FeatureLocation(find_pos->second.back()) - +- FeatureMatchLocation(feature)) +- .Norm2(), +- 1e-4); ++ ABSL_CHECK_LT((FeatureLocation(find_pos->second.back()) - ++ FeatureMatchLocation(feature)) ++ .Norm2(), ++ 1e-4); + } + find_pos->second.push_back(feature); + } else { +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h +index 2f9b34227629c..db70a2b8ec71e 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h +@@ -24,6 +24,7 @@ + #include <utility> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/vector.h" + #include "mediapipe/util/tracking/motion_models.h" +@@ -82,9 +83,9 @@ inline float PatchDescriptorColorStdevL1(const PatchDescriptor& descriptor) { + constexpr int kRedIdx = 3; + constexpr int kGreenIdx = 6; + constexpr int kBlueIdx = 8; +- DCHECK_GE(descriptor.data(kRedIdx), 0); +- DCHECK_GE(descriptor.data(kGreenIdx), 0); +- DCHECK_GE(descriptor.data(kBlueIdx), 0); ++ ABSL_DCHECK_GE(descriptor.data(kRedIdx), 0); ++ ABSL_DCHECK_GE(descriptor.data(kGreenIdx), 0); ++ ABSL_DCHECK_GE(descriptor.data(kBlueIdx), 0); + + if (descriptor.data_size() > kBlueIdx) { + return std::sqrt(descriptor.data(kRedIdx)) + +@@ -591,7 +592,7 @@ void BuildFeatureGrid( + Vector2_i* num_grid_bins, // Optional. + std::vector<FeatureGrid<Feature>>* feature_grids) { + CHECK(feature_grids); +- CHECK_GT(grid_resolution, 0.0f); ++ ABSL_CHECK_GT(grid_resolution, 0.0f); + + const int num_frames = feature_views.size(); + const int grid_dim_x = std::ceil(frame_width / grid_resolution); +@@ -612,8 +613,8 @@ void BuildFeatureGrid( + Vector2_f feature_loc = evaluator(*feature); + const int x = feature_loc.x() * grid_scale; + const int y = feature_loc.y() * grid_scale; +- DCHECK_LT(y, grid_dim_y); +- DCHECK_LT(x, grid_dim_x); ++ ABSL_DCHECK_LT(y, grid_dim_y); ++ ABSL_DCHECK_LT(x, grid_dim_x); + const int grid_loc = y * grid_dim_x + x; + curr_grid[grid_loc].push_back(feature); + } +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc +index b6704cc61fd28..2446e726ee89d 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc +@@ -28,6 +28,7 @@ + #include "Eigen/Core" + #include "absl/container/flat_hash_map.h" + #include "absl/container/node_hash_set.h" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/opencv_core_inc.h" +@@ -207,19 +208,19 @@ class PatchDescriptorInvoker { + ++feature_idx) { + RegionFlowFeature* feature = features_->mutable_feature(feature_idx); + Vector2_i pt(FeatureIntLocation(*feature)); +- DCHECK_GE(pt.x(), radius_); +- DCHECK_GE(pt.y(), radius_); +- DCHECK_LT(pt.x(), rgb_frame_.cols - radius_); +- DCHECK_LT(pt.y(), rgb_frame_.rows - radius_); ++ ABSL_DCHECK_GE(pt.x(), radius_); ++ ABSL_DCHECK_GE(pt.y(), radius_); ++ ABSL_DCHECK_LT(pt.x(), rgb_frame_.cols - radius_); ++ ABSL_DCHECK_LT(pt.y(), rgb_frame_.rows - radius_); + GetPatchDescriptorAtPoint(rgb_frame_, pt, radius_, &lab_window, + feature->mutable_feature_descriptor()); + + if (prev_rgb_frame_) { + Vector2_i pt_match(FeatureMatchIntLocation(*feature)); +- DCHECK_GE(pt_match.x(), radius_); +- DCHECK_GE(pt_match.y(), radius_); +- DCHECK_LT(pt_match.x(), rgb_frame_.cols - radius_); +- DCHECK_LT(pt_match.y(), rgb_frame_.rows - radius_); ++ ABSL_DCHECK_GE(pt_match.x(), radius_); ++ ABSL_DCHECK_GE(pt_match.y(), radius_); ++ ABSL_DCHECK_LT(pt_match.x(), rgb_frame_.cols - radius_); ++ ABSL_DCHECK_LT(pt_match.y(), rgb_frame_.rows - radius_); + GetPatchDescriptorAtPoint(*prev_rgb_frame_, pt_match, radius_, + &lab_window, + feature->mutable_feature_match_descriptor()); +@@ -247,17 +248,18 @@ void ComputeRegionFlowFeatureDescriptors( + int patch_descriptor_radius, RegionFlowFeatureList* flow_feature_list) { + const int rows = rgb_frame.rows; + const int cols = rgb_frame.cols; +- CHECK_EQ(rgb_frame.depth(), CV_8U); +- CHECK_EQ(rgb_frame.channels(), 3); ++ ABSL_CHECK_EQ(rgb_frame.depth(), CV_8U); ++ ABSL_CHECK_EQ(rgb_frame.channels(), 3); + + if (prev_rgb_frame) { +- CHECK_EQ(prev_rgb_frame->depth(), CV_8U); +- CHECK_EQ(prev_rgb_frame->channels(), 3); +- CHECK_EQ(prev_rgb_frame->rows, rows); +- CHECK_EQ(prev_rgb_frame->cols, cols); ++ ABSL_CHECK_EQ(prev_rgb_frame->depth(), CV_8U); ++ ABSL_CHECK_EQ(prev_rgb_frame->channels(), 3); ++ ABSL_CHECK_EQ(prev_rgb_frame->rows, rows); ++ ABSL_CHECK_EQ(prev_rgb_frame->cols, cols); + } + +- CHECK_LE(patch_descriptor_radius, flow_feature_list->distance_from_border()); ++ ABSL_CHECK_LE(patch_descriptor_radius, ++ flow_feature_list->distance_from_border()); + + ParallelFor( + 0, flow_feature_list->feature_size(), 1, +@@ -380,7 +382,7 @@ struct RegionFlowComputation::FrameTrackingData { + iwidth = (iwidth + 1) / 2; + iheight = (iheight + 1) / 2; + } +- CHECK_GE(extraction_levels, 1); ++ ABSL_CHECK_GE(extraction_levels, 1); + // Frame is the same as first extraction level. + frame = extraction_pyramid[0]; + +@@ -458,7 +460,7 @@ struct RegionFlowComputation::FrameTrackingData { + } + + void RemoveFeature(int pos) { +- DCHECK_LT(pos, features.size()); ++ ABSL_DCHECK_LT(pos, features.size()); + features.erase(features.begin() + pos); + feature_source_map.erase(feature_source_map.begin() + pos); + corner_responses.erase(corner_responses.begin() + pos); +@@ -616,8 +618,8 @@ RegionFlowComputation::RegionFlowComputation( + } + } + +- CHECK_NE(options.tracking_options().output_flow_direction(), +- TrackingOptions::CONSECUTIVELY) ++ ABSL_CHECK_NE(options.tracking_options().output_flow_direction(), ++ TrackingOptions::CONSECUTIVELY) + << "Output direction must be either set to FORWARD or BACKWARD."; + use_downsampling_ = options_.downsample_mode() != + RegionFlowComputationOptions::DOWNSAMPLE_NONE; +@@ -650,7 +652,7 @@ RegionFlowComputation::RegionFlowComputation( + } + case RegionFlowComputationOptions::DOWNSAMPLE_BY_FACTOR: + case RegionFlowComputationOptions::DOWNSAMPLE_TO_INPUT_SIZE: { +- CHECK_GE(options_.downsample_factor(), 1); ++ ABSL_CHECK_GE(options_.downsample_factor(), 1); + downsample_scale_ = options_.downsample_factor(); + break; + } +@@ -728,7 +730,7 @@ RegionFlowComputation::RegionFlowComputation( + frames_to_track_ = 1; + break; + case TrackingOptions::POLICY_MULTI_FRAME: +- CHECK_GT(options_.tracking_options().multi_frames_to_track(), 0); ++ ABSL_CHECK_GT(options_.tracking_options().multi_frames_to_track(), 0); + frames_to_track_ = options_.tracking_options().multi_frames_to_track(); + break; + case TrackingOptions::POLICY_LONG_TRACKS: +@@ -808,7 +810,7 @@ RegionFlowComputation::RegionFlowComputation( + + // Compute settings for block based flow. + const float block_size = options_.fast_estimation_block_size(); +- CHECK_GT(block_size, 0) << "Need positive block size"; ++ ABSL_CHECK_GT(block_size, 0) << "Need positive block size"; + + block_width_ = block_size < 1 ? block_size * original_width_ : block_size; + block_height_ = block_size < 1 ? block_size * original_height_ : block_size; +@@ -869,7 +871,7 @@ RegionFlowComputation::RetrieveRegionFlowFeatureListImpl( + int track_index, bool compute_feature_descriptor, + bool compute_match_descriptor, const cv::Mat* curr_color_image, + const cv::Mat* prev_color_image) { +- CHECK_GT(region_flow_results_.size(), track_index); ++ ABSL_CHECK_GT(region_flow_results_.size(), track_index); + CHECK(region_flow_results_[track_index].get()); + + std::unique_ptr<RegionFlowFeatureList> feature_list( +@@ -877,10 +879,10 @@ RegionFlowComputation::RetrieveRegionFlowFeatureListImpl( + + if (compute_feature_descriptor) { + CHECK(curr_color_image != nullptr); +- CHECK_EQ(3, curr_color_image->channels()); ++ ABSL_CHECK_EQ(3, curr_color_image->channels()); + if (compute_match_descriptor) { + CHECK(prev_color_image != nullptr); +- CHECK_EQ(3, prev_color_image->channels()); ++ ABSL_CHECK_EQ(3, prev_color_image->channels()); + } + + ComputeRegionFlowFeatureDescriptors( +@@ -1006,7 +1008,7 @@ bool RegionFlowComputation::InitFrame(const cv::Mat& source, + LOG(ERROR) << "Expecting 1 channel input for GRAYSCALE."; + return false; + } +- CHECK_EQ(1, source_ptr->channels()); ++ ABSL_CHECK_EQ(1, source_ptr->channels()); + if (source_ptr != &dest_frame) { + source_ptr->copyTo(dest_frame); + } +@@ -1024,8 +1026,8 @@ bool RegionFlowComputation::InitFrame(const cv::Mat& source, + } + + // Consistency checks; not input governed. +- CHECK_EQ(dest_frame.cols, frame_width_); +- CHECK_EQ(dest_frame.rows, frame_height_); ++ ABSL_CHECK_EQ(dest_frame.cols, frame_width_); ++ ABSL_CHECK_EQ(dest_frame.rows, frame_height_); + + data->BuildPyramid(pyramid_levels_, + options_.tracking_options().tracking_window_size(), +@@ -1089,8 +1091,8 @@ bool RegionFlowComputation::AddImageAndTrack( + curr_data->Reset(frame_num_, timestamp_usec); + + if (!IsModelIdentity(initial_transform)) { +- CHECK_EQ(1, frames_to_track_) << "Initial transform is not supported " +- << "for multi frame tracking"; ++ ABSL_CHECK_EQ(1, frames_to_track_) << "Initial transform is not supported " ++ << "for multi frame tracking"; + Homography transform = initial_transform; + if (downsample_scale_ != 1) { + const float scale = 1.0f / downsample_scale_; +@@ -1204,7 +1206,7 @@ bool RegionFlowComputation::AddImageAndTrack( + } + + cv::Mat RegionFlowComputation::GetGrayscaleFrameFromResults() { +- CHECK_GT(data_queue_.size(), 0) << "Empty queue, was AddImage* called?"; ++ ABSL_CHECK_GT(data_queue_.size(), 0) << "Empty queue, was AddImage* called?"; + FrameTrackingData* curr_data = data_queue_.back().get(); + CHECK(curr_data); + return curr_data->frame; +@@ -1228,9 +1230,9 @@ void RegionFlowComputation::GetFeatureTrackInliers( + + float RegionFlowComputation::ComputeVisualConsistency( + FrameTrackingData* previous, FrameTrackingData* current) const { +- CHECK_EQ(previous->frame_num + 1, current->frame_num); ++ ABSL_CHECK_EQ(previous->frame_num + 1, current->frame_num); + const int total = previous->tiny_image.total(); +- CHECK_GT(total, 0) << "Tiny image dimension set to zero."; ++ ABSL_CHECK_GT(total, 0) << "Tiny image dimension set to zero."; + current->tiny_image_diff = + FrameDifferenceMedian(previous->tiny_image, current->tiny_image) * + (1.0f / total); +@@ -1263,10 +1265,10 @@ void RegionFlowComputation::ComputeRegionFlow( + } else { + const int index1 = data_queue_.size() + from - 1; + const int index2 = data_queue_.size() + to - 1; +- CHECK_GE(index1, 0); +- CHECK_LT(index1, data_queue_.size()); +- CHECK_GE(index2, 0); +- CHECK_LT(index2, data_queue_.size()); ++ ABSL_CHECK_GE(index1, 0); ++ ABSL_CHECK_LT(index1, data_queue_.size()); ++ ABSL_CHECK_GE(index2, 0); ++ ABSL_CHECK_LT(index2, data_queue_.size()); + data1 = data_queue_[index1].get(); + data2 = data_queue_[index2].get(); + +@@ -1611,14 +1613,14 @@ class GridFeatureLocator { + // or adds K to the existing mask if add is set to true. + template <int N, int K, bool add> + inline void SetMaskNeighborhood(int mask_x, int mask_y, cv::Mat* mask) { +- DCHECK_EQ(mask->type(), CV_8U); ++ ABSL_DCHECK_EQ(mask->type(), CV_8U); + const int mask_start_x = max(0, mask_x - N); + const int mask_end_x = min(mask->cols - 1, mask_x + N); + const int mask_dx = mask_end_x - mask_start_x + 1; + const int mask_start_y = max(0, mask_y - N); + const int mask_end_y = min(mask->rows - 1, mask_y + N); +- DCHECK_LE(mask_start_x, mask_end_x); +- DCHECK_LE(mask_start_y, mask_end_y); ++ ABSL_DCHECK_LE(mask_start_x, mask_end_x); ++ ABSL_DCHECK_LE(mask_start_y, mask_end_y); + + if (!add) { + for (int i = mask_start_y; i <= mask_end_y; ++i) { +@@ -1651,7 +1653,7 @@ void RegionFlowComputation::AdaptiveGoodFeaturesToTrack( + + // Setup grid information. + const float block_size = tracking_options.adaptive_features_block_size(); +- CHECK_GT(block_size, 0) << "Need positive block size"; ++ ABSL_CHECK_GT(block_size, 0) << "Need positive block size"; + + int block_width = block_size < 1 ? block_size * frame_width_ : block_size; + int block_height = block_size < 1 ? block_size * frame_height_ : block_size; +@@ -1703,8 +1705,8 @@ void RegionFlowComputation::AdaptiveGoodFeaturesToTrack( + std::vector<cv::KeyPoint> fast_keypoints; + if (e == 0) { + MEASURE_TIME << "Corner extraction"; +- CHECK_EQ(rows, frame_height_); +- CHECK_EQ(cols, frame_width_); ++ ABSL_CHECK_EQ(rows, frame_height_); ++ ABSL_CHECK_EQ(cols, frame_width_); + + if (use_fast) { + fast_detector->detect(image, fast_keypoints); +@@ -1716,8 +1718,8 @@ void RegionFlowComputation::AdaptiveGoodFeaturesToTrack( + } else { + // Compute corner response on a down-scaled image and upsample. + step *= 2; +- CHECK_EQ(rows, (extraction_pyramid[e - 1].rows + 1) / 2); +- CHECK_EQ(cols, (extraction_pyramid[e - 1].cols + 1) / 2); ++ ABSL_CHECK_EQ(rows, (extraction_pyramid[e - 1].rows + 1) / 2); ++ ABSL_CHECK_EQ(cols, (extraction_pyramid[e - 1].cols + 1) / 2); + + if (use_fast) { + fast_detector->detect(image, fast_keypoints); +@@ -2015,8 +2017,8 @@ bool RegionFlowComputation::GainCorrectFrame(const cv::Mat& reference_frame, + float input_mean, + cv::Mat* calibrated_frame) const { + CHECK(calibrated_frame); +- CHECK_EQ(reference_frame.rows, input_frame.rows); +- CHECK_EQ(reference_frame.cols, input_frame.cols); ++ ABSL_CHECK_EQ(reference_frame.rows, input_frame.rows); ++ ABSL_CHECK_EQ(reference_frame.cols, input_frame.cols); + + // Do not attempt gain correction for tiny images. + if (std::min(reference_frame.rows, reference_frame.cols) < 10) { +@@ -2185,7 +2187,7 @@ void RegionFlowComputation::RemoveAbsentFeatures( + // Build hash set of track ids. + absl::node_hash_set<int> track_ids; + for (const auto& feature : prev_result) { +- DCHECK_NE(feature.track_id, -1); ++ ABSL_DCHECK_NE(feature.track_id, -1); + track_ids.insert(feature.track_id); + } + +@@ -2233,8 +2235,8 @@ void RegionFlowComputation::ExtractFeatures( + + if (data->last_feature_extraction_time == 0) { + // Features already extracted from this frame. +- CHECK_EQ(data->corner_responses.size(), data->features.size()); +- CHECK_EQ(data->octaves.size(), data->features.size()); ++ ABSL_CHECK_EQ(data->corner_responses.size(), data->features.size()); ++ ABSL_CHECK_EQ(data->octaves.size(), data->features.size()); + VLOG(1) << "Features already present (extracted from this frame)"; + return; + } +@@ -2242,8 +2244,8 @@ void RegionFlowComputation::ExtractFeatures( + // Remove features that lie outside feature extraction mask. + RemoveFeaturesOutsideMask(data); + +- CHECK_EQ(data->corner_responses.size(), data->features.size()); +- CHECK_EQ(data->octaves.size(), data->features.size()); ++ ABSL_CHECK_EQ(data->corner_responses.size(), data->features.size()); ++ ABSL_CHECK_EQ(data->octaves.size(), data->features.size()); + + float feature_fraction = 0; + if (data->num_original_extracted_and_tracked > 0) { +@@ -2309,7 +2311,7 @@ void RegionFlowComputation::ExtractFeatures( + data->neighborhoods->reserve(features_to_allocate); + } + +- CHECK_EQ(data->extraction_pyramid.size(), extraction_levels_); ++ ABSL_CHECK_EQ(data->extraction_pyramid.size(), extraction_levels_); + for (int i = 1; i < extraction_levels_; ++i) { + // Need factor 2 as OpenCV stores image + gradient pairs when + // "with_derivative" is set to true. +@@ -2357,8 +2359,8 @@ void RegionFlowComputation::ExtractFeatures( + // For FORWARD output flow, we need to add flow to obtain the match + // position, for BACKWARD output flow, flow is inverted, so that feature + // locations already point to locations in the current frame. +- CHECK_EQ(options_.tracking_options().internal_tracking_direction(), +- TrackingOptions::FORWARD); ++ ABSL_CHECK_EQ(options_.tracking_options().internal_tracking_direction(), ++ TrackingOptions::FORWARD); + float match_sign = options_.tracking_options().output_flow_direction() == + TrackingOptions::FORWARD + ? 1.0f +@@ -2426,9 +2428,9 @@ void RegionFlowComputation::ExtractFeatures( + mask_scale, &mask, data); + + const int num_features = data->features.size(); +- CHECK_EQ(num_features, data->octaves.size()); +- CHECK_EQ(num_features, data->corner_responses.size()); +- CHECK_EQ(num_features, data->track_ids.size()); ++ ABSL_CHECK_EQ(num_features, data->octaves.size()); ++ ABSL_CHECK_EQ(num_features, data->corner_responses.size()); ++ ABSL_CHECK_EQ(num_features, data->track_ids.size()); + } + + // Selects features based on lambda evaluator: bool (int index) +@@ -2439,23 +2441,23 @@ int RegionFlowComputation::InplaceFeatureSelection( + std::vector<std::vector<float>*> float_vecs, const Eval& eval) { + int num_selected_features = 0; + const int num_features = data->features.size(); +- DCHECK_EQ(num_features, data->corner_responses.size()); +- DCHECK_EQ(num_features, data->octaves.size()); +- DCHECK_EQ(num_features, data->track_ids.size()); +- DCHECK_EQ(num_features, data->feature_source_map.size()); ++ ABSL_DCHECK_EQ(num_features, data->corner_responses.size()); ++ ABSL_DCHECK_EQ(num_features, data->octaves.size()); ++ ABSL_DCHECK_EQ(num_features, data->track_ids.size()); ++ ABSL_DCHECK_EQ(num_features, data->feature_source_map.size()); + if (data->neighborhoods != nullptr) { +- DCHECK_EQ(num_features, data->neighborhoods->size()); ++ ABSL_DCHECK_EQ(num_features, data->neighborhoods->size()); + } + + for (const auto vec_ptr : int_vecs) { +- DCHECK_EQ(num_features, vec_ptr->size()); ++ ABSL_DCHECK_EQ(num_features, vec_ptr->size()); + } + for (const auto vec_ptr : float_vecs) { +- DCHECK_EQ(num_features, vec_ptr->size()); ++ ABSL_DCHECK_EQ(num_features, vec_ptr->size()); + } + + for (int i = 0; i < num_features; ++i) { +- DCHECK_LE(num_selected_features, i); ++ ABSL_DCHECK_LE(num_selected_features, i); + if (eval(i)) { + data->features[num_selected_features] = data->features[i]; + data->corner_responses[num_selected_features] = data->corner_responses[i]; +@@ -2549,14 +2551,14 @@ void RegionFlowComputation::TrackFeatures(FrameTrackingData* from_data_ptr, + octaves2.resize(num_features); + data2.source = from_data_ptr; + } else { +- CHECK_EQ(data2.source, from_data_ptr); +- CHECK_EQ(num_features, features2.size()); ++ ABSL_CHECK_EQ(data2.source, from_data_ptr); ++ ABSL_CHECK_EQ(num_features, features2.size()); + tracking_flags |= cv::OPTFLOW_USE_INITIAL_FLOW; + } + + const int track_win_size = options_.tracking_options().tracking_window_size(); +- CHECK_GT(track_win_size, 1) << "Needs to be at least 2 pixels in each " +- << "direction"; ++ ABSL_CHECK_GT(track_win_size, 1) << "Needs to be at least 2 pixels in each " ++ << "direction"; + + // Proceed with gain correction only if it succeeds, and set flag accordingly. + bool frame1_gain_reference = true; +@@ -2946,14 +2948,14 @@ void RegionFlowComputation::InitializeFeatureLocationsFromTransform( + + void RegionFlowComputation::InitializeFeatureLocationsFromPreviousResult( + int from, int to) { +- CHECK_NE(from, to) << "Cannot initialize FrameTrackingData from itself."; ++ ABSL_CHECK_NE(from, to) << "Cannot initialize FrameTrackingData from itself."; + + const int index1 = data_queue_.size() + from - 1; + const int index2 = data_queue_.size() + to - 1; +- CHECK_GE(index1, 0); +- CHECK_LT(index1, data_queue_.size()); +- CHECK_GE(index2, 0); +- CHECK_LT(index2, data_queue_.size()); ++ ABSL_CHECK_GE(index1, 0); ++ ABSL_CHECK_LT(index1, data_queue_.size()); ++ ABSL_CHECK_GE(index2, 0); ++ ABSL_CHECK_LT(index2, data_queue_.size()); + const FrameTrackingData& data1 = *data_queue_[index1]; + FrameTrackingData* data2 = data_queue_[index2].get(); + CHECK(data1.source != nullptr); +@@ -2965,7 +2967,7 @@ void RegionFlowComputation::InitializeFeatureLocationsFromPreviousResult( + } + } else { + data2->features = data1.features; +- CHECK_EQ(data1.features.size(), data1.source->features.size()); ++ ABSL_CHECK_EQ(data1.features.size(), data1.source->features.size()); + } + data2->source = data1.source; + data2->features_initialized = true; +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc +index dc067da7c9a34..841ce5e0dc54c 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc +@@ -19,6 +19,7 @@ + #include <memory> + #include <numeric> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/util/tracking/measure_time.h" +@@ -138,7 +139,7 @@ void VisualizeLongFeatureStreamImpl(const LongFeatureStream& stream, + if (min_track_length > 0 && pts.size() < min_track_length) { + continue; + } +- CHECK_GT(pts.size(), 1); // Should have at least two points per track. ++ ABSL_CHECK_GT(pts.size(), 1); // Should have at least two points per track. + + // Tracks are ordered with oldest point first, most recent one last. + const int start_k = +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc +index 2e5b0ac2f034e..286edbb8e5055 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc +@@ -14,6 +14,7 @@ + + #include "mediapipe/util/tracking/streaming_buffer.h" + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_cat.h" + + namespace mediapipe { +@@ -21,7 +22,7 @@ namespace mediapipe { + StreamingBuffer::StreamingBuffer( + const std::vector<TaggedType>& data_configuration, int overlap) + : overlap_(overlap) { +- CHECK_GE(overlap, 0); ++ ABSL_CHECK_GE(overlap, 0); + for (auto& item : data_configuration) { + CHECK(data_config_.find(item.first) == data_config_.end()) + << "Tag " << item.first << " already exists"; +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h +index 41aadbbb5ad5f..bdaeb0cef05fa 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h +@@ -23,6 +23,7 @@ + #include <vector> + + #include "absl/container/node_hash_map.h" ++#include "absl/log/absl_check.h" + #include "absl/types/any.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/tool/type_util.h" +@@ -324,7 +325,7 @@ template <class T> + void StreamingBuffer::AddDatum(const std::string& tag, + std::unique_ptr<T> pointer) { + CHECK(HasTag(tag)); +- CHECK_EQ(data_config_[tag], kTypeId<PointerType<T>>.hash_code()); ++ ABSL_CHECK_EQ(data_config_[tag], kTypeId<PointerType<T>>.hash_code()); + auto& buffer = data_[tag]; + absl::any packet(PointerType<T>(CreatePointer(pointer.release()))); + buffer.push_back(packet); +@@ -344,7 +345,7 @@ void StreamingBuffer::AddDatumCopy(const std::string& tag, const T& datum) { + template <class... Types> + void StreamingBuffer::AddData(const std::vector<std::string>& tags, + std::unique_ptr<Types>... pointers) { +- CHECK_EQ(tags.size(), sizeof...(pointers)) ++ ABSL_CHECK_EQ(tags.size(), sizeof...(pointers)) + << "Number of tags and data pointers is inconsistent"; + return AddDataImpl(tags, std::move(pointers)...); + } +@@ -387,7 +388,7 @@ T& StreamingBuffer::GetDatumRef(const std::string& tag, int frame_index) const { + template <class T> + T* StreamingBuffer::GetMutableDatum(const std::string& tag, + int frame_index) const { +- CHECK_GE(frame_index, 0); ++ ABSL_CHECK_GE(frame_index, 0); + CHECK(HasTag(tag)); + auto& buffer = data_.find(tag)->second; + if (frame_index > buffer.size()) { +@@ -488,7 +489,7 @@ template <class T> + std::unique_ptr<T> StreamingBuffer::ReleaseDatum(const std::string& tag, + int frame_index) { + CHECK(HasTag(tag)); +- CHECK_GE(frame_index, 0); ++ ABSL_CHECK_GE(frame_index, 0); + + auto& buffer = data_.find(tag)->second; + if (frame_index >= buffer.size()) { +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc +index 587fe96f2ee80..2fdfa114a362d 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc +@@ -21,6 +21,7 @@ + #include <numeric> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/util/tracking/motion_models.pb.h" + #include "mediapipe/util/tracking/tone_models.pb.h" + +@@ -58,7 +59,7 @@ ToneEstimation::ToneEstimation(const ToneEstimationOptions& options, + break; + } + case ToneEstimationOptions::DOWNSAMPLE_BY_FACTOR: { +- CHECK_GE(options_.downsample_factor(), 1); ++ ABSL_CHECK_GE(options_.downsample_factor(), 1); + frame_width_ /= options_.downsample_factor(); + frame_height_ /= options_.downsample_factor(); + downsample_scale_ = options_.downsample_factor(); +@@ -80,8 +81,8 @@ void ToneEstimation::EstimateToneChange( + const RegionFlowFeatureList& feature_list_input, + const cv::Mat& curr_frame_input, const cv::Mat* prev_frame_input, + ToneChange* tone_change, cv::Mat* debug_output) { +- CHECK_EQ(original_height_, curr_frame_input.rows); +- CHECK_EQ(original_width_, curr_frame_input.cols); ++ ABSL_CHECK_EQ(original_height_, curr_frame_input.rows); ++ ABSL_CHECK_EQ(original_width_, curr_frame_input.cols); + CHECK(tone_change != nullptr); + + const cv::Mat& curr_frame = +@@ -106,8 +107,8 @@ void ToneEstimation::EstimateToneChange( + TransformRegionFlowFeatureList(scale_transform, &scaled_feature_list); + } + +- CHECK_EQ(frame_height_, curr_frame.rows); +- CHECK_EQ(frame_width_, curr_frame.cols); ++ ABSL_CHECK_EQ(frame_height_, curr_frame.rows); ++ ABSL_CHECK_EQ(frame_width_, curr_frame.cols); + + ClipMask<3> curr_clip; + ComputeClipMask<3>(options_.clip_mask_options(), curr_frame, &curr_clip); +@@ -219,8 +220,8 @@ void ToneEstimation::EstimateGainBiasModel(int irls_iterations, + float solution_ptr[6] = {1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f}; + + const int num_channels = color_tone_matches->size(); +- CHECK_GT(num_channels, 0); +- CHECK_LE(num_channels, 3); ++ ABSL_CHECK_GT(num_channels, 0); ++ ABSL_CHECK_LE(num_channels, 3); + + // TODO: One IRLS weight per color match. + for (int c = 0; c < num_channels; ++c) { +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h +index 0fa049e2bc685..9f37cdd374b1e 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h +@@ -25,6 +25,7 @@ + #include <memory> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/opencv_core_inc.h" +@@ -151,7 +152,7 @@ void ToneEstimation::ComputeClipMask(const ClipMaskOptions& options, + const cv::Mat& frame, + ClipMask<C>* clip_mask) { + CHECK(clip_mask != nullptr); +- CHECK_EQ(frame.channels(), C); ++ ABSL_CHECK_EQ(frame.channels(), C); + + // Over / Underexposure handling. + // Masks pixels affected by clipping. +@@ -163,7 +164,7 @@ void ToneEstimation::ComputeClipMask(const ClipMaskOptions& options, + + std::vector<cv::Mat> planes; + cv::split(frame, planes); +- CHECK_EQ(C, planes.size()); ++ ABSL_CHECK_EQ(C, planes.size()); + float min_exposure[C]; + float max_exposure[C]; + for (int c = 0; c < C; ++c) { +@@ -224,8 +225,8 @@ void ToneEstimation::ComputeToneMatches( + const ClipMask<C>& prev_clip_mask, // Optional. + ColorToneMatches* color_tone_matches, cv::Mat* debug_output) { + CHECK(color_tone_matches != nullptr); +- CHECK_EQ(curr_frame.channels(), C); +- CHECK_EQ(prev_frame.channels(), C); ++ ABSL_CHECK_EQ(curr_frame.channels(), C); ++ ABSL_CHECK_EQ(prev_frame.channels(), C); + + color_tone_matches->clear(); + color_tone_matches->resize(C); +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc +index 9410834bdd129..4ab896a5644a7 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc +@@ -16,6 +16,7 @@ + + #include <cmath> + ++#include "absl/log/absl_check.h" + #include "absl/strings/str_format.h" + + namespace mediapipe { +@@ -50,10 +51,10 @@ void ToneModelMethods<Model, Adapter>::MapImage(const Model& model, + CHECK(output != nullptr); + + const int out_channels = output->channels(); +- CHECK_EQ(input.channels(), 3); +- CHECK_LE(out_channels, 3); +- CHECK_EQ(input.rows, output->rows); +- CHECK_EQ(input.cols, output->cols); ++ ABSL_CHECK_EQ(input.channels(), 3); ++ ABSL_CHECK_LE(out_channels, 3); ++ ABSL_CHECK_EQ(input.rows, output->rows); ++ ABSL_CHECK_EQ(input.cols, output->cols); + + float norm_scale = + normalized_model +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h +index 266257e1fcc85..17b4427ae39e3 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h +@@ -23,6 +23,7 @@ + #include <string> + #include <vector> + ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/integral_types.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/opencv_core_inc.h" +@@ -593,8 +594,8 @@ void ToneModelMethods<Model, Adapter>::MapImageIndependent( + const Model& model, bool log_domain, bool normalized_model, + const cv::Mat& input, cv::Mat* output) { + CHECK(output != nullptr); +- CHECK_EQ(input.channels(), C); +- CHECK_EQ(output->channels(), C); ++ ABSL_CHECK_EQ(input.channels(), C); ++ ABSL_CHECK_EQ(output->channels(), C); + + // Input LUT which will be mapped to the output LUT by the tone change model. + // Needs 3 channels to represent input RGB colors, but since they are assumed +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc +index 50aaa940cfe41..efac37dd0d35b 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc +@@ -25,6 +25,7 @@ + #include "Eigen/Dense" + #include "Eigen/SVD" + #include "absl/algorithm/container.h" ++#include "absl/log/absl_check.h" + #include "absl/memory/memory.h" + #include "mediapipe/framework/port/logging.h" + #include "mediapipe/framework/port/opencv_calib3d_inc.h" +@@ -63,7 +64,7 @@ void StoreInternalState(const std::vector<const MotionVector*>& vectors, + const std::vector<float>& inlier_weights, + float aspect_ratio, MotionBoxInternalState* internal) { + const int num_vectors = vectors.size(); +- CHECK_EQ(num_vectors, inlier_weights.size()); ++ ABSL_CHECK_EQ(num_vectors, inlier_weights.size()); + + float scale_x = 1.0f; + float scale_y = 1.0f; +@@ -171,7 +172,7 @@ bool LinearSimilarityL2Solve( + matrix.setTo(0); + rhs.setTo(0); + +- CHECK_EQ(motion_vectors.size(), weights.size()); ++ ABSL_CHECK_EQ(motion_vectors.size(), weights.size()); + for (int k = 0; k < motion_vectors.size(); ++k) { + const float x = motion_vectors[k]->pos.x(); + const float y = motion_vectors[k]->pos.y(); +@@ -245,7 +246,7 @@ bool HomographyL2Solve(const std::vector<const MotionVector*>& motion_vectors, + + // Matrix multiplications are hand-coded for speed improvements vs. + // opencv's cvGEMM calls. +- CHECK_EQ(motion_vectors.size(), weights.size()); ++ ABSL_CHECK_EQ(motion_vectors.size(), weights.size()); + for (int k = 0; k < motion_vectors.size(); ++k) { + const float x = motion_vectors[k]->pos.x(); + const float y = motion_vectors[k]->pos.y(); +@@ -828,7 +829,7 @@ void InitializePnpHomographyInMotionBoxState( + } + + const int kQuadCornersSize = 4; +- CHECK_EQ(state->quad().vertices_size(), kQuadCornersSize * 2); ++ ABSL_CHECK_EQ(state->quad().vertices_size(), kQuadCornersSize * 2); + float scale_x, scale_y; + ScaleFromAspect(tracking.frame_aspect(), false, &scale_x, &scale_y); + std::vector<cv::Point2f> corners_2d(kQuadCornersSize); +@@ -910,7 +911,7 @@ void InitializePnpHomographyInMotionBoxState( + state->set_aspect_ratio(width_norm / height_norm); + } + +- CHECK_GT(state->aspect_ratio(), 0.0f); ++ ABSL_CHECK_GT(state->aspect_ratio(), 0.0f); + + const float half_width = state->aspect_ratio(); + const float half_height = 1.0f; +@@ -973,7 +974,7 @@ void ScaleStateAspect(float aspect, bool invert, MotionBoxState* state) { + + MotionVector MotionVector::FromInternalState( + const MotionBoxInternalState& internal, int index) { +- CHECK_LT(index, internal.pos_x_size()); ++ ABSL_CHECK_LT(index, internal.pos_x_size()); + MotionVector v; + v.pos = Vector2_f(internal.pos_x(index), internal.pos_y(index)); + v.object = Vector2_f(internal.dx(index), internal.dy(index)); +@@ -1150,7 +1151,7 @@ void ComputeSpatialPrior(bool interpolate, bool use_next_position, + std::vector<float> old_confidence(update_pos->spatial_confidence().begin(), + update_pos->spatial_confidence().end()); + +- CHECK_EQ(old_confidence.size(), old_prior.size()); ++ ABSL_CHECK_EQ(old_confidence.size(), old_prior.size()); + CHECK(old_confidence.empty() || + grid_size * grid_size == old_confidence.size()) + << "Empty or priors of constant size expected"; +@@ -1192,10 +1193,10 @@ void ComputeSpatialPrior(bool interpolate, bool use_next_position, + const int int_x = static_cast<int>(grid_pos.x()); + const int int_y = static_cast<int>(grid_pos.y()); + +- CHECK_GE(grid_pos.x(), 0) << pos.x() << ", " << update_pos->pos_x(); +- CHECK_GE(grid_pos.y(), 0); +- CHECK_LE(grid_pos.x(), grid_size - 1); +- CHECK_LE(grid_pos.y(), grid_size - 1); ++ ABSL_CHECK_GE(grid_pos.x(), 0) << pos.x() << ", " << update_pos->pos_x(); ++ ABSL_CHECK_GE(grid_pos.y(), 0); ++ ABSL_CHECK_LE(grid_pos.x(), grid_size - 1); ++ ABSL_CHECK_LE(grid_pos.y(), grid_size - 1); + + const float dx = grid_pos.x() - int_x; + const float dy = grid_pos.y() - int_y; +@@ -1431,8 +1432,8 @@ MotionBox::DistanceWeightsComputer::DistanceWeightsComputer( + tracking_degrees_ = options.tracking_degrees(); + const Vector2_f box_domain(current_state.width() * current_state.scale(), + current_state.height() * current_state.scale()); +- CHECK_GT(box_domain.x(), 0.0f); +- CHECK_GT(box_domain.y(), 0.0f); ++ ABSL_CHECK_GT(box_domain.x(), 0.0f); ++ ABSL_CHECK_GT(box_domain.y(), 0.0f); + inv_box_domain_ = Vector2_f(1.0f / box_domain.x(), 1.0f / box_domain.y()); + + // Space sigma depends on how much the tracked object fills the rectangle. +@@ -1575,8 +1576,8 @@ bool MotionBox::GetVectorsAndWeights( + const Vector2_f box_domain(box_state.width() * box_state.scale(), + box_state.height() * box_state.scale()); + +- CHECK_GT(box_domain.x(), 0.0f); +- CHECK_GT(box_domain.y(), 0.0f); ++ ABSL_CHECK_GT(box_domain.x(), 0.0f); ++ ABSL_CHECK_GT(box_domain.y(), 0.0f); + const Vector2_f inv_box_domain(1.0f / box_domain.x(), 1.0f / box_domain.y()); + + // The four lines of the rotated and scaled box. +@@ -1670,8 +1671,8 @@ bool MotionBox::GetVectorsAndWeights( + is_outlier.push_back(is_outlier_flag); + } + +- CHECK_EQ(vectors->size(), is_inlier.size()); +- CHECK_EQ(vectors->size(), is_outlier.size()); ++ ABSL_CHECK_EQ(vectors->size(), is_inlier.size()); ++ ABSL_CHECK_EQ(vectors->size(), is_outlier.size()); + + const float prev_motion_mag = MotionBoxVelocity(box_state).Norm(); + +@@ -1814,7 +1815,7 @@ bool MotionBox::GetVectorsAndWeights( + } + + const int num_vectors = vectors->size(); +- CHECK_EQ(num_vectors, weights->size()); ++ ABSL_CHECK_EQ(num_vectors, weights->size()); + + const float weight_sum = + std::accumulate(weights->begin(), weights->end(), 0.0f); +@@ -1917,8 +1918,8 @@ void MotionBox::EstimateObjectMotion( + CHECK(object_homography); + + const int num_vectors = motion_vectors.size(); +- CHECK_EQ(num_vectors, prior_weights.size()); +- CHECK_EQ(num_vectors, weights->size()); ++ ABSL_CHECK_EQ(num_vectors, prior_weights.size()); ++ ABSL_CHECK_EQ(num_vectors, weights->size()); + + // Create backup of weights if needed. + std::vector<float> similarity_weights; +@@ -2440,8 +2441,8 @@ void MotionBox::ComputeInlierCenterAndExtent( + float weight_sum = 0; + float inlier_sum = 0; + const int num_vectors = motion_vectors.size(); +- CHECK_EQ(num_vectors, weights.size()); +- CHECK_EQ(num_vectors, density.size()); ++ ABSL_CHECK_EQ(num_vectors, weights.size()); ++ ABSL_CHECK_EQ(num_vectors, density.size()); + + Vector2_f first_moment(0.0f, 0.0f); + Vector2_f second_moment(0.0f, 0.0f); +@@ -2498,7 +2499,7 @@ float MotionBox::ScaleEstimate( + const std::vector<const MotionVector*>& motion_vectors, + const std::vector<float>& weights, float min_sum) const { + const int num_vectors = motion_vectors.size(); +- CHECK_EQ(num_vectors, weights.size()); ++ ABSL_CHECK_EQ(num_vectors, weights.size()); + + float scale_sum = 0; + +@@ -2793,7 +2794,7 @@ void MotionBox::TrackStepImplDeNormalized( + VLOG(1) << "Good inits: " << num_good_inits; + + const int num_vectors = vectors.size(); +- CHECK_EQ(num_vectors, prior_weights.size()); ++ ABSL_CHECK_EQ(num_vectors, prior_weights.size()); + + Vector2_f object_translation; + +diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h +index 4d3343f583e54..248d20bcb83f0 100644 +--- a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h ++++ b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h +@@ -26,6 +26,7 @@ + #include <vector> + + #include "absl/container/flat_hash_set.h" ++#include "absl/log/absl_check.h" + #include "mediapipe/framework/port/vector.h" + #include "mediapipe/util/tracking/flow_packager.pb.h" + #include "mediapipe/util/tracking/motion_models.h" +@@ -122,7 +123,7 @@ inline void MotionBoxInliers(const MotionBoxState& state, + std::unordered_map<int, int>* inliers) { + CHECK(inliers); + const int num_inliers = state.inlier_ids_size(); +- DCHECK_EQ(num_inliers, state.inlier_length_size()); ++ ABSL_DCHECK_EQ(num_inliers, state.inlier_length_size()); + + for (int k = 0; k < num_inliers; ++k) { + (*inliers)[state.inlier_ids(k)] = +@@ -572,7 +573,7 @@ class MotionBox { + // Check if it is a convex quad. + static bool IsValidQuad(const MotionBoxState::Quad& quad) { + const int kQuadVerticesSize = 8; +- CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); ++ ABSL_CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); + for (int a = 0; a < kQuadVerticesSize; a += 2) { + int b = (a + 2) % kQuadVerticesSize; + int c = (a - 2 + kQuadVerticesSize) % kQuadVerticesSize; +@@ -595,7 +596,7 @@ class MotionBox { + static bool IsQuadOutOfFov(const MotionBoxState::Quad& quad, + const Vector2_f& fov) { + const int kQuadVerticesSize = 8; +- CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); ++ ABSL_CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); + bool too_far = true; + for (int j = 0; j < kQuadVerticesSize; j += 2) { + if (quad.vertices(j) < fov.x() && quad.vertices(j) > 0.0f &&
diff --git a/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc index 60ec405..b9e2fe4a 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/core/packet_resampler_calculator.cc
@@ -200,15 +200,15 @@ Timestamp PacketResamplerCalculator::PeriodIndexToTimestamp( int64_t index) const { - CHECK_EQ(jitter_, 0.0); - CHECK_NE(first_timestamp_, Timestamp::Unset()); + ABSL_CHECK_EQ(jitter_, 0.0); + ABSL_CHECK_NE(first_timestamp_, Timestamp::Unset()); return first_timestamp_ + TimestampDiffFromSeconds(index / frame_rate_); } int64_t PacketResamplerCalculator::TimestampToPeriodIndex( Timestamp timestamp) const { - CHECK_EQ(jitter_, 0.0); - CHECK_NE(first_timestamp_, Timestamp::Unset()); + ABSL_CHECK_EQ(jitter_, 0.0); + ABSL_CHECK_NE(first_timestamp_, Timestamp::Unset()); return MathUtil::SafeRound<int64_t, double>( (timestamp - first_timestamp_).Seconds() * frame_rate_); } @@ -340,8 +340,8 @@ next_output_timestamp_ = Timestamp(ReflectBetween( next_output_timestamp_.Value(), next_output_timestamp_min_.Value(), next_output_timestamp_max_.Value())); - CHECK_GE(next_output_timestamp_, next_output_timestamp_min_); - CHECK_LT(next_output_timestamp_, next_output_timestamp_max_); + ABSL_CHECK_GE(next_output_timestamp_, next_output_timestamp_min_); + ABSL_CHECK_LT(next_output_timestamp_, next_output_timestamp_max_); } absl::Status ReproducibleJitterWithReflectionStrategy::Open(
diff --git a/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc index 35cd966..ecb6ca57 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/core/packet_thinner_calculator.cc
@@ -17,6 +17,7 @@ #include <cmath> // for ceil #include <memory> +#include "absl/log/absl_check.h" #include "mediapipe/calculators/core/packet_thinner_calculator.pb.h" #include "mediapipe/framework/calculator_context.h" #include "mediapipe/framework/calculator_framework.h" @@ -177,7 +178,8 @@ } else { period_ = TimestampDiff(options.period()); } - CHECK_LT(TimestampDiff(0), period_) << "Specified period must be positive."; + ABSL_CHECK_LT(TimestampDiff(0), period_) + << "Specified period must be positive."; if (options.has_start_time()) { start_time_ = Timestamp(options.start_time()); @@ -189,7 +191,7 @@ end_time_ = options.has_end_time() ? Timestamp(options.end_time()) : Timestamp::Max(); - CHECK_LT(start_time_, end_time_) + ABSL_CHECK_LT(start_time_, end_time_) << "Invalid PacketThinner: start_time must be earlier than end_time"; sync_output_timestamps_ = options.sync_output_timestamps(); @@ -232,7 +234,7 @@ // Emit any saved packets before quitting. if (!saved_packet_.IsEmpty()) { // Only sync thinner should have saved packets. - CHECK_EQ(PacketThinnerCalculatorOptions::SYNC, thinner_type_); + ABSL_CHECK_EQ(PacketThinnerCalculatorOptions::SYNC, thinner_type_); if (sync_output_timestamps_) { cc->Outputs().Index(0).AddPacket( saved_packet_.At(NearestSyncTimestamp(saved_packet_.Timestamp()))); @@ -269,7 +271,7 @@ const Timestamp saved_sync = NearestSyncTimestamp(saved); const Timestamp now = cc->InputTimestamp(); const Timestamp now_sync = NearestSyncTimestamp(now); - CHECK_LE(saved_sync, now_sync); + ABSL_CHECK_LE(saved_sync, now_sync); if (saved_sync == now_sync) { // Saved Packet is in same interval as current packet. // Replace saved packet with current if it is at least as @@ -295,7 +297,7 @@ } Timestamp PacketThinnerCalculator::NearestSyncTimestamp(Timestamp now) const { - CHECK_NE(start_time_, Timestamp::Unset()) + ABSL_CHECK_NE(start_time_, Timestamp::Unset()) << "Method only valid for sync thinner calculator."; // Computation is done using int64 arithmetic. No easy way to avoid @@ -303,12 +305,12 @@ const int64_t now64 = now.Value(); const int64_t start64 = start_time_.Value(); const int64_t period64 = period_.Value(); - CHECK_LE(0, period64); + ABSL_CHECK_LE(0, period64); // Round now64 to its closest interval (units of period64). int64_t sync64 = (now64 - start64 + period64 / 2) / period64 * period64 + start64; - CHECK_LE(abs(now64 - sync64), period64 / 2) + ABSL_CHECK_LE(abs(now64 - sync64), period64 / 2) << "start64: " << start64 << "; now64: " << now64 << "; sync64: " << sync64;
diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc index 6bb43dc..5eac351 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/image/bilateral_filter_calculator.cc
@@ -15,6 +15,7 @@ #include <memory> #include <string> +#include "absl/log/absl_check.h" #include "absl/strings/str_replace.h" #include "mediapipe/calculators/image/bilateral_filter_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" @@ -112,7 +113,7 @@ REGISTER_CALCULATOR(BilateralFilterCalculator); absl::Status BilateralFilterCalculator::GetContract(CalculatorContract* cc) { - CHECK_GE(cc->Inputs().NumEntries(), 1); + ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); if (cc->Inputs().HasTag(kInputFrameTag) && cc->Inputs().HasTag(kInputFrameTagGpu)) { @@ -183,8 +184,8 @@ sigma_color_ = options_.sigma_color(); sigma_space_ = options_.sigma_space(); - CHECK_GE(sigma_color_, 0.0); - CHECK_GE(sigma_space_, 0.0); + ABSL_CHECK_GE(sigma_color_, 0.0); + ABSL_CHECK_GE(sigma_space_, 0.0); if (!use_gpu_) sigma_color_ *= 255.0; if (use_gpu_) {
diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc index 93ec9435..0308b9b8 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/image/opencv_image_encoder_calculator.cc
@@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "absl/log/absl_check.h" #include "mediapipe/calculators/image/opencv_image_encoder_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/image_frame_opencv.h" @@ -61,7 +62,7 @@ absl::Status OpenCvImageEncoderCalculator::Process(CalculatorContext* cc) { const ImageFrame& image_frame = cc->Inputs().Index(0).Get<ImageFrame>(); - CHECK_EQ(1, image_frame.ByteDepth()); + ABSL_CHECK_EQ(1, image_frame.ByteDepth()); std::unique_ptr<OpenCvImageEncoderCalculatorResults> encoded_result = absl::make_unique<OpenCvImageEncoderCalculatorResults>();
diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc index d8a3cb93..128aa42 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_calculator.cc
@@ -18,6 +18,7 @@ #include <memory> #include <string> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/substitute.h" #include "libyuv/scale.h" @@ -507,7 +508,7 @@ absl::Status ScaleImageCalculator::ValidateYUVImage(CalculatorContext* cc, const YUVImage& yuv_image) { - CHECK_EQ(input_format_, ImageFormat::YCBCR420P); + ABSL_CHECK_EQ(input_format_, ImageFormat::YCBCR420P); if (!has_header_) { if (input_width_ != yuv_image.width() || input_height_ != yuv_image.height()) {
diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc index 86a53ff..e119a87 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/image/scale_image_utils.cc
@@ -18,6 +18,7 @@ #include <string> +#include "absl/log/absl_check.h" #include "absl/strings/str_split.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/ret_check.h" @@ -83,8 +84,8 @@ } } - CHECK_LE(*crop_width, input_width); - CHECK_LE(*crop_height, input_height); + ABSL_CHECK_LE(*crop_width, input_width); + ABSL_CHECK_LE(*crop_height, input_height); return absl::OkStatus(); }
diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc index 81732f9..9b4a262 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/image/segmentation_smoothing_calculator.cc
@@ -32,6 +32,7 @@ #endif // !MEDIAPIPE_DISABLE_GPU #if !MEDIAPIPE_DISABLE_OPENCV +#include "absl/log/absl_check.h" #include "mediapipe/framework/formats/image_frame_opencv.h" #include "mediapipe/framework/formats/image_opencv.h" #include "mediapipe/framework/port/opencv_core_inc.h" @@ -110,7 +111,7 @@ absl::Status SegmentationSmoothingCalculator::GetContract( CalculatorContract* cc) { - CHECK_GE(cc->Inputs().NumEntries(), 1); + ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); cc->Inputs().Tag(kCurrentMaskTag).Set<Image>(); cc->Inputs().Tag(kPreviousMaskTag).Set<Image>();
diff --git a/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc index e20621e..211c2840 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/image/set_alpha_calculator.cc
@@ -14,6 +14,7 @@ #include <memory> +#include "absl/log/absl_check.h" #include "mediapipe/calculators/image/set_alpha_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_options.pb.h" @@ -142,7 +143,7 @@ REGISTER_CALCULATOR(SetAlphaCalculator); absl::Status SetAlphaCalculator::GetContract(CalculatorContract* cc) { - CHECK_GE(cc->Inputs().NumEntries(), 1); + ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); bool use_gpu = false;
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc index 01cc60a..e8c9a6c 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/audio_to_tensor_calculator.cc
@@ -20,6 +20,7 @@ #include <utility> #include <vector> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" @@ -457,7 +458,7 @@ } void AudioToTensorCalculator::AppendZerosToSampleBuffer(int num_samples) { - CHECK_GE(num_samples, 0); // Ensured by `UpdateContract`. + ABSL_CHECK_GE(num_samples, 0); // Ensured by `UpdateContract`. if (num_samples == 0) { return; }
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc index c1bd9296..a9606e65 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensor_converter_calculator.cc
@@ -15,6 +15,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/calculators/tensor/tensor_converter_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/image_frame.h" @@ -582,7 +583,7 @@ if (options.has_output_tensor_float_range()) { output_range_.emplace(options.output_tensor_float_range().min(), options.output_tensor_float_range().max()); - CHECK_GT(output_range_->second, output_range_->first); + ABSL_CHECK_GT(output_range_->second, output_range_->first); } // Custom div and sub values. @@ -600,9 +601,9 @@ // Get desired way to handle input channels. max_num_channels_ = options.max_num_channels(); - CHECK_GE(max_num_channels_, 1); - CHECK_LE(max_num_channels_, 4); - CHECK_NE(max_num_channels_, 2); + ABSL_CHECK_GE(max_num_channels_, 1); + ABSL_CHECK_LE(max_num_channels_, 4); + ABSL_CHECK_NE(max_num_channels_, 2); return absl::OkStatus(); }
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc index 246269d..3e19ae5b 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_detections_calculator.cc
@@ -15,6 +15,7 @@ #include <unordered_map> #include <vector> +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "mediapipe/calculators/tensor/tensors_to_detections_calculator.pb.h" @@ -83,7 +84,7 @@ void ConvertAnchorsToRawValues(const std::vector<Anchor>& anchors, int num_boxes, float* raw_anchors) { - CHECK_EQ(anchors.size(), num_boxes); + ABSL_CHECK_EQ(anchors.size(), num_boxes); int box = 0; for (const auto& anchor : anchors) { raw_anchors[box * kNumCoordsPerBox + 0] = anchor.y_center(); @@ -703,18 +704,18 @@ num_boxes_ = options_.num_boxes(); num_coords_ = options_.num_coords(); box_output_format_ = GetBoxFormat(options_); - CHECK_NE(options_.max_results(), 0) + ABSL_CHECK_NE(options_.max_results(), 0) << "The maximum number of the top-scored detection results must be " "non-zero."; max_results_ = options_.max_results(); // Currently only support 2D when num_values_per_keypoint equals to 2. - CHECK_EQ(options_.num_values_per_keypoint(), 2); + ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); // Check if the output size is equal to the requested boxes and keypoints. - CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + - kNumCoordsPerBox, - num_coords_); + ABSL_CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + + kNumCoordsPerBox, + num_coords_); if (kSideInIgnoreClasses(cc).IsConnected()) { RET_CHECK(!kSideInIgnoreClasses(cc).IsEmpty()); @@ -1154,11 +1155,12 @@ } // TODO support better filtering. if (class_index_set_.is_allowlist) { - CHECK_EQ(class_index_set_.values.size(), - IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) + ABSL_CHECK_EQ(class_index_set_.values.size(), + IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) << "Only all classes >= class 0 or >= class 1"; } else { - CHECK_EQ(class_index_set_.values.size(), IsClassIndexAllowed(0) ? 0 : 1) + ABSL_CHECK_EQ(class_index_set_.values.size(), + IsClassIndexAllowed(0) ? 0 : 1) << "Only ignore class 0 is allowed"; } @@ -1379,11 +1381,12 @@ // TODO support better filtering. if (class_index_set_.is_allowlist) { - CHECK_EQ(class_index_set_.values.size(), - IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) + ABSL_CHECK_EQ(class_index_set_.values.size(), + IsClassIndexAllowed(0) ? num_classes_ : num_classes_ - 1) << "Only all classes >= class 0 or >= class 1"; } else { - CHECK_EQ(class_index_set_.values.size(), IsClassIndexAllowed(0) ? 0 : 1) + ABSL_CHECK_EQ(class_index_set_.values.size(), + IsClassIndexAllowed(0) ? 0 : 1) << "Only ignore class 0 is allowed"; }
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc index a1cc4e20..cfee6bad 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tensor/tensors_to_landmarks_calculator.cc
@@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "absl/log/absl_check.h" #include "mediapipe/calculators/tensor/tensors_to_landmarks_calculator.pb.h" #include "mediapipe/framework/api2/node.h" #include "mediapipe/framework/calculator_framework.h" @@ -142,7 +143,7 @@ RET_CHECK(input_tensors[0].element_type() == Tensor::ElementType::kFloat32); int num_values = input_tensors[0].shape().num_elements(); const int num_dimensions = num_values / num_landmarks_; - CHECK_GT(num_dimensions, 0); + ABSL_CHECK_GT(num_dimensions, 0); auto view = input_tensors[0].GetCpuReadView(); auto raw_landmarks = view.buffer<float>();
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc index cb90276..04c3ba1 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator.cc
@@ -15,6 +15,7 @@ // Converts a single int or vector<int> or vector<vector<int>> to 1D (or 2D) // tf::Tensor. +#include "absl/log/absl_check.h" #include "mediapipe/calculators/tensorflow/vector_int_to_tensor_calculator_options.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/port/ret_check.h" @@ -113,11 +114,11 @@ .Get<std::vector<std::vector<int>>>(); const int32_t rows = input.size(); - CHECK_GE(rows, 1); + ABSL_CHECK_GE(rows, 1); const int32_t cols = input[0].size(); - CHECK_GE(cols, 1); + ABSL_CHECK_GE(cols, 1); for (int i = 1; i < rows; ++i) { - CHECK_EQ(input[i].size(), cols); + ABSL_CHECK_EQ(input[i].size(), cols); } if (options_.transpose()) { tensor_shape = tf::TensorShape({cols, rows}); @@ -171,7 +172,7 @@ } else { input = cc->Inputs().Tag(kVectorInt).Value().Get<std::vector<int>>(); } - CHECK_GE(input.size(), 1); + ABSL_CHECK_GE(input.size(), 1); const int32_t length = input.size(); tensor_shape = tf::TensorShape({length}); auto output = ::absl::make_unique<tf::Tensor>(options_.tensor_data_type(),
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc index 5ed5a95d..e56765d94 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/ssd_anchors_calculator.cc
@@ -16,6 +16,7 @@ #include <utility> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/calculators/tflite/ssd_anchors_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/object_detection/anchor.pb.h" @@ -274,11 +275,11 @@ if (options.strides_size()) { LOG(ERROR) << "Found feature map shapes. Strides will be ignored."; } - CHECK_EQ(options.feature_map_height_size(), kNumLayers); - CHECK_EQ(options.feature_map_height_size(), - options.feature_map_width_size()); + ABSL_CHECK_EQ(options.feature_map_height_size(), kNumLayers); + ABSL_CHECK_EQ(options.feature_map_height_size(), + options.feature_map_width_size()); } else { - CHECK_EQ(options.strides_size(), kNumLayers); + ABSL_CHECK_EQ(options.strides_size(), kNumLayers); } if (options.multiscale_anchor_generation()) {
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc index ff6b2ff..7188cbc 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_converter_calculator.cc
@@ -15,6 +15,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/calculators/tflite/tflite_converter_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/image_frame.h" @@ -643,7 +644,7 @@ if (options.has_output_tensor_float_range()) { output_range_.emplace(options.output_tensor_float_range().min(), options.output_tensor_float_range().max()); - CHECK_GT(output_range_->second, output_range_->first); + ABSL_CHECK_GT(output_range_->second, output_range_->first); } // Custom div and sub values. @@ -661,9 +662,9 @@ // Get desired way to handle input channels. max_num_channels_ = options.max_num_channels(); - CHECK_GE(max_num_channels_, 1); - CHECK_LE(max_num_channels_, 4); - CHECK_NE(max_num_channels_, 2); + ABSL_CHECK_GE(max_num_channels_, 1); + ABSL_CHECK_LE(max_num_channels_, 4); + ABSL_CHECK_NE(max_num_channels_, 2); #if defined(MEDIAPIPE_IOS) if (cc->Inputs().HasTag(kGpuBufferTag)) // Currently on iOS, tflite gpu input tensor must be 4 channels,
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc index add9bb1..4b891332 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_inference_calculator.cc
@@ -17,6 +17,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "mediapipe/calculators/tflite/tflite_inference_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" @@ -109,8 +110,8 @@ edgetpu::EdgeTpuContext* edgetpu_context) { resolver->AddCustom(edgetpu::kCustomOp, edgetpu::RegisterCustomOp()); std::unique_ptr<tflite::Interpreter> interpreter; - CHECK_EQ(tflite::InterpreterBuilder(model, *resolver)(&interpreter), - kTfLiteOk); + ABSL_CHECK_EQ(tflite::InterpreterBuilder(model, *resolver)(&interpreter), + kTfLiteOk); interpreter->SetExternalContext(kTfLiteEdgeTpuContext, edgetpu_context); return interpreter; }
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc index 4d28b91e..98ab4b1d 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.cc
@@ -17,6 +17,7 @@ #include <vector> #include "absl/container/node_hash_map.h" +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "mediapipe/calculators/tflite/tflite_tensors_to_classification_calculator.pb.h" @@ -172,7 +173,7 @@ // Note that partial_sort will raise error when top_k_ > // classification_list->classification_size(). - CHECK_GE(classification_list->classification_size(), top_k_); + ABSL_CHECK_GE(classification_list->classification_size(), top_k_); auto raw_classification_list = classification_list->mutable_classification(); if (top_k_ > 0 && classification_list->classification_size() >= top_k_) { std::partial_sort(raw_classification_list->begin(),
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc index 2ed62c4..2d91f54 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.cc
@@ -15,6 +15,7 @@ #include <unordered_map> #include <vector> +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "mediapipe/calculators/tflite/tflite_tensors_to_detections_calculator.pb.h" @@ -93,7 +94,7 @@ void ConvertAnchorsToRawValues(const std::vector<Anchor>& anchors, int num_boxes, float* raw_anchors) { - CHECK_EQ(anchors.size(), num_boxes); + ABSL_CHECK_EQ(anchors.size(), num_boxes); int box = 0; for (const auto& anchor : anchors) { raw_anchors[box * kNumCoordsPerBox + 0] = anchor.y_center(); @@ -288,14 +289,14 @@ const TfLiteTensor* raw_score_tensor = &input_tensors[1]; // TODO: Add flexible input tensor size handling. - CHECK_EQ(raw_box_tensor->dims->size, 3); - CHECK_EQ(raw_box_tensor->dims->data[0], 1); - CHECK_EQ(raw_box_tensor->dims->data[1], num_boxes_); - CHECK_EQ(raw_box_tensor->dims->data[2], num_coords_); - CHECK_EQ(raw_score_tensor->dims->size, 3); - CHECK_EQ(raw_score_tensor->dims->data[0], 1); - CHECK_EQ(raw_score_tensor->dims->data[1], num_boxes_); - CHECK_EQ(raw_score_tensor->dims->data[2], num_classes_); + ABSL_CHECK_EQ(raw_box_tensor->dims->size, 3); + ABSL_CHECK_EQ(raw_box_tensor->dims->data[0], 1); + ABSL_CHECK_EQ(raw_box_tensor->dims->data[1], num_boxes_); + ABSL_CHECK_EQ(raw_box_tensor->dims->data[2], num_coords_); + ABSL_CHECK_EQ(raw_score_tensor->dims->size, 3); + ABSL_CHECK_EQ(raw_score_tensor->dims->data[0], 1); + ABSL_CHECK_EQ(raw_score_tensor->dims->data[1], num_boxes_); + ABSL_CHECK_EQ(raw_score_tensor->dims->data[2], num_classes_); const float* raw_boxes = raw_box_tensor->data.f; const float* raw_scores = raw_score_tensor->data.f; @@ -303,9 +304,9 @@ if (!anchors_init_) { if (input_tensors.size() == kNumInputTensorsWithAnchors) { const TfLiteTensor* anchor_tensor = &input_tensors[2]; - CHECK_EQ(anchor_tensor->dims->size, 2); - CHECK_EQ(anchor_tensor->dims->data[0], num_boxes_); - CHECK_EQ(anchor_tensor->dims->data[1], kNumCoordsPerBox); + ABSL_CHECK_EQ(anchor_tensor->dims->size, 2); + ABSL_CHECK_EQ(anchor_tensor->dims->data[0], num_boxes_); + ABSL_CHECK_EQ(anchor_tensor->dims->data[1], kNumCoordsPerBox); const float* raw_anchors = anchor_tensor->data.f; ConvertRawValuesToAnchors(raw_anchors, num_boxes_, &anchors_); } else if (side_packet_anchors_) { @@ -417,7 +418,7 @@ MP_RETURN_IF_ERROR(gpu_data_->raw_anchors_buffer.Write<float>( absl::MakeSpan(raw_anchors))); } else { - CHECK_EQ(input_tensors.size(), kNumInputTensorsWithAnchors); + ABSL_CHECK_EQ(input_tensors.size(), kNumInputTensorsWithAnchors); MP_RETURN_IF_ERROR( CopyBuffer(input_tensors[2], gpu_data_->raw_anchors_buffer)); } @@ -567,12 +568,12 @@ num_coords_ = options_.num_coords(); // Currently only support 2D when num_values_per_keypoint equals to 2. - CHECK_EQ(options_.num_values_per_keypoint(), 2); + ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); // Check if the output size is equal to the requested boxes and keypoints. - CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + - kNumCoordsPerBox, - num_coords_); + ABSL_CHECK_EQ(options_.num_keypoints() * options_.num_values_per_keypoint() + + kNumCoordsPerBox, + num_coords_); for (int i = 0; i < options_.ignore_classes_size(); ++i) { ignore_classes_.insert(options_.ignore_classes(i)); @@ -897,10 +898,11 @@ int max_wg_size; // typically <= 1024 glGetIntegeri_v(GL_MAX_COMPUTE_WORK_GROUP_SIZE, 1, &max_wg_size); // y-dim - CHECK_LT(num_classes_, max_wg_size) + ABSL_CHECK_LT(num_classes_, max_wg_size) << "# classes must be < " << max_wg_size; // TODO support better filtering. - CHECK_LE(ignore_classes_.size(), 1) << "Only ignore class 0 is allowed"; + ABSL_CHECK_LE(ignore_classes_.size(), 1) + << "Only ignore class 0 is allowed"; // Shader program GlShader score_shader; @@ -1115,7 +1117,7 @@ ignore_classes_.size() ? 1 : 0); // TODO support better filtering. - CHECK_LE(ignore_classes_.size(), 1) << "Only ignore class 0 is allowed"; + ABSL_CHECK_LE(ignore_classes_.size(), 1) << "Only ignore class 0 is allowed"; { // Shader program @@ -1147,7 +1149,8 @@ options:MTLResourceStorageModeShared]; // # filter classes supported is hardware dependent. int max_wg_size = gpu_data_->score_program.maxTotalThreadsPerThreadgroup; - CHECK_LT(num_classes_, max_wg_size) << "# classes must be <" << max_wg_size; + ABSL_CHECK_LT(num_classes_, max_wg_size) + << "# classes must be <" << max_wg_size; } #endif // MEDIAPIPE_TFLITE_GL_INFERENCE
diff --git a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc index 1be83bb..6740f0a 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.cc
@@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "absl/log/absl_check.h" #include "mediapipe/calculators/tflite/tflite_tensors_to_landmarks_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/landmark.pb.h" @@ -199,7 +200,7 @@ num_values *= raw_tensor->dims->data[i]; } const int num_dimensions = num_values / num_landmarks_; - CHECK_GT(num_dimensions, 0); + ABSL_CHECK_GT(num_dimensions, 0); const float* raw_landmarks = raw_tensor->data.f;
diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc index 34093702..fbd24ee 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/util/annotation_overlay_calculator.cc
@@ -14,6 +14,7 @@ #include <memory> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/calculators/util/annotation_overlay_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" @@ -172,7 +173,7 @@ REGISTER_CALCULATOR(AnnotationOverlayCalculator); absl::Status AnnotationOverlayCalculator::GetContract(CalculatorContract* cc) { - CHECK_GE(cc->Inputs().NumEntries(), 1); + ABSL_CHECK_GE(cc->Inputs().NumEntries(), 1); bool use_gpu = false;
diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h b/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h index 037ea83..1cec63c 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h +++ b/third_party/mediapipe/src/mediapipe/calculators/util/association_calculator.h
@@ -18,6 +18,7 @@ #include <memory> #include <vector> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "mediapipe/calculators/util/association_calculator.pb.h" #include "mediapipe/framework/calculator_context.h" @@ -72,7 +73,7 @@ prev_input_stream_id_ = cc->Inputs().GetId("PREV", 0); } options_ = cc->Options<::mediapipe::AssociationCalculatorOptions>(); - CHECK_GE(options_.min_similarity_threshold(), 0); + ABSL_CHECK_GE(options_.min_similarity_threshold(), 0); return absl::OkStatus(); }
diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc index 25d74ba..7343009 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/util/detections_to_render_data_calculator.cc
@@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" @@ -239,7 +240,7 @@ "is present."; const auto num_labels = std::max(detection.label_size(), detection.label_id_size()); - CHECK_EQ(detection.score_size(), num_labels) + ABSL_CHECK_EQ(detection.score_size(), num_labels) << "Number of scores and labels should match for detection."; // Extracts all "label(_id),score" for the detection.
diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc index dcd76d4..314640e 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/util/labels_to_render_data_calculator.cc
@@ -19,6 +19,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/calculators/util/labels_to_render_data_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" @@ -114,7 +115,8 @@ video_height_ = video_header.height; return absl::OkStatus(); } else { - CHECK_EQ(options_.location(), LabelsToRenderDataCalculatorOptions::TOP_LEFT) + ABSL_CHECK_EQ(options_.location(), + LabelsToRenderDataCalculatorOptions::TOP_LEFT) << "Only TOP_LEFT is supported without VIDEO_PRESTREAM."; } @@ -144,7 +146,7 @@ if (cc->Inputs().HasTag(kScoresTag)) { std::vector<float> score_vector = cc->Inputs().Tag(kScoresTag).Get<std::vector<float>>(); - CHECK_EQ(label_vector.size(), score_vector.size()); + ABSL_CHECK_EQ(label_vector.size(), score_vector.size()); scores.resize(label_vector.size()); for (int i = 0; i < label_vector.size(); ++i) { scores[i] = score_vector[i];
diff --git a/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc index 535e2a7..1bab7af 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/util/non_max_suppression_calculator.cc
@@ -18,6 +18,7 @@ #include <utility> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/calculators/util/non_max_suppression_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/detection.pb.h" @@ -171,9 +172,9 @@ cc->SetOffset(TimestampDiff(0)); options_ = cc->Options<NonMaxSuppressionCalculatorOptions>(); - CHECK_GT(options_.num_detection_streams(), 0) + ABSL_CHECK_GT(options_.num_detection_streams(), 0) << "At least one detection stream need to be specified."; - CHECK_NE(options_.max_num_detections(), 0) + ABSL_CHECK_NE(options_.max_num_detections(), 0) << "max_num_detections=0 is not a valid value. Please choose a " << "positive number of you want to limit the number of output " << "detections, or set -1 if you do not want any limit.";
diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc index 14ac12e5..4767d4d 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/video/box_detector_calculator.cc
@@ -17,6 +17,7 @@ #include <memory> #include <unordered_set> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/numbers.h" #include "mediapipe/calculators/video/box_detector_calculator.pb.h" @@ -359,7 +360,7 @@ const auto& descriptors = descriptor_stream->Get<std::vector<float>>(); const int dims = options_.detector_options().descriptor_dims(); - CHECK_GE(descriptors.size(), feature_size * dims); + ABSL_CHECK_GE(descriptors.size(), feature_size * dims); cv::Mat descriptors_mat(feature_size, dims, CV_32F); for (int j = 0; j < feature_size; ++j) { features_vec[j].Set(features[j].pt.x * inv_scale,
diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc index b5f3b5b..c71e6857 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/video/box_tracker_calculator.cc
@@ -22,6 +22,7 @@ #include "absl/container/flat_hash_set.h" #include "absl/container/node_hash_map.h" #include "absl/container/node_hash_set.h" +#include "absl/log/absl_check.h" #include "absl/strings/numbers.h" #include "mediapipe/calculators/video/box_tracker_calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" @@ -323,8 +324,8 @@ const float in_center_y = (in_top + in_bottom) * 0.5f; const float in_width = in_right - in_left; const float in_height = in_bottom - in_top; - CHECK_GT(in_width, 0); - CHECK_GT(in_height, 0); + ABSL_CHECK_GT(in_width, 0); + ABSL_CHECK_GT(in_height, 0); float out_center_x; float out_center_y; float out_width; @@ -999,7 +1000,7 @@ const int init_frame = timestamp_pos - track_timestamps_.begin() + track_timestamps_base_index_; - CHECK_GE(init_frame, 0); + ABSL_CHECK_GE(init_frame, 0); MotionBoxMap single_map = PrepareRandomAccessTrack(start, init_frame, forward_track, start_data); @@ -1233,7 +1234,7 @@ // Start at previous frame. const int init_frame = timestamp_pos - track_timestamps_.begin() + track_timestamps_base_index_; - CHECK_GE(init_frame, 0); + ABSL_CHECK_GE(init_frame, 0); // Locate corresponding tracking data. auto start_data = std::find_if(
diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc index 2965cd8..f30fed88b 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/video/flow_packager_calculator.cc
@@ -17,6 +17,7 @@ #include <fstream> #include <memory> +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" #include "absl/strings/string_view.h" #include "mediapipe/calculators/video/flow_packager_calculator.pb.h" @@ -160,7 +161,7 @@ timestamp.Value() / 1000 / options_.caching_chunk_size_msec(); tracking_chunk_.set_first_chunk(true); } - CHECK_GE(chunk_idx_, 0); + ABSL_CHECK_GE(chunk_idx_, 0); TrackingDataChunk::Item* item = tracking_chunk_.add_item(); item->set_frame_idx(frame_idx_);
diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc index 544439ae..fe320b1 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/video/motion_analysis_calculator.cc
@@ -17,6 +17,7 @@ #include <memory> #include <string> +#include "absl/log/absl_check.h" #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" @@ -620,7 +621,7 @@ const int num_results = motion_analysis_->GetResults( flush, &features, &camera_motions, with_saliency_ ? &saliency : nullptr); - CHECK_LE(num_results, buffer_size); + ABSL_CHECK_LE(num_results, buffer_size); if (num_results == 0) { return; @@ -695,7 +696,7 @@ if (hybrid_meta_analysis_) { hybrid_meta_offset_ -= num_results; - CHECK_GE(hybrid_meta_offset_, 0); + ABSL_CHECK_GE(hybrid_meta_offset_, 0); } timestamp_buffer_.erase(timestamp_buffer_.begin(), @@ -901,7 +902,7 @@ const CameraMotion& meta_motion, const RegionFlowFeatureList& meta_features, RegionFlowFeatureList* features, CameraMotion* motion) { // Restore old feature location. - CHECK_EQ(meta_features.feature_size(), features->feature_size()); + ABSL_CHECK_EQ(meta_features.feature_size(), features->feature_size()); for (int k = 0; k < meta_features.feature_size(); ++k) { auto feature = features->mutable_feature(k); const auto& meta_feature = meta_features.feature(k); @@ -947,8 +948,9 @@ } const int models_per_frame = options_.meta_models_per_frame(); - CHECK_GT(models_per_frame, 0) << "At least one model per frame is needed"; - CHECK_EQ(0, homographies.size() % models_per_frame); + ABSL_CHECK_GT(models_per_frame, 0) + << "At least one model per frame is needed"; + ABSL_CHECK_EQ(0, homographies.size() % models_per_frame); const int num_frames = homographies.size() / models_per_frame; // Heuristic sigma, similar to what we use for rolling shutter removal.
diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc b/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc index f0b0006..146dc4a 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/video/tool/flow_quantizer_model.cc
@@ -14,6 +14,7 @@ #include "mediapipe/calculators/video/tool/flow_quantizer_model.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/type_map.h" @@ -21,7 +22,7 @@ // Uniform normalization to 0-255. uint8_t FlowQuantizerModel::Apply(const float val, const int channel) const { - CHECK_LT(channel, model_.min_value_size()); + ABSL_CHECK_LT(channel, model_.min_value_size()); const auto& min_value = model_.min_value(channel); const auto& max_value = model_.max_value(channel); QCHECK_GT(max_value, min_value); @@ -51,7 +52,7 @@ // TODO: Taking the min and max over all training flow fields might be // sensitive to noise. We should use more robust statistics. void FlowQuantizerModel::AddSampleFlowField(const OpticalFlowField& flow) { - CHECK_EQ(model_.min_value_size(), 2); + ABSL_CHECK_EQ(model_.min_value_size(), 2); const cv::Mat_<cv::Point2f>& flow_mat = flow.flow_data(); for (int i = 0; i != flow.width(); ++i) { for (int j = 0; j != flow.height(); ++j) {
diff --git a/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc b/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc index 56f3253..dd87ae6 100644 --- a/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/calculators/video/tvl1_optical_flow_calculator.cc
@@ -13,6 +13,7 @@ // limitations under the License. #include "absl/base/macros.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/image_frame.h" @@ -182,7 +183,7 @@ flow->Allocate(first.cols, first.rows); cv::Mat cv_flow(flow->mutable_flow_data()); tvl1_computer->calc(first, second, cv_flow); - CHECK_EQ(flow->mutable_flow_data().data, cv_flow.data); + ABSL_CHECK_EQ(flow->mutable_flow_data().data, cv_flow.data); // Inserts the idle DenseOpticalFlow object back to the cache for reuse. { absl::MutexLock lock(&mutex_);
diff --git a/third_party/mediapipe/src/mediapipe/framework/api2/builder.h b/third_party/mediapipe/src/mediapipe/framework/api2/builder.h index 0c4c82f..89f25c7 100644 --- a/third_party/mediapipe/src/mediapipe/framework/api2/builder.h +++ b/third_party/mediapipe/src/mediapipe/framework/api2/builder.h
@@ -11,6 +11,7 @@ #include <vector> #include "absl/container/btree_map.h" +#include "absl/log/absl_check.h" #include "absl/strings/string_view.h" #include "google/protobuf/message_lite.h" #include "mediapipe/framework/api2/port.h" @@ -109,7 +110,7 @@ : Single(vec), vec_(*vec) {} Single operator[](int index) { - CHECK_GE(index, 0); + ABSL_CHECK_GE(index, 0); return Single{&GetWithAutoGrow(&vec_, index)}; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/api2/packet.h b/third_party/mediapipe/src/mediapipe/framework/api2/packet.h index c059a988..f231f4c 100644 --- a/third_party/mediapipe/src/mediapipe/framework/api2/packet.h +++ b/third_party/mediapipe/src/mediapipe/framework/api2/packet.h
@@ -13,6 +13,7 @@ #include <functional> #include <type_traits> +#include "absl/log/absl_check.h" #include "absl/meta/type_traits.h" #include "mediapipe/framework/api2/tuple.h" #include "mediapipe/framework/packet.h" @@ -102,9 +103,9 @@ template <typename T> inline const T& PacketBase::Get() const { - CHECK(payload_); + ABSL_CHECK(payload_); packet_internal::Holder<T>* typed_payload = payload_->As<T>(); - CHECK(typed_payload) << absl::StrCat( + ABSL_CHECK(typed_payload) << absl::StrCat( "The Packet stores \"", payload_->DebugTypeName(), "\", but \"", MediaPipeTypeStringOrDemangled<T>(), "\" was requested."); return typed_payload->data(); @@ -134,17 +135,17 @@ template <class T> inline void CheckCompatibleType(const HolderBase& holder, internal::Wrap<T>) { const packet_internal::Holder<T>* typed_payload = holder.As<T>(); - CHECK(typed_payload) << absl::StrCat( + ABSL_CHECK(typed_payload) << absl::StrCat( "The Packet stores \"", holder.DebugTypeName(), "\", but \"", MediaPipeTypeStringOrDemangled<T>(), "\" was requested."); - // CHECK(payload_->has_type<T>()); + // ABSL_CHECK(payload_->has_type<T>()); } template <class... T> inline void CheckCompatibleType(const HolderBase& holder, internal::Wrap<OneOf<T...>>) { bool compatible = (holder.As<T>() || ...); - CHECK(compatible) + ABSL_CHECK(compatible) << "The Packet stores \"" << holder.DebugTypeName() << "\", but one of " << absl::StrJoin( {absl::StrCat("\"", MediaPipeTypeStringOrDemangled<T>(), "\"")...}, @@ -211,9 +212,9 @@ Packet<T> At(Timestamp timestamp) &&; const T& Get() const { - CHECK(payload_); + ABSL_CHECK(payload_); packet_internal::Holder<T>* typed_payload = payload_->As<T>(); - CHECK(typed_payload); + ABSL_CHECK(typed_payload); return typed_payload->data(); } const T& operator*() const { return Get(); } @@ -330,9 +331,9 @@ template <class U, class = AllowedType<U>> const U& Get() const { - CHECK(payload_); + ABSL_CHECK(payload_); packet_internal::Holder<U>* typed_payload = payload_->As<U>(); - CHECK(typed_payload); + ABSL_CHECK(typed_payload); return typed_payload->data(); } @@ -343,7 +344,7 @@ template <class... F> auto Visit(const F&... args) const { - CHECK(payload_); + ABSL_CHECK(payload_); auto f = internal::Overload{args...}; using FirstT = typename internal::First<T...>::type; using ResultType = absl::result_of_t<decltype(f)(const FirstT&)>; @@ -364,7 +365,7 @@ template <class... F> auto ConsumeAndVisit(const F&... args) { - CHECK(payload_); + ABSL_CHECK(payload_); auto f = internal::Overload{args...}; using FirstT = typename internal::First<T...>::type; using VisitorResultType =
diff --git a/third_party/mediapipe/src/mediapipe/framework/api2/port.h b/third_party/mediapipe/src/mediapipe/framework/api2/port.h index 18a7860..075e884 100644 --- a/third_party/mediapipe/src/mediapipe/framework/api2/port.h +++ b/third_party/mediapipe/src/mediapipe/framework/api2/port.h
@@ -20,6 +20,7 @@ #include <type_traits> #include <utility> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "mediapipe/framework/api2/const_str.h" @@ -243,8 +244,8 @@ // container? int Count() { return count_; } AccessT operator[](int pos) { - CHECK_GE(pos, 0); - CHECK_LT(pos, count_); + ABSL_CHECK_GE(pos, 0); + ABSL_CHECK_LT(pos, count_); return SinglePortAccess<ValueT>(cc_, &first_[pos]); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_context.h b/third_party/mediapipe/src/mediapipe/framework/calculator_context.h index 9568ba74..315d265 100644 --- a/third_party/mediapipe/src/mediapipe/framework/calculator_context.h +++ b/third_party/mediapipe/src/mediapipe/framework/calculator_context.h
@@ -20,6 +20,7 @@ #include <string> #include <utility> +#include "absl/log/absl_check.h" #include "mediapipe/framework/calculator_state.h" #include "mediapipe/framework/counter.h" #include "mediapipe/framework/graph_service.h" @@ -147,7 +148,7 @@ } void PopInputTimestamp() { - CHECK(!input_timestamps_.empty()); + ABSL_CHECK(!input_timestamps_.empty()); input_timestamps_.pop(); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h b/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h index 6b988b03..ae697e1 100644 --- a/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h +++ b/third_party/mediapipe/src/mediapipe/framework/calculator_context_manager.h
@@ -21,6 +21,7 @@ #include <memory> #include "absl/base/thread_annotations.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/calculator_context.h" #include "mediapipe/framework/calculator_state.h" @@ -97,18 +98,18 @@ void PushInputTimestampToContext(CalculatorContext* calculator_context, Timestamp input_timestamp) { - CHECK(calculator_context); + ABSL_CHECK(calculator_context); calculator_context->PushInputTimestamp(input_timestamp); } void PopInputTimestampFromContext(CalculatorContext* calculator_context) { - CHECK(calculator_context); + ABSL_CHECK(calculator_context); calculator_context->PopInputTimestamp(); } void SetGraphStatusInContext(CalculatorContext* calculator_context, const absl::Status& status) { - CHECK(calculator_context); + ABSL_CHECK(calculator_context); calculator_context->SetGraphStatus(status); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc b/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc index 33ca41fb..770f8337 100644 --- a/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc +++ b/third_party/mediapipe/src/mediapipe/framework/calculator_graph.cc
@@ -25,6 +25,7 @@ #include "absl/container/fixed_array.h" #include "absl/container/flat_hash_set.h" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" @@ -904,7 +905,7 @@ "graph input stream.", stream_name); int node_id = mediapipe::FindOrDie(graph_input_stream_node_ids_, stream_name); - CHECK_GE(node_id, validated_graph_->CalculatorInfos().size()); + ABSL_CHECK_GE(node_id, validated_graph_->CalculatorInfos().size()); { absl::MutexLock lock(&full_input_streams_mutex_); if (full_input_streams_.empty()) { @@ -1155,10 +1156,10 @@ .set_stream_id(&stream->Name())); bool was_throttled = !full_input_streams_[node_id].empty(); if (stream_is_full) { - DCHECK_EQ(full_input_streams_[node_id].count(stream), 0); + ABSL_DCHECK_EQ(full_input_streams_[node_id].count(stream), 0); full_input_streams_[node_id].insert(stream); } else { - DCHECK_EQ(full_input_streams_[node_id].count(stream), 1); + ABSL_DCHECK_EQ(full_input_streams_[node_id].count(stream), 1); full_input_streams_[node_id].erase(stream); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc b/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc index f6a1c7d..5618038 100644 --- a/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc +++ b/third_party/mediapipe/src/mediapipe/framework/calculator_node.cc
@@ -19,6 +19,7 @@ #include <unordered_map> #include <utility> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" @@ -341,7 +342,7 @@ void CalculatorNode::SetExecutor(const std::string& executor) { absl::MutexLock status_lock(&status_mutex_); - CHECK_LT(status_, kStateOpened); + ABSL_CHECK_LT(status_, kStateOpened); executor_ = executor; } @@ -539,7 +540,7 @@ void CalculatorNode::ActivateNode() { absl::MutexLock status_lock(&status_mutex_); - CHECK_EQ(status_, kStateOpened) << DebugName(); + ABSL_CHECK_EQ(status_, kStateOpened) << DebugName(); status_ = kStateActive; } @@ -694,7 +695,7 @@ bool ready_for_open = false; { absl::MutexLock lock(&status_mutex_); - CHECK_EQ(status_, kStatePrepared) << DebugName(); + ABSL_CHECK_EQ(status_, kStatePrepared) << DebugName(); CHECK(!input_stream_headers_ready_called_); input_stream_headers_ready_called_ = true; input_stream_headers_ready_ = true; @@ -709,7 +710,7 @@ bool ready_for_open = false; { absl::MutexLock lock(&status_mutex_); - CHECK_EQ(status_, kStatePrepared) << DebugName(); + ABSL_CHECK_EQ(status_, kStatePrepared) << DebugName(); CHECK(!input_side_packets_ready_called_); input_side_packets_ready_called_ = true; input_side_packets_ready_ = true; @@ -760,7 +761,7 @@ return; } --current_in_flight_; - CHECK_GE(current_in_flight_, 0); + ABSL_CHECK_GE(current_in_flight_, 0); if (scheduling_state_ == kScheduling) { // Changes the state to scheduling pending if another thread is doing the @@ -893,9 +894,9 @@ // open input streams for Process(). So this node needs to be closed // too. // If the streams are closed, there shouldn't be more input. - CHECK_EQ(calculator_context_manager_.NumberOfContextTimestamps( - *calculator_context), - 1); + ABSL_CHECK_EQ(calculator_context_manager_.NumberOfContextTimestamps( + *calculator_context), + 1); return CloseNode(absl::OkStatus(), /*graph_run_ended=*/false); } else { RET_CHECK_FAIL()
diff --git a/third_party/mediapipe/src/mediapipe/framework/collection.h b/third_party/mediapipe/src/mediapipe/framework/collection.h index c7b6fb0d..a2ab39f 100644 --- a/third_party/mediapipe/src/mediapipe/framework/collection.h +++ b/third_party/mediapipe/src/mediapipe/framework/collection.h
@@ -24,6 +24,7 @@ #include <vector> #include "absl/base/macros.h" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" @@ -413,16 +414,16 @@ template <typename T, CollectionStorage storage, typename ErrorHandler> typename Collection<T, storage, ErrorHandler>::value_type& Collection<T, storage, ErrorHandler>::Get(CollectionItemId id) { - CHECK_LE(BeginId(), id); - CHECK_LT(id, EndId()); + ABSL_CHECK_LE(BeginId(), id); + ABSL_CHECK_LT(id, EndId()); return begin()[id.value()]; } template <typename T, CollectionStorage storage, typename ErrorHandler> const typename Collection<T, storage, ErrorHandler>::value_type& Collection<T, storage, ErrorHandler>::Get(CollectionItemId id) const { - CHECK_LE(BeginId(), id); - CHECK_LT(id, EndId()); + ABSL_CHECK_LE(BeginId(), id); + ABSL_CHECK_LT(id, EndId()); return begin()[id.value()]; } @@ -433,8 +434,8 @@ "mediapipe::internal::Collection<T>::GetPtr() is only " "available for collections that were defined with template " "argument storage == CollectionStorage::kStorePointer."); - CHECK_LE(BeginId(), id); - CHECK_LT(id, EndId()); + ABSL_CHECK_LE(BeginId(), id); + ABSL_CHECK_LT(id, EndId()); return data_[id.value()]; } @@ -445,8 +446,8 @@ "mediapipe::internal::Collection<T>::GetPtr() is only " "available for collections that were defined with template " "argument storage == CollectionStorage::kStorePointer."); - CHECK_LE(BeginId(), id); - CHECK_LT(id, EndId()); + ABSL_CHECK_LE(BeginId(), id); + ABSL_CHECK_LT(id, EndId()); return data_[id.value()]; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h b/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h index 315b78c..24543d4 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h +++ b/third_party/mediapipe/src/mediapipe/framework/deps/mathutil.h
@@ -23,6 +23,7 @@ #include <limits> #include <type_traits> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" @@ -364,7 +365,7 @@ // absolute margin of error. template <typename T> static bool WithinMargin(const T x, const T y, const T margin) { - DCHECK_GE(margin, 0); + ABSL_DCHECK_GE(margin, 0); return (std::abs(x) <= std::abs(y) + margin) && (std::abs(x) >= std::abs(y) - margin); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc b/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc index 503ef5cf..e3cc9de 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc +++ b/third_party/mediapipe/src/mediapipe/framework/deps/monotonic_clock.cc
@@ -16,6 +16,7 @@ #include "absl/base/macros.h" #include "absl/base/thread_annotations.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "absl/time/time.h" #include "mediapipe/framework/port/logging.h" @@ -80,7 +81,7 @@ absl::MutexLock m(&state_->lock); // Check consistency of internal data with state_. - CHECK_LE(last_raw_time_, state_->max_time) + ABSL_CHECK_LE(last_raw_time_, state_->max_time) << "non-monotonic behavior: last_raw_time_=" << last_raw_time_ << ", max_time=" << state_->max_time; @@ -107,7 +108,7 @@ // First, update correction metrics. ++correction_count_; absl::Duration delta = state_->max_time - raw_time; - CHECK_LT(absl::ZeroDuration(), delta); + ABSL_CHECK_LT(absl::ZeroDuration(), delta); if (delta > max_correction_) { max_correction_ = delta; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/registration.h b/third_party/mediapipe/src/mediapipe/framework/deps/registration.h index c67f073..9abc30ee 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/registration.h +++ b/third_party/mediapipe/src/mediapipe/framework/deps/registration.h
@@ -28,6 +28,7 @@ #include "absl/base/thread_annotations.h" #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" +#include "absl/log/absl_check.h" #include "absl/meta/type_traits.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" @@ -270,7 +271,7 @@ if (names[0].empty()) { names.erase(names.begin()); } else { - CHECK_EQ(1u, names.size()) + ABSL_CHECK_EQ(1u, names.size()) << "A registered class name must be either fully qualified " << "with a leading :: or unqualified, got: " << name << "."; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h b/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h index f6dbb931..8b717cb 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h +++ b/third_party/mediapipe/src/mediapipe/framework/deps/safe_int.h
@@ -44,6 +44,7 @@ #include <limits> #include <type_traits> +#include "absl/log/absl_check.h" #include "mediapipe/framework/deps/strong_int.h" #include "mediapipe/framework/port/logging.h" @@ -67,17 +68,17 @@ // Check that the underlying integral type provides a range that is // compatible with two's complement. if (std::numeric_limits<T>::is_signed) { - CHECK_EQ(-1, - std::numeric_limits<T>::min() + std::numeric_limits<T>::max()) + ABSL_CHECK_EQ( + -1, std::numeric_limits<T>::min() + std::numeric_limits<T>::max()) << "unexpected integral bounds"; } // Check that division truncates towards 0 (implementation defined in // C++'03, but standard in C++'11). - CHECK_EQ(12, 127 / 10) << "division does not truncate towards 0"; - CHECK_EQ(-12, -127 / 10) << "division does not truncate towards 0"; - CHECK_EQ(-12, 127 / -10) << "division does not truncate towards 0"; - CHECK_EQ(12, -127 / -10) << "division does not truncate towards 0"; + ABSL_CHECK_EQ(12, 127 / 10) << "division does not truncate towards 0"; + ABSL_CHECK_EQ(-12, -127 / 10) << "division does not truncate towards 0"; + ABSL_CHECK_EQ(-12, 127 / -10) << "division does not truncate towards 0"; + ABSL_CHECK_EQ(12, -127 / -10) << "division does not truncate towards 0"; } public:
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc b/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc index d9c32d3..9610f374 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc +++ b/third_party/mediapipe/src/mediapipe/framework/deps/threadpool_pthread_impl.cc
@@ -18,6 +18,7 @@ #include <sys/syscall.h> #include <unistd.h> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "mediapipe/framework/deps/threadpool.h" @@ -48,7 +49,7 @@ const std::string& name_prefix) : pool_(pool), name_prefix_(name_prefix) { int res = pthread_create(&thread_, nullptr, ThreadBody, this); - CHECK_EQ(res, 0) << "pthread_create failed"; + ABSL_CHECK_EQ(res, 0) << "pthread_create failed"; } ThreadPool::WorkerThread::~WorkerThread() {}
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc b/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc index 67fc6ad..65cd825 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc +++ b/third_party/mediapipe/src/mediapipe/framework/deps/topologicalsorter.cc
@@ -16,12 +16,13 @@ #include <algorithm> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" namespace mediapipe { TopologicalSorter::TopologicalSorter(int num_nodes) : num_nodes_(num_nodes) { - CHECK_GE(num_nodes_, 0); + ABSL_CHECK_GE(num_nodes_, 0); adjacency_lists_.resize(num_nodes_); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/deps/vector.h b/third_party/mediapipe/src/mediapipe/framework/deps/vector.h index 2d4de82..5775753 100644 --- a/third_party/mediapipe/src/mediapipe/framework/deps/vector.h +++ b/third_party/mediapipe/src/mediapipe/framework/deps/vector.h
@@ -24,6 +24,7 @@ #include <limits> #include <type_traits> +#include "absl/log/absl_check.h" #include "absl/utility/utility.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" @@ -78,13 +79,13 @@ void Clear() { AsD() = D(); } T& operator[](int b) { - DCHECK_GE(b, 0); - DCHECK_LT(b, SIZE); + ABSL_DCHECK_GE(b, 0); + ABSL_DCHECK_LT(b, SIZE); return static_cast<D&>(*this).Data()[b]; } T operator[](int b) const { - DCHECK_GE(b, 0); - DCHECK_LT(b, SIZE); + ABSL_DCHECK_GE(b, 0); + ABSL_DCHECK_LT(b, SIZE); return static_cast<const D&>(*this).Data()[b]; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h b/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h index 21a5f53..4ebf3c6 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h +++ b/third_party/mediapipe/src/mediapipe/framework/formats/frame_buffer.h
@@ -18,6 +18,7 @@ #include <vector> +#include "absl/log/absl_check.h" #include "absl/log/check.h" #include "absl/status/statusor.h" #include "mediapipe/framework/port/integral_types.h" @@ -147,15 +148,15 @@ // Returns plane indexed by the input `index`. const Plane& plane(int index) const { - CHECK_GE(index, 0); - CHECK_LT(static_cast<size_t>(index), planes_.size()); + ABSL_CHECK_GE(index, 0); + ABSL_CHECK_LT(static_cast<size_t>(index), planes_.size()); return planes_[index]; } // Returns mutable plane indexed by the input `index`. Plane mutable_plane(int index) { - CHECK_GE(index, 0); - CHECK_LT(static_cast<size_t>(index), planes_.size()); + ABSL_CHECK_GE(index, 0); + ABSL_CHECK_LT(static_cast<size_t>(index), planes_.size()); return planes_[index]; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc b/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc index 2de819a..458d130 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc +++ b/third_party/mediapipe/src/mediapipe/framework/formats/image_frame.cc
@@ -23,6 +23,7 @@ #include <algorithm> #include <utility> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/framework/formats/image_format.pb.h" #include "mediapipe/framework/port/aligned_malloc_and_free.h" @@ -98,7 +99,7 @@ format_ = format; width_ = width; height_ = height; - CHECK_NE(ImageFormat::UNKNOWN, format_); + ABSL_CHECK_NE(ImageFormat::UNKNOWN, format_); CHECK(IsValidAlignmentNumber(alignment_boundary)); width_step_ = width * NumberOfChannels() * ByteDepth(); if (alignment_boundary == 1) { @@ -124,8 +125,8 @@ height_ = height; width_step_ = width_step; - CHECK_NE(ImageFormat::UNKNOWN, format_); - CHECK_GE(width_step_, width * NumberOfChannels() * ByteDepth()); + ABSL_CHECK_NE(ImageFormat::UNKNOWN, format_); + ABSL_CHECK_GE(width_step_, width * NumberOfChannels() * ByteDepth()); pixel_data_ = {pixel_data, deleter}; } @@ -136,8 +137,8 @@ void ImageFrame::InternalCopyFrom(int width, int height, int width_step, int channel_size, const uint8_t* pixel_data) { - CHECK_EQ(width_, width); - CHECK_EQ(height_, height); + ABSL_CHECK_EQ(width_, width); + ABSL_CHECK_EQ(height_, height); // row_bytes = channel_size * num_channels * width const int row_bytes = channel_size * NumberOfChannels() * width; if (width_step == 0) { @@ -187,8 +188,8 @@ if (!pixel_data_) { return; } - CHECK_GE(width_, 1); - CHECK_GE(height_, 1); + ABSL_CHECK_GE(width_, 1); + ABSL_CHECK_GE(height_, 1); const int pixel_size = ByteDepth() * NumberOfChannels(); const int padding_size = width_step_ - width_ * pixel_size; @@ -359,7 +360,7 @@ Reset(image_frame.Format(), image_frame.Width(), image_frame.Height(), alignment_boundary); - CHECK_EQ(format_, image_frame.Format()); + ABSL_CHECK_EQ(format_, image_frame.Format()); InternalCopyFrom(image_frame.Width(), image_frame.Height(), image_frame.WidthStep(), image_frame.ChannelSize(), image_frame.PixelData()); @@ -383,9 +384,9 @@ void ImageFrame::CopyToBuffer(uint8_t* buffer, int buffer_size) const { CHECK(buffer); - CHECK_EQ(1, ByteDepth()); + ABSL_CHECK_EQ(1, ByteDepth()); const int data_size = width_ * height_ * NumberOfChannels(); - CHECK_LE(data_size, buffer_size); + ABSL_CHECK_LE(data_size, buffer_size); if (IsContiguous()) { // The data is stored contiguously, we can just copy. const uint8_t* src = reinterpret_cast<const uint8_t*>(pixel_data_.get()); @@ -398,9 +399,9 @@ void ImageFrame::CopyToBuffer(uint16_t* buffer, int buffer_size) const { CHECK(buffer); - CHECK_EQ(2, ByteDepth()); + ABSL_CHECK_EQ(2, ByteDepth()); const int data_size = width_ * height_ * NumberOfChannels(); - CHECK_LE(data_size, buffer_size); + ABSL_CHECK_LE(data_size, buffer_size); if (IsContiguous()) { // The data is stored contiguously, we can just copy. const uint16_t* src = reinterpret_cast<const uint16_t*>(pixel_data_.get()); @@ -413,9 +414,9 @@ void ImageFrame::CopyToBuffer(float* buffer, int buffer_size) const { CHECK(buffer); - CHECK_EQ(4, ByteDepth()); + ABSL_CHECK_EQ(4, ByteDepth()); const int data_size = width_ * height_ * NumberOfChannels(); - CHECK_LE(data_size, buffer_size); + ABSL_CHECK_LE(data_size, buffer_size); if (IsContiguous()) { // The data is stored contiguously, we can just copy. const float* src = reinterpret_cast<float*>(pixel_data_.get());
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc b/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc index 655064d..5953d0f 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc +++ b/third_party/mediapipe/src/mediapipe/framework/formats/image_multi_pool.cc
@@ -16,6 +16,7 @@ #include <tuple> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/logging.h" @@ -43,7 +44,7 @@ IBufferSpec spec) { OSType cv_format = mediapipe::CVPixelFormatForGpuBufferFormat( GpuBufferFormatForImageFormat(spec.format)); - CHECK_NE(cv_format, -1) << "unsupported pixel format"; + ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; return MakeCFHolderAdopting(mediapipe::CreateCVPixelBufferPool( spec.width, spec.height, cv_format, kKeepCount, 0.1 /* max age in seconds */)); @@ -61,7 +62,7 @@ // pool to give us contiguous data. OSType cv_format = mediapipe::CVPixelFormatForGpuBufferFormat( mediapipe::GpuBufferFormatForImageFormat(spec.format)); - CHECK_NE(cv_format, -1) << "unsupported pixel format"; + ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; CVPixelBufferRef buffer; CVReturn err = mediapipe::CreateCVPixelBufferWithoutPool( spec.width, spec.height, cv_format, &buffer); @@ -188,7 +189,7 @@ ImageMultiPool::~ImageMultiPool() { #if !MEDIAPIPE_DISABLE_GPU #ifdef __APPLE__ - CHECK_EQ(texture_caches_.size(), 0) + ABSL_CHECK_EQ(texture_caches_.size(), 0) << "Failed to unregister texture caches before deleting pool"; #endif // defined(__APPLE__) #endif // !MEDIAPIPE_DISABLE_GPU
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/location.cc b/third_party/mediapipe/src/mediapipe/framework/formats/location.cc index 205edf1..f2d7be0f 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/location.cc +++ b/third_party/mediapipe/src/mediapipe/framework/formats/location.cc
@@ -18,6 +18,7 @@ #include <cmath> #include <memory> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/substitute.h" #include "mediapipe/framework/formats/annotation/locus.pb.h" @@ -152,7 +153,7 @@ template <> Rectangle_i Location::GetBBox<Rectangle_i>() const { - CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); + ABSL_CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); const auto& box = location_data_.bounding_box(); return Rectangle_i(box.xmin(), box.ymin(), box.width(), box.height()); } @@ -160,7 +161,7 @@ Location& Location::Scale(const float scale) { CHECK(!location_data_.has_mask()) << "Location mask scaling is not implemented."; - CHECK_GT(scale, 0.0f); + ABSL_CHECK_GT(scale, 0.0f); switch (location_data_.format()) { case LocationData::GLOBAL: { // Do nothing. @@ -247,7 +248,7 @@ // This function is inteded to shift boundaries of intervals such that they // best fit within an image. float BestShift(float min_value, float max_value, float range) { - CHECK_LE(min_value, max_value); + ABSL_CHECK_LE(min_value, max_value); const float value_range = max_value - min_value; if (value_range > range) { return 0.5f * (range - min_value - max_value); @@ -294,8 +295,8 @@ const float y_shift = BestShift(mask_bounding_box.xmin(), mask_bounding_box.xmax(), image_height); auto* mask = location_data_.mutable_mask(); - CHECK_EQ(image_width, mask->width()); - CHECK_EQ(image_height, mask->height()); + ABSL_CHECK_EQ(image_width, mask->width()); + ABSL_CHECK_EQ(image_height, mask->height()); for (auto& interval : *mask->mutable_rasterization()->mutable_interval()) { interval.set_y(interval.y() + y_shift); @@ -418,7 +419,7 @@ } Rectangle_f Location::GetRelativeBBox() const { - CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); + ABSL_CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); const auto& box = location_data_.relative_bounding_box(); return Rectangle_f(box.xmin(), box.ymin(), box.width(), box.height()); } @@ -457,7 +458,7 @@ template <> ::mediapipe::BoundingBox Location::GetBBox<::mediapipe::BoundingBox>() const { - CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); + ABSL_CHECK_EQ(LocationData::BOUNDING_BOX, location_data_.format()); const auto& box = location_data_.bounding_box(); ::mediapipe::BoundingBox bounding_box; bounding_box.set_left_x(box.xmin()); @@ -480,7 +481,7 @@ } std::vector<Point2_f> Location::GetRelativeKeypoints() const { - CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); + ABSL_CHECK_EQ(LocationData::RELATIVE_BOUNDING_BOX, location_data_.format()); std::vector<Point2_f> keypoints; for (const auto& keypoint : location_data_.relative_keypoints()) { keypoints.emplace_back(Point2_f(keypoint.x(), keypoint.y()));
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc b/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc index 6e15b299..90cd2bb 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc +++ b/third_party/mediapipe/src/mediapipe/framework/formats/location_opencv.cc
@@ -14,6 +14,7 @@ #include "mediapipe/framework/formats/location_opencv.h" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/substitute.h" #include "mediapipe/framework/formats/annotation/rasterization.pb.h" @@ -85,7 +86,7 @@ std::unique_ptr<cv::Mat> GetCvMask(const Location& location) { const auto location_data = location.ConvertToProto(); - CHECK_EQ(LocationData::MASK, location_data.format()); + ABSL_CHECK_EQ(LocationData::MASK, location_data.format()); const auto& mask = location_data.mask(); std::unique_ptr<cv::Mat> mat( new cv::Mat(mask.height(), mask.width(), CV_8UC1, cv::Scalar(0))); @@ -128,7 +129,7 @@ } void EnlargeLocation(Location& location, const float factor) { - CHECK_GT(factor, 0.0f); + ABSL_CHECK_GT(factor, 0.0f); if (factor == 1.0f) return; auto location_data = location.ConvertToProto(); switch (location_data.format()) { @@ -183,7 +184,7 @@ template <typename T> Location CreateCvMaskLocation(const cv::Mat_<T>& mask) { - CHECK_EQ(1, mask.channels()) + ABSL_CHECK_EQ(1, mask.channels()) << "The specified cv::Mat mask should be single-channel."; LocationData location_data;
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc b/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc index 42f2df5f..daad9c0 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc +++ b/third_party/mediapipe/src/mediapipe/framework/formats/matrix.cc
@@ -15,6 +15,7 @@ #include <algorithm> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/core_proto_inc.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/proto_ns.h" @@ -33,8 +34,8 @@ } void MatrixFromMatrixDataProto(const MatrixData& matrix_data, Matrix* matrix) { - CHECK_EQ(matrix_data.rows() * matrix_data.cols(), - matrix_data.packed_data_size()); + ABSL_CHECK_EQ(matrix_data.rows() * matrix_data.cols(), + matrix_data.packed_data_size()); if (matrix_data.layout() == MatrixData::ROW_MAJOR) { matrix->resize(matrix_data.cols(), matrix_data.rows()); } else {
diff --git a/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc b/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc index a965041..8b3dd3f 100644 --- a/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc +++ b/third_party/mediapipe/src/mediapipe/framework/formats/motion/optical_flow_field.cc
@@ -18,6 +18,7 @@ #include <cmath> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "mediapipe/framework/deps/mathutil.h" @@ -105,7 +106,7 @@ std::max(std::numeric_limits<float>::epsilon(), MaxAbsoluteValueIgnoringHuge(magnitudes, kHugeToIgnore)); } - CHECK_LT(0, max_magnitude); + ABSL_CHECK_LT(0, max_magnitude); cv::Mat hsv = MakeVisualizationHsv(angles, magnitudes, max_magnitude); cv::Mat viz; cv::cvtColor(hsv, viz, 71 /*cv::COLOR_HSV2RGB_FULL*/); @@ -119,7 +120,7 @@ cv::Mat OpticalFlowField::GetVisualizationSaturatedAt( float max_magnitude) const { - CHECK_LT(0, max_magnitude) + ABSL_CHECK_LT(0, max_magnitude) << "Specified saturation magnitude must be positive."; return GetVisualizationInternal(max_magnitude, true); } @@ -147,9 +148,9 @@ } void OpticalFlowField::CopyFromTensor(const tensorflow::Tensor& tensor) { - CHECK_EQ(tensorflow::DT_FLOAT, tensor.dtype()); - CHECK_EQ(3, tensor.dims()) << "Tensor must be height x width x 2."; - CHECK_EQ(2, tensor.dim_size(2)) << "Tensor must be height x width x 2."; + ABSL_CHECK_EQ(tensorflow::DT_FLOAT, tensor.dtype()); + ABSL_CHECK_EQ(3, tensor.dims()) << "Tensor must be height x width x 2."; + ABSL_CHECK_EQ(2, tensor.dim_size(2)) << "Tensor must be height x width x 2."; const int height = tensor.dim_size(0); const int width = tensor.dim_size(1); Allocate(width, height); @@ -163,8 +164,8 @@ } void OpticalFlowField::SetFromProto(const OpticalFlowFieldData& proto) { - CHECK_EQ(proto.width() * proto.height(), proto.dx_size()); - CHECK_EQ(proto.width() * proto.height(), proto.dy_size()); + ABSL_CHECK_EQ(proto.width() * proto.height(), proto.dx_size()); + ABSL_CHECK_EQ(proto.width() * proto.height(), proto.dy_size()); flow_data_.create(proto.height(), proto.width()); int i = 0; for (int r = 0; r < flow_data_.rows; ++r) { @@ -205,10 +206,10 @@ cv::Point2f OpticalFlowField::InterpolatedFlowAt(float x, float y) const { // Sanity bounds checks. - CHECK_GE(x, 0); - CHECK_GE(y, 0); - CHECK_LE(x, flow_data_.cols - 1); - CHECK_LE(y, flow_data_.rows - 1); + ABSL_CHECK_GE(x, 0); + ABSL_CHECK_GE(y, 0); + ABSL_CHECK_LE(x, flow_data_.cols - 1); + ABSL_CHECK_LE(y, flow_data_.rows - 1); const int x0 = static_cast<int>(std::floor(x)); const int y0 = static_cast<int>(std::floor(y)); @@ -265,9 +266,9 @@ const OpticalFlowField& forward, const OpticalFlowField& backward, double spatial_distance_threshold, Location* occluded_mask, Location* disoccluded_mask) { - CHECK_EQ(forward.width(), backward.width()) + ABSL_CHECK_EQ(forward.width(), backward.width()) << "Flow fields have different widths."; - CHECK_EQ(forward.height(), backward.height()) + ABSL_CHECK_EQ(forward.height(), backward.height()) << "Flow fields have different heights."; if (occluded_mask != nullptr) { *occluded_mask = FindMotionInconsistentPixels(forward, backward,
diff --git a/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc b/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc index de024df..34b4ffea 100644 --- a/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc +++ b/third_party/mediapipe/src/mediapipe/framework/graph_output_stream.cc
@@ -14,6 +14,7 @@ #include "mediapipe/framework/graph_output_stream.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/status.h" @@ -212,7 +213,7 @@ bool stream_is_done = false; *packet = input_stream_->PopPacketAtTimestamp( min_timestamp, &num_packets_dropped, &stream_is_done); - CHECK_EQ(num_packets_dropped, 0) + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, input_stream_->Name()); } else if (timestamp_bound_changed) {
diff --git a/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc index a7bd9ef..42830510 100644 --- a/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/input_stream_handler.cc
@@ -14,6 +14,7 @@ #include "mediapipe/framework/input_stream_handler.h" +#include "absl/log/absl_check.h" #include "absl/strings/str_join.h" #include "absl/strings/substitute.h" #include "mediapipe/framework/collection_item_id.h" @@ -102,7 +103,7 @@ return; } if (!input_stream_managers_.Get(id)->BackEdge()) { - CHECK_GT(unset_header_count_, 0); + ABSL_CHECK_GT(unset_header_count_, 0); if (unset_header_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) { headers_ready_callback_(); } @@ -321,9 +322,11 @@ << "Batching cannot be combined with parallel execution."; CHECK(!late_preparation_ || batch_size == 1) << "Batching cannot be combined with late preparation."; - CHECK_GE(batch_size, 1) << "Batch size has to be greater than or equal to 1."; + ABSL_CHECK_GE(batch_size, 1) + << "Batch size has to be greater than or equal to 1."; // Source nodes shouldn't specify batch_size even if it's set to 1. - CHECK_GE(NumInputStreams(), 0) << "Source nodes cannot batch input packets."; + ABSL_CHECK_GE(NumInputStreams(), 0) + << "Source nodes cannot batch input packets."; batch_size_ = batch_size; } @@ -412,7 +415,7 @@ bool stream_is_done = false; Packet current_packet = stream->PopPacketAtTimestamp( input_timestamp, &num_packets_dropped, &stream_is_done); - CHECK_EQ(num_packets_dropped, 0) + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, stream->Name()); input_stream_handler_->AddPacketToShard(
diff --git a/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc b/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc index 1af2e2cc..d38f3c6 100644 --- a/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc +++ b/third_party/mediapipe/src/mediapipe/framework/input_stream_manager.cc
@@ -17,6 +17,7 @@ #include <type_traits> #include <utility> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/packet.h" @@ -252,7 +253,7 @@ { absl::MutexLock stream_lock(&stream_mutex_); // Make sure timestamp didn't decrease from last time. - CHECK_LE(last_select_timestamp_, timestamp); + ABSL_CHECK_LE(last_select_timestamp_, timestamp); last_select_timestamp_ = timestamp; // Make sure AddPacket and SetNextTimestampBound are not called with
diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc index ba8f467..74138cd7 100644 --- a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.cc
@@ -14,6 +14,7 @@ #include "mediapipe/framework/output_stream_handler.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/collection_item_id.h" #include "mediapipe/framework/output_stream_shard.h" @@ -79,7 +80,7 @@ if (task_timestamp_bound_ == timestamp) { return; } - CHECK_GT(timestamp, task_timestamp_bound_); + ABSL_CHECK_GT(timestamp, task_timestamp_bound_); task_timestamp_bound_ = timestamp; if (propagation_state_ == kPropagatingBound) { propagation_state_ = kPropagationPending;
diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h index 0b8dbed2..cb6b2d6 100644 --- a/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h +++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_handler.h
@@ -25,6 +25,7 @@ // TODO: Move protos in another CL after the C++ code migration. #include "absl/base/thread_annotations.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/calculator_context_manager.h" #include "mediapipe/framework/collection.h" @@ -63,7 +64,7 @@ calculator_context_manager_(calculator_context_manager), options_(options), calculator_run_in_parallel_(calculator_run_in_parallel) { - CHECK(calculator_context_manager_); + ABSL_CHECK(calculator_context_manager_); } virtual ~OutputStreamHandler() = default;
diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h b/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h index 26c0e72..98ebda3 100644 --- a/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h +++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_poller.h
@@ -17,6 +17,7 @@ #include <memory> +#include "absl/log/absl_check.h" #include "mediapipe/framework/graph_output_stream.h" namespace mediapipe { @@ -34,7 +35,7 @@ // Resets OutputStramPollerImpl and cleans the internal packet queue. void Reset() { auto poller = internal_poller_impl_.lock(); - CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; + ABSL_CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; poller->Reset(); } @@ -50,14 +51,14 @@ void SetMaxQueueSize(int queue_size) { auto poller = internal_poller_impl_.lock(); - CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; + ABSL_CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; return poller->SetMaxQueueSize(queue_size); } // Returns the number of packets in the queue. int QueueSize() { auto poller = internal_poller_impl_.lock(); - CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; + ABSL_CHECK(poller) << "OutputStreamPollerImpl is already destroyed."; return poller->QueueSize(); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h b/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h index 718174c4..81a89759 100644 --- a/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h +++ b/third_party/mediapipe/src/mediapipe/framework/output_stream_shard.h
@@ -18,6 +18,7 @@ #include <list> #include <string> +#include "absl/log/absl_check.h" #include "mediapipe/framework/output_stream.h" #include "mediapipe/framework/packet.h" #include "mediapipe/framework/packet_type.h" @@ -34,7 +35,7 @@ // Triggers the error callback with absl::Status info when an error // occurs. void TriggerErrorCallback(const absl::Status& status) const { - CHECK(error_callback); + ABSL_CHECK(error_callback); error_callback(status); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/packet.h b/third_party/mediapipe/src/mediapipe/framework/packet.h index 1024cbc..2739b09 100644 --- a/third_party/mediapipe/src/mediapipe/framework/packet.h +++ b/third_party/mediapipe/src/mediapipe/framework/packet.h
@@ -23,6 +23,7 @@ #include <type_traits> #include "absl/base/macros.h" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" @@ -742,7 +743,7 @@ inline bool Packet::IsEmpty() const { return holder_ == nullptr; } inline TypeId Packet::GetTypeId() const { - CHECK(holder_); + ABSL_CHECK(holder_); return holder_->GetTypeId(); } @@ -761,13 +762,13 @@ template <typename T> Packet Adopt(const T* ptr) { - CHECK(ptr != nullptr); + ABSL_CHECK(ptr != nullptr); return packet_internal::Create(new packet_internal::Holder<T>(ptr)); } template <typename T> Packet PointToForeign(const T* ptr) { - CHECK(ptr != nullptr); + ABSL_CHECK(ptr != nullptr); return packet_internal::Create(new packet_internal::ForeignHolder<T>(ptr)); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/packet_type.h b/third_party/mediapipe/src/mediapipe/framework/packet_type.h index 9b4bbd3..d4a0438 100644 --- a/third_party/mediapipe/src/mediapipe/framework/packet_type.h +++ b/third_party/mediapipe/src/mediapipe/framework/packet_type.h
@@ -23,6 +23,7 @@ #include <vector> #include "absl/base/macros.h" +#include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" @@ -162,7 +163,7 @@ if (!missing_) { missing_ = absl::make_unique<Missing>(); } - CHECK(!missing_->initialized_errors); + ABSL_CHECK(!missing_->initialized_errors); std::string key = absl::StrCat(tag, ":", index); return missing_->entries[key]; } @@ -181,9 +182,9 @@ // Get the error messages that have been deferred. // This function can only be called if HasError() is true. const std::vector<std::string>& ErrorMessages() const { - CHECK(missing_) << "ErrorMessages() can only be called if errors have " - "occurred. Call HasError() before calling this " - "function."; + ABSL_CHECK(missing_) << "ErrorMessages() can only be called if errors have " + "occurred. Call HasError() before calling this " + "function."; if (!missing_->initialized_errors) { for (const auto& entry : missing_->entries) { // Optional entries that were missing are not considered errors.
diff --git a/third_party/mediapipe/src/mediapipe/framework/scheduler.cc b/third_party/mediapipe/src/mediapipe/framework/scheduler.cc index ceadce7..f281ce4 100644 --- a/third_party/mediapipe/src/mediapipe/framework/scheduler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/scheduler.cc
@@ -19,6 +19,7 @@ #include <utility> #include <vector> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/calculator_graph.h" @@ -77,7 +78,7 @@ void Scheduler::CloseAllSourceNodes() { shared_.stopping = true; } void Scheduler::SetExecutor(Executor* executor) { - CHECK_EQ(state_, STATE_NOT_STARTED) + ABSL_CHECK_EQ(state_, STATE_NOT_STARTED) << "SetExecutor must not be called after the scheduler has started"; default_queue_.SetExecutor(executor); } @@ -198,7 +199,7 @@ shared_.timer.StartRun(); { absl::MutexLock lock(&state_mutex_); - CHECK_EQ(state_, STATE_NOT_STARTED); + ABSL_CHECK_EQ(state_, STATE_NOT_STARTED); state_ = STATE_RUNNING; SetQueuesRunning(true); @@ -427,8 +428,9 @@ } void Scheduler::AddUnopenedSourceNode(CalculatorNode* node) { - CHECK_EQ(state_, STATE_NOT_STARTED) << "AddUnopenedSourceNode can only be " - "called before starting the scheduler"; + ABSL_CHECK_EQ(state_, STATE_NOT_STARTED) + << "AddUnopenedSourceNode can only be " + "called before starting the scheduler"; unopened_sources_.insert(node); } @@ -539,7 +541,7 @@ } internal::SchedulerTimes Scheduler::GetSchedulerTimes() { - CHECK_EQ(state_, STATE_TERMINATED); + ABSL_CHECK_EQ(state_, STATE_TERMINATED); return shared_.timer.GetSchedulerTimes(); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc b/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc index 33214cf6..08360ec 100644 --- a/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc +++ b/third_party/mediapipe/src/mediapipe/framework/scheduler_queue.cc
@@ -18,6 +18,7 @@ #include <queue> #include <utility> +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/calculator_node.h" #include "mediapipe/framework/executor.h" @@ -104,7 +105,7 @@ void SchedulerQueue::SetRunning(bool running) { absl::MutexLock lock(&mutex_); running_count_ += running ? 1 : -1; - DCHECK_LE(running_count_, 1); + ABSL_DCHECK_LE(running_count_, 1); } void SchedulerQueue::AddNode(CalculatorNode* node, CalculatorContext* cc) { @@ -221,7 +222,7 @@ bool is_idle; { absl::MutexLock lock(&mutex_); - DCHECK_GT(num_pending_tasks_, 0); + ABSL_DCHECK_GT(num_pending_tasks_, 0); --num_pending_tasks_; is_idle = IsIdle(); } @@ -299,8 +300,8 @@ { absl::MutexLock lock(&mutex_); was_idle = IsIdle(); - CHECK_EQ(num_pending_tasks_, 0); - CHECK_EQ(num_tasks_to_add_, queue_.size()); + ABSL_CHECK_EQ(num_pending_tasks_, 0); + ABSL_CHECK_EQ(num_tasks_to_add_, queue_.size()); num_tasks_to_add_ = 0; while (!queue_.empty()) { queue_.pop();
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc index ece873b..250d3da27 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/barrier_input_stream_handler.cc
@@ -16,6 +16,7 @@ #include <memory> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/input_stream_handler.h" namespace mediapipe { @@ -67,7 +68,7 @@ *min_stream_timestamp = std::min(*min_stream_timestamp, stream_timestamp); } - CHECK_NE(*min_stream_timestamp, Timestamp::Done()); + ABSL_CHECK_NE(*min_stream_timestamp, Timestamp::Done()); if (all_available) { return NodeReadiness::kReadyForProcess; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc index 983b986..c0ec0b67 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/early_close_input_stream_handler.cc
@@ -16,6 +16,7 @@ #include <memory> #include <vector> +#include "absl/log/absl_check.h" #include "absl/strings/substitute.h" #include "mediapipe/framework/input_stream_handler.h" @@ -56,13 +57,13 @@ *min_stream_timestamp = std::min(*min_stream_timestamp, stream_timestamp); } - CHECK_NE(*min_stream_timestamp, Timestamp::Done()); + ABSL_CHECK_NE(*min_stream_timestamp, Timestamp::Done()); if (min_bound > *min_stream_timestamp) { return NodeReadiness::kReadyForProcess; } - CHECK_EQ(min_bound, *min_stream_timestamp); + ABSL_CHECK_EQ(min_bound, *min_stream_timestamp); return NodeReadiness::kNotReady; } @@ -78,7 +79,7 @@ bool stream_is_done = false; Packet current_packet = stream->PopPacketAtTimestamp( input_timestamp, &num_packets_dropped, &stream_is_done); - CHECK_EQ(num_packets_dropped, 0) + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, stream->Name()); AddPacketToShard(&input_set->Get(id), std::move(current_packet),
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc index c34fc96b..2951c833 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/immediate_input_stream_handler.cc
@@ -15,6 +15,7 @@ #include <memory> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/input_stream_handler.h" namespace mediapipe { @@ -115,7 +116,7 @@ ready_timestamps_[i] = stream_ts; input_timestamp = std::min(input_timestamp, stream_ts); } else if (readiness == NodeReadiness::kReadyForClose) { - CHECK_EQ(stream_ts, Timestamp::Done()); + ABSL_CHECK_EQ(stream_ts, Timestamp::Done()); if (ProcessTimestampBounds()) { // With kReadyForClose, the timestamp-bound Done is returned. // TODO: Make all InputStreamHandlers process Done() like this.
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc index 9af38ec..8faaace 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/in_order_output_stream_handler.cc
@@ -14,6 +14,7 @@ #include "mediapipe/framework/stream_handler/in_order_output_stream_handler.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/collection.h" #include "mediapipe/framework/collection_item_id.h" #include "mediapipe/framework/output_stream_shard.h" @@ -23,7 +24,7 @@ REGISTER_OUTPUT_STREAM_HANDLER(InOrderOutputStreamHandler); void InOrderOutputStreamHandler::PropagationLoop() { - CHECK_EQ(propagation_state_, kIdle); + ABSL_CHECK_EQ(propagation_state_, kIdle); Timestamp context_timestamp; CalculatorContext* calculator_context; if (!calculator_context_manager_->HasActiveContexts()) { @@ -34,7 +35,7 @@ if (!completed_input_timestamps_.empty()) { Timestamp completed_timestamp = *completed_input_timestamps_.begin(); if (context_timestamp != completed_timestamp) { - CHECK_LT(context_timestamp, completed_timestamp); + ABSL_CHECK_LT(context_timestamp, completed_timestamp); return; } propagation_state_ = kPropagatingPackets; @@ -45,7 +46,7 @@ if (propagation_state_ == kPropagatingPackets) { PropagatePackets(&calculator_context, &context_timestamp); } else { - CHECK_EQ(kPropagatingBound, propagation_state_); + ABSL_CHECK_EQ(kPropagatingBound, propagation_state_); PropagationBound(&calculator_context, &context_timestamp); } } @@ -105,12 +106,12 @@ } // Some recent changes require the propagation thread to recheck if any // new packets can be propagated. - CHECK_EQ(propagation_state_, kPropagationPending); + ABSL_CHECK_EQ(propagation_state_, kPropagationPending); // task_timestamp_bound_ was updated while the propagation thread was // doing timestamp propagation. This thread will redo timestamp // propagation for the new task_timestamp_bound_. if (!calculator_context_manager_->HasActiveContexts()) { - CHECK_LT(bound_to_propagate, task_timestamp_bound_); + ABSL_CHECK_LT(bound_to_propagate, task_timestamp_bound_); propagation_state_ = kPropagatingBound; return; }
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc index 0303a57..699aa91 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/mux_input_stream_handler.cc
@@ -12,6 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include "absl/log/absl_check.h" #include "absl/strings/substitute.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/collection_item_id.h" @@ -73,8 +74,8 @@ Packet control_packet = control_stream->QueueHead(); CHECK(!control_packet.IsEmpty()); int control_value = control_packet.Get<int>(); - CHECK_LE(0, control_value); - CHECK_LT(control_value, input_stream_managers_.NumEntries() - 1); + ABSL_CHECK_LE(0, control_value); + ABSL_CHECK_LT(control_value, input_stream_managers_.NumEntries() - 1); const auto& data_stream = input_stream_managers_.Get( input_stream_managers_.BeginId() + control_value); @@ -100,7 +101,7 @@ // indicated as timestamp boun update. return NodeReadiness::kReadyForProcess; } - CHECK_EQ(stream_timestamp, *min_stream_timestamp); + ABSL_CHECK_EQ(stream_timestamp, *min_stream_timestamp); return NodeReadiness::kReadyForProcess; } @@ -118,7 +119,7 @@ bool stream_is_done = false; Packet control_packet = control_stream->PopPacketAtTimestamp( input_timestamp, &num_packets_dropped, &stream_is_done); - CHECK_EQ(num_packets_dropped, 0) + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, control_stream->Name()); CHECK(!control_packet.IsEmpty()); @@ -128,13 +129,13 @@ const CollectionItemId data_stream_id = input_stream_managers_.BeginId() + control_value; - CHECK_LE(input_stream_managers_.BeginId(), data_stream_id); - CHECK_LT(data_stream_id, control_stream_id); + ABSL_CHECK_LE(input_stream_managers_.BeginId(), data_stream_id); + ABSL_CHECK_LT(data_stream_id, control_stream_id); auto& data_stream = input_stream_managers_.Get(data_stream_id); stream_is_done = false; Packet data_packet = data_stream->PopPacketAtTimestamp( input_timestamp, &num_packets_dropped, &stream_is_done); - CHECK_EQ(num_packets_dropped, 0) + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, data_stream->Name()); AddPacketToShard(&input_set->Get(data_stream_id), std::move(data_packet),
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc index 1001d64..adb4c05 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/sync_set_input_stream_handler.cc
@@ -15,6 +15,7 @@ #include <algorithm> // TODO: Move protos in another CL after the C++ code migration. +#include "absl/log/absl_check.h" #include "absl/strings/substitute.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/collection_item_id.h" @@ -102,7 +103,7 @@ std::set<CollectionItemId> used_ids; for (const auto& sync_set : handler_options.sync_set()) { std::vector<CollectionItemId> stream_ids; - CHECK_LT(0, sync_set.tag_index_size()); + ABSL_CHECK_LT(0, sync_set.tag_index_size()); for (const auto& tag_index : sync_set.tag_index()) { std::string tag; int index; @@ -185,7 +186,7 @@ InputStreamShardSet* input_set) { // Assume that all current packets are already cleared. absl::MutexLock lock(&mutex_); - CHECK_LE(0, ready_sync_set_index_); + ABSL_CHECK_LE(0, ready_sync_set_index_); sync_sets_[ready_sync_set_index_].FillInputSet(input_timestamp, input_set); for (int i = 0; i < sync_sets_.size(); ++i) { if (i != ready_sync_set_index_) {
diff --git a/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc b/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc index ae075d78..cb78618c 100644 --- a/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc +++ b/third_party/mediapipe/src/mediapipe/framework/stream_handler/timestamp_align_input_stream_handler.cc
@@ -17,6 +17,7 @@ #include <utility> #include <vector> +#include "absl/log/absl_check.h" #include "absl/strings/substitute.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/collection_item_id.h" @@ -178,7 +179,7 @@ return NodeReadiness::kReadyForProcess; } - CHECK_EQ(min_bound, *min_stream_timestamp); + ABSL_CHECK_EQ(min_bound, *min_stream_timestamp); return NodeReadiness::kNotReady; } @@ -198,7 +199,7 @@ if (id == timestamp_base_stream_id_) { current_packet = stream->PopPacketAtTimestamp( input_timestamp, &num_packets_dropped, &stream_is_done); - CHECK_EQ(num_packets_dropped, 0) << absl::Substitute( + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute( "Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, stream->Name()); } @@ -218,10 +219,10 @@ Packet current_packet = stream->PopPacketAtTimestamp( stream_timestamp, &num_packets_dropped, &stream_is_done); if (!current_packet.IsEmpty()) { - CHECK_EQ(current_packet.Timestamp(), stream_timestamp); + ABSL_CHECK_EQ(current_packet.Timestamp(), stream_timestamp); current_packet = current_packet.At(input_timestamp); } - CHECK_EQ(num_packets_dropped, 0) + ABSL_CHECK_EQ(num_packets_dropped, 0) << absl::Substitute("Dropped $0 packet(s) on input stream \"$1\".", num_packets_dropped, stream->Name()); AddPacketToShard(&input_set->Get(id), std::move(current_packet),
diff --git a/third_party/mediapipe/src/mediapipe/framework/timestamp.h b/third_party/mediapipe/src/mediapipe/framework/timestamp.h index d125d28..8949dcc 100644 --- a/third_party/mediapipe/src/mediapipe/framework/timestamp.h +++ b/third_party/mediapipe/src/mediapipe/framework/timestamp.h
@@ -47,6 +47,7 @@ #include <cmath> #include <string> +#include "absl/log/absl_check.h" #include "mediapipe/framework/deps/safe_int.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" @@ -270,14 +271,14 @@ inline Timestamp::Timestamp() : timestamp_(kint64min) {} inline Timestamp::Timestamp(int64 timestamp) : timestamp_(timestamp) { - CHECK(!IsSpecialValue()) + ABSL_CHECK(!IsSpecialValue()) << "Cannot directly create a Timestamp with a special value: " << CreateNoErrorChecking(timestamp); } inline Timestamp::Timestamp(TimestampBaseType timestamp) : timestamp_(timestamp) { - CHECK(!IsSpecialValue()) + ABSL_CHECK(!IsSpecialValue()) << "Cannot directly create a Timestamp with a special value: " << CreateNoErrorChecking(timestamp.value()); }
diff --git a/third_party/mediapipe/src/mediapipe/framework/type_map.h b/third_party/mediapipe/src/mediapipe/framework/type_map.h index 42f6fe6..f958a658 100644 --- a/third_party/mediapipe/src/mediapipe/framework/type_map.h +++ b/third_party/mediapipe/src/mediapipe/framework/type_map.h
@@ -64,6 +64,7 @@ #include <vector> #include "absl/base/macros.h" +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/demangle.h" #include "mediapipe/framework/port/status.h" @@ -127,7 +128,7 @@ } static void GetKeys(std::vector<KeyType>* keys) { - CHECK(keys); + ABSL_CHECK(keys); keys->clear(); const MapType& internal_map = GetMap()->internal_map_; for (typename MapType::const_iterator i = internal_map.begin(); @@ -158,12 +159,12 @@ // Type has been already registered. const MediaPipeTypeData& existing_data = it->second.second; - CHECK_EQ(existing_data.type_id, value.type_id) + ABSL_CHECK_EQ(existing_data.type_id, value.type_id) << "Found inconsistent type ids (" << existing_data.type_id << " vs " << value.type_id << ") during mediapipe type registration. Previous definition at " << it->second.first << " and current definition at " << file_and_line; - CHECK_EQ(existing_data.type_string, value.type_string) + ABSL_CHECK_EQ(existing_data.type_string, value.type_string) << "Found inconsistent type strings (" << existing_data.type_string << " vs " << value.type_string << ") during mediapipe type registration. Previous registration at " @@ -171,7 +172,7 @@ << file_and_line; if (value.serialize_fn && value.deserialize_fn) { // Doesn't allow to redefine the existing type serialization functions. - CHECK(!existing_data.serialize_fn && !existing_data.deserialize_fn) + ABSL_CHECK(!existing_data.serialize_fn && !existing_data.deserialize_fn) << "Attempting to redefine serialization functions of type " << value.type_string << ", that have been defined at " << it->second.first << ", at " << file_and_line;
diff --git a/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm b/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm index c0703e6e..db8bb0a 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm +++ b/third_party/mediapipe/src/mediapipe/gpu/MPPMetalHelper.mm
@@ -20,6 +20,7 @@ #import "mediapipe/gpu/metal_shared_resources.h" #import "GTMDefines.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/ret_check.h" @interface MPPMetalHelper () { @@ -78,7 +79,7 @@ - (instancetype)initWithSidePackets:(const mediapipe::PacketSet&)inputSidePackets { auto cc = mediapipe::MetalHelperLegacySupport::GetCalculatorContext(); if (cc) { - CHECK_EQ(&inputSidePackets, &cc->InputSidePackets()); + ABSL_CHECK_EQ(&inputSidePackets, &cc->InputSidePackets()); return [self initWithCalculatorContext:cc]; } @@ -96,7 +97,7 @@ + (absl::Status)setupInputSidePackets:(mediapipe::PacketTypeSet*)inputSidePackets { auto cc = mediapipe::MetalHelperLegacySupport::GetCalculatorContract(); if (cc) { - CHECK_EQ(inputSidePackets, &cc->InputSidePackets()); + ABSL_CHECK_EQ(inputSidePackets, &cc->InputSidePackets()); return [self updateContract:cc]; } @@ -180,7 +181,7 @@ NULL, _gpuResources->metal_shared().resources().mtlTextureCache, mediapipe::GetCVPixelBufferRef(gpuBuffer), NULL, metalPixelFormat, width, height, plane, &texture); - CHECK_EQ(err, kCVReturnSuccess); + ABSL_CHECK_EQ(err, kCVReturnSuccess); return texture; }
diff --git a/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc b/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc index 6e077ae..b0689cd6 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/cv_pixel_buffer_pool_wrapper.cc
@@ -17,6 +17,7 @@ #include <tuple> #include "CoreFoundation/CFBase.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/objc/CFHolder.h" #include "mediapipe/objc/util.h" @@ -27,7 +28,7 @@ int width, int height, GpuBufferFormat format, CFTimeInterval maxAge, CvTextureCacheManager* texture_caches) { OSType cv_format = CVPixelFormatForGpuBufferFormat(format); - CHECK_NE(cv_format, -1) << "unsupported pixel format"; + ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; pool_ = MakeCFHolderAdopting( /* keep count is 0 because the age param keeps buffers around anyway */ CreateCVPixelBufferPool(width, height, cv_format, 0, maxAge)); @@ -73,7 +74,7 @@ CFHolder<CVPixelBufferRef> CvPixelBufferPoolWrapper::CreateBufferWithoutPool( const internal::GpuBufferSpec& spec) { OSType cv_format = CVPixelFormatForGpuBufferFormat(spec.format); - CHECK_NE(cv_format, -1) << "unsupported pixel format"; + ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; CVPixelBufferRef buffer; CVReturn err = CreateCVPixelBufferWithoutPool(spec.width, spec.height, cv_format, &buffer);
diff --git a/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc b/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc index b977a89..5e06ab6 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/cv_texture_cache_manager.cc
@@ -14,6 +14,7 @@ #include "mediapipe/gpu/cv_texture_cache_manager.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" namespace mediapipe { @@ -48,7 +49,7 @@ } CvTextureCacheManager::~CvTextureCacheManager() { - CHECK_EQ(texture_caches_.size(), 0) + ABSL_CHECK_EQ(texture_caches_.size(), 0) << "Failed to unregister texture caches before deleting manager"; }
diff --git a/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc b/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc index 974525a..0a422f3 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/gl_calculator_helper.cc
@@ -14,6 +14,7 @@ #include "mediapipe/gpu/gl_calculator_helper.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/formats/image.h" #include "mediapipe/framework/formats/image_frame.h" #include "mediapipe/framework/legacy_calculator_support.h" @@ -71,7 +72,7 @@ PacketTypeSet* input_side_packets) { auto cc = LegacyCalculatorSupport::Scoped<CalculatorContract>::current(); if (cc) { - CHECK_EQ(input_side_packets, &cc->InputSidePackets()); + ABSL_CHECK_EQ(input_side_packets, &cc->InputSidePackets()); return UpdateContract(cc); }
diff --git a/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc b/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc index d7381ba..c596430 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/gl_context.cc
@@ -34,6 +34,7 @@ #ifndef __EMSCRIPTEN__ #include "absl/debugging/leak_check.h" +#include "absl/log/absl_check.h" #include "mediapipe/gpu/gl_thread_collector.h" #endif @@ -69,17 +70,17 @@ } GlContext::DedicatedThread::DedicatedThread() { - CHECK_EQ(pthread_create(&gl_thread_id_, nullptr, ThreadBody, this), 0); + ABSL_CHECK_EQ(pthread_create(&gl_thread_id_, nullptr, ThreadBody, this), 0); } GlContext::DedicatedThread::~DedicatedThread() { if (IsCurrentThread()) { CHECK(self_destruct_); - CHECK_EQ(pthread_detach(gl_thread_id_), 0); + ABSL_CHECK_EQ(pthread_detach(gl_thread_id_), 0); } else { // Give an invalid job to signal termination. PutJob({}); - CHECK_EQ(pthread_join(gl_thread_id_, nullptr), 0); + ABSL_CHECK_EQ(pthread_join(gl_thread_id_, nullptr), 0); } }
diff --git a/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc b/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc index 4e5ce4e..8c7df3a0 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/gl_texture_buffer.cc
@@ -20,6 +20,7 @@ #include "mediapipe/gpu/gpu_buffer_storage_image_frame.h" #if MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER +#include "absl/log/absl_check.h" #include "mediapipe/gpu/gl_texture_util.h" #include "mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.h" #endif // MEDIAPIPE_GPU_BUFFER_USE_CV_PIXEL_BUFFER @@ -152,7 +153,7 @@ CHECK(!deletion_callback_); deletion_callback_ = [this, context](std::shared_ptr<GlSyncPoint> sync_token) { - CHECK_NE(name_, 0); + ABSL_CHECK_NE(name_, 0); GLuint name_to_delete = name_; context->RunWithoutWaiting([name_to_delete]() { // Note that we do not wait for consumers to be done before deleting the @@ -264,7 +265,7 @@ int plane) const { auto gl_context = GlContext::GetCurrent(); CHECK(gl_context); - CHECK_EQ(plane, 0); + ABSL_CHECK_EQ(plane, 0); // Note that this method is only supposed to be called by GpuBuffer, which // ensures this condition is satisfied. DCHECK(!weak_from_this().expired()) @@ -285,7 +286,7 @@ int plane) { auto gl_context = GlContext::GetCurrent(); CHECK(gl_context); - CHECK_EQ(plane, 0); + ABSL_CHECK_EQ(plane, 0); // Note that this method is only supposed to be called by GpuBuffer, which // ensures this condition is satisfied. DCHECK(!weak_from_this().expired())
diff --git a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc index e88aa602..e9f8d0b9 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_format.cc
@@ -15,6 +15,7 @@ #include "mediapipe/gpu/gpu_buffer_format.h" #include "absl/container/flat_hash_map.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/deps/no_destructor.h" #include "mediapipe/framework/port/logging.h" @@ -194,11 +195,11 @@ << static_cast<std::underlying_type_t<decltype(format)>>(format); const auto& planes = iter->second; #ifndef __APPLE__ - CHECK_EQ(planes.size(), 1) + ABSL_CHECK_EQ(planes.size(), 1) << "multiplanar formats are not supported on this platform"; #endif - CHECK_GE(plane, 0) << "invalid plane number"; - CHECK_LT(plane, planes.size()) << "invalid plane number"; + ABSL_CHECK_GE(plane, 0) << "invalid plane number"; + ABSL_CHECK_LT(plane, planes.size()) << "invalid plane number"; return planes[plane]; } #endif // MEDIAPIPE_DISABLE_GPU
diff --git a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc index 7cac32b..642ce23b 100644 --- a/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc +++ b/third_party/mediapipe/src/mediapipe/gpu/gpu_buffer_storage_cv_pixel_buffer.cc
@@ -2,6 +2,7 @@ #include <memory> +#include "absl/log/absl_check.h" #include "mediapipe/gpu/gl_context.h" #include "mediapipe/gpu/gpu_buffer_storage_image_frame.h" #include "mediapipe/objc/util.h" @@ -17,7 +18,7 @@ GpuBufferStorageCvPixelBuffer::GpuBufferStorageCvPixelBuffer( int width, int height, GpuBufferFormat format) { OSType cv_format = CVPixelFormatForGpuBufferFormat(format); - CHECK_NE(cv_format, -1) << "unsupported pixel format"; + ABSL_CHECK_NE(cv_format, -1) << "unsupported pixel format"; CVPixelBufferRef buffer; CVReturn err = CreateCVPixelBufferWithoutPool(width, height, cv_format, &buffer);
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc index bd2ce57..9b3e434 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/box.cc
@@ -15,6 +15,7 @@ #include "mediapipe/modules/objectron/calculators/box.h" #include "Eigen/Core" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" namespace mediapipe { @@ -107,12 +108,12 @@ } float* Box::GetVertex(size_t vertex_id) { - CHECK_LT(vertex_id, kNumKeypoints); + ABSL_CHECK_LT(vertex_id, kNumKeypoints); return bounding_box_[vertex_id].data(); } const float* Box::GetVertex(size_t vertex_id) const { - CHECK_LT(vertex_id, kNumKeypoints); + ABSL_CHECK_LT(vertex_id, kNumKeypoints); return bounding_box_[vertex_id].data(); } @@ -135,7 +136,7 @@ } void Box::Deserialize(const Object& obj) { - CHECK_EQ(obj.keypoints_size(), kNumKeypoints); + ABSL_CHECK_EQ(obj.keypoints_size(), kNumKeypoints); Model::Deserialize(obj); } @@ -222,7 +223,7 @@ template <typename T> void Box::Fit(const std::vector<T>& vertices) { - CHECK_EQ(vertices.size(), kNumKeypoints); + ABSL_CHECK_EQ(vertices.size(), kNumKeypoints); scale_.setZero(); // The scale would remain invariant under rotation and translation. // We can safely estimate the scale from the oriented box.
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc index 0af3458..ba6e98a 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/decoder.cc
@@ -19,6 +19,7 @@ #include "Eigen/Core" #include "Eigen/Dense" +#include "absl/log/absl_check.h" #include "absl/status/status.h" #include "mediapipe/framework/port/canonical_errors.h" #include "mediapipe/framework/port/logging.h" @@ -46,10 +47,10 @@ FrameAnnotation Decoder::DecodeBoundingBoxKeypoints( const cv::Mat& heatmap, const cv::Mat& offsetmap) const { - CHECK_EQ(1, heatmap.channels()); - CHECK_EQ(kNumOffsetmaps, offsetmap.channels()); - CHECK_EQ(heatmap.cols, offsetmap.cols); - CHECK_EQ(heatmap.rows, offsetmap.rows); + ABSL_CHECK_EQ(1, heatmap.channels()); + ABSL_CHECK_EQ(kNumOffsetmaps, offsetmap.channels()); + ABSL_CHECK_EQ(heatmap.cols, offsetmap.cols); + ABSL_CHECK_EQ(heatmap.rows, offsetmap.rows); const float offset_scale = std::min(offsetmap.cols, offsetmap.rows); const std::vector<cv::Point> center_points = ExtractCenterKeypoints(heatmap); @@ -204,7 +205,7 @@ CHECK(estimated_box != nullptr); for (auto& annotation : *estimated_box->mutable_annotations()) { - CHECK_EQ(kNumKeypoints, annotation.keypoints_size()); + ABSL_CHECK_EQ(kNumKeypoints, annotation.keypoints_size()); // Fill input 2D Points; std::vector<Vector2f> input_points_2d;
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc index 8bd7151..03b78c72 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/epnp.cc
@@ -14,6 +14,8 @@ #include "mediapipe/modules/objectron/calculators/epnp.h" +#include "absl/log/absl_check.h" + namespace mediapipe { namespace { @@ -126,7 +128,7 @@ if (eigen_solver.info() != Eigen::Success) { return absl::AbortedError("Eigen decomposition failed."); } - CHECK_EQ(12, eigen_solver.eigenvalues().size()); + ABSL_CHECK_EQ(12, eigen_solver.eigenvalues().size()); // Eigenvalues are sorted in increasing order for SelfAdjointEigenSolver // only! If you use other Eigen Solvers, it's not guaranteed to be in
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc index 40aca39..d6fe9ed 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/model.cc
@@ -14,6 +14,7 @@ #include "mediapipe/modules/objectron/calculators/model.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" namespace mediapipe { @@ -66,9 +67,9 @@ const std::string& Model::GetCategory() const { return category_; } void Model::Deserialize(const Object& obj) { - CHECK_EQ(obj.rotation_size(), 9); - CHECK_EQ(obj.translation_size(), 3); - CHECK_EQ(obj.scale_size(), 3); + ABSL_CHECK_EQ(obj.rotation_size(), 9); + ABSL_CHECK_EQ(obj.translation_size(), 3); + ABSL_CHECK_EQ(obj.scale_size(), 3); category_ = obj.category(); using RotationMatrix = Eigen::Matrix<float, 3, 3, Eigen::RowMajor>;
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc index 0004edd..e482565 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensor_util.cc
@@ -14,6 +14,7 @@ #include "mediapipe/modules/objectron/calculators/tensor_util.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" namespace mediapipe { @@ -21,7 +22,8 @@ cv::Mat ConvertTfliteTensorToCvMat(const TfLiteTensor& tensor) { // Check tensor is BxCxWxH (size = 4) and the batch size is one(data[0] = 1) CHECK(tensor.dims->size == 4 && tensor.dims->data[0] == 1); - CHECK_EQ(kTfLiteFloat32, tensor.type) << "tflite_tensor type is not float"; + ABSL_CHECK_EQ(kTfLiteFloat32, tensor.type) + << "tflite_tensor type is not float"; const size_t num_output_channels = tensor.dims->data[3]; const int dims = 2; @@ -33,8 +35,8 @@ cv::Mat ConvertTensorToCvMat(const mediapipe::Tensor& tensor) { // Check tensor is BxCxWxH (size = 4) and the batch size is one(data[0] = 1) CHECK(tensor.shape().dims.size() == 4 && tensor.shape().dims[0] == 1); - CHECK_EQ(mediapipe::Tensor::ElementType::kFloat32 == tensor.element_type(), - true) + ABSL_CHECK_EQ( + mediapipe::Tensor::ElementType::kFloat32 == tensor.element_type(), true) << "tensor type is not float"; const size_t num_output_channels = tensor.shape().dims[3];
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc index 6989c34c..d0fc612 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tensors_to_objects_calculator.cc
@@ -17,6 +17,7 @@ #include <vector> #include "Eigen/Dense" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" @@ -170,7 +171,7 @@ num_keypoints_ = options_.num_keypoints(); // Currently only support 2D when num_values_per_keypoint equals to 2. - CHECK_EQ(options_.num_values_per_keypoint(), 2); + ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); return absl::OkStatus(); }
diff --git a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc index d74b59a..98aeb736 100644 --- a/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc +++ b/third_party/mediapipe/src/mediapipe/modules/objectron/calculators/tflite_tensors_to_objects_calculator.cc
@@ -17,6 +17,7 @@ #include <vector> #include "Eigen/Dense" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" @@ -178,7 +179,7 @@ num_keypoints_ = options_.num_keypoints(); // Currently only support 2D when num_values_per_keypoint equals to 2. - CHECK_EQ(options_.num_values_per_keypoint(), 2); + ABSL_CHECK_EQ(options_.num_values_per_keypoint(), 2); return absl::OkStatus(); }
diff --git a/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc b/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc index a0eadd7..3f0ed01 100644 --- a/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc +++ b/third_party/mediapipe/src/mediapipe/tasks/cc/text/custom_ops/ragged/ragged_tensor_to_tensor_tflite.cc
@@ -18,6 +18,7 @@ #include <cstdint> #include <memory> +#include "absl/log/absl_check.h" #include "flatbuffers/flexbuffers.h" #include "tensorflow/core/util/ragged_to_dense_util_common.h" #include "tensorflow/lite/c/common.h" @@ -357,7 +358,7 @@ }; int current_output_column = 0; int current_value_rowid = value_rowids_val(0); - // DCHECK_LT(current_value_rowid, parent_output_index.size()); + // ABSL_DCHECK_LT(current_value_rowid, parent_output_index.size()); int current_output_index = parent_output_index[current_value_rowid]; result->push_back(current_output_index); for (int i = 1; i < index_size; ++i) { @@ -374,12 +375,12 @@ } else { current_output_column = 0; current_value_rowid = next_value_rowid; - // DCHECK_LT(next_value_rowid, parent_output_index.size()); + // ABSL_DCHECK_LT(next_value_rowid, parent_output_index.size()); current_output_index = parent_output_index[next_value_rowid]; } result->push_back(current_output_index); } - // DCHECK_EQ(result->size(), value_rowids.size()); + // ABSL_DCHECK_EQ(result->size(), value_rowids.size()); } void CalculateOutputIndexRowSplit(const TfLiteTensor& row_split, @@ -420,7 +421,7 @@ } } // if (row_split_size > 0) { - // DCHECK_EQ(result->size(), row_split(row_split_size - 1)); + // ABSL_DCHECK_EQ(result->size(), row_split(row_split_size - 1)); //} }
diff --git a/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc b/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc index d8516f9b..e1aa484 100644 --- a/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc +++ b/third_party/mediapipe/src/mediapipe/util/annotation_renderer.cc
@@ -19,6 +19,7 @@ #include <algorithm> #include <cmath> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/vector.h" #include "mediapipe/util/color.pb.h" @@ -49,8 +50,8 @@ int* y_px) { CHECK(x_px != nullptr); CHECK(y_px != nullptr); - CHECK_GT(image_width, 0); - CHECK_GT(image_height, 0); + ABSL_CHECK_GT(image_width, 0); + ABSL_CHECK_GT(image_height, 0); if (normalized_x < 0 || normalized_x > 1.0 || normalized_y < 0 || normalized_y > 1.0) {
diff --git a/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc b/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc index bf2773f..d276942 100644 --- a/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc +++ b/third_party/mediapipe/src/mediapipe/util/image_frame_util.cc
@@ -20,6 +20,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" #include "absl/strings/string_view.h" @@ -47,7 +48,7 @@ const int open_cv_interpolation_algorithm, ImageFrame* destination_frame) { CHECK(destination_frame); - CHECK_EQ(ImageFormat::SRGB, source_frame.Format()); + ABSL_CHECK_EQ(ImageFormat::SRGB, source_frame.Format()); cv::Mat source_mat = ::mediapipe::formats::MatView(&source_frame); destination_frame->Reset(source_frame.Format(), width, height, @@ -106,7 +107,7 @@ u, uv_stride, // v, uv_stride, // width, height); - CHECK_EQ(0, rv); + ABSL_CHECK_EQ(0, rv); } void ImageFrameToYUVNV12Image(const ImageFrame& image_frame, @@ -136,7 +137,7 @@ yuv_i420_image.stride(2), yuv_nv12_image->mutable_data(0), yuv_nv12_image->stride(0), yuv_nv12_image->mutable_data(1), yuv_nv12_image->stride(1), width, height); - CHECK_EQ(0, rv); + ABSL_CHECK_EQ(0, rv); } void YUVImageToImageFrame(const YUVImage& yuv_image, ImageFrame* image_frame, @@ -161,7 +162,7 @@ image_frame->MutablePixelData(), image_frame->WidthStep(), width, height); } - CHECK_EQ(0, rv); + ABSL_CHECK_EQ(0, rv); } void YUVImageToImageFrameFromFormat(const YUVImage& yuv_image,
diff --git a/third_party/mediapipe/src/mediapipe/util/resource_cache.h b/third_party/mediapipe/src/mediapipe/util/resource_cache.h index 2b3ccbc..da0e4adf 100644 --- a/third_party/mediapipe/src/mediapipe/util/resource_cache.h +++ b/third_party/mediapipe/src/mediapipe/util/resource_cache.h
@@ -19,6 +19,7 @@ #include "absl/container/flat_hash_map.h" #include "absl/functional/function_ref.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" namespace mediapipe { @@ -40,10 +41,12 @@ std::tie(map_it, std::ignore) = map_.try_emplace(key, std::make_unique<Entry>(key)); entry = map_it->second.get(); - CHECK_EQ(entry->request_count, 0); + ABSL_CHECK_EQ(entry->request_count, 0); entry->request_count = 1; entry_list_.Append(entry); - if (entry->prev != nullptr) CHECK_GE(entry->prev->request_count, 1); + if (entry->prev != nullptr) { + ABSL_CHECK_GE(entry->prev->request_count, 1); + } } else { entry = map_it->second.get(); ++entry->request_count;
diff --git a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc index 21d030f..372a2c61 100644 --- a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc +++ b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence.cc
@@ -17,6 +17,7 @@ #include <cmath> #include <limits> +#include "absl/log/absl_check.h" #include "absl/strings/str_split.h" #include "mediapipe/framework/port/opencv_imgcodecs_inc.h" #include "mediapipe/framework/port/ret_check.h" @@ -534,7 +535,7 @@ << "GetAudioAt requires num_channels context to be specified as key: " << merge_prefix(prefix, kFeatureNumChannelsKey); int num_channels = GetFeatureNumChannels(prefix, sequence); - CHECK_EQ(flat_data.size() % num_channels, 0) + ABSL_CHECK_EQ(flat_data.size() % num_channels, 0) << "The data size is not a multiple of the number of channels: " << flat_data.size() << " % " << num_channels << " = " << flat_data.size() % num_channels << " for sequence index " << index;
diff --git a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h index 1737f91..2e73828 100644 --- a/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h +++ b/third_party/mediapipe/src/mediapipe/util/sequence/media_sequence_util.h
@@ -92,6 +92,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/proto_ns.h" @@ -220,7 +221,7 @@ const tensorflow::SequenceExample& sequence, const std::string& key, const int index) { const tensorflow::FeatureList& fl = GetFeatureList(sequence, key); - CHECK_LT(index, fl.feature_size()) + ABSL_CHECK_LT(index, fl.feature_size()) << "Sequence: \n " << sequence.DebugString(); return fl.feature().Get(index).float_list().value(); } @@ -231,7 +232,7 @@ const tensorflow::SequenceExample& sequence, const std::string& key, const int index) { const tensorflow::FeatureList& fl = GetFeatureList(sequence, key); - CHECK_LT(index, fl.feature_size()) + ABSL_CHECK_LT(index, fl.feature_size()) << "Sequence: \n " << sequence.DebugString(); return fl.feature().Get(index).int64_list().value(); } @@ -242,7 +243,7 @@ const tensorflow::SequenceExample& sequence, const std::string& key, const int index) { const tensorflow::FeatureList& fl = GetFeatureList(sequence, key); - CHECK_LT(index, fl.feature_size()) + ABSL_CHECK_LT(index, fl.feature_size()) << "Sequence: \n " << sequence.DebugString(); return fl.feature().Get(index).bytes_list().value(); }
diff --git a/third_party/mediapipe/src/mediapipe/util/time_series_util.cc b/third_party/mediapipe/src/mediapipe/util/time_series_util.cc index 87f69475..128cc117 100644 --- a/third_party/mediapipe/src/mediapipe/util/time_series_util.cc +++ b/third_party/mediapipe/src/mediapipe/util/time_series_util.cc
@@ -19,6 +19,7 @@ #include <iostream> #include <string> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/formats/time_series_header.pb.h" @@ -127,7 +128,7 @@ } double SamplesToSeconds(int64_t num_samples, double sample_rate) { - DCHECK_NE(sample_rate, 0.0); + ABSL_DCHECK_NE(sample_rate, 0.0); return (num_samples / sample_rate); }
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc b/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc index 58d85553..44567d7 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/box_detector.cc
@@ -16,6 +16,7 @@ #include <vector> +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "mediapipe/framework/port/opencv_calib3d_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" @@ -46,7 +47,7 @@ CHECK(!descriptors.empty()) << "empty descriptors."; const int descriptors_dims = descriptors[0].size(); - CHECK_GT(descriptors_dims, 0); + ABSL_CHECK_GT(descriptors_dims, 0); cv::Mat mat(descriptors.size(), descriptors_dims, CV_8U); @@ -59,13 +60,13 @@ cv::Mat GetDescriptorsWithIndices(const cv::Mat &frame_descriptors, const std::vector<int> &indices) { - CHECK_GT(frame_descriptors.rows, 0); + ABSL_CHECK_GT(frame_descriptors.rows, 0); const int num_inlier_descriptors = indices.size(); - CHECK_GT(num_inlier_descriptors, 0); + ABSL_CHECK_GT(num_inlier_descriptors, 0); const int descriptors_dims = frame_descriptors.cols; - CHECK_GT(descriptors_dims, 0); + ABSL_CHECK_GT(descriptors_dims, 0); cv::Mat mat(num_inlier_descriptors, descriptors_dims, CV_32F); @@ -301,7 +302,7 @@ orb_extractor_->detect(resize_image, keypoints); orb_extractor_->compute(resize_image, keypoints, descriptors); - CHECK_EQ(keypoints.size(), descriptors.rows); + ABSL_CHECK_EQ(keypoints.size(), descriptors.rows); float inv_scale = 1.0f / std::max(resize_image.cols, resize_image.rows); std::vector<Vector2_f> v_keypoints(keypoints.size()); @@ -681,15 +682,15 @@ continue; } - CHECK_EQ(frame_entry.keypoints_size(), - frame_entry.descriptors_size() * 2); + ABSL_CHECK_EQ(frame_entry.keypoints_size(), + frame_entry.descriptors_size() * 2); const int num_features = frame_entry.descriptors_size(); - CHECK_GT(num_features, 0); + ABSL_CHECK_GT(num_features, 0); std::vector<Vector2_f> features(num_features); const int descriptors_dims = frame_entry.descriptors(0).data().size(); - CHECK_GT(descriptors_dims, 0); + ABSL_CHECK_GT(descriptors_dims, 0); cv::Mat descriptors_mat(num_features, descriptors_dims / sizeof(float), CV_32F); @@ -713,7 +714,7 @@ BoxDetectorOpencvBfImpl::MatchFeatureDescriptors( const std::vector<Vector2_f> &features, const cv::Mat &descriptors, int box_idx) { - CHECK_EQ(features.size(), descriptors.rows); + ABSL_CHECK_EQ(features.size(), descriptors.rows); std::vector<FeatureCorrespondence> correspondence_result( frame_box_[box_idx].size());
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc b/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc index 2d1af77..61a9437b 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/box_tracker.cc
@@ -19,6 +19,7 @@ #include <fstream> #include <limits> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/synchronization/mutex.h" #include "absl/time/clock.h" @@ -36,7 +37,7 @@ void MotionBoxStateQuadToVertices(const MotionBoxState::Quad& quad, std::vector<Vector2_f>* vertices) { - CHECK_EQ(TimedBox::kNumQuadVertices * 2, quad.vertices_size()); + ABSL_CHECK_EQ(TimedBox::kNumQuadVertices * 2, quad.vertices_size()); CHECK(vertices != nullptr); vertices->clear(); for (int i = 0; i < TimedBox::kNumQuadVertices; ++i) { @@ -47,7 +48,7 @@ void VerticesToMotionBoxStateQuad(const std::vector<Vector2_f>& vertices, MotionBoxState::Quad* quad) { - CHECK_EQ(TimedBox::kNumQuadVertices, vertices.size()); + ABSL_CHECK_EQ(TimedBox::kNumQuadVertices, vertices.size()); CHECK(quad != nullptr); for (const Vector2_f& vertex : vertices) { quad->add_vertices(vertex.x()); @@ -113,7 +114,7 @@ TimedBox BlendTimedBoxes(const TimedBox& lhs, const TimedBox& rhs, int64_t time_msec) { - CHECK_LT(lhs.time_msec, rhs.time_msec); + ABSL_CHECK_LT(lhs.time_msec, rhs.time_msec); const double alpha = (time_msec - lhs.time_msec) * 1.0 / (rhs.time_msec - lhs.time_msec); return TimedBox::Blend(lhs, rhs, alpha); @@ -245,10 +246,10 @@ void BoxTracker::AddTrackingDataChunk(const TrackingDataChunk* chunk, bool copy_data) { - CHECK_GT(chunk->item_size(), 0) << "Empty chunk."; + ABSL_CHECK_GT(chunk->item_size(), 0) << "Empty chunk."; int64_t chunk_time_msec = chunk->item(0).timestamp_usec() / 1000; int chunk_idx = ChunkIdxFromTime(chunk_time_msec); - CHECK_GE(chunk_idx, tracking_data_.size()) << "Chunk is out of order."; + ABSL_CHECK_GE(chunk_idx, tracking_data_.size()) << "Chunk is out of order."; if (chunk_idx > tracking_data_.size()) { LOG(INFO) << "Resize tracking_data_ to " << chunk_idx; tracking_data_.resize(chunk_idx); @@ -688,7 +689,7 @@ int BoxTracker::ClosestFrameIndex(int64_t msec, const TrackingDataChunk& chunk) const { - CHECK_GT(chunk.item_size(), 0); + ABSL_CHECK_GT(chunk.item_size(), 0); typedef TrackingDataChunk::Item Item; Item item_to_find; item_to_find.set_timestamp_usec(msec * 1000); @@ -749,8 +750,8 @@ MotionBox motion_box(track_step_options); const int chunk_data_size = a.chunk_data->item_size(); - CHECK_GE(a.start_frame, 0); - CHECK_LT(a.start_frame, chunk_data_size); + ABSL_CHECK_GE(a.start_frame, 0); + ABSL_CHECK_LT(a.start_frame, chunk_data_size); VLOG(1) << " a.start_frame = " << a.start_frame << " @" << a.chunk_data->item(a.start_frame).timestamp_usec() << " with "
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc index e753be7..b2c137c8 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.cc
@@ -16,6 +16,7 @@ #include <numeric> +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" #include "mediapipe/util/tracking/region_flow.h" @@ -76,8 +77,8 @@ CameraMotion ComposeCameraMotion(const CameraMotion& lhs, const CameraMotion& rhs) { - CHECK_EQ(lhs.frame_width(), rhs.frame_width()); - CHECK_EQ(lhs.frame_height(), rhs.frame_height()); + ABSL_CHECK_EQ(lhs.frame_width(), rhs.frame_width()); + ABSL_CHECK_EQ(lhs.frame_height(), rhs.frame_height()); CameraMotion result = rhs; if (lhs.has_translation() || rhs.has_translation()) { @@ -185,7 +186,7 @@ const std::vector<CameraMotion>& camera_motions, std::vector<RegionFlowFeatureList*>* feature_lists) { CHECK(feature_lists != nullptr); - CHECK_GE(camera_motions.size(), feature_lists->size()); + ABSL_CHECK_GE(camera_motions.size(), feature_lists->size()); if (feature_lists->empty()) { return; }
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h index cadee78..379920b1 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/camera_motion.h
@@ -17,6 +17,7 @@ #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/util/tracking/camera_motion.pb.h" #include "mediapipe/util/tracking/motion_models.h" #include "mediapipe/util/tracking/region_flow.pb.h" @@ -236,7 +237,7 @@ std::vector<Model>* downsampled_models, std::vector<CameraMotion::Type>* downsampled_types) { if (model_type) { - CHECK_EQ(models.size(), model_type->size()); + ABSL_CHECK_EQ(models.size(), model_type->size()); CHECK(downsampled_models) << "Expecting output models."; }
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc b/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc index dceacbcd..01ee6f6 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/flow_packager.cc
@@ -20,6 +20,7 @@ #include <cmath> #include <memory> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "mediapipe/framework/port/logging.h" @@ -36,8 +37,8 @@ FlowPackager::FlowPackager(const FlowPackagerOptions& options) : options_(options) { if (options_.binary_tracking_data_support()) { - CHECK_LE(options.domain_width(), 256); - CHECK_LE(options.domain_height(), 256); + ABSL_CHECK_LE(options.domain_width(), 256); + ABSL_CHECK_LE(options.domain_height(), 256); } } @@ -135,8 +136,8 @@ const CameraMotion* camera_motion, TrackingData* tracking_data) const { CHECK(tracking_data); - CHECK_GT(feature_list.frame_width(), 0); - CHECK_GT(feature_list.frame_height(), 0); + ABSL_CHECK_GT(feature_list.frame_width(), 0); + ABSL_CHECK_GT(feature_list.frame_height(), 0); // Scale flow to output domain. const float dim_x_scale = @@ -231,12 +232,12 @@ const int curr_col = loc.x(); if (curr_col != last_col) { - CHECK_LT(last_col, curr_col); - CHECK_EQ(-1, col_start[curr_col]); + ABSL_CHECK_LT(last_col, curr_col); + ABSL_CHECK_EQ(-1, col_start[curr_col]); col_start[curr_col] = data->row_indices_size() - 1; last_col = curr_col; } else { - CHECK_LE(last_row, loc.y()); + ABSL_CHECK_LE(last_row, loc.y()); } last_row = loc.y(); } @@ -247,7 +248,7 @@ // Fill unset values with previously set value. Propagate end value. for (int i = options_.domain_width() - 1; i > 0; --i) { if (col_start[i] < 0) { - DCHECK_GE(col_start[i + 1], 0); + ABSL_DCHECK_GE(col_start[i + 1], 0); col_start[i] = col_start[i + 1]; } } @@ -261,11 +262,11 @@ const int r_start = data->col_starts(c); const int r_end = data->col_starts(c + 1); for (int r = r_start; r < r_end - 1; ++r) { - CHECK_LE(data->row_indices(r), data->row_indices(r + 1)); + ABSL_CHECK_LE(data->row_indices(r), data->row_indices(r + 1)); } } - CHECK_EQ(data->vector_data_size(), 2 * data->row_indices_size()); + ABSL_CHECK_EQ(data->vector_data_size(), 2 * data->row_indices_size()); *data->mutable_actively_discarded_tracked_ids() = feature_list.actively_discarded_tracked_ids(); @@ -313,7 +314,7 @@ const int32_t domain_width = tracking_data.domain_width(); const int32_t domain_height = tracking_data.domain_height(); - CHECK_LT(domain_height, 256) << "Only heights below 256 are supported."; + ABSL_CHECK_LT(domain_height, 256) << "Only heights below 256 are supported."; const float frame_aspect = tracking_data.frame_aspect(); // Limit vector value from above (to 20% frame diameter) and below (small @@ -393,7 +394,7 @@ flow_compressed_8.push_back(flow_y); } - DCHECK_LT(motion_data.row_indices(r), 256); + ABSL_DCHECK_LT(motion_data.row_indices(r), 256); row_idx.push_back(motion_data.row_indices(r)); } } @@ -470,7 +471,7 @@ // Delta compress. int delta_row = motion_data.row_indices(r) - (r == r_start ? 0 : motion_data.row_indices(r - 1)); - CHECK_GE(delta_row, 0); + ABSL_CHECK_GE(delta_row, 0); bool combined = false; if (r > r_start) { @@ -520,9 +521,9 @@ } if (options_.high_fidelity_16bit_encode()) { - CHECK_EQ(2 * encoded, flow_compressed_16.size()); + ABSL_CHECK_EQ(2 * encoded, flow_compressed_16.size()); } else { - CHECK_EQ(2 * encoded, flow_compressed_8.size()); + ABSL_CHECK_EQ(2 * encoded, flow_compressed_8.size()); } // Adjust column start by compressions. @@ -530,11 +531,11 @@ for (int k = 0; k < domain_width; ++k) { curr_adjust -= compressions_per_column[k]; col_starts[k + 1] += curr_adjust; - CHECK_LE(col_starts[k], col_starts[k + 1]); + ABSL_CHECK_LE(col_starts[k], col_starts[k + 1]); } - CHECK_EQ(row_idx.size(), col_starts.back()); - CHECK_EQ(num_vectors, row_idx.size() + compressible); + ABSL_CHECK_EQ(row_idx.size(), col_starts.back()); + ABSL_CHECK_EQ(num_vectors, row_idx.size() + compressible); } // Delta compress col_starts. @@ -542,7 +543,7 @@ col_start_delta[0] = col_starts[0]; for (int k = 1; k < domain_width + 1; ++k) { const int delta = col_starts[k] - col_starts[k - 1]; - CHECK_LT(delta, 256) << "Only up to 255 items per column supported."; + ABSL_CHECK_LT(delta, 256) << "Only up to 255 items per column supported."; col_start_delta[k] = delta; } @@ -618,8 +619,8 @@ DecodeFromStringView(PopSubstring(4, &data), &domain_height); DecodeFromStringView(PopSubstring(4, &data), &frame_aspect); - CHECK_LE(domain_width, 256); - CHECK_LE(domain_height, 256); + ABSL_CHECK_LE(domain_width, 256); + ABSL_CHECK_LE(domain_height, 256); DecodeVectorFromStringView( PopSubstring(4 * HomographyAdapter::NumParameters(), &data), @@ -662,7 +663,7 @@ // Should not have more row indices than vectors. (One for each in baseline // profile, less in high profile). - CHECK_LE(row_idx_size, num_vectors); + ABSL_CHECK_LE(row_idx_size, num_vectors); DecodeVectorFromStringView(PopSubstring(row_idx_size, &data), &row_idx); // Records for each vector whether to advance pointer in the vector data array @@ -707,7 +708,7 @@ } } row_idx.swap(row_idx_unpacked); - CHECK_EQ(num_vectors, row_idx.size()); + ABSL_CHECK_EQ(num_vectors, row_idx.size()); // Adjust column start by expansions. int curr_adjust = 0; @@ -717,7 +718,7 @@ } } - CHECK_EQ(num_vectors, col_starts.back()); + ABSL_CHECK_EQ(num_vectors, col_starts.back()); int vector_data_size; DecodeFromStringView(PopSubstring(4, &data), &vector_data_size); @@ -749,7 +750,7 @@ motion_data->add_vector_data(prev_flow_y * flow_denom); } } - CHECK_EQ(vector_data_size, counter); + ABSL_CHECK_EQ(vector_data_size, counter); } else { std::vector<int8_t> vector_data; DecodeVectorFromStringView( @@ -775,7 +776,7 @@ motion_data->add_vector_data(prev_flow_y * flow_denom); } } - CHECK_EQ(vector_data_size, counter); + ABSL_CHECK_EQ(vector_data_size, counter); } for (auto idx : row_idx) { @@ -799,8 +800,8 @@ void FlowPackager::BinaryTrackingDataFromContainer( const TrackingContainer& container, BinaryTrackingData* binary_data) const { - CHECK_EQ("TRAK", container.header()); - CHECK_EQ(1, container.version()) << "Unsupported version."; + ABSL_CHECK_EQ("TRAK", container.header()); + ABSL_CHECK_EQ(1, container.version()) << "Unsupported version."; *binary_data->mutable_data() = container.data(); } @@ -808,8 +809,8 @@ MetaData* meta_data) const { CHECK(meta_data != nullptr); - CHECK_EQ("META", container_data.header()); - CHECK_EQ(1, container_data.version()) << "Unsupported version."; + ABSL_CHECK_EQ("META", container_data.header()); + ABSL_CHECK_EQ(1, container_data.version()) << "Unsupported version."; absl::string_view data(container_data.data()); @@ -840,7 +841,7 @@ std::vector<uint32_t> msecs(num_frames, 0); if (timestamps) { - CHECK_EQ(num_frames, timestamps->size()); + ABSL_CHECK_EQ(num_frames, timestamps->size()); msecs = *timestamps; } std::vector<int> sizes(num_frames, 0); @@ -884,7 +885,7 @@ std::vector<uint32_t> msecs(num_frames, 0); if (timestamps) { - CHECK_EQ(num_frames, timestamps->size()); + ABSL_CHECK_EQ(num_frames, timestamps->size()); msecs = *timestamps; } @@ -909,8 +910,8 @@ const std::vector<int>& data_sizes, MetaData* meta_data) const { meta_data->set_num_frames(num_frames); - CHECK_EQ(num_frames, msecs.size()); - CHECK_EQ(num_frames, data_sizes.size()); + ABSL_CHECK_EQ(num_frames, msecs.size()); + ABSL_CHECK_EQ(num_frames, data_sizes.size()); int curr_offset = 0; for (int f = 0; f < num_frames; ++f) { @@ -925,7 +926,7 @@ std::string* binary_data) { CHECK(binary_data != nullptr); std::string header_string(container.header()); - CHECK_EQ(4, header_string.size()); + ABSL_CHECK_EQ(4, header_string.size()); std::vector<char> header{header_string[0], header_string[1], header_string[2], header_string[3]}; @@ -938,8 +939,8 @@ absl::string_view* binary_data, TrackingContainer* container) { CHECK(binary_data != nullptr); CHECK(container != nullptr); - CHECK_GE(binary_data->size(), 12) << "Data does not contain " - << "valid container"; + ABSL_CHECK_GE(binary_data->size(), 12) << "Data does not contain " + << "valid container"; container->set_header(PopSubstring(4, binary_data)); @@ -979,18 +980,18 @@ absl::string_view data(binary); - CHECK_EQ("META", SplitContainerFromString( - &data, container_format->mutable_meta_data())); + ABSL_CHECK_EQ("META", SplitContainerFromString( + &data, container_format->mutable_meta_data())); MetaData meta_data; DecodeMetaData(container_format->meta_data(), &meta_data); for (int f = 0; f < meta_data.num_frames(); ++f) { TrackingContainer* container = container_format->add_track_data(); - CHECK_EQ("TRAK", SplitContainerFromString(&data, container)); + ABSL_CHECK_EQ("TRAK", SplitContainerFromString(&data, container)); } - CHECK_EQ("TERM", SplitContainerFromString( - &data, container_format->mutable_term_data())); + ABSL_CHECK_EQ("TERM", SplitContainerFromString( + &data, container_format->mutable_term_data())); } void FlowPackager::SortRegionFlowFeatureList(
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc index a44c00b0..a7e4a2f4 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.cc
@@ -17,6 +17,7 @@ #include <algorithm> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/util/tracking/motion_models.h" #include "mediapipe/util/tracking/region_flow.h" @@ -26,7 +27,7 @@ // Returns median of the L1 color distance between img_1 and img_2 float FrameDifferenceMedian(const cv::Mat& img_1, const cv::Mat& img_2) { CHECK(img_1.size() == img_2.size()); - CHECK_EQ(img_1.channels(), img_2.channels()); + ABSL_CHECK_EQ(img_1.channels(), img_2.channels()); std::vector<float> color_diffs; color_diffs.reserve(img_1.cols * img_1.rows);
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h index ba58d34..f1e7eda 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/image_util.h
@@ -17,6 +17,7 @@ #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/opencv_core_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" #include "mediapipe/framework/port/vector.h" @@ -75,7 +76,7 @@ } // src and dst should point to same column from here. - DCHECK_EQ(0, (src_ptr - dst_ptr) * sizeof(T) % mat->step[0]); + ABSL_DCHECK_EQ(0, (src_ptr - dst_ptr) * sizeof(T) % mat->step[0]); // Top row copy. memcpy(dst_ptr, src_ptr, width * channels * sizeof(dst_ptr[0])); @@ -122,7 +123,7 @@ } // src and dst should point to same column from here. - DCHECK_EQ(0, (dst_ptr - src_ptr) * sizeof(T) % mat->step[0]); + ABSL_DCHECK_EQ(0, (dst_ptr - src_ptr) * sizeof(T) % mat->step[0]); memcpy(dst_ptr, src_ptr, width * channels * sizeof(dst_ptr[0])); src_ptr += width * channels; // Points one behind the end. dst_ptr += width * channels;
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc index 67973cbc..d7509774 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_analysis.cc
@@ -20,6 +20,7 @@ #include <deque> #include <memory> +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" @@ -92,8 +93,8 @@ use_spatial_bias; if (compute_feature_descriptors_) { - CHECK_EQ(RegionFlowComputationOptions::FORMAT_RGB, - options_.flow_options().image_format()) + ABSL_CHECK_EQ(RegionFlowComputationOptions::FORMAT_RGB, + options_.flow_options().image_format()) << "Feature descriptors only support RGB currently."; prev_frame_.reset(new cv::Mat(frame_height_, frame_width_, CV_8UC3)); } @@ -479,7 +480,7 @@ const int num_features_lists = buffer_->BufferSize("features"); const int num_new_feature_lists = num_features_lists - overlap_start_; - CHECK_GE(num_new_feature_lists, 0); + ABSL_CHECK_GE(num_new_feature_lists, 0); if (!flush && num_new_feature_lists < options_.estimation_clip_size()) { // Nothing to compute, return. @@ -487,7 +488,7 @@ } const bool compute_saliency = options_.compute_motion_saliency(); - CHECK_EQ(compute_saliency, saliency != nullptr) + ABSL_CHECK_EQ(compute_saliency, saliency != nullptr) << "Computing saliency requires saliency output and vice versa"; // Estimate motions for newly buffered RegionFlowFeatureLists, which also @@ -528,7 +529,7 @@ std::vector<std::unique_ptr<CameraMotion>>* camera_motion, std::vector<std::unique_ptr<SalientPointFrame>>* saliency) { const bool compute_saliency = options_.compute_motion_saliency(); - CHECK_EQ(compute_saliency, saliency != nullptr) + ABSL_CHECK_EQ(compute_saliency, saliency != nullptr) << "Computing saliency requires saliency output and vice versa"; CHECK(buffer_->HaveEqualSize({"features", "motion"})); @@ -598,7 +599,7 @@ // Reset for next chunk. prev_overlap_start_ = num_output_frames - new_overlap_start; - CHECK_GE(prev_overlap_start_, 0); + ABSL_CHECK_GE(prev_overlap_start_, 0); CHECK(buffer_->TruncateBuffer(flush)); @@ -612,8 +613,8 @@ cv::Mat* rendered_results) { #ifndef NO_RENDERING CHECK(rendered_results != nullptr); - CHECK_EQ(frame_width_, rendered_results->cols); - CHECK_EQ(frame_height_, rendered_results->rows); + ABSL_CHECK_EQ(frame_width_, rendered_results->cols); + ABSL_CHECK_EQ(frame_height_, rendered_results->rows); const auto viz_options = options_.visualization_options(); @@ -797,7 +798,7 @@ void MotionAnalysis::ComputeSaliency() { MEASURE_TIME << "Saliency computation."; - CHECK_EQ(overlap_start_, buffer_->BufferSize("saliency")); + ABSL_CHECK_EQ(overlap_start_, buffer_->BufferSize("saliency")); const int num_features_lists = buffer_->BufferSize("features");
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc index b608b47..1da6496 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_estimation.cc
@@ -31,6 +31,7 @@ #include "Eigen/SVD" #include "absl/container/node_hash_map.h" #include "absl/container/node_hash_set.h" +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/util/tracking/camera_motion.h" @@ -175,7 +176,7 @@ std::vector<float>* motion_prior) { CHECK(motion_prior != nullptr); const int num_features = feature_list.feature_size(); - CHECK_EQ(num_features, motion_prior->size()); + ABSL_CHECK_EQ(num_features, motion_prior->size()); // Return, if prior is too low. const float kMinTranslationPrior = 0.5f; @@ -185,7 +186,7 @@ } const float prev_magnitude = translation_.Norm(); - CHECK_EQ(num_features, motion_prior->size()); + ABSL_CHECK_EQ(num_features, motion_prior->size()); const float inv_prev_magnitude = prev_magnitude < options_.min_translation_norm() ? (1.0f / options_.min_translation_norm()) @@ -398,21 +399,21 @@ void CheckInitialization() const { CHECK(feature_lists != nullptr); CHECK(camera_motions != nullptr); - CHECK_EQ(feature_lists->size(), camera_motions->size()); + ABSL_CHECK_EQ(feature_lists->size(), camera_motions->size()); if (feature_lists->empty()) { return; } - CHECK_EQ(num_frames(), irls_weight_input.size()); - CHECK_EQ(num_frames(), homog_irls_weight_input.size()); + ABSL_CHECK_EQ(num_frames(), irls_weight_input.size()); + ABSL_CHECK_EQ(num_frames(), homog_irls_weight_input.size()); if (irls_weight_backup) { - CHECK_EQ(num_frames(), irls_weight_backup->size()); + ABSL_CHECK_EQ(num_frames(), irls_weight_backup->size()); } for (int k = 0; k < num_frames(); ++k) { const int num_features = (*feature_lists)[k]->feature_size(); - CHECK_EQ(num_features, irls_weight_input[k].size()); - CHECK_EQ(num_features, homog_irls_weight_input[k].size()); + ABSL_CHECK_EQ(num_features, irls_weight_input[k].size()); + ABSL_CHECK_EQ(num_features, homog_irls_weight_input[k].size()); } } @@ -500,15 +501,15 @@ } // Check for deprecated options. - CHECK_NE(options.estimate_similarity(), true) + ABSL_CHECK_NE(options.estimate_similarity(), true) << "Option estimate_similarity is deprecated, use static function " << "EstimateSimilarityModelL2 instead."; - CHECK_NE(options.linear_similarity_estimation(), - MotionEstimationOptions::ESTIMATION_LS_L2_RANSAC) + ABSL_CHECK_NE(options.linear_similarity_estimation(), + MotionEstimationOptions::ESTIMATION_LS_L2_RANSAC) << "Option ESTIMATION_LS_L2_RANSAC is deprecated, use " << "ESTIMATION_LS_IRLS instead."; - CHECK_NE(options.linear_similarity_estimation(), - MotionEstimationOptions::ESTIMATION_LS_L1) + ABSL_CHECK_NE(options.linear_similarity_estimation(), + MotionEstimationOptions::ESTIMATION_LS_L1) << "Option ESTIMATION_LS_L1 is deprecated, use static function " << "EstimateLinearSimilarityL1 instead."; @@ -825,7 +826,7 @@ CHECK(camera_motions != nullptr); const int num_frames = feature_lists->size(); - CHECK_EQ(num_frames, camera_motions->size()); + ABSL_CHECK_EQ(num_frames, camera_motions->size()); // Initialize camera_motions. for (int f = 0; f < num_frames; ++f) { @@ -866,7 +867,7 @@ const int num_motion_models = use_joint_tracks ? options_.joint_track_estimation().num_motion_models() : 1; - CHECK_GT(num_motion_models, 0); + ABSL_CHECK_GT(num_motion_models, 0); // Several single track clip datas, we seek to process. std::vector<SingleTrackClipData> clip_datas(num_motion_models); @@ -1080,7 +1081,8 @@ // Estimate mixtures across a spectrum a different regularizers, from the // weakest to the most regularized one. const int num_mixture_levels = options_.mixture_regularizer_levels(); - CHECK_LE(num_mixture_levels, 10) << "Only up to 10 mixtures are supported."; + ABSL_CHECK_LE(num_mixture_levels, 10) + << "Only up to 10 mixtures are supported."; // Initialize to weakest regularizer. float regularizer = options_.mixture_regularizer(); @@ -1124,8 +1126,8 @@ // Check that mixture spectrum has sufficient entries. for (const CameraMotion& motion : *camera_motions) { if (motion.mixture_homography_spectrum_size() > 0) { - CHECK_EQ(motion.mixture_homography_spectrum_size(), - options_.mixture_regularizer_levels()); + ABSL_CHECK_EQ(motion.mixture_homography_spectrum_size(), + options_.mixture_regularizer_levels()); } } @@ -1570,7 +1572,7 @@ // Initialize priors from irls weights. if (use_prior_weights) { - CHECK_LT(frame, clip_data_->prior_weights.size()); + ABSL_CHECK_LT(frame, clip_data_->prior_weights.size()); if (clip_data_->prior_weights[frame].priors.empty()) { clip_data_->prior_weights[frame].priors.resize( @@ -1610,7 +1612,7 @@ return; } - CHECK_EQ(num_features, irls_weights->size()); + ABSL_CHECK_EQ(num_features, irls_weights->size()); // Determine actual scale to be applied to each feature. std::vector<float> feature_scales(num_features); @@ -1644,7 +1646,7 @@ std::vector<float>* irls_weights) const { CHECK(irls_weights); const int num_features = feature_list.feature_size(); - CHECK_EQ(num_features, irls_weights->size()); + ABSL_CHECK_EQ(num_features, irls_weights->size()); // Compute mask index for each feature. std::vector<int> bin_indices; @@ -1707,13 +1709,13 @@ float normalizer = 0; int bin_idx = int_grid_y * mask_size + int_grid_x; - CHECK_LT(bin_idx, max_bins); + ABSL_CHECK_LT(bin_idx, max_bins); // See above. normalizer += bin_normalizer[bin_idx] * (1 - dx_plus_dy + dxdy); normalizer += bin_normalizer[bin_idx + inc_x] * (dx - dxdy); bin_idx += mask_size * inc_y; - CHECK_LT(bin_idx, max_bins); + ABSL_CHECK_LT(bin_idx, max_bins); normalizer += bin_normalizer[bin_idx] * (dy - dxdy); normalizer += bin_normalizer[bin_idx + inc_x] * dxdy; @@ -1738,8 +1740,8 @@ SingleTrackClipData* clip_data) const { if (options_.estimation_policy() == MotionEstimationOptions::TEMPORAL_LONG_FEATURE_BIAS) { - CHECK_NE(frame, -1) << "Only per frame processing for this policy " - << "supported."; + ABSL_CHECK_NE(frame, -1) << "Only per frame processing for this policy " + << "supported."; } IrlsInitializationInvoker invoker(type, max_unstable_type, model_options, @@ -1763,8 +1765,8 @@ for_function(0, clip_data->num_frames(), 1, invoker); } else { - CHECK_GE(frame, 0); - CHECK_LT(frame, clip_data->num_frames()); + ABSL_CHECK_GE(frame, 0); + ABSL_CHECK_LT(frame, clip_data->num_frames()); invoker(BlockedRange(frame, frame + 1, 1)); } } @@ -1960,7 +1962,7 @@ prior_weights->priors.resize(num_features, 1.0f); } - CHECK_EQ(num_features, prior_weights->priors.size()); + ABSL_CHECK_EQ(num_features, prior_weights->priors.size()); for (int k = 0; k < num_features; ++k) { prior_weights->priors[k] *= bias[k]; auto* feature = feature_list->mutable_feature(k); @@ -1993,7 +1995,7 @@ BuildFeatureGrid(NormalizedDomain().x(), NormalizedDomain().y(), bias_options.grid_size(), {feature_view}, FeatureLocation, &feature_taps_3, nullptr, nullptr, &feature_grids); - CHECK_EQ(1, feature_grids.size()); + ABSL_CHECK_EQ(1, feature_grids.size()); const FeatureGrid<RegionFlowFeature>& single_grid = feature_grids[0]; const float long_track_threshold = bias_options.long_track_threshold(); @@ -2118,7 +2120,7 @@ const auto& bias_options = options_.long_feature_bias_options(); const int num_irls_observations = bias_options.num_irls_observations(); - CHECK_GT(num_irls_observations, 0) << "Specify value > 0"; + ABSL_CHECK_GT(num_irls_observations, 0) << "Specify value > 0"; const float inv_num_irls_observations = 1.0f / num_irls_observations; SpatialBiasMap spatial_bias; @@ -2137,7 +2139,7 @@ // Scale applied to irls weight for linear interpolation between inlier and // outlier bias. - CHECK_GT(bias_options.inlier_irls_weight(), 0); + ABSL_CHECK_GT(bias_options.inlier_irls_weight(), 0); const float irls_scale = 1.0f / bias_options.inlier_irls_weight(); const float long_track_scale = 1.0f / bias_options.long_track_confidence_fraction(); @@ -2434,9 +2436,9 @@ CHECK(camera_motions != nullptr); const int num_frames = feature_lists->size(); if (reset_irls_weights) { - DCHECK_EQ(num_frames, reset_irls_weights->size()); + ABSL_DCHECK_EQ(num_frames, reset_irls_weights->size()); } - DCHECK_EQ(num_frames, camera_motions->size()); + ABSL_DCHECK_EQ(num_frames, camera_motions->size()); for (int f = 0; f < num_frames; ++f) { CameraMotion& camera_motion = (*camera_motions)[f]; @@ -2470,7 +2472,7 @@ camera_motion->translation_variance(), *feature_list)) { // Translation can never be singular. - CHECK_EQ( + ABSL_CHECK_EQ( 0, camera_motion->flags() & CameraMotion::FLAG_SINGULAR_ESTIMATION); } else { // Invalid model. @@ -2697,7 +2699,7 @@ const std::vector<RegionFlowFeatureList*>& feature_lists, std::vector<CameraMotion>* camera_motions) const { CHECK(camera_motions != nullptr); - CHECK_EQ(feature_lists.size(), camera_motions->size()); + ABSL_CHECK_EQ(feature_lists.size(), camera_motions->size()); const auto& shot_options = options_.shot_boundary_options(); // Verify empty feature frames and invalid models via visual consistency. @@ -3493,11 +3495,11 @@ float threshold = std::max<float>(similarity_bounds.inlier_threshold(), similarity_bounds.frac_inlier_threshold() * hypot(frame_width_, frame_height_)); - CHECK_GT(threshold, 0); + ABSL_CHECK_GT(threshold, 0); threshold = 1.0f / threshold; float strict_threshold = similarity_bounds.strict_inlier_threshold(); - CHECK_GT(strict_threshold, 0); + ABSL_CHECK_GT(strict_threshold, 0); strict_threshold = 1.0f / strict_threshold; if (!options_.irls_use_l0_norm()) { @@ -3761,12 +3763,12 @@ Eigen::Matrix<T, 8, 1>* solution) { CHECK(matrix); CHECK(solution); - CHECK_EQ(8, matrix->cols()); + ABSL_CHECK_EQ(8, matrix->cols()); const int num_rows = 2 * feature_list.feature_size() + (perspective_regularizer == 0 ? 0 : 1); - CHECK_EQ(num_rows, matrix->rows()); - CHECK_EQ(1, solution->cols()); - CHECK_EQ(8, solution->rows()); + ABSL_CHECK_EQ(num_rows, matrix->rows()); + ABSL_CHECK_EQ(1, solution->cols()); + ABSL_CHECK_EQ(8, solution->rows()); // Compute homography from features (H * location = prev_location). *matrix = Eigen::Matrix<T, Eigen::Dynamic, 8>::Zero(matrix->rows(), 8); @@ -4066,11 +4068,12 @@ const int num_dof = 8 * num_models; const int num_constraints = num_dof - 8; - CHECK_EQ(matrix->cols(), num_dof); + ABSL_CHECK_EQ(matrix->cols(), num_dof); // 2 Rows (x,y) per feature. - CHECK_EQ(matrix->rows(), 2 * feature_list.feature_size() + num_constraints); - CHECK_EQ(solution->cols(), 1); - CHECK_EQ(solution->rows(), num_dof); + ABSL_CHECK_EQ(matrix->rows(), + 2 * feature_list.feature_size() + num_constraints); + ABSL_CHECK_EQ(solution->cols(), 1); + ABSL_CHECK_EQ(solution->rows(), num_dof); // Compute homography from features. (H * location = prev_location) *matrix = Eigen::MatrixXf::Zero(matrix->rows(), matrix->cols()); @@ -4162,11 +4165,12 @@ const int num_dof = 6 + 2 * num_models; const int num_constraints = 2 * (num_models - 1); - CHECK_EQ(matrix->cols(), num_dof); + ABSL_CHECK_EQ(matrix->cols(), num_dof); // 2 Rows (x,y) per feature. - CHECK_EQ(matrix->rows(), 2 * feature_list.feature_size() + num_constraints); - CHECK_EQ(solution->cols(), 1); - CHECK_EQ(solution->rows(), num_dof); + ABSL_CHECK_EQ(matrix->rows(), + 2 * feature_list.feature_size() + num_constraints); + ABSL_CHECK_EQ(solution->cols(), 1); + ABSL_CHECK_EQ(solution->rows(), num_dof); // Compute homography from features. (H * location = prev_location) *matrix = Eigen::MatrixXf::Zero(matrix->rows(), matrix->cols()); @@ -4261,11 +4265,12 @@ const int num_dof = 4 + 4 * num_models; const int num_constraints = 4 * (num_models - 1); - CHECK_EQ(matrix->cols(), num_dof); + ABSL_CHECK_EQ(matrix->cols(), num_dof); // 2 Rows (x,y) per feature. - CHECK_EQ(matrix->rows(), 2 * feature_list.feature_size() + num_constraints); - CHECK_EQ(solution->cols(), 1); - CHECK_EQ(solution->rows(), num_dof); + ABSL_CHECK_EQ(matrix->rows(), + 2 * feature_list.feature_size() + num_constraints); + ABSL_CHECK_EQ(solution->cols(), 1); + ABSL_CHECK_EQ(solution->rows(), num_dof); // Compute homography from features. (H * location = prev_location) *matrix = Eigen::MatrixXf::Zero(matrix->rows(), matrix->cols()); @@ -4669,7 +4674,7 @@ const std::vector<float>& grid_cell_weights = thread_storage->GridCoverageInitializationWeights(); - CHECK_EQ(mask_size, grid_cell_weights.size()); + ABSL_CHECK_EQ(mask_size, grid_cell_weights.size()); const float max_inlier_score = 1.75f * min_inlier_score; const float mid_inlier_score = 0.5 * (min_inlier_score + max_inlier_score); @@ -4694,7 +4699,7 @@ normalized_domain_.x() / grid_size * overlap_x / num_overlaps; std::vector<std::vector<float>>& irls_mask = *thread_storage->EmptyGridCoverageIrlsMask(); - CHECK_EQ(mask_size, irls_mask.size()); + ABSL_CHECK_EQ(mask_size, irls_mask.size()); // Bin features. for (const auto& feature : feature_list.feature()) { @@ -4738,7 +4743,7 @@ const float cell_weight_sum = std::accumulate(grid_cell_weights.begin(), grid_cell_weights.end(), 0.0f); - CHECK_GT(cell_weight_sum, 0); + ABSL_CHECK_GT(cell_weight_sum, 0); return std::inner_product(max_coverage.begin(), max_coverage.end(), grid_cell_weights.begin(), 0.0f) / @@ -5088,8 +5093,8 @@ // Compute weights if necessary. // Compute scale to index mixture weights from normalization. CHECK(row_weights_.get() != nullptr); - CHECK_EQ(row_weights_->YScale(), frame_height_ / normalized_domain_.y()); - CHECK_EQ(row_weights_->NumModels(), num_mixtures); + ABSL_CHECK_EQ(row_weights_->YScale(), frame_height_ / normalized_domain_.y()); + ABSL_CHECK_EQ(row_weights_->NumModels(), num_mixtures); const MotionEstimationOptions::MixtureModelMode mixture_mode = options_.mixture_model_mode(); @@ -5444,7 +5449,7 @@ // Two stage estimation: First translation only, followed by // overlay analysis. const int num_frames = feature_lists->size(); - CHECK_EQ(num_frames, camera_motions->size()); + ABSL_CHECK_EQ(num_frames, camera_motions->size()); std::vector<CameraMotion> translation_motions(num_frames); const int irls_per_round = options_.irls_rounds(); @@ -5521,7 +5526,7 @@ std::vector<int>* overlay_indices) const { CHECK(feature_lists != nullptr); CHECK(overlay_indices != nullptr); - CHECK_EQ(feature_lists->size(), translations.size()); + ABSL_CHECK_EQ(feature_lists->size(), translations.size()); overlay_indices->clear(); const int grid_size = @@ -5717,7 +5722,7 @@ } // Only zero if spatial AND feature sigma = 0. - DCHECK_GT(weight_sum, 0); + ABSL_DCHECK_GT(weight_sum, 0); feature->mutable_internal_irls()->set_weight_sum(weight_sum); feature->mutable_internal_irls()->set_value_sum(value_sum); } @@ -5829,7 +5834,7 @@ } } - CHECK_GT(weight_sum, 0) << feature->irls_weight(); + ABSL_CHECK_GT(weight_sum, 0) << feature->irls_weight(); feature->mutable_internal_irls()->set_weight_sum(weight_sum); feature->mutable_internal_irls()->set_value_sum(value_sum); }
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc index eb6a8b3..5d6645f 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.cc
@@ -22,6 +22,7 @@ #include "Eigen/Core" #include "Eigen/Dense" +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" // Set to true to use catmull rom mixture weights instead of Gaussian weights @@ -43,10 +44,10 @@ TranslationModel ModelAdapter<TranslationModel>::FromAffine( const AffineModel& model) { - DCHECK_EQ(model.a(), 1); - DCHECK_EQ(model.b(), 0); - DCHECK_EQ(model.c(), 0); - DCHECK_EQ(model.d(), 1); + ABSL_DCHECK_EQ(model.a(), 1); + ABSL_DCHECK_EQ(model.b(), 0); + ABSL_DCHECK_EQ(model.c(), 0); + ABSL_DCHECK_EQ(model.d(), 1); return TranslationAdapter::FromArgs(model.dx(), model.dy()); } @@ -235,7 +236,7 @@ SimilarityModel ModelAdapter<SimilarityModel>::NormalizationTransform( float frame_width, float frame_height) { const float scale = std::hypot(frame_width, frame_height); - DCHECK_NE(scale, 0); + ABSL_DCHECK_NE(scale, 0); return SimilarityAdapter::FromArgs(0, 0, 1.0 / scale, 0); } @@ -262,8 +263,8 @@ LinearSimilarityModel ModelAdapter<LinearSimilarityModel>::FromAffine( const AffineModel& model) { - DCHECK_EQ(model.a(), model.d()); - DCHECK_EQ(model.b(), -model.c()); + ABSL_DCHECK_EQ(model.a(), model.d()); + ABSL_DCHECK_EQ(model.b(), -model.c()); return LinearSimilarityAdapter::FromArgs(model.dx(), model.dy(), model.a(), -model.b()); @@ -330,7 +331,7 @@ ModelAdapter<LinearSimilarityModel>::NormalizationTransform( float frame_width, float frame_height) { const float scale = std::hypot(frame_width, frame_height); - DCHECK_NE(scale, 0); + ABSL_DCHECK_NE(scale, 0); return LinearSimilarityAdapter::FromArgs(0, 0, 1.0 / scale, 0); } @@ -368,7 +369,7 @@ AffineModel ModelAdapter<AffineModel>::NormalizationTransform( float frame_width, float frame_height) { const float scale = std::hypot(frame_width, frame_height); - DCHECK_NE(scale, 0); + ABSL_DCHECK_NE(scale, 0); return AffineAdapter::FromArgs(0, 0, 1.0f / scale, 0, 0, 1.0f / scale); } @@ -379,8 +380,8 @@ } AffineModel ModelAdapter<AffineModel>::FromHomography(const Homography& model) { - DCHECK_EQ(model.h_20(), 0); - DCHECK_EQ(model.h_21(), 0); + ABSL_DCHECK_EQ(model.h_20(), 0); + ABSL_DCHECK_EQ(model.h_21(), 0); float params[6] = {model.h_02(), model.h_12(), // dx, dy model.h_00(), model.h_01(), // a, b @@ -582,8 +583,8 @@ } AffineModel ModelAdapter<Homography>::ToAffine(const Homography& model) { - DCHECK_EQ(model.h_20(), 0); - DCHECK_EQ(model.h_21(), 0); + ABSL_DCHECK_EQ(model.h_20(), 0); + ABSL_DCHECK_EQ(model.h_21(), 0); AffineModel affine_model; affine_model.set_a(model.h_00()); affine_model.set_b(model.h_01()); @@ -629,7 +630,7 @@ Homography ModelAdapter<Homography>::NormalizationTransform( float frame_width, float frame_height) { const float scale = std::hypot(frame_width, frame_height); - DCHECK_NE(scale, 0); + ABSL_DCHECK_NE(scale, 0); return HomographyAdapter::FromArgs(1.0f / scale, 0, 0, 0, 1.0f / scale, 0, 0, 0); } @@ -860,7 +861,7 @@ weight_ptr[int_pos] += spline_weights[0]; // Double knot. } - CHECK_LT(int_pos, num_models - 1); + ABSL_CHECK_LT(int_pos, num_models - 1); weight_ptr[int_pos + 1] += spline_weights[2]; if (int_pos + 1 < num_models - 1) { weight_ptr[int_pos + 2] += spline_weights[3]; @@ -897,7 +898,7 @@ } // Normalize. - DCHECK_GT(weight_sum, 0); + ABSL_DCHECK_GT(weight_sum, 0); const float inv_weight_sum = 1.0f / weight_sum; for (int j = 0; j < num_models; ++j) { weight_ptr[j] *= inv_weight_sum;
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h index 567831ad..4edf28a 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_models.h
@@ -21,6 +21,7 @@ #include <vector> #include "absl/container/node_hash_map.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/singleton.h" #include "mediapipe/framework/port/vector.h" @@ -762,8 +763,8 @@ template <class Model> Model BlendModels(const Model& a, const Model& b, float weight_b) { Model blended; - DCHECK_GE(weight_b, 0); - DCHECK_LE(weight_b, 1); + ABSL_DCHECK_GE(weight_b, 0); + ABSL_DCHECK_LE(weight_b, 1); const float weight_a = 1 - weight_b; for (int p = 0; p < ModelAdapter<Model>::NumParameters(); ++p) { const float pa = ModelAdapter<Model>::GetParameter(a, p); @@ -822,8 +823,8 @@ const float* RowWeights(float y) const { int bin_y = y * y_scale_ + 0.5; - DCHECK_LT(bin_y, frame_height_ + margin_); - DCHECK_GE(bin_y, -margin_); + ABSL_DCHECK_LT(bin_y, frame_height_ + margin_); + ABSL_DCHECK_GE(bin_y, -margin_); return &weights_[(bin_y + margin_) * num_models_]; } @@ -1398,7 +1399,7 @@ Homography result; const float z = lhs.h_20() * rhs.h_02() + lhs.h_21() * rhs.h_12() + 1.0f * 1.0f; - CHECK_NE(z, 0) << "Degenerate homography. See proto."; + ABSL_CHECK_NE(z, 0) << "Degenerate homography. See proto."; const float inv_z = 1.0 / z; result.set_h_00((lhs.h_00() * rhs.h_00() + lhs.h_01() * rhs.h_10() + @@ -1631,7 +1632,7 @@ } const double denom = sum_xx - inv_models * sum_x * sum_x; - CHECK_NE(denom, 0); // As num_models > 1. + ABSL_CHECK_NE(denom, 0); // As num_models > 1. const double a = (sum_xy - inv_models * sum_x * sum_y) * denom; const double b = inv_models * (sum_y - a * sum_x); @@ -1688,7 +1689,7 @@ BaseModelAdapter::TransformPoint3(model.model(i), pt3 * weights[i]); } - DCHECK_NE(result.z(), 0) << "Degenerate mapping."; + ABSL_DCHECK_NE(result.z(), 0) << "Degenerate mapping."; return Vector2_f(result.x() / result.z(), result.y() / result.z()); } @@ -1818,7 +1819,7 @@ LOG(FATAL) << "Unknown type."; } - DCHECK_NE(result.z(), 0) << "Degenerate mapping."; + ABSL_DCHECK_NE(result.z(), 0) << "Degenerate mapping."; return Vector2_f(result.x() / result.z(), result.y() / result.z()); }
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc b/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc index 5adafca..9e2911e 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/motion_saliency.cc
@@ -24,6 +24,7 @@ #include <memory> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/util/tracking/camera_motion.h" #include "mediapipe/util/tracking/measure_time.h" @@ -45,11 +46,11 @@ std::vector<float>* irls_weights, // optional. SalientPointFrame* salient_frame) { CHECK(salient_frame); - CHECK_EQ(frame_width_, feature_list.frame_width()); - CHECK_EQ(frame_height_, feature_list.frame_height()); + ABSL_CHECK_EQ(frame_width_, feature_list.frame_width()); + ABSL_CHECK_EQ(frame_height_, feature_list.frame_height()); if (irls_weights) { - CHECK_EQ(feature_list.feature_size(), irls_weights->size()); + ABSL_CHECK_EQ(feature_list.feature_size(), irls_weights->size()); } if (feature_list.feature_size() < 1) { @@ -106,7 +107,7 @@ SalientPointFrame* salient_frame) { // TODO: Handle vectors of size zero. CHECK(salient_frame); - CHECK_EQ(points->size(), weights->size()); + ABSL_CHECK_EQ(points->size(), weights->size()); float max_weight = *std::max_element(weights->begin(), weights->end()); @@ -477,7 +478,7 @@ nullptr, &grid_dims, &feature_grids); // Just one frame input, expect one grid as output. - CHECK_EQ(1, feature_grids.size()); + ABSL_CHECK_EQ(1, feature_grids.size()); const auto& feature_grid = feature_grids[0]; // Setup Gaussian LUT for smoothing in space, using 2^10 discretization bins. @@ -595,8 +596,8 @@ if (angle < 0) { angle += M_PI; } - CHECK_GE(angle, 0); - CHECK_LE(angle, M_PI + 1e-3); + ABSL_CHECK_GE(angle, 0); + ABSL_CHECK_LE(angle, M_PI + 1e-3); } SalientMode irls_mode; @@ -665,7 +666,7 @@ constexpr float kEpsilon = 1e-4f; - CHECK_GT(foreground_threshold, 0.0f); + ABSL_CHECK_GT(foreground_threshold, 0.0f); if (camera_motion) { foreground_threshold *= std::max(kEpsilon, InlierCoverage(*camera_motion, false)); @@ -694,7 +695,7 @@ std::max(kEpsilon, std::pow(foreground_measure, foreground_gamma))); } } - CHECK_EQ(feature_list.feature_size(), weights->size()); + ABSL_CHECK_EQ(feature_list.feature_size(), weights->size()); } } // namespace mediapipe
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h b/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h index 8235223..734e990 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/parallel_invoker.h
@@ -71,6 +71,7 @@ #include <memory> +#include "absl/log/absl_check.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/logging.h" @@ -282,9 +283,10 @@ } #endif // PARALLEL_INVOKER_ACTIVE - CHECK_LT(flags_parallel_invoker_mode, PARALLEL_INVOKER_MAX_VALUE) + ABSL_CHECK_LT(flags_parallel_invoker_mode, PARALLEL_INVOKER_MAX_VALUE) << "Invalid invoker mode specified."; - CHECK_GE(flags_parallel_invoker_mode, 0) << "Invalid invoker mode specified."; + ABSL_CHECK_GE(flags_parallel_invoker_mode, 0) + << "Invalid invoker mode specified."; } // Performs parallel iteration from [start to end), scheduling grain_size @@ -301,7 +303,7 @@ #if defined(__APPLE__) case PARALLEL_INVOKER_GCD: { int iterations_remain = (end - start + grain_size - 1) / grain_size; - CHECK_GT(iterations_remain, 0); + ABSL_CHECK_GT(iterations_remain, 0); if (iterations_remain == 1) { // Execute invoker serially. invoker(BlockedRange(start, std::min(end, start + grain_size), 1)); @@ -313,7 +315,7 @@ dispatch_apply_f(iterations_remain, concurrent_queue, &context, ParallelForGCDTask<Invoker>); #if CHECK_GCD_PARALLEL_WORK_COUNT - CHECK_EQ(iterations_remain, context.count()); + ABSL_CHECK_EQ(iterations_remain, context.count()); #endif } break; @@ -322,7 +324,7 @@ case PARALLEL_INVOKER_THREAD_POOL: { int iterations_remain = (end - start + grain_size - 1) / grain_size; - CHECK_GT(iterations_remain, 0); + ABSL_CHECK_GT(iterations_remain, 0); if (iterations_remain == 1) { // Execute invoker serially. invoker(BlockedRange(start, std::min(end, start + grain_size), 1)); @@ -413,7 +415,7 @@ case PARALLEL_INVOKER_GCD: { const int iterations_remain = (end_row - start_row + grain_size - 1) / grain_size; - CHECK_GT(iterations_remain, 0); + ABSL_CHECK_GT(iterations_remain, 0); if (iterations_remain == 1) { // Execute invoker serially. invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1), @@ -427,7 +429,7 @@ dispatch_apply_f(iterations_remain, concurrent_queue, &context, ParallelForGCDTask2D<Invoker>); #if CHECK_GCD_PARALLEL_WORK_COUNT - CHECK_EQ(iterations_remain, context.count()); + ABSL_CHECK_EQ(iterations_remain, context.count()); #endif } break; @@ -436,7 +438,7 @@ case PARALLEL_INVOKER_THREAD_POOL: { int iterations_remain = end_row - start_row; // Guarded by loop_mutex - CHECK_GT(iterations_remain, 0); + ABSL_CHECK_GT(iterations_remain, 0); if (iterations_remain == 1) { // Execute invoker serially. invoker(BlockedRange2D(BlockedRange(start_row, end_row, 1),
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h b/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h index f9b2c6c3..cdf451f 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/push_pull_filtering.h
@@ -33,6 +33,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/opencv_core_inc.h" #include "mediapipe/util/tracking/image_util.h" #include "mediapipe/util/tracking/push_pull_filtering.pb.h" @@ -148,7 +149,7 @@ // Returns domain size of n-th pyramid level (including border depending on // filter_type). cv::Size NthPyramidDomain(int level) { - CHECK_LT(level, PyramidLevels()); + ABSL_CHECK_LT(level, PyramidLevels()); return downsample_pyramid_[level].size(); } @@ -469,14 +470,14 @@ void PushPullFiltering<C, FilterWeightMultiplier>::InitializeImagePyramid( const cv::Mat& input_frame, std::vector<cv::Mat>* pyramid) { CHECK(pyramid != nullptr); - CHECK_GT(pyramid->size(), 0); + ABSL_CHECK_GT(pyramid->size(), 0); cv::Mat base_level((*pyramid)[0], cv::Range(border_, (*pyramid)[0].rows - border_), cv::Range(border_, (*pyramid)[0].cols - border_)); - CHECK_EQ(base_level.rows, input_frame.rows); - CHECK_EQ(base_level.cols, input_frame.cols); - CHECK_EQ(base_level.type(), input_frame.type()); + ABSL_CHECK_EQ(base_level.rows, input_frame.rows); + ABSL_CHECK_EQ(base_level.cols, input_frame.cols); + ABSL_CHECK_EQ(base_level.type(), input_frame.type()); input_frame.copyTo(base_level); CopyNecessaryBorder<uint8, 3>(&(*pyramid)[0]); @@ -743,11 +744,11 @@ cv::Point2i origin, int readout_level, const std::vector<float>* data_weights, const cv::Mat* input_frame, cv::Mat* results) { - CHECK_EQ(data_locations.size(), data_values.size()); + ABSL_CHECK_EQ(data_locations.size(), data_values.size()); CHECK(results != nullptr); if (data_weights) { - CHECK_EQ(data_weights->size(), data_locations.size()); + ABSL_CHECK_EQ(data_weights->size(), data_locations.size()); } origin.x += border_; @@ -760,13 +761,13 @@ mip_map[i] = &downsample_pyramid_[i]; } - CHECK_GE(readout_level, 0); - CHECK_LT(readout_level, PyramidLevels()); + ABSL_CHECK_GE(readout_level, 0); + ABSL_CHECK_LT(readout_level, PyramidLevels()); // CHECK if passed results matrix is compatible w.r.t. type and domain. - CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); - CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); - CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); + ABSL_CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); + ABSL_CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); + ABSL_CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); // Use caller-allocated results Mat. mip_map[readout_level] = results; @@ -815,18 +816,18 @@ mip_map[i] = &downsample_pyramid_[i]; } - CHECK_GE(readout_level, 0); - CHECK_LT(readout_level, PyramidLevels()); + ABSL_CHECK_GE(readout_level, 0); + ABSL_CHECK_LT(readout_level, PyramidLevels()); // CHECK if passed mip_map at level[0] is compatible w.r.t. type and domain. - CHECK_EQ(mip_map_level_0.cols, results->cols); - CHECK_EQ(mip_map_level_0.rows, results->rows); - CHECK_EQ(mip_map_level_0.type(), results->type()); + ABSL_CHECK_EQ(mip_map_level_0.cols, results->cols); + ABSL_CHECK_EQ(mip_map_level_0.rows, results->rows); + ABSL_CHECK_EQ(mip_map_level_0.type(), results->type()); // CHECK if passed results matrix is compatible w.r.t. type and domain. - CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); - CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); - CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); + ABSL_CHECK_EQ(downsample_pyramid_[readout_level].cols, results->cols); + ABSL_CHECK_EQ(downsample_pyramid_[readout_level].rows, results->rows); + ABSL_CHECK_EQ(downsample_pyramid_[readout_level].type(), results->type()); // Use caller-allocated results Mat. mip_map[readout_level] = results; @@ -1049,7 +1050,7 @@ } } - DCHECK_GE(weight_sum, 0); + ABSL_DCHECK_GE(weight_sum, 0); if (weight_sum >= kBilateralEps * kBilateralEps) { const float inv_weight_sum = 1.f / weight_sum;
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc index cdd6bcd8..1babddd 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.cc
@@ -22,6 +22,7 @@ #include "absl/container/node_hash_map.h" #include "absl/container/node_hash_set.h" +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/util/tracking/measure_time.h" @@ -76,8 +77,8 @@ float RegionFlowFeatureDistance(const PatchDescriptor& patch_desc_1, const PatchDescriptor& patch_desc_2) { - DCHECK_EQ(patch_desc_1.data_size(), patch_desc_2.data_size()); - DCHECK_GE(patch_desc_1.data_size(), 3); + ABSL_DCHECK_EQ(patch_desc_1.data_size(), patch_desc_2.data_size()); + ABSL_DCHECK_GE(patch_desc_1.data_size(), 3); constexpr int kNumMeans = 3; float sq_distance_sum = 0; @@ -212,7 +213,7 @@ void SetRegionFlowFeatureIRLSWeights(const std::vector<float>& irls_weights, RegionFlowFeatureList* flow_feature_list) { CHECK(flow_feature_list != nullptr); - CHECK_EQ(irls_weights.size(), flow_feature_list->feature_size()); + ABSL_CHECK_EQ(irls_weights.size(), flow_feature_list->feature_size()); int idx = 0; for (auto feature = flow_feature_list->mutable_feature()->begin(); feature != flow_feature_list->mutable_feature()->end(); @@ -515,7 +516,7 @@ src->mutable_feature()->Swap(empty_list.mutable_feature()); // src_features should be empty as in the beginning. - CHECK_EQ(0, empty_list.feature_size()); + ABSL_CHECK_EQ(0, empty_list.feature_size()); } void IntersectRegionFlowFeatureList( @@ -607,10 +608,10 @@ if (find_pos != tracks_.end()) { // Track is present, add to it. if (check_connectivity) { - CHECK_LT((FeatureLocation(find_pos->second.back()) - - FeatureMatchLocation(feature)) - .Norm2(), - 1e-4); + ABSL_CHECK_LT((FeatureLocation(find_pos->second.back()) - + FeatureMatchLocation(feature)) + .Norm2(), + 1e-4); } find_pos->second.push_back(feature); } else {
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h index 2f9b342..db70a2b 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow.h
@@ -24,6 +24,7 @@ #include <utility> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/vector.h" #include "mediapipe/util/tracking/motion_models.h" @@ -82,9 +83,9 @@ constexpr int kRedIdx = 3; constexpr int kGreenIdx = 6; constexpr int kBlueIdx = 8; - DCHECK_GE(descriptor.data(kRedIdx), 0); - DCHECK_GE(descriptor.data(kGreenIdx), 0); - DCHECK_GE(descriptor.data(kBlueIdx), 0); + ABSL_DCHECK_GE(descriptor.data(kRedIdx), 0); + ABSL_DCHECK_GE(descriptor.data(kGreenIdx), 0); + ABSL_DCHECK_GE(descriptor.data(kBlueIdx), 0); if (descriptor.data_size() > kBlueIdx) { return std::sqrt(descriptor.data(kRedIdx)) + @@ -591,7 +592,7 @@ Vector2_i* num_grid_bins, // Optional. std::vector<FeatureGrid<Feature>>* feature_grids) { CHECK(feature_grids); - CHECK_GT(grid_resolution, 0.0f); + ABSL_CHECK_GT(grid_resolution, 0.0f); const int num_frames = feature_views.size(); const int grid_dim_x = std::ceil(frame_width / grid_resolution); @@ -612,8 +613,8 @@ Vector2_f feature_loc = evaluator(*feature); const int x = feature_loc.x() * grid_scale; const int y = feature_loc.y() * grid_scale; - DCHECK_LT(y, grid_dim_y); - DCHECK_LT(x, grid_dim_x); + ABSL_DCHECK_LT(y, grid_dim_y); + ABSL_DCHECK_LT(x, grid_dim_x); const int grid_loc = y * grid_dim_x + x; curr_grid[grid_loc].push_back(feature); }
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc index b6704cc..2446e72 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_computation.cc
@@ -28,6 +28,7 @@ #include "Eigen/Core" #include "absl/container/flat_hash_map.h" #include "absl/container/node_hash_set.h" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/opencv_core_inc.h" @@ -207,19 +208,19 @@ ++feature_idx) { RegionFlowFeature* feature = features_->mutable_feature(feature_idx); Vector2_i pt(FeatureIntLocation(*feature)); - DCHECK_GE(pt.x(), radius_); - DCHECK_GE(pt.y(), radius_); - DCHECK_LT(pt.x(), rgb_frame_.cols - radius_); - DCHECK_LT(pt.y(), rgb_frame_.rows - radius_); + ABSL_DCHECK_GE(pt.x(), radius_); + ABSL_DCHECK_GE(pt.y(), radius_); + ABSL_DCHECK_LT(pt.x(), rgb_frame_.cols - radius_); + ABSL_DCHECK_LT(pt.y(), rgb_frame_.rows - radius_); GetPatchDescriptorAtPoint(rgb_frame_, pt, radius_, &lab_window, feature->mutable_feature_descriptor()); if (prev_rgb_frame_) { Vector2_i pt_match(FeatureMatchIntLocation(*feature)); - DCHECK_GE(pt_match.x(), radius_); - DCHECK_GE(pt_match.y(), radius_); - DCHECK_LT(pt_match.x(), rgb_frame_.cols - radius_); - DCHECK_LT(pt_match.y(), rgb_frame_.rows - radius_); + ABSL_DCHECK_GE(pt_match.x(), radius_); + ABSL_DCHECK_GE(pt_match.y(), radius_); + ABSL_DCHECK_LT(pt_match.x(), rgb_frame_.cols - radius_); + ABSL_DCHECK_LT(pt_match.y(), rgb_frame_.rows - radius_); GetPatchDescriptorAtPoint(*prev_rgb_frame_, pt_match, radius_, &lab_window, feature->mutable_feature_match_descriptor()); @@ -247,17 +248,18 @@ int patch_descriptor_radius, RegionFlowFeatureList* flow_feature_list) { const int rows = rgb_frame.rows; const int cols = rgb_frame.cols; - CHECK_EQ(rgb_frame.depth(), CV_8U); - CHECK_EQ(rgb_frame.channels(), 3); + ABSL_CHECK_EQ(rgb_frame.depth(), CV_8U); + ABSL_CHECK_EQ(rgb_frame.channels(), 3); if (prev_rgb_frame) { - CHECK_EQ(prev_rgb_frame->depth(), CV_8U); - CHECK_EQ(prev_rgb_frame->channels(), 3); - CHECK_EQ(prev_rgb_frame->rows, rows); - CHECK_EQ(prev_rgb_frame->cols, cols); + ABSL_CHECK_EQ(prev_rgb_frame->depth(), CV_8U); + ABSL_CHECK_EQ(prev_rgb_frame->channels(), 3); + ABSL_CHECK_EQ(prev_rgb_frame->rows, rows); + ABSL_CHECK_EQ(prev_rgb_frame->cols, cols); } - CHECK_LE(patch_descriptor_radius, flow_feature_list->distance_from_border()); + ABSL_CHECK_LE(patch_descriptor_radius, + flow_feature_list->distance_from_border()); ParallelFor( 0, flow_feature_list->feature_size(), 1, @@ -380,7 +382,7 @@ iwidth = (iwidth + 1) / 2; iheight = (iheight + 1) / 2; } - CHECK_GE(extraction_levels, 1); + ABSL_CHECK_GE(extraction_levels, 1); // Frame is the same as first extraction level. frame = extraction_pyramid[0]; @@ -458,7 +460,7 @@ } void RemoveFeature(int pos) { - DCHECK_LT(pos, features.size()); + ABSL_DCHECK_LT(pos, features.size()); features.erase(features.begin() + pos); feature_source_map.erase(feature_source_map.begin() + pos); corner_responses.erase(corner_responses.begin() + pos); @@ -616,8 +618,8 @@ } } - CHECK_NE(options.tracking_options().output_flow_direction(), - TrackingOptions::CONSECUTIVELY) + ABSL_CHECK_NE(options.tracking_options().output_flow_direction(), + TrackingOptions::CONSECUTIVELY) << "Output direction must be either set to FORWARD or BACKWARD."; use_downsampling_ = options_.downsample_mode() != RegionFlowComputationOptions::DOWNSAMPLE_NONE; @@ -650,7 +652,7 @@ } case RegionFlowComputationOptions::DOWNSAMPLE_BY_FACTOR: case RegionFlowComputationOptions::DOWNSAMPLE_TO_INPUT_SIZE: { - CHECK_GE(options_.downsample_factor(), 1); + ABSL_CHECK_GE(options_.downsample_factor(), 1); downsample_scale_ = options_.downsample_factor(); break; } @@ -728,7 +730,7 @@ frames_to_track_ = 1; break; case TrackingOptions::POLICY_MULTI_FRAME: - CHECK_GT(options_.tracking_options().multi_frames_to_track(), 0); + ABSL_CHECK_GT(options_.tracking_options().multi_frames_to_track(), 0); frames_to_track_ = options_.tracking_options().multi_frames_to_track(); break; case TrackingOptions::POLICY_LONG_TRACKS: @@ -808,7 +810,7 @@ // Compute settings for block based flow. const float block_size = options_.fast_estimation_block_size(); - CHECK_GT(block_size, 0) << "Need positive block size"; + ABSL_CHECK_GT(block_size, 0) << "Need positive block size"; block_width_ = block_size < 1 ? block_size * original_width_ : block_size; block_height_ = block_size < 1 ? block_size * original_height_ : block_size; @@ -869,7 +871,7 @@ int track_index, bool compute_feature_descriptor, bool compute_match_descriptor, const cv::Mat* curr_color_image, const cv::Mat* prev_color_image) { - CHECK_GT(region_flow_results_.size(), track_index); + ABSL_CHECK_GT(region_flow_results_.size(), track_index); CHECK(region_flow_results_[track_index].get()); std::unique_ptr<RegionFlowFeatureList> feature_list( @@ -877,10 +879,10 @@ if (compute_feature_descriptor) { CHECK(curr_color_image != nullptr); - CHECK_EQ(3, curr_color_image->channels()); + ABSL_CHECK_EQ(3, curr_color_image->channels()); if (compute_match_descriptor) { CHECK(prev_color_image != nullptr); - CHECK_EQ(3, prev_color_image->channels()); + ABSL_CHECK_EQ(3, prev_color_image->channels()); } ComputeRegionFlowFeatureDescriptors( @@ -1006,7 +1008,7 @@ LOG(ERROR) << "Expecting 1 channel input for GRAYSCALE."; return false; } - CHECK_EQ(1, source_ptr->channels()); + ABSL_CHECK_EQ(1, source_ptr->channels()); if (source_ptr != &dest_frame) { source_ptr->copyTo(dest_frame); } @@ -1024,8 +1026,8 @@ } // Consistency checks; not input governed. - CHECK_EQ(dest_frame.cols, frame_width_); - CHECK_EQ(dest_frame.rows, frame_height_); + ABSL_CHECK_EQ(dest_frame.cols, frame_width_); + ABSL_CHECK_EQ(dest_frame.rows, frame_height_); data->BuildPyramid(pyramid_levels_, options_.tracking_options().tracking_window_size(), @@ -1089,8 +1091,8 @@ curr_data->Reset(frame_num_, timestamp_usec); if (!IsModelIdentity(initial_transform)) { - CHECK_EQ(1, frames_to_track_) << "Initial transform is not supported " - << "for multi frame tracking"; + ABSL_CHECK_EQ(1, frames_to_track_) << "Initial transform is not supported " + << "for multi frame tracking"; Homography transform = initial_transform; if (downsample_scale_ != 1) { const float scale = 1.0f / downsample_scale_; @@ -1204,7 +1206,7 @@ } cv::Mat RegionFlowComputation::GetGrayscaleFrameFromResults() { - CHECK_GT(data_queue_.size(), 0) << "Empty queue, was AddImage* called?"; + ABSL_CHECK_GT(data_queue_.size(), 0) << "Empty queue, was AddImage* called?"; FrameTrackingData* curr_data = data_queue_.back().get(); CHECK(curr_data); return curr_data->frame; @@ -1228,9 +1230,9 @@ float RegionFlowComputation::ComputeVisualConsistency( FrameTrackingData* previous, FrameTrackingData* current) const { - CHECK_EQ(previous->frame_num + 1, current->frame_num); + ABSL_CHECK_EQ(previous->frame_num + 1, current->frame_num); const int total = previous->tiny_image.total(); - CHECK_GT(total, 0) << "Tiny image dimension set to zero."; + ABSL_CHECK_GT(total, 0) << "Tiny image dimension set to zero."; current->tiny_image_diff = FrameDifferenceMedian(previous->tiny_image, current->tiny_image) * (1.0f / total); @@ -1263,10 +1265,10 @@ } else { const int index1 = data_queue_.size() + from - 1; const int index2 = data_queue_.size() + to - 1; - CHECK_GE(index1, 0); - CHECK_LT(index1, data_queue_.size()); - CHECK_GE(index2, 0); - CHECK_LT(index2, data_queue_.size()); + ABSL_CHECK_GE(index1, 0); + ABSL_CHECK_LT(index1, data_queue_.size()); + ABSL_CHECK_GE(index2, 0); + ABSL_CHECK_LT(index2, data_queue_.size()); data1 = data_queue_[index1].get(); data2 = data_queue_[index2].get(); @@ -1611,14 +1613,14 @@ // or adds K to the existing mask if add is set to true. template <int N, int K, bool add> inline void SetMaskNeighborhood(int mask_x, int mask_y, cv::Mat* mask) { - DCHECK_EQ(mask->type(), CV_8U); + ABSL_DCHECK_EQ(mask->type(), CV_8U); const int mask_start_x = max(0, mask_x - N); const int mask_end_x = min(mask->cols - 1, mask_x + N); const int mask_dx = mask_end_x - mask_start_x + 1; const int mask_start_y = max(0, mask_y - N); const int mask_end_y = min(mask->rows - 1, mask_y + N); - DCHECK_LE(mask_start_x, mask_end_x); - DCHECK_LE(mask_start_y, mask_end_y); + ABSL_DCHECK_LE(mask_start_x, mask_end_x); + ABSL_DCHECK_LE(mask_start_y, mask_end_y); if (!add) { for (int i = mask_start_y; i <= mask_end_y; ++i) { @@ -1651,7 +1653,7 @@ // Setup grid information. const float block_size = tracking_options.adaptive_features_block_size(); - CHECK_GT(block_size, 0) << "Need positive block size"; + ABSL_CHECK_GT(block_size, 0) << "Need positive block size"; int block_width = block_size < 1 ? block_size * frame_width_ : block_size; int block_height = block_size < 1 ? block_size * frame_height_ : block_size; @@ -1703,8 +1705,8 @@ std::vector<cv::KeyPoint> fast_keypoints; if (e == 0) { MEASURE_TIME << "Corner extraction"; - CHECK_EQ(rows, frame_height_); - CHECK_EQ(cols, frame_width_); + ABSL_CHECK_EQ(rows, frame_height_); + ABSL_CHECK_EQ(cols, frame_width_); if (use_fast) { fast_detector->detect(image, fast_keypoints); @@ -1716,8 +1718,8 @@ } else { // Compute corner response on a down-scaled image and upsample. step *= 2; - CHECK_EQ(rows, (extraction_pyramid[e - 1].rows + 1) / 2); - CHECK_EQ(cols, (extraction_pyramid[e - 1].cols + 1) / 2); + ABSL_CHECK_EQ(rows, (extraction_pyramid[e - 1].rows + 1) / 2); + ABSL_CHECK_EQ(cols, (extraction_pyramid[e - 1].cols + 1) / 2); if (use_fast) { fast_detector->detect(image, fast_keypoints); @@ -2015,8 +2017,8 @@ float input_mean, cv::Mat* calibrated_frame) const { CHECK(calibrated_frame); - CHECK_EQ(reference_frame.rows, input_frame.rows); - CHECK_EQ(reference_frame.cols, input_frame.cols); + ABSL_CHECK_EQ(reference_frame.rows, input_frame.rows); + ABSL_CHECK_EQ(reference_frame.cols, input_frame.cols); // Do not attempt gain correction for tiny images. if (std::min(reference_frame.rows, reference_frame.cols) < 10) { @@ -2185,7 +2187,7 @@ // Build hash set of track ids. absl::node_hash_set<int> track_ids; for (const auto& feature : prev_result) { - DCHECK_NE(feature.track_id, -1); + ABSL_DCHECK_NE(feature.track_id, -1); track_ids.insert(feature.track_id); } @@ -2233,8 +2235,8 @@ if (data->last_feature_extraction_time == 0) { // Features already extracted from this frame. - CHECK_EQ(data->corner_responses.size(), data->features.size()); - CHECK_EQ(data->octaves.size(), data->features.size()); + ABSL_CHECK_EQ(data->corner_responses.size(), data->features.size()); + ABSL_CHECK_EQ(data->octaves.size(), data->features.size()); VLOG(1) << "Features already present (extracted from this frame)"; return; } @@ -2242,8 +2244,8 @@ // Remove features that lie outside feature extraction mask. RemoveFeaturesOutsideMask(data); - CHECK_EQ(data->corner_responses.size(), data->features.size()); - CHECK_EQ(data->octaves.size(), data->features.size()); + ABSL_CHECK_EQ(data->corner_responses.size(), data->features.size()); + ABSL_CHECK_EQ(data->octaves.size(), data->features.size()); float feature_fraction = 0; if (data->num_original_extracted_and_tracked > 0) { @@ -2309,7 +2311,7 @@ data->neighborhoods->reserve(features_to_allocate); } - CHECK_EQ(data->extraction_pyramid.size(), extraction_levels_); + ABSL_CHECK_EQ(data->extraction_pyramid.size(), extraction_levels_); for (int i = 1; i < extraction_levels_; ++i) { // Need factor 2 as OpenCV stores image + gradient pairs when // "with_derivative" is set to true. @@ -2357,8 +2359,8 @@ // For FORWARD output flow, we need to add flow to obtain the match // position, for BACKWARD output flow, flow is inverted, so that feature // locations already point to locations in the current frame. - CHECK_EQ(options_.tracking_options().internal_tracking_direction(), - TrackingOptions::FORWARD); + ABSL_CHECK_EQ(options_.tracking_options().internal_tracking_direction(), + TrackingOptions::FORWARD); float match_sign = options_.tracking_options().output_flow_direction() == TrackingOptions::FORWARD ? 1.0f @@ -2426,9 +2428,9 @@ mask_scale, &mask, data); const int num_features = data->features.size(); - CHECK_EQ(num_features, data->octaves.size()); - CHECK_EQ(num_features, data->corner_responses.size()); - CHECK_EQ(num_features, data->track_ids.size()); + ABSL_CHECK_EQ(num_features, data->octaves.size()); + ABSL_CHECK_EQ(num_features, data->corner_responses.size()); + ABSL_CHECK_EQ(num_features, data->track_ids.size()); } // Selects features based on lambda evaluator: bool (int index) @@ -2439,23 +2441,23 @@ std::vector<std::vector<float>*> float_vecs, const Eval& eval) { int num_selected_features = 0; const int num_features = data->features.size(); - DCHECK_EQ(num_features, data->corner_responses.size()); - DCHECK_EQ(num_features, data->octaves.size()); - DCHECK_EQ(num_features, data->track_ids.size()); - DCHECK_EQ(num_features, data->feature_source_map.size()); + ABSL_DCHECK_EQ(num_features, data->corner_responses.size()); + ABSL_DCHECK_EQ(num_features, data->octaves.size()); + ABSL_DCHECK_EQ(num_features, data->track_ids.size()); + ABSL_DCHECK_EQ(num_features, data->feature_source_map.size()); if (data->neighborhoods != nullptr) { - DCHECK_EQ(num_features, data->neighborhoods->size()); + ABSL_DCHECK_EQ(num_features, data->neighborhoods->size()); } for (const auto vec_ptr : int_vecs) { - DCHECK_EQ(num_features, vec_ptr->size()); + ABSL_DCHECK_EQ(num_features, vec_ptr->size()); } for (const auto vec_ptr : float_vecs) { - DCHECK_EQ(num_features, vec_ptr->size()); + ABSL_DCHECK_EQ(num_features, vec_ptr->size()); } for (int i = 0; i < num_features; ++i) { - DCHECK_LE(num_selected_features, i); + ABSL_DCHECK_LE(num_selected_features, i); if (eval(i)) { data->features[num_selected_features] = data->features[i]; data->corner_responses[num_selected_features] = data->corner_responses[i]; @@ -2549,14 +2551,14 @@ octaves2.resize(num_features); data2.source = from_data_ptr; } else { - CHECK_EQ(data2.source, from_data_ptr); - CHECK_EQ(num_features, features2.size()); + ABSL_CHECK_EQ(data2.source, from_data_ptr); + ABSL_CHECK_EQ(num_features, features2.size()); tracking_flags |= cv::OPTFLOW_USE_INITIAL_FLOW; } const int track_win_size = options_.tracking_options().tracking_window_size(); - CHECK_GT(track_win_size, 1) << "Needs to be at least 2 pixels in each " - << "direction"; + ABSL_CHECK_GT(track_win_size, 1) << "Needs to be at least 2 pixels in each " + << "direction"; // Proceed with gain correction only if it succeeds, and set flag accordingly. bool frame1_gain_reference = true; @@ -2946,14 +2948,14 @@ void RegionFlowComputation::InitializeFeatureLocationsFromPreviousResult( int from, int to) { - CHECK_NE(from, to) << "Cannot initialize FrameTrackingData from itself."; + ABSL_CHECK_NE(from, to) << "Cannot initialize FrameTrackingData from itself."; const int index1 = data_queue_.size() + from - 1; const int index2 = data_queue_.size() + to - 1; - CHECK_GE(index1, 0); - CHECK_LT(index1, data_queue_.size()); - CHECK_GE(index2, 0); - CHECK_LT(index2, data_queue_.size()); + ABSL_CHECK_GE(index1, 0); + ABSL_CHECK_LT(index1, data_queue_.size()); + ABSL_CHECK_GE(index2, 0); + ABSL_CHECK_LT(index2, data_queue_.size()); const FrameTrackingData& data1 = *data_queue_[index1]; FrameTrackingData* data2 = data_queue_[index2].get(); CHECK(data1.source != nullptr); @@ -2965,7 +2967,7 @@ } } else { data2->features = data1.features; - CHECK_EQ(data1.features.size(), data1.source->features.size()); + ABSL_CHECK_EQ(data1.features.size(), data1.source->features.size()); } data2->source = data1.source; data2->features_initialized = true;
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc index dc067da7..841ce5e0 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/region_flow_visualization.cc
@@ -19,6 +19,7 @@ #include <memory> #include <numeric> +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/util/tracking/measure_time.h" @@ -138,7 +139,7 @@ if (min_track_length > 0 && pts.size() < min_track_length) { continue; } - CHECK_GT(pts.size(), 1); // Should have at least two points per track. + ABSL_CHECK_GT(pts.size(), 1); // Should have at least two points per track. // Tracks are ordered with oldest point first, most recent one last. const int start_k =
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc index 2e5b0ac2..286edbb 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.cc
@@ -14,6 +14,7 @@ #include "mediapipe/util/tracking/streaming_buffer.h" +#include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" namespace mediapipe { @@ -21,7 +22,7 @@ StreamingBuffer::StreamingBuffer( const std::vector<TaggedType>& data_configuration, int overlap) : overlap_(overlap) { - CHECK_GE(overlap, 0); + ABSL_CHECK_GE(overlap, 0); for (auto& item : data_configuration) { CHECK(data_config_.find(item.first) == data_config_.end()) << "Tag " << item.first << " already exists";
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h index 41aadbb..bdaeb0c 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/streaming_buffer.h
@@ -23,6 +23,7 @@ #include <vector> #include "absl/container/node_hash_map.h" +#include "absl/log/absl_check.h" #include "absl/types/any.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/tool/type_util.h" @@ -324,7 +325,7 @@ void StreamingBuffer::AddDatum(const std::string& tag, std::unique_ptr<T> pointer) { CHECK(HasTag(tag)); - CHECK_EQ(data_config_[tag], kTypeId<PointerType<T>>.hash_code()); + ABSL_CHECK_EQ(data_config_[tag], kTypeId<PointerType<T>>.hash_code()); auto& buffer = data_[tag]; absl::any packet(PointerType<T>(CreatePointer(pointer.release()))); buffer.push_back(packet); @@ -344,7 +345,7 @@ template <class... Types> void StreamingBuffer::AddData(const std::vector<std::string>& tags, std::unique_ptr<Types>... pointers) { - CHECK_EQ(tags.size(), sizeof...(pointers)) + ABSL_CHECK_EQ(tags.size(), sizeof...(pointers)) << "Number of tags and data pointers is inconsistent"; return AddDataImpl(tags, std::move(pointers)...); } @@ -387,7 +388,7 @@ template <class T> T* StreamingBuffer::GetMutableDatum(const std::string& tag, int frame_index) const { - CHECK_GE(frame_index, 0); + ABSL_CHECK_GE(frame_index, 0); CHECK(HasTag(tag)); auto& buffer = data_.find(tag)->second; if (frame_index > buffer.size()) { @@ -488,7 +489,7 @@ std::unique_ptr<T> StreamingBuffer::ReleaseDatum(const std::string& tag, int frame_index) { CHECK(HasTag(tag)); - CHECK_GE(frame_index, 0); + ABSL_CHECK_GE(frame_index, 0); auto& buffer = data_.find(tag)->second; if (frame_index >= buffer.size()) {
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc index 587fe96..2fdfa11 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.cc
@@ -21,6 +21,7 @@ #include <numeric> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/util/tracking/motion_models.pb.h" #include "mediapipe/util/tracking/tone_models.pb.h" @@ -58,7 +59,7 @@ break; } case ToneEstimationOptions::DOWNSAMPLE_BY_FACTOR: { - CHECK_GE(options_.downsample_factor(), 1); + ABSL_CHECK_GE(options_.downsample_factor(), 1); frame_width_ /= options_.downsample_factor(); frame_height_ /= options_.downsample_factor(); downsample_scale_ = options_.downsample_factor(); @@ -80,8 +81,8 @@ const RegionFlowFeatureList& feature_list_input, const cv::Mat& curr_frame_input, const cv::Mat* prev_frame_input, ToneChange* tone_change, cv::Mat* debug_output) { - CHECK_EQ(original_height_, curr_frame_input.rows); - CHECK_EQ(original_width_, curr_frame_input.cols); + ABSL_CHECK_EQ(original_height_, curr_frame_input.rows); + ABSL_CHECK_EQ(original_width_, curr_frame_input.cols); CHECK(tone_change != nullptr); const cv::Mat& curr_frame = @@ -106,8 +107,8 @@ TransformRegionFlowFeatureList(scale_transform, &scaled_feature_list); } - CHECK_EQ(frame_height_, curr_frame.rows); - CHECK_EQ(frame_width_, curr_frame.cols); + ABSL_CHECK_EQ(frame_height_, curr_frame.rows); + ABSL_CHECK_EQ(frame_width_, curr_frame.cols); ClipMask<3> curr_clip; ComputeClipMask<3>(options_.clip_mask_options(), curr_frame, &curr_clip); @@ -219,8 +220,8 @@ float solution_ptr[6] = {1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f}; const int num_channels = color_tone_matches->size(); - CHECK_GT(num_channels, 0); - CHECK_LE(num_channels, 3); + ABSL_CHECK_GT(num_channels, 0); + ABSL_CHECK_LE(num_channels, 3); // TODO: One IRLS weight per color match. for (int c = 0; c < num_channels; ++c) {
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h index 0fa049e..9f37cdd3 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_estimation.h
@@ -25,6 +25,7 @@ #include <memory> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/opencv_core_inc.h" @@ -151,7 +152,7 @@ const cv::Mat& frame, ClipMask<C>* clip_mask) { CHECK(clip_mask != nullptr); - CHECK_EQ(frame.channels(), C); + ABSL_CHECK_EQ(frame.channels(), C); // Over / Underexposure handling. // Masks pixels affected by clipping. @@ -163,7 +164,7 @@ std::vector<cv::Mat> planes; cv::split(frame, planes); - CHECK_EQ(C, planes.size()); + ABSL_CHECK_EQ(C, planes.size()); float min_exposure[C]; float max_exposure[C]; for (int c = 0; c < C; ++c) { @@ -224,8 +225,8 @@ const ClipMask<C>& prev_clip_mask, // Optional. ColorToneMatches* color_tone_matches, cv::Mat* debug_output) { CHECK(color_tone_matches != nullptr); - CHECK_EQ(curr_frame.channels(), C); - CHECK_EQ(prev_frame.channels(), C); + ABSL_CHECK_EQ(curr_frame.channels(), C); + ABSL_CHECK_EQ(prev_frame.channels(), C); color_tone_matches->clear(); color_tone_matches->resize(C);
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc index 9410834..4ab896a 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.cc
@@ -16,6 +16,7 @@ #include <cmath> +#include "absl/log/absl_check.h" #include "absl/strings/str_format.h" namespace mediapipe { @@ -50,10 +51,10 @@ CHECK(output != nullptr); const int out_channels = output->channels(); - CHECK_EQ(input.channels(), 3); - CHECK_LE(out_channels, 3); - CHECK_EQ(input.rows, output->rows); - CHECK_EQ(input.cols, output->cols); + ABSL_CHECK_EQ(input.channels(), 3); + ABSL_CHECK_LE(out_channels, 3); + ABSL_CHECK_EQ(input.rows, output->rows); + ABSL_CHECK_EQ(input.cols, output->cols); float norm_scale = normalized_model
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h index 266257e..17b4427 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/tone_models.h
@@ -23,6 +23,7 @@ #include <string> #include <vector> +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/integral_types.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/opencv_core_inc.h" @@ -593,8 +594,8 @@ const Model& model, bool log_domain, bool normalized_model, const cv::Mat& input, cv::Mat* output) { CHECK(output != nullptr); - CHECK_EQ(input.channels(), C); - CHECK_EQ(output->channels(), C); + ABSL_CHECK_EQ(input.channels(), C); + ABSL_CHECK_EQ(output->channels(), C); // Input LUT which will be mapped to the output LUT by the tone change model. // Needs 3 channels to represent input RGB colors, but since they are assumed
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc index 50aaa940..efac37d 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc +++ b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.cc
@@ -25,6 +25,7 @@ #include "Eigen/Dense" #include "Eigen/SVD" #include "absl/algorithm/container.h" +#include "absl/log/absl_check.h" #include "absl/memory/memory.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/opencv_calib3d_inc.h" @@ -63,7 +64,7 @@ const std::vector<float>& inlier_weights, float aspect_ratio, MotionBoxInternalState* internal) { const int num_vectors = vectors.size(); - CHECK_EQ(num_vectors, inlier_weights.size()); + ABSL_CHECK_EQ(num_vectors, inlier_weights.size()); float scale_x = 1.0f; float scale_y = 1.0f; @@ -171,7 +172,7 @@ matrix.setTo(0); rhs.setTo(0); - CHECK_EQ(motion_vectors.size(), weights.size()); + ABSL_CHECK_EQ(motion_vectors.size(), weights.size()); for (int k = 0; k < motion_vectors.size(); ++k) { const float x = motion_vectors[k]->pos.x(); const float y = motion_vectors[k]->pos.y(); @@ -245,7 +246,7 @@ // Matrix multiplications are hand-coded for speed improvements vs. // opencv's cvGEMM calls. - CHECK_EQ(motion_vectors.size(), weights.size()); + ABSL_CHECK_EQ(motion_vectors.size(), weights.size()); for (int k = 0; k < motion_vectors.size(); ++k) { const float x = motion_vectors[k]->pos.x(); const float y = motion_vectors[k]->pos.y(); @@ -828,7 +829,7 @@ } const int kQuadCornersSize = 4; - CHECK_EQ(state->quad().vertices_size(), kQuadCornersSize * 2); + ABSL_CHECK_EQ(state->quad().vertices_size(), kQuadCornersSize * 2); float scale_x, scale_y; ScaleFromAspect(tracking.frame_aspect(), false, &scale_x, &scale_y); std::vector<cv::Point2f> corners_2d(kQuadCornersSize); @@ -910,7 +911,7 @@ state->set_aspect_ratio(width_norm / height_norm); } - CHECK_GT(state->aspect_ratio(), 0.0f); + ABSL_CHECK_GT(state->aspect_ratio(), 0.0f); const float half_width = state->aspect_ratio(); const float half_height = 1.0f; @@ -973,7 +974,7 @@ MotionVector MotionVector::FromInternalState( const MotionBoxInternalState& internal, int index) { - CHECK_LT(index, internal.pos_x_size()); + ABSL_CHECK_LT(index, internal.pos_x_size()); MotionVector v; v.pos = Vector2_f(internal.pos_x(index), internal.pos_y(index)); v.object = Vector2_f(internal.dx(index), internal.dy(index)); @@ -1150,7 +1151,7 @@ std::vector<float> old_confidence(update_pos->spatial_confidence().begin(), update_pos->spatial_confidence().end()); - CHECK_EQ(old_confidence.size(), old_prior.size()); + ABSL_CHECK_EQ(old_confidence.size(), old_prior.size()); CHECK(old_confidence.empty() || grid_size * grid_size == old_confidence.size()) << "Empty or priors of constant size expected"; @@ -1192,10 +1193,10 @@ const int int_x = static_cast<int>(grid_pos.x()); const int int_y = static_cast<int>(grid_pos.y()); - CHECK_GE(grid_pos.x(), 0) << pos.x() << ", " << update_pos->pos_x(); - CHECK_GE(grid_pos.y(), 0); - CHECK_LE(grid_pos.x(), grid_size - 1); - CHECK_LE(grid_pos.y(), grid_size - 1); + ABSL_CHECK_GE(grid_pos.x(), 0) << pos.x() << ", " << update_pos->pos_x(); + ABSL_CHECK_GE(grid_pos.y(), 0); + ABSL_CHECK_LE(grid_pos.x(), grid_size - 1); + ABSL_CHECK_LE(grid_pos.y(), grid_size - 1); const float dx = grid_pos.x() - int_x; const float dy = grid_pos.y() - int_y; @@ -1431,8 +1432,8 @@ tracking_degrees_ = options.tracking_degrees(); const Vector2_f box_domain(current_state.width() * current_state.scale(), current_state.height() * current_state.scale()); - CHECK_GT(box_domain.x(), 0.0f); - CHECK_GT(box_domain.y(), 0.0f); + ABSL_CHECK_GT(box_domain.x(), 0.0f); + ABSL_CHECK_GT(box_domain.y(), 0.0f); inv_box_domain_ = Vector2_f(1.0f / box_domain.x(), 1.0f / box_domain.y()); // Space sigma depends on how much the tracked object fills the rectangle. @@ -1575,8 +1576,8 @@ const Vector2_f box_domain(box_state.width() * box_state.scale(), box_state.height() * box_state.scale()); - CHECK_GT(box_domain.x(), 0.0f); - CHECK_GT(box_domain.y(), 0.0f); + ABSL_CHECK_GT(box_domain.x(), 0.0f); + ABSL_CHECK_GT(box_domain.y(), 0.0f); const Vector2_f inv_box_domain(1.0f / box_domain.x(), 1.0f / box_domain.y()); // The four lines of the rotated and scaled box. @@ -1670,8 +1671,8 @@ is_outlier.push_back(is_outlier_flag); } - CHECK_EQ(vectors->size(), is_inlier.size()); - CHECK_EQ(vectors->size(), is_outlier.size()); + ABSL_CHECK_EQ(vectors->size(), is_inlier.size()); + ABSL_CHECK_EQ(vectors->size(), is_outlier.size()); const float prev_motion_mag = MotionBoxVelocity(box_state).Norm(); @@ -1814,7 +1815,7 @@ } const int num_vectors = vectors->size(); - CHECK_EQ(num_vectors, weights->size()); + ABSL_CHECK_EQ(num_vectors, weights->size()); const float weight_sum = std::accumulate(weights->begin(), weights->end(), 0.0f); @@ -1917,8 +1918,8 @@ CHECK(object_homography); const int num_vectors = motion_vectors.size(); - CHECK_EQ(num_vectors, prior_weights.size()); - CHECK_EQ(num_vectors, weights->size()); + ABSL_CHECK_EQ(num_vectors, prior_weights.size()); + ABSL_CHECK_EQ(num_vectors, weights->size()); // Create backup of weights if needed. std::vector<float> similarity_weights; @@ -2440,8 +2441,8 @@ float weight_sum = 0; float inlier_sum = 0; const int num_vectors = motion_vectors.size(); - CHECK_EQ(num_vectors, weights.size()); - CHECK_EQ(num_vectors, density.size()); + ABSL_CHECK_EQ(num_vectors, weights.size()); + ABSL_CHECK_EQ(num_vectors, density.size()); Vector2_f first_moment(0.0f, 0.0f); Vector2_f second_moment(0.0f, 0.0f); @@ -2498,7 +2499,7 @@ const std::vector<const MotionVector*>& motion_vectors, const std::vector<float>& weights, float min_sum) const { const int num_vectors = motion_vectors.size(); - CHECK_EQ(num_vectors, weights.size()); + ABSL_CHECK_EQ(num_vectors, weights.size()); float scale_sum = 0; @@ -2793,7 +2794,7 @@ VLOG(1) << "Good inits: " << num_good_inits; const int num_vectors = vectors.size(); - CHECK_EQ(num_vectors, prior_weights.size()); + ABSL_CHECK_EQ(num_vectors, prior_weights.size()); Vector2_f object_translation;
diff --git a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h index 4d3343f5..248d20b 100644 --- a/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h +++ b/third_party/mediapipe/src/mediapipe/util/tracking/tracking.h
@@ -26,6 +26,7 @@ #include <vector> #include "absl/container/flat_hash_set.h" +#include "absl/log/absl_check.h" #include "mediapipe/framework/port/vector.h" #include "mediapipe/util/tracking/flow_packager.pb.h" #include "mediapipe/util/tracking/motion_models.h" @@ -122,7 +123,7 @@ std::unordered_map<int, int>* inliers) { CHECK(inliers); const int num_inliers = state.inlier_ids_size(); - DCHECK_EQ(num_inliers, state.inlier_length_size()); + ABSL_DCHECK_EQ(num_inliers, state.inlier_length_size()); for (int k = 0; k < num_inliers; ++k) { (*inliers)[state.inlier_ids(k)] = @@ -572,7 +573,7 @@ // Check if it is a convex quad. static bool IsValidQuad(const MotionBoxState::Quad& quad) { const int kQuadVerticesSize = 8; - CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); + ABSL_CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); for (int a = 0; a < kQuadVerticesSize; a += 2) { int b = (a + 2) % kQuadVerticesSize; int c = (a - 2 + kQuadVerticesSize) % kQuadVerticesSize; @@ -595,7 +596,7 @@ static bool IsQuadOutOfFov(const MotionBoxState::Quad& quad, const Vector2_f& fov) { const int kQuadVerticesSize = 8; - CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); + ABSL_CHECK_EQ(quad.vertices_size(), kQuadVerticesSize); bool too_far = true; for (int j = 0; j < kQuadVerticesSize; j += 2) { if (quad.vertices(j) < fov.x() && quad.vertices(j) > 0.0f &&
diff --git a/third_party/mediapipe/update_checks.sh b/third_party/mediapipe/update_checks.sh new file mode 100755 index 0000000..84bb9bf3 --- /dev/null +++ b/third_party/mediapipe/update_checks.sh
@@ -0,0 +1,50 @@ +#!/bin/sh +# Copyright 2023 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# This files modifies all uses of CHECK/DCHECK to be prefixed with ABSL. + +git grep --name-only " CHECK" > /tmp/to_change +git grep --name-only " DCHECK" >> /tmp/to_change +files=`sort -u /tmp/to_change` + +if [ -z "$files" ]; then + echo 'No files to rename' + exit -1 +fi + +# mediapipe defines it's own CHECK_OK +# (in src/mediapipe/framework/deps/status.h), which means only some CHECK's need +# to be modified. `check_extensions` is the list to replace. X is replaced with +# the empty string. +check_extensions="_EQ _NE _LE _LT _GE _GT _" + +for file in $files +do + echo "Modifying ${file}" + for extension in $check_extensions + do + if [ $extension = "_" ]; then + extension="" + fi + sed -i -e "s| CHECK${extension}(| ABSL_CHECK${extension}(|g" $file + sed -i -e "s| DCHECK${extension}(| ABSL_DCHECK${extension}(|g" $file + done + # Check to see if we modified the file. Only add the include if we did. + git diff --quiet $file + if [ $? -eq 1 ]; then + check_include=`grep "^#include \"absl/log/absl_check.h\"" $file` + if [ -z "$check_include" ]; then + line_number=`grep -n "^#include" $file | tail -1 | awk -F: '{print $1}'` + if [ ! -z "$line_number" ]; then + ((line_number=line_number+1)) + echo "Adding include to ${file} at line ${line_number}" + sed -i "${line_number} i #include \"absl/log/absl_check.h\"" $file + fi + fi + fi +done + +echo "WARNING: this script may have added includes to the wrong section (such as" +echo "shaders) be sure to sanity check results."
diff --git a/tools/metrics/actions/actions.xml b/tools/metrics/actions/actions.xml index 96dea60..e1d89e0 100644 --- a/tools/metrics/actions/actions.xml +++ b/tools/metrics/actions/actions.xml
@@ -7223,7 +7223,7 @@ </description> </action> -<action name="ContentSuggestions.Feed.SignIn.ShowSyncnHalfSheetFromFeed"> +<action name="ContentSuggestions.Feed.SignIn.ShowSyncHalfSheetFromFeed"> <owner>sczs@google.com</owner> <owner>tinazwang@chromium.org</owner> <owner>feed@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/cookie/histograms.xml b/tools/metrics/histograms/metadata/cookie/histograms.xml index 52cbec1e..7477cd0b 100644 --- a/tools/metrics/histograms/metadata/cookie/histograms.xml +++ b/tools/metrics/histograms/metadata/cookie/histograms.xml
@@ -386,20 +386,6 @@ </summary> </histogram> -<histogram name="Cookie.FirstPartySets.ComputeContext.Latency" - units="microseconds" expires_after="M124"> - <owner>cfredric@chromium.org</owner> - <owner>chrome-first-party-sets@chromium.org</owner> - <summary> - This histogram records the (TimeTicks) latency of computing the - same-partiness of a given context. - - This metric is sampled every time a SamePartyContext is computed (e.g. when - computing the cookies for a URL request, once per request). Only sampled for - users with high-resolution clocks. - </summary> -</histogram> - <histogram name="Cookie.FirstPartySets.ContextDelayedQueriesCount" units="queries" expires_after="M124"> <owner>shuuran@chromium.org</owner>
diff --git a/ui/base/clipboard/clipboard_util_win.cc b/ui/base/clipboard/clipboard_util_win.cc index 4031bb9..a6acef1 100644 --- a/ui/base/clipboard/clipboard_util_win.cc +++ b/ui/base/clipboard/clipboard_util_win.cc
@@ -655,7 +655,7 @@ return false; } -bool GetVirtualFilesAsTempFiles( +void GetVirtualFilesAsTempFiles( IDataObject* data_object, base::OnceCallback< void(const std::vector<std::pair</*temp path*/ base::FilePath, @@ -663,8 +663,10 @@ callback) { // Retrieve the display names of the virtual files. std::vector<base::FilePath> display_names; - if (!GetVirtualFilenames(data_object, &display_names)) - return false; + if (!GetVirtualFilenames(data_object, &display_names)) { + std::move(callback).Run({}); + return; + } // Write the file contents to global memory. std::vector<HGLOBAL> memory_backed_contents; @@ -679,8 +681,6 @@ base::BindOnce(&WriteAllFileContentsToTempFiles, display_names, memory_backed_contents), std::move(callback)); // callback on the UI thread - - return true; } bool GetPlainText(IDataObject* data_object, std::u16string* plain_text) {
diff --git a/ui/base/clipboard/clipboard_util_win.h b/ui/base/clipboard/clipboard_util_win.h index c31312e..bb9d5f65 100644 --- a/ui/base/clipboard/clipboard_util_win.h +++ b/ui/base/clipboard/clipboard_util_win.h
@@ -70,14 +70,14 @@ // Method is called on dropping on the Chromium drop target. Since creating // the temp files involves file I/O, the method is asynchronous and the caller // must provide a callback function that receives a vector of pairs of temp -// file paths and display names. Method immediately returns false if there are -// no virtual files in the data object, in which case the callback will never -// be invoked. +// file paths and display names. The method will invoke the callback with an +// empty vector if there are no virtual files in the data object. +// // TODO(https://crbug.com/951574): Implement virtual file extraction to // dynamically stream data to the renderer when File's bytes are actually // requested COMPONENT_EXPORT(UI_BASE_CLIPBOARD) -bool GetVirtualFilesAsTempFiles( +void GetVirtualFilesAsTempFiles( IDataObject* data_object, base::OnceCallback< void(const std::vector<std::pair</*temp path*/ base::FilePath,
diff --git a/ui/base/cocoa/nsmenuitem_additions_unittest.mm b/ui/base/cocoa/nsmenuitem_additions_unittest.mm index bb062af..2665482 100644 --- a/ui/base/cocoa/nsmenuitem_additions_unittest.mm +++ b/ui/base/cocoa/nsmenuitem_additions_unittest.mm
@@ -617,7 +617,8 @@ if ([layout_id isEqualToString:@"com.apple.keylayout.Belgian"] || [layout_id isEqualToString:@"com.apple.keylayout.Italian"] || [layout_id isEqualToString:@"com.apple.keylayout.ABC-AZERTY"] || - [layout_id hasPrefix:@"com.apple.keylayout.French"]) { + [layout_id hasPrefix:@"com.apple.keylayout.French"] || + [layout_id isEqualToString:@"com.apple.keylayout.Kabyle-AZERTY"]) { key_code = 0x29; } else if ([layout_id isEqualToString:@"com.apple.keylayout.Turkish"] || [layout_id @@ -639,6 +640,11 @@ // There is no way to type an "m" using the Amharic keyboard. It's // designed for the Ge'ez language. continue; + } else if ([layout_id + isEqualToString:@"com.apple.keylayout.Tifinagh-AZERTY"]) { + // There is no way to type an "m" using the Tamazight keyboard. It's + // designed for Moroccan. + continue; } else if (IsCommandlessCyrillicLayout(layout_id)) { // Commandless layouts have no way to trigger a menu key equivalent at // all, in any app.
diff --git a/ui/base/dragdrop/os_exchange_data.cc b/ui/base/dragdrop/os_exchange_data.cc index 99c9b04..d6720fe 100644 --- a/ui/base/dragdrop/os_exchange_data.cc +++ b/ui/base/dragdrop/os_exchange_data.cc
@@ -150,11 +150,11 @@ return provider_->GetVirtualFilenames(filenames); } -bool OSExchangeData::GetVirtualFilesAsTempFiles( +void OSExchangeData::GetVirtualFilesAsTempFiles( base::OnceCallback< void(const std::vector<std::pair<base::FilePath, base::FilePath>>&)> callback) const { - return provider_->GetVirtualFilesAsTempFiles(std::move(callback)); + provider_->GetVirtualFilesAsTempFiles(std::move(callback)); } #endif
diff --git a/ui/base/dragdrop/os_exchange_data.h b/ui/base/dragdrop/os_exchange_data.h index 0c5a628..a5a7fbf 100644 --- a/ui/base/dragdrop/os_exchange_data.h +++ b/ui/base/dragdrop/os_exchange_data.h
@@ -172,13 +172,13 @@ // Method is called on dropping on the Chromium drop target. Since creating // the temp files involves file I/O, the method is asynchronous and the caller // must provide a callback function that receives a vector of pairs of temp - // file paths and display names. Method immediately returns false if there are - // no virtual files in the data object, in which case the callback will never - // be invoked. + // file paths and display names. The method will invoke the callback with an + // empty vector if there are no virtual files in the data object. + // // TODO(https://crbug.com/951574): Implement virtual file extraction to // dynamically stream data to the renderer when File's bytes are actually // requested - bool GetVirtualFilesAsTempFiles( + void GetVirtualFilesAsTempFiles( base::OnceCallback<void(const std::vector</*temp path*/ std::pair< base::FilePath, /*display name*/ base::FilePath>>&)> callback)
diff --git a/ui/base/dragdrop/os_exchange_data_provider.h b/ui/base/dragdrop/os_exchange_data_provider.h index 5ebf0e3..5e03b3d 100644 --- a/ui/base/dragdrop/os_exchange_data_provider.h +++ b/ui/base/dragdrop/os_exchange_data_provider.h
@@ -83,7 +83,7 @@ #if BUILDFLAG(IS_WIN) virtual bool HasVirtualFilenames() const = 0; virtual bool GetVirtualFilenames(std::vector<FileInfo>* file_names) const = 0; - virtual bool GetVirtualFilesAsTempFiles( + virtual void GetVirtualFilesAsTempFiles( base::OnceCallback< void(const std::vector<std::pair</*temp path*/ base::FilePath, /*display name*/ base::FilePath>>&)>
diff --git a/ui/base/dragdrop/os_exchange_data_provider_win.cc b/ui/base/dragdrop/os_exchange_data_provider_win.cc index 45c5782..02bdffd 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_win.cc +++ b/ui/base/dragdrop/os_exchange_data_provider_win.cc
@@ -618,12 +618,12 @@ return success; } -bool OSExchangeDataProviderWin::GetVirtualFilesAsTempFiles( +void OSExchangeDataProviderWin::GetVirtualFilesAsTempFiles( base::OnceCallback< void(const std::vector<std::pair<base::FilePath, base::FilePath>>&)> callback) const { - return clipboard_util::GetVirtualFilesAsTempFiles(source_object_.Get(), - std::move(callback)); + clipboard_util::GetVirtualFilesAsTempFiles(source_object_.Get(), + std::move(callback)); } bool OSExchangeDataProviderWin::GetPickledData(
diff --git a/ui/base/dragdrop/os_exchange_data_provider_win.h b/ui/base/dragdrop/os_exchange_data_provider_win.h index 87a84d1..0927e117 100644 --- a/ui/base/dragdrop/os_exchange_data_provider_win.h +++ b/ui/base/dragdrop/os_exchange_data_provider_win.h
@@ -176,7 +176,7 @@ bool GetFilenames(std::vector<FileInfo>* filenames) const override; bool HasVirtualFilenames() const override; bool GetVirtualFilenames(std::vector<FileInfo>* filenames) const override; - bool GetVirtualFilesAsTempFiles( + void GetVirtualFilesAsTempFiles( base::OnceCallback< void(const std::vector<std::pair<base::FilePath, base::FilePath>>&)> callback) const override;
diff --git a/ui/base/dragdrop/os_exchange_data_win_unittest.cc b/ui/base/dragdrop/os_exchange_data_win_unittest.cc index 00de31b..daca3f3 100644 --- a/ui/base/dragdrop/os_exchange_data_win_unittest.cc +++ b/ui/base/dragdrop/os_exchange_data_win_unittest.cc
@@ -11,6 +11,7 @@ #include "base/files/file_util.h" #include "base/functional/bind.h" #include "base/functional/callback.h" +#include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "base/sequence_checker.h" #include "base/strings/string_util.h" @@ -127,6 +128,8 @@ void OnGotVirtualFilesAsTempFiles( const std::vector<std::pair<base::FilePath, base::FilePath>>& filepaths_and_names) { + on_got_virtual_files_as_temp_files_called_ = true; + // Clear any previous results and cache a vector of FileInfo objects for // verification. retrieved_virtual_files_.clear(); @@ -138,8 +141,23 @@ } protected: + class OnGotVirtualFilesAsTempFilesCalledChecker { + public: + OnGotVirtualFilesAsTempFilesCalledChecker(OSExchangeDataWinTest* test) + : test_(test) { + test_->on_got_virtual_files_as_temp_files_called_ = false; + } + ~OnGotVirtualFilesAsTempFilesCalledChecker() { + EXPECT_TRUE(test_->on_got_virtual_files_as_temp_files_called_); + } + + private: + raw_ptr<OSExchangeDataWinTest> test_; + }; + std::vector<FileInfo> retrieved_virtual_files_; base::test::TaskEnvironment task_environment_; + bool on_got_virtual_files_as_temp_files_called_ = false; }; // Test getting using the IDataObject COM API @@ -465,7 +483,8 @@ base::BindOnce(&OSExchangeDataWinTest::OnGotVirtualFilesAsTempFiles, base::Unretained(this)); - EXPECT_TRUE(copy.GetVirtualFilesAsTempFiles(std::move(callback))); + OnGotVirtualFilesAsTempFilesCalledChecker checker(this); + copy.GetVirtualFilesAsTempFiles(std::move(callback)); // RunUntilIdle assures all async tasks are run. task_environment_.RunUntilIdle(); @@ -541,7 +560,8 @@ base::BindOnce(&OSExchangeDataWinTest::OnGotVirtualFilesAsTempFiles, base::Unretained(this)); - EXPECT_FALSE(copy.GetVirtualFilesAsTempFiles(std::move(callback))); + OnGotVirtualFilesAsTempFilesCalledChecker checker(this); + copy.GetVirtualFilesAsTempFiles(std::move(callback)); // RunUntilIdle assures all async tasks are run. task_environment_.RunUntilIdle(); @@ -590,7 +610,8 @@ base::BindOnce(&OSExchangeDataWinTest::OnGotVirtualFilesAsTempFiles, base::Unretained(this)); - EXPECT_TRUE(copy.GetVirtualFilesAsTempFiles(std::move(callback))); + OnGotVirtualFilesAsTempFilesCalledChecker checker(this); + copy.GetVirtualFilesAsTempFiles(std::move(callback)); // RunUntilIdle assures all async tasks are run. task_environment_.RunUntilIdle(); @@ -673,7 +694,8 @@ base::BindOnce(&OSExchangeDataWinTest::OnGotVirtualFilesAsTempFiles, base::Unretained(this)); - EXPECT_TRUE(copy.GetVirtualFilesAsTempFiles(std::move(callback))); + OnGotVirtualFilesAsTempFilesCalledChecker checker(this); + copy.GetVirtualFilesAsTempFiles(std::move(callback)); // RunUntilIdle assures all async tasks are run. task_environment_.RunUntilIdle(); @@ -783,7 +805,8 @@ base::BindOnce(&OSExchangeDataWinTest::OnGotVirtualFilesAsTempFiles, base::Unretained(this)); - EXPECT_TRUE(copy.GetVirtualFilesAsTempFiles(std::move(callback))); + OnGotVirtualFilesAsTempFilesCalledChecker checker(this); + copy.GetVirtualFilesAsTempFiles(std::move(callback)); // RunUntilIdle assures all async tasks are run. task_environment_.RunUntilIdle(); @@ -868,7 +891,8 @@ base::BindOnce(&OSExchangeDataWinTest::OnGotVirtualFilesAsTempFiles, base::Unretained(this)); - EXPECT_TRUE(copy.GetVirtualFilesAsTempFiles(std::move(callback))); + OnGotVirtualFilesAsTempFilesCalledChecker checker(this); + copy.GetVirtualFilesAsTempFiles(std::move(callback)); // RunUntilIdle assures all async tasks are run. task_environment_.RunUntilIdle();
diff --git a/ui/gtk/gtk_ui.cc b/ui/gtk/gtk_ui.cc index 2b6bb89e..a463500 100644 --- a/ui/gtk/gtk_ui.cc +++ b/ui/gtk/gtk_ui.cc
@@ -463,6 +463,14 @@ return dark; } +void GtkUi::SetDarkTheme(bool dark) { + auto* settings = gtk_settings_get_default(); + g_object_set(settings, "gtk-application-prefer-dark-theme", dark, nullptr); + // OnThemeChanged() will be called via the + // notify::gtk-application-prefer-dark-theme handler to update the native + // theme. +} + bool GtkUi::AnimationsEnabled() const { gboolean animations_enabled = false; g_object_get(gtk_settings_get_default(), "gtk-enable-animations",
diff --git a/ui/gtk/gtk_ui.h b/ui/gtk/gtk_ui.h index 573ea40..53c02c5 100644 --- a/ui/gtk/gtk_ui.h +++ b/ui/gtk/gtk_ui.h
@@ -106,6 +106,7 @@ void GetInactiveSelectionBgColor(SkColor* color) const override; void GetInactiveSelectionFgColor(SkColor* color) const override; bool PreferDarkTheme() const override; + void SetDarkTheme(bool dark) override; std::unique_ptr<ui::NavButtonProvider> CreateNavButtonProvider() override; ui::WindowFrameProvider* GetWindowFrameProvider(bool solid_frame) override;
diff --git a/ui/linux/fake_linux_ui.cc b/ui/linux/fake_linux_ui.cc index d236a09..8b67f04 100644 --- a/ui/linux/fake_linux_ui.cc +++ b/ui/linux/fake_linux_ui.cc
@@ -93,6 +93,8 @@ return false; } +void FakeLinuxUi::SetDarkTheme(bool dark) {} + bool FakeLinuxUi::AnimationsEnabled() const { return true; }
diff --git a/ui/linux/fake_linux_ui.h b/ui/linux/fake_linux_ui.h index 87aa82c..daba20d1 100644 --- a/ui/linux/fake_linux_ui.h +++ b/ui/linux/fake_linux_ui.h
@@ -64,6 +64,7 @@ void GetInactiveSelectionBgColor(SkColor* color) const override; void GetInactiveSelectionFgColor(SkColor* color) const override; bool PreferDarkTheme() const override; + void SetDarkTheme(bool dark) override; std::unique_ptr<ui::NavButtonProvider> CreateNavButtonProvider() override; ui::WindowFrameProvider* GetWindowFrameProvider(bool solid_frame) override; };
diff --git a/ui/linux/fallback_linux_ui.cc b/ui/linux/fallback_linux_ui.cc index ab116fd..6d77be0 100644 --- a/ui/linux/fallback_linux_ui.cc +++ b/ui/linux/fallback_linux_ui.cc
@@ -112,7 +112,11 @@ } bool FallbackLinuxUi::PreferDarkTheme() const { - return false; + return theme_is_dark_; +} + +void FallbackLinuxUi::SetDarkTheme(bool dark) { + theme_is_dark_ = dark; } bool FallbackLinuxUi::AnimationsEnabled() const {
diff --git a/ui/linux/fallback_linux_ui.h b/ui/linux/fallback_linux_ui.h index 0d0df25..9901d49 100644 --- a/ui/linux/fallback_linux_ui.h +++ b/ui/linux/fallback_linux_ui.h
@@ -65,12 +65,14 @@ void GetInactiveSelectionBgColor(SkColor* color) const override; void GetInactiveSelectionFgColor(SkColor* color) const override; bool PreferDarkTheme() const override; + void SetDarkTheme(bool dark) override; std::unique_ptr<ui::NavButtonProvider> CreateNavButtonProvider() override; ui::WindowFrameProvider* GetWindowFrameProvider(bool solid_frame) override; private: std::string default_font_family_; gfx::FontRenderParams default_font_render_params_; + bool theme_is_dark_ = false; }; } // namespace ui
diff --git a/ui/linux/linux_ui.h b/ui/linux/linux_ui.h index 45b36fb..a47134d 100644 --- a/ui/linux/linux_ui.h +++ b/ui/linux/linux_ui.h
@@ -300,6 +300,10 @@ // preferred. virtual bool PreferDarkTheme() const = 0; + // Override the toolkit's dark mode preference. Used when the dark mode + // setting is provided by org.freedesktop.appearance instead of the toolkit. + virtual void SetDarkTheme(bool dark) = 0; + // Returns a new NavButtonProvider, or nullptr if the underlying // toolkit does not support drawing client-side navigation buttons. virtual std::unique_ptr<NavButtonProvider> CreateNavButtonProvider() = 0;
diff --git a/ui/linux/linux_ui_factory.cc b/ui/linux/linux_ui_factory.cc index 5555ff3..21be358 100644 --- a/ui/linux/linux_ui_factory.cc +++ b/ui/linux/linux_ui_factory.cc
@@ -10,6 +10,7 @@ #include "base/command_line.h" #include "base/environment.h" #include "base/nix/xdg_util.h" +#include "base/no_destructor.h" #include "base/strings/string_util.h" #include "build/chromecast_buildflags.h" #include "ui/base/buildflags.h" @@ -35,10 +36,16 @@ const char kUiToolkitFlag[] = "ui-toolkit"; +std::vector<LinuxUiTheme*>& GetLinuxUiThemesImpl() { + static base::NoDestructor<std::vector<LinuxUiTheme*>> themes; + return *themes; +} + std::unique_ptr<LinuxUiAndTheme> CreateGtkUi() { #if BUILDFLAG(USE_GTK) auto gtk_ui = BuildGtkUi(); if (gtk_ui->Initialize()) { + GetLinuxUiThemesImpl().push_back(gtk_ui.get()); return gtk_ui; } #endif @@ -61,6 +68,7 @@ #if BUILDFLAG(USE_QT) auto qt_ui = qt::CreateQtUi(GetGtkUi()); if (qt_ui->Initialize()) { + GetLinuxUiThemesImpl().push_back(qt_ui.get()); return qt_ui; } #endif @@ -156,6 +164,10 @@ } } +const std::vector<LinuxUiTheme*>& GetLinuxUiThemes() { + return GetLinuxUiThemesImpl(); +} + SystemTheme GetDefaultSystemTheme() { std::unique_ptr<base::Environment> env = base::Environment::Create();
diff --git a/ui/linux/linux_ui_factory.h b/ui/linux/linux_ui_factory.h index 5d4f4f4..2f4820f2 100644 --- a/ui/linux/linux_ui_factory.h +++ b/ui/linux/linux_ui_factory.h
@@ -32,6 +32,10 @@ COMPONENT_EXPORT(LINUX_UI_FACTORY) LinuxUiTheme* GetLinuxUiTheme(SystemTheme system_theme); +// Returns all `LinuxUiTheme`s that have been created. +COMPONENT_EXPORT(LINUX_UI_FACTORY) +const std::vector<LinuxUiTheme*>& GetLinuxUiThemes(); + COMPONENT_EXPORT(LINUX_UI_FACTORY) SystemTheme GetDefaultSystemTheme();
diff --git a/ui/qt/qt_ui.cc b/ui/qt/qt_ui.cc index cd12c72a..37e165d76 100644 --- a/ui/qt/qt_ui.cc +++ b/ui/qt/qt_ui.cc
@@ -356,6 +356,11 @@ } DISABLE_CFI_VCALL +void QtUi::SetDarkTheme(bool dark) { + // Qt::ColorScheme is only available in QT 6.5 and later. +} + +DISABLE_CFI_VCALL bool QtUi::AnimationsEnabled() const { return shim_->GetAnimationDurationMs() > 0; }
diff --git a/ui/qt/qt_ui.h b/ui/qt/qt_ui.h index 38ce871..787a955 100644 --- a/ui/qt/qt_ui.h +++ b/ui/qt/qt_ui.h
@@ -82,6 +82,7 @@ void GetInactiveSelectionBgColor(SkColor* color) const override; void GetInactiveSelectionFgColor(SkColor* color) const override; bool PreferDarkTheme() const override; + void SetDarkTheme(bool dark) override; std::unique_ptr<ui::NavButtonProvider> CreateNavButtonProvider() override; ui::WindowFrameProvider* GetWindowFrameProvider(bool solid_frame) override;
diff --git a/ui/views/controls/menu/menu_controller.cc b/ui/views/controls/menu/menu_controller.cc index 7816e1f..c950111e 100644 --- a/ui/views/controls/menu/menu_controller.cc +++ b/ui/views/controls/menu/menu_controller.cc
@@ -234,7 +234,7 @@ T converted_event = event; if (submenu.GetWidget()->GetRootView() != &root_view) { converted_event.set_location(View::ConvertPointFromScreen( - &root_view, View::ConvertPointToScreen(&submenu, event.location()))); + &root_view, ConvertToScreen(submenu, event.location()))); } return converted_event; }