diff --git a/DEPS b/DEPS index 4d4bbe9..9914899 100644 --- a/DEPS +++ b/DEPS
@@ -290,7 +290,7 @@ 'sysroots_json_path': 'build/linux/sysroot_scripts/sysroots.json', # siso CIPD package version. - 'siso_version': 'git_revision:c349fcb5f693249d938e2d4ce4c4b4d037dceb5b', + 'siso_version': 'git_revision:07d585d17bdd3c521080e2aa5f7b9f6a12f18ded', # download libaom test data 'download_libaom_testdata': False, @@ -314,15 +314,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': '27b242111cb0f5db82e5c0e0fd3bb29cc089475e', + 'skia_revision': 'f13ee6ee543386ec5f06bb59eeccbd40fd0405b2', # 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': '03ce2c9168f9ffcfc24779e7e91b16cdd10b7290', + 'v8_revision': 'dbe1cf7904a5fa20697de6ed247a5e9f4247dba1', # 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': '8f5a61243e6fb5bb6112c98470163e7f64dfb194', + 'angle_revision': '86d128c0f37f4ed1c598319c418ae13a37bfb909', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling SwiftShader # and whatever else without interference from each other. @@ -385,11 +385,11 @@ # 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': '48345f326d5760814286f85797a4b59cd0b25c2e', + 'catapult_revision': '0ad1d60e958e2f42e5fe9303035cc10eec1304f7', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling chromium_variations # and whatever else without interference from each other. - 'chromium_variations_revision': 'ccae3b7052f414b1d83983cf7d4e77339249848b', + 'chromium_variations_revision': 'ada6b2f7876642ae86fb79d8f98a636bfeddb36d', # Three lines of non-changing comments so that # the commit queue can handle CLs rolling CrossBench # and whatever else without interference from each other. @@ -837,12 +837,12 @@ 'src/clank': { 'url': Var('chrome_git') + '/clank/internal/apps.git' + '@' + - 'd3687a2437fad1d6f61c52e060d4ca56533e6c56', + '9dc2c844ca3d5ed26a6a91b44c5490da4a77d325', 'condition': 'checkout_android and checkout_src_internal', }, 'src/docs/website': { - 'url': Var('chromium_git') + '/website.git' + '@' + '1c9b8067445f91d772e1087d783fbfbaf4041e5b', + 'url': Var('chromium_git') + '/website.git' + '@' + '4816910e134254e7155c90dcbf9f5055ce8b4099', }, 'src/ios/third_party/earl_grey2/src': { @@ -1933,10 +1933,10 @@ Var('chromium_git') + '/external/khronosgroup/webgl.git' + '@' + '3e71f3b643f8095babbd46cf4e7d34e4f1ddf7a8', 'src/third_party/webgpu-cts/src': - Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '0369f5dc081b75a1c94d31259aff37244f527e92', + Var('chromium_git') + '/external/github.com/gpuweb/cts.git' + '@' + '3acbf58bd5c2d28fb84d953e65de7582fad28faa', 'src/third_party/webrtc': - Var('webrtc_git') + '/src.git' + '@' + '86f9fa23842e5e8d824e3337e5c921763cb26eda', + Var('webrtc_git') + '/src.git' + '@' + '1ee5bfec9f50728c135795ee966ff220fc6f60dc', # 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. @@ -2048,7 +2048,7 @@ 'packages': [ { 'package': 'chromeos_internal/apps/eche_app/app', - 'version': 'iIVCj0p56GionKvwYgG0NMAMqTL4vCJcYHVnDWvyvUwC', + 'version': 'f5Rd655OB0qwwkjv7MQ4k0HK-YieLfZ04I8YiSvWHY8C', }, ], 'condition': 'checkout_chromeos and checkout_src_internal',
diff --git a/ash/components/arc/mojom/intent_helper.mojom b/ash/components/arc/mojom/intent_helper.mojom index 8fda54d5..5ee6e913 100644 --- a/ash/components/arc/mojom/intent_helper.mojom +++ b/ash/components/arc/mojom/intent_helper.mojom
@@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // -// Next MinVersion: 52 +// Next MinVersion: 53 module arc.mojom; @@ -265,6 +265,45 @@ kGeoLocationUserTriggered, }; +// The type of shadow used for Chrome captions. +// https://developer.android.com/reference/android/view/accessibility/CaptioningManager.CaptionStyle +[Extensible] +enum CaptionTextShadowType { + // Edge type value specifying no character edges. + kNone = 0, + + // Edge type value specifying uniformly outlined character edges. + kUniform = 1, + + // Edge type value specifying drop-shadowed character edges. + kDropShadow = 2, + + // Edge type value specifying raised bevel character edges. + kRaised = 3, + + // Edge type value specifying depressed bevel character edges. + kDepressed = 4, + + [Default] kInvalidEnumValue = -1, +}; + +struct CaptionColor { + uint8 alpha; + uint8 red; + uint8 green; + uint8 blue; +}; + +// Encapsulates settings to stylize captions. +// https://developer.android.com/reference/android/view/accessibility/CaptioningManager.CaptionStyle.html +struct CaptionStyle { + string user_locale; + float font_scale; + CaptionColor? text_color; + CaptionColor? background_color; + CaptionTextShadowType text_shadow_type; +}; + // Interface to interact with a custom tab. // Close the interface pointer to close the custom tab. // Next method ID: 1 @@ -385,7 +424,7 @@ // Sends intents to ARC on behalf of Chrome. // Deprecated method ID: 0, 7, 11, 12, 14, 17, 18 -// Next method ID: 22 +// Next method ID: 23 interface IntentHelperInstance { // Sets the given package as a preferred package. The next time an ACTION_VIEW // intent is sent with a URL that requires disambiguation, instead of opening @@ -463,4 +502,7 @@ // Request ARC to send the domain verification status update for all packages // to Chrome OS. [MinVersion=37] RequestDomainVerificationStatusUpdate@19(); + + // Requests the service to set the caption style. + [MinVersion=52] SetCaptionStyle@22(CaptionStyle style); };
diff --git a/ash/constants/ash_features.cc b/ash/constants/ash_features.cc index 31b5dd2..ccd75da 100644 --- a/ash/constants/ash_features.cc +++ b/ash/constants/ash_features.cc
@@ -5,15 +5,17 @@ #include "ash/constants/ash_features.h" #include "ash/constants/ash_switches.h" -#include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial_params.h" -#include "base/system/sys_info.h" #include "build/branding_buildflags.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #include "chromeos/constants/chromeos_features.h" +#if defined(ARCH_CPU_ARM_FAMILY) +#include "base/command_line.h" +#endif // defined(ARCH_CPU_ARM_FAMILY) + namespace ash::features { namespace { @@ -3071,11 +3073,6 @@ return base::FeatureList::IsEnabled(kDriveFsMirroring); } -bool IsDriveFsBulkPinningEnabled() { - return base::FeatureList::IsEnabled(kFeatureManagementDriveFsBulkPinning) && - base::FeatureList::IsEnabled(kDriveFsBulkPinning); -} - int GetDriveFsBulkPinningQueueSize() { return base::GetFieldTrialParamByFeatureAsInt(kDriveFsBulkPinningExperiment, "queue_size", 5); @@ -3614,11 +3611,6 @@ return base::FeatureList::IsEnabled(kOobeChoobe); } -bool IsOobeDrivePinningEnabled() { - return base::FeatureList::IsEnabled(kOobeDrivePinning) && - IsOobeChoobeEnabled() && IsDriveFsBulkPinningEnabled(); -} - bool IsOobeSoftwareUpdateEnabled() { return base::FeatureList::IsEnabled(kOobeSoftwareUpdate); }
diff --git a/ash/constants/ash_features.h b/ash/constants/ash_features.h index b136aaec..1b2c2c61 100644 --- a/ash/constants/ash_features.h +++ b/ash/constants/ash_features.h
@@ -869,7 +869,6 @@ COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDnsOverHttpsWithIdentifiersEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDisplayAlignmentAssistanceEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDriveFsMirroringEnabled(); -COMPONENT_EXPORT(ASH_CONSTANTS) bool IsDriveFsBulkPinningEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) int GetDriveFsBulkPinningQueueSize(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInlineSyncStatusEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsInlineSyncStatusOldEventsEnabled(); @@ -993,7 +992,6 @@ COMPONENT_EXPORT(ASH_CONSTANTS) bool IsNotificationsInContextMenuEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOAuthIppEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeChoobeEnabled(); -COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeDrivePinningEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeLazyLoadingEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeChromeVoxHintEnabled(); COMPONENT_EXPORT(ASH_CONSTANTS) bool IsOobeHidDetectionRevampEnabled();
diff --git a/ash/display/cursor_window_controller.cc b/ash/display/cursor_window_controller.cc index a993d789..42911d2b 100644 --- a/ash/display/cursor_window_controller.cc +++ b/ash/display/cursor_window_controller.cc
@@ -178,7 +178,10 @@ : delegate_(new CursorWindowDelegate()), is_cursor_motion_blur_enabled_( base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kAshEnableCursorMotionBlur)) {} + switches::kAshEnableCursorMotionBlur)), + // TODO(b/296641218): Find another way to make sure gpu process is fully + // initialized first before updating cursor view. + start_time_(base::TimeTicks::Now()) {} CursorWindowController::~CursorWindowController() { SetContainer(NULL); @@ -217,8 +220,9 @@ } bool CursorWindowController::ShouldEnableCursorCompositing() { - if (is_cursor_motion_blur_enabled_) + if (CanEnableMotionBlur()) { return true; + } if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceShowCursor)) { @@ -392,6 +396,18 @@ UpdateCursorVisibility(); } +void CursorWindowController::OnWindowBoundsChanged( + aura::Window* window, + const gfx::Rect& old_bounds, + const gfx::Rect& new_bounds, + ui::PropertyChangeReason reason) { + DCHECK_EQ(container_, window); + + if (cursor_view_widget_) { + UpdateCursorView(); + } +} + const aura::Window* CursorWindowController::GetContainerForTest() const { return container_; } @@ -408,6 +424,9 @@ if (container_ == container) { return; } + + scoped_container_observer_.Reset(); + container_ = container; if (!container) { cursor_window_.reset(); @@ -415,10 +434,12 @@ return; } + scoped_container_observer_.Observe(container_); + bounds_in_screen_ = display_.bounds(); rotation_ = display_.rotation(); - if (is_cursor_motion_blur_enabled_) { + if (CanEnableMotionBlur()) { UpdateCursorView(); } else { // Reusing the window does not work when the display is disconnected. @@ -539,6 +560,11 @@ } void CursorWindowController::UpdateCursorView() { + // Return if the container's size is not updated yet. + if (container_->GetBoundsInRootWindow().size() != bounds_in_screen_.size()) { + return; + } + cursor_view_widget_ = CursorView::Create(aura::Env::GetInstance()->last_mouse_location(), is_cursor_motion_blur_enabled_, container_); @@ -549,4 +575,9 @@ return delegate_->cursor_image(); } +bool CursorWindowController::CanEnableMotionBlur() const { + return is_cursor_motion_blur_enabled_ && + base::TimeTicks::Now() - start_time_ > base::Seconds(5); +} + } // namespace ash
diff --git a/ash/display/cursor_window_controller.h b/ash/display/cursor_window_controller.h index 3e208b28..420be60 100644 --- a/ash/display/cursor_window_controller.h +++ b/ash/display/cursor_window_controller.h
@@ -32,7 +32,7 @@ // When cursor compositing is disabled, draw nothing as the native cursor is // shown. // When cursor compositing is enabled, just draw the cursor as-is. -class ASH_EXPORT CursorWindowController { +class ASH_EXPORT CursorWindowController : public aura::WindowObserver { public: class Observer : public base::CheckedObserver { public: @@ -47,7 +47,7 @@ CursorWindowController(const CursorWindowController&) = delete; CursorWindowController& operator=(const CursorWindowController&) = delete; - ~CursorWindowController(); + ~CursorWindowController() override; bool is_cursor_compositing_enabled() const { return is_cursor_compositing_enabled_; @@ -87,6 +87,12 @@ void SetCursorSize(ui::CursorSize cursor_size); void SetVisibility(bool visible); + // aura::WindowObserver: + void OnWindowBoundsChanged(aura::Window* window, + const gfx::Rect& old_bounds, + const gfx::Rect& new_bounds, + ui::PropertyChangeReason reason) override; + // Gets the cursor container for testing purposes. const aura::Window* GetContainerForTest() const; SkColor GetCursorColorForTest() const; @@ -115,6 +121,8 @@ const gfx::ImageSkia& GetCursorImageForTest() const; + bool CanEnableMotionBlur() const; + base::ObserverList<Observer> observers_; raw_ptr<aura::Window, DanglingUntriaged | ExperimentalAsh> container_ = @@ -150,6 +158,9 @@ views::UniqueWidgetPtr cursor_view_widget_; const bool is_cursor_motion_blur_enabled_; + base::TimeTicks start_time_; + base::ScopedObservation<aura::Window, aura::WindowObserver> + scoped_container_observer_{this}; }; } // namespace ash
diff --git a/ash/fast_ink/cursor/cursor_view.cc b/ash/fast_ink/cursor/cursor_view.cc index f4d6039..03634539 100644 --- a/ash/fast_ink/cursor/cursor_view.cc +++ b/ash/fast_ink/cursor/cursor_view.cc
@@ -4,14 +4,20 @@ #include "ash/fast_ink/cursor/cursor_view.h" +#include <memory> + #include "base/functional/bind.h" +#include "base/functional/callback.h" #include "base/memory/ptr_util.h" #include "base/task/single_thread_task_runner.h" #include "base/task/thread_pool.h" #include "base/trace_event/trace_event.h" #include "cc/paint/paint_canvas.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/aura/window.h" +#include "ui/aura/window_tree_host.h" #include "ui/gfx/geometry/skia_conversions.h" +#include "ui/gfx/image/image_skia_rep_default.h" #include "ui/gfx/presentation_feedback.h" namespace ash { @@ -53,36 +59,350 @@ } // namespace //////////////////////////////////////////////////////////////////////////////// +// CursorView::Painter + +class CursorView::Painter : public viz::DelayBasedTimeSourceClient { + public: + using UpdateSurfaceCallback = + base::RepeatingCallback<void(const gfx::Rect&, const gfx::Rect&, bool)>; + + Painter(CursorView* cursor_view, + const gfx::Point& initial_location, + bool is_motion_blur_enabled) + : cursor_view_(cursor_view), + is_motion_blur_enabled_(is_motion_blur_enabled), + location_(initial_location), + pending_location_(initial_location), + ui_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), + paint_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner( + {base::TaskPriority::USER_BLOCKING, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), + stationary_timer_( + FROM_HERE, + base::Milliseconds(kStationaryDelayMs), + base::BindRepeating(&CursorView::Painter::StationaryOnPaintThread, + base::Unretained(this))) { + // Detach sequence checker for future usage on paint thread. + DETACH_FROM_SEQUENCE(paint_sequence_checker_); + } + ~Painter() override = default; + + void Init(UpdateSurfaceCallback update_surface_callback) { + DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); + + dsf_ = cursor_view_->GetWidget() + ->GetNativeView() + ->GetHost() + ->device_scale_factor(); + update_surface_callback_ = std::move(update_surface_callback); + } + + void Shutdown() { + DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); + + // Waits for the current paint (if any) to finish. + base::AutoLock lock(lock_); + + cursor_view_ = nullptr; + + if (time_source_) { + time_source_->SetClient(nullptr); + } + paint_task_runner_->DeleteSoon(FROM_HERE, this); + } + + void SetCursorLocation(const gfx::Point& new_location) { + // This is called from `CursorView::OnCursorLocationChanged` which could be + // either on ui thread or evdev thread. + + // base::Unretained() is safe because `this` is deleted on the paint thread. + paint_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&CursorView::Painter::SetCursorLocationOnPaintThread, + base::Unretained(this), new_location)); + } + + void SetCursorImage(const gfx::ImageSkia& cursor_image, + const gfx::Size& cursor_size, + const gfx::Point& cursor_hotspot) { + DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); + + gfx::ImageSkia scaled_cursor_image = gfx::ImageSkia::CreateFrom1xBitmap( + cursor_image.GetRepresentation(dsf_).GetBitmap()); + + // base::Unretained() is safe because `this` is deleted on the paint thread. + paint_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&CursorView::Painter::SetCursorImageOnPaintThread, + base::Unretained(this), scaled_cursor_image, cursor_size, + cursor_hotspot)); + } + + void SetTimebaseAndInterval(base::TimeTicks timebase, + base::TimeDelta interval) { + DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); + + // base::Unretained() is safe because `this` is deleted on the paint thread. + paint_task_runner_->PostTask( + FROM_HERE, + base::BindOnce( + &CursorView::Painter::SetTimebaseAndIntervalOnPaintThread, + base::Unretained(this), timebase, interval)); + } + + // viz::DelayBasedTimeSourceClient overrides: + void OnTimerTick() override { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + + gfx::Point old_location = location_; + location_ = pending_location_; + + // Restart stationary timer if pointer location changed. + if (location_ != old_location) { + stationary_timer_.Reset(); + } + + base::TimeDelta interval = time_source_->Interval(); + // Compute velocity unless this is the first tick. + if (time_source_->LastTickTime() == next_tick_time_) { + // Velocity is pixels/second as interval might change. + velocity_ = gfx::ScaleVector2d(old_location - location_, + 1.f / interval.InSecondsF()); + velocity_.SetToMin(gfx::Vector2dF(kVelocityMax, kVelocityMax)); + } + + // Save next tick time. + next_tick_time_ = time_source_->NextTickTime(); + + // Use "Complementary Filter" algorithm to determine velocity. + // This allows us to be responsive in the short term and accurate + // in the long term. + responsive_velocity_ = InterpolateBetween(responsive_velocity_, velocity_, + kResponsiveVelocityFactor); + smooth_velocity_ = + InterpolateBetween(smooth_velocity_, velocity_, kSmoothVelocityFactor); + + // Estimate movement over one time source (VSYNC) interval. + gfx::Vector2dF movement = gfx::ScaleVector2d( + InterpolateBetween(responsive_velocity_, smooth_velocity_, + kMovementFactor), + interval.InSecondsF()); + + float distance = movement.Length(); + if (is_motion_blur_enabled_ && distance >= kMinimumMovementForMotionBlur) { + float sigma = std::min(distance / 3.f, kSigmaMax); + + // Create directional blur filter for |sigma|. + motion_blur_filter_ = sk_make_sp<cc::BlurPaintFilter>( + sigma, 0.f, SkTileMode::kDecal, nullptr); + + // Compute blur offset. + motion_blur_offset_ = + gfx::ScaleVector2d(movement, std::ceil(sigma * 3.f) / distance); + + // Determine angle of movement. + SkScalar angle = SkScalarATan2(SkFloatToScalar(movement.y()), + SkFloatToScalar(movement.x())); + SkScalar cos_angle = SkScalarCos(angle); + SkScalar sin_angle = SkScalarSin(angle); + + // Create transformation matrices for blur space. + motion_blur_matrix_.setSinCos(-sin_angle, cos_angle); + motion_blur_inverse_matrix_.setSinCos(sin_angle, cos_angle); + } else { + motion_blur_filter_.reset(); + responsive_velocity_ = gfx::Vector2dF(); + smooth_velocity_ = gfx::Vector2dF(); + time_source_->SetActive(false); + } + + // Damage is the union of old and new cursor rectangles. + gfx::Rect damage_rect = cursor_rect_; + cursor_rect_ = CalculateCursorRectOnPaintThread(); + damage_rect.Union(cursor_rect_); + + // Paint damaged area now that all parameters have been determined. + { + // Ensures that `cursor_view_` is not destructed during lifetime of + // `paint`. + base::AutoLock lock(lock_); + if (!cursor_view_) { + return; + } + + TRACE_EVENT1("ui", "CursorView::Paint", "damage_rect", + damage_rect.ToString()); + + auto paint = cursor_view_->GetScopedPaint(damage_rect); + + cc::PaintCanvas* sk_canvas = paint->canvas().sk_canvas(); + sk_canvas->translate(SkIntToScalar(location_.x() - cursor_hotspot_.x()), + SkIntToScalar(location_.y() - cursor_hotspot_.y())); + + // Undo scaling because drawing bitmaps on a scaled canvas has artifacts. + // The cursor image is scaled in `SetCursorImage` and drawn in 1x here. + sk_canvas->scale(SkFloatToScalar(1 / dsf_)); + + if (motion_blur_filter_) { + sk_canvas->translate(SkIntToScalar(motion_blur_offset_.x()), + SkIntToScalar(motion_blur_offset_.y())); + + sk_canvas->concat(SkM44(motion_blur_inverse_matrix_)); + SkRect blur_rect = SkRect::MakeWH(SkIntToScalar(cursor_size_.width()), + SkIntToScalar(cursor_size_.height())); + motion_blur_matrix_.mapRect(&blur_rect); + cc::PaintFlags flags; + flags.setImageFilter(motion_blur_filter_); + sk_canvas->saveLayer(blur_rect, flags); + sk_canvas->concat(SkM44(motion_blur_matrix_)); + paint->canvas().DrawImageInt(cursor_image_, 0, 0); + sk_canvas->restore(); + } else { + // Fast path for when motion blur is not present. + paint->canvas().DrawImageInt(cursor_image_, 0, 0); + } + } + + ui_task_runner_->PostTask( + FROM_HERE, + base::BindOnce(update_surface_callback_, cursor_rect_, damage_rect, + /*auto_refresh=*/stationary_timer_.IsRunning())); + } + + private: + void SetCursorLocationOnPaintThread(const gfx::Point& new_location) { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + if (location_ == new_location) { + return; + } + + pending_location_ = new_location; + SetActiveOnPaintThread(true); + } + + void SetCursorImageOnPaintThread(const gfx::ImageSkia& cursor_image, + const gfx::Size& cursor_size, + const gfx::Point& cursor_hotspot) { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + + cursor_image_ = cursor_image; + cursor_size_ = cursor_size; + cursor_hotspot_ = cursor_hotspot; + + SetActiveOnPaintThread(true); + } + + void StationaryOnPaintThread() { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + + stationary_timer_.Stop(); + + ui_task_runner_->PostTask( + FROM_HERE, base::BindOnce(update_surface_callback_, cursor_rect_, + /*damage_rect=*/gfx::Rect(), + /*auto_refresh=*/false)); + } + + gfx::Rect CalculateCursorRectOnPaintThread() const { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + + if (cursor_size_.IsEmpty()) { + return gfx::Rect(); + } + + SkRect cursor_rect = SkRect::MakeWH(SkIntToScalar(cursor_size_.width()), + SkIntToScalar(cursor_size_.height())); + + if (motion_blur_filter_) { + // Map cursor rectangle to blur space. + motion_blur_matrix_.mapRect(&cursor_rect); + + // Expand rectangle using current blur filter. + cc::PaintFlags flags; + flags.setImageFilter(motion_blur_filter_); + DCHECK(flags.ToSkPaint().canComputeFastBounds()); + flags.ToSkPaint().computeFastBounds(cursor_rect, &cursor_rect); + + // Map rectangle back to cursor space. + motion_blur_inverse_matrix_.mapRect(&cursor_rect); + + // Add motion blur offset. + cursor_rect.offset(SkIntToScalar(motion_blur_offset_.x()), + SkIntToScalar(motion_blur_offset_.y())); + } + + cursor_rect.offset(SkIntToScalar(location_.x() - cursor_hotspot_.x()), + SkIntToScalar(location_.y() - cursor_hotspot_.y())); + + return gfx::ToEnclosingRect(gfx::SkRectToRectF(cursor_rect)); + } + + void SetActiveOnPaintThread(bool active) { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + + // Create time source if it doesn't exist. + if (!time_source_) { + time_source_ = + std::make_unique<viz::DelayBasedTimeSource>(paint_task_runner_.get()); + time_source_->SetClient(this); + } + time_source_->SetActive(active); + } + + void SetTimebaseAndIntervalOnPaintThread(base::TimeTicks timebase, + base::TimeDelta interval) { + DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); + + DCHECK(time_source_); + time_source_->SetTimebaseAndInterval( + timebase + base::Milliseconds(kVSyncOffsetMs), interval); + } + + // Ensures painter is not destructed during paint. + base::Lock lock_; + + raw_ptr<CursorView> cursor_view_; + const bool is_motion_blur_enabled_; + + float dsf_ = 1.0f; + + gfx::Point location_; + gfx::Point pending_location_; + gfx::ImageSkia cursor_image_; + gfx::Size cursor_size_; + gfx::Point cursor_hotspot_; + gfx::Rect cursor_rect_; + base::TimeTicks next_tick_time_; + gfx::Vector2dF velocity_; + gfx::Vector2dF responsive_velocity_; + gfx::Vector2dF smooth_velocity_; + sk_sp<cc::PaintFilter> motion_blur_filter_; + gfx::Vector2dF motion_blur_offset_; + SkMatrix motion_blur_matrix_; + SkMatrix motion_blur_inverse_matrix_; + + const scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; + const scoped_refptr<base::SingleThreadTaskRunner> paint_task_runner_; + + std::unique_ptr<viz::DelayBasedTimeSource> time_source_; + base::RetainingOneShotTimer stationary_timer_; + SEQUENCE_CHECKER(paint_sequence_checker_); + + SEQUENCE_CHECKER(ui_sequence_checker_); + UpdateSurfaceCallback update_surface_callback_; +}; + +//////////////////////////////////////////////////////////////////////////////// // CursorView, public: CursorView::CursorView(const gfx::Point& initial_location, bool is_motion_blur_enabled) - : is_motion_blur_enabled_(is_motion_blur_enabled), - ui_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()), - paint_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner( - {base::TaskPriority::USER_BLOCKING, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})), - new_location_(initial_location), - stationary_timer_( - FROM_HERE, - base::Milliseconds(kStationaryDelayMs), - base::BindRepeating(&CursorView::StationaryOnPaintThread, - base::Unretained(this))) { + : painter_(std::make_unique<Painter>(this, + initial_location, + is_motion_blur_enabled)), + ui_task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()) { DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); - // Detach sequence checker for future usage on paint thread. - DETACH_FROM_SEQUENCE(paint_sequence_checker_); - - // Create update surface callback that will be posted from paint thread - // to UI thread. - update_surface_callback_ = base::BindRepeating( - &CursorView::UpdateSurface, weak_ptr_factory_.GetWeakPtr()); - - // Create transform used to convert cursor controller coordinates to screen - // coordinates. - buffer_to_screen_transform_ = - host()->window_to_buffer_transform().GetCheckedInverse(); - ui::CursorController::GetInstance()->AddCursorObserver(this); } @@ -90,6 +410,9 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); ui::CursorController::GetInstance()->RemoveCursorObserver(this); + + // `painter_` schedules its destruction in Shutdown. + painter_.release()->Shutdown(); } // static @@ -102,245 +425,61 @@ container); } -FastInkHost::PresentationCallback CursorView::GetPresentationCallback() { - return base::BindRepeating(&CursorView::DidPresentCompositorFrame, - base::Unretained(this)); -} - void CursorView::SetCursorImage(const gfx::ImageSkia& cursor_image, const gfx::Size& cursor_size, const gfx::Point& cursor_hotspot) { DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); - { - base::AutoLock lock(lock_); - - new_cursor_image_ = cursor_image; - new_cursor_size_ = cursor_size; - new_cursor_hotspot_ = cursor_hotspot; - } - - // Unretained is safe as |paint_task_runner_| uses SKIP_ON_SHUTDOWN. - paint_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&CursorView::SetActiveOnPaintThread, - base::Unretained(this), true)); + painter_->SetCursorImage(cursor_image, cursor_size, cursor_hotspot); } //////////////////////////////////////////////////////////////////////////////// // ui::CursorController::CursorObserver overrides: void CursorView::OnCursorLocationChanged(const gfx::PointF& location) { - gfx::PointF new_location_f = buffer_to_screen_transform_.MapPoint(location); + if (!buffer_to_screen_transform_) { + if (!ui_task_runner_->BelongsToCurrentThread()) { + // If it is not called from ui thread, post it to ui thread. + ui_task_runner_->PostTask( + FROM_HERE, base::BindOnce(&CursorView::OnCursorLocationChanged, + weak_ptr_factory_.GetWeakPtr(), location)); + return; + } + // Create transform used to convert cursor controller coordinates to screen + // coordinates. + buffer_to_screen_transform_ = + this->host()->window_to_buffer_transform().GetCheckedInverse(); + } + gfx::PointF new_location_f = buffer_to_screen_transform_->MapPoint(location); gfx::Point new_location = gfx::ToRoundedPoint(new_location_f); - { - base::AutoLock lock(lock_); - - if (new_location_ == new_location) - return; - new_location_ = new_location; - } - - // Unretained is safe as |paint_task_runner_| uses SKIP_ON_SHUTDOWN. - paint_task_runner_->PostTask( - FROM_HERE, base::BindOnce(&CursorView::SetActiveOnPaintThread, - base::Unretained(this), true)); + painter_->SetCursorLocation(new_location); } //////////////////////////////////////////////////////////////////////////////// -// viz::DelayBasedTimeSourceClient overrides: +// ash::FastInkView overrides: -void CursorView::OnTimerTick() { - DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); +FastInkHost::PresentationCallback CursorView::GetPresentationCallback() { + return base::BindRepeating(&CursorView::DidPresentCompositorFrame, + weak_ptr_factory_.GetWeakPtr()); +} - gfx::Point old_location = location_; +//////////////////////////////////////////////////////////////////////////////// +// views::View overrides: - { - base::AutoLock lock(lock_); - - location_ = new_location_; - cursor_size_ = new_cursor_size_; - cursor_image_ = new_cursor_image_; - cursor_hotspot_ = new_cursor_hotspot_; - } - - // Restart stationary timer if pointer location changed. - if (location_ != old_location) - stationary_timer_.Reset(); - - base::TimeDelta interval = time_source_->Interval(); - // Compute velocity unless this is the first tick. - if (time_source_->LastTickTime() == next_tick_time_) { - // Velocity is pixels/second as interval might change. - velocity_ = gfx::ScaleVector2d(old_location - location_, - 1.f / interval.InSecondsF()); - velocity_.SetToMin(gfx::Vector2dF(kVelocityMax, kVelocityMax)); - } - - // Save next tick time. - next_tick_time_ = time_source_->NextTickTime(); - - // Use "Complementary Filter" algorithm to determine velocity. - // This allows us to be responsive in the short term and accurate - // in the long term. - responsive_velocity_ = InterpolateBetween(responsive_velocity_, velocity_, - kResponsiveVelocityFactor); - smooth_velocity_ = - InterpolateBetween(smooth_velocity_, velocity_, kSmoothVelocityFactor); - - // Estimate movement over one time source (VSYNC) interval. - gfx::Vector2dF movement = - gfx::ScaleVector2d(InterpolateBetween(responsive_velocity_, - smooth_velocity_, kMovementFactor), - interval.InSecondsF()); - - float distance = movement.Length(); - if (is_motion_blur_enabled_ && distance >= kMinimumMovementForMotionBlur) { - float sigma = std::min(distance / 3.f, kSigmaMax); - - // Create directional blur filter for |sigma|. - motion_blur_filter_ = sk_make_sp<cc::BlurPaintFilter>( - sigma, 0.f, SkTileMode::kDecal, nullptr); - - // Compute blur offset. - motion_blur_offset_ = - gfx::ScaleVector2d(movement, std::ceil(sigma * 3.f) / distance); - - // Determine angle of movement. - SkScalar angle = SkScalarATan2(SkFloatToScalar(movement.y()), - SkFloatToScalar(movement.x())); - SkScalar cos_angle = SkScalarCos(angle); - SkScalar sin_angle = SkScalarSin(angle); - - // Create transformation matrices for blur space. - motion_blur_matrix_.setSinCos(-sin_angle, cos_angle); - motion_blur_inverse_matrix_.setSinCos(sin_angle, cos_angle); - } else { - motion_blur_filter_.reset(); - responsive_velocity_ = gfx::Vector2dF(); - smooth_velocity_ = gfx::Vector2dF(); - time_source_->SetActive(false); - } - - // Damage is the union of old and new cursor rectangles. - gfx::Rect damage_rect = cursor_rect_; - cursor_rect_ = CalculateCursorRectOnPaintThread(); - damage_rect.Union(cursor_rect_); - - // Paint damaged area now that all parameters have been determined. - { - TRACE_EVENT1("ui", "CursorView::Paint", "damage_rect", - damage_rect.ToString()); - - auto paint = GetScopedPaint(damage_rect); - - cc::PaintCanvas* sk_canvas = paint->canvas().sk_canvas(); - sk_canvas->translate(SkIntToScalar(location_.x() - cursor_hotspot_.x()), - SkIntToScalar(location_.y() - cursor_hotspot_.y())); - - if (motion_blur_filter_) { - sk_canvas->translate(SkIntToScalar(motion_blur_offset_.x()), - SkIntToScalar(motion_blur_offset_.y())); - - sk_canvas->concat(SkM44(motion_blur_inverse_matrix_)); - SkRect blur_rect = SkRect::MakeWH(SkIntToScalar(cursor_size_.width()), - SkIntToScalar(cursor_size_.height())); - motion_blur_matrix_.mapRect(&blur_rect); - cc::PaintFlags flags; - flags.setImageFilter(motion_blur_filter_); - sk_canvas->saveLayer(blur_rect, flags); - sk_canvas->concat(SkM44(motion_blur_matrix_)); - paint->canvas().DrawImageInt(cursor_image_, 0, 0); - sk_canvas->restore(); - } else { - // Fast path for when motion blur is not present. - paint->canvas().DrawImageInt(cursor_image_, 0, 0); - } - } - - ui_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(update_surface_callback_, cursor_rect_, damage_rect, - /*auto_refresh=*/stationary_timer_.IsRunning())); +void CursorView::AddedToWidget() { + painter_->Init(base::BindRepeating(&CursorView::UpdateSurface, + weak_ptr_factory_.GetWeakPtr())); } //////////////////////////////////////////////////////////////////////////////// // CursorView, private: -void CursorView::StationaryOnPaintThread() { - DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); - - stationary_timer_.Stop(); - ui_task_runner_->PostTask( - FROM_HERE, base::BindOnce(update_surface_callback_, cursor_rect_, - /*damage_rect=*/gfx::Rect(), - /*auto_refresh=*/false)); -} - -gfx::Rect CursorView::CalculateCursorRectOnPaintThread() const { - DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); - - if (cursor_size_.IsEmpty()) - return gfx::Rect(); - - SkRect cursor_rect = SkRect::MakeWH(SkIntToScalar(cursor_size_.width()), - SkIntToScalar(cursor_size_.height())); - - if (motion_blur_filter_) { - // Map curser rectangle to blur space. - motion_blur_matrix_.mapRect(&cursor_rect); - - // Expand rectangle using current blur filter. - cc::PaintFlags flags; - flags.setImageFilter(motion_blur_filter_); - DCHECK(flags.ToSkPaint().canComputeFastBounds()); - flags.ToSkPaint().computeFastBounds(cursor_rect, &cursor_rect); - - // Map rectangle back to cursor space. - motion_blur_inverse_matrix_.mapRect(&cursor_rect); - - // Add motion blur offset. - cursor_rect.offset(SkIntToScalar(motion_blur_offset_.x()), - SkIntToScalar(motion_blur_offset_.y())); - } - - cursor_rect.offset(SkIntToScalar(location_.x() - cursor_hotspot_.x()), - SkIntToScalar(location_.y() - cursor_hotspot_.y())); - - return gfx::ToEnclosingRect(gfx::SkRectToRectF(cursor_rect)); -} - -void CursorView::SetActiveOnPaintThread(bool active) { - DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); - - // Create time source if it doesn't exist. - if (!time_source_) { - time_source_ = - std::make_unique<viz::DelayBasedTimeSource>(paint_task_runner_.get()); - time_source_->SetClient(this); - } - time_source_->SetActive(active); -} - -void CursorView::SetTimebaseAndIntervalOnPaintThread(base::TimeTicks timebase, - base::TimeDelta interval) { - DCHECK_CALLED_ON_VALID_SEQUENCE(paint_sequence_checker_); - - DCHECK(time_source_); - time_source_->SetTimebaseAndInterval( - timebase + base::Milliseconds(kVSyncOffsetMs), interval); -} - void CursorView::DidPresentCompositorFrame( const gfx::PresentationFeedback& feedback) { DCHECK_CALLED_ON_VALID_SEQUENCE(ui_sequence_checker_); - // Unretained is safe as |paint_task_runner_| uses SKIP_ON_SHUTDOWN. - paint_task_runner_->PostTask( - FROM_HERE, - base::BindOnce(&CursorView::SetTimebaseAndIntervalOnPaintThread, - base::Unretained(this), feedback.timestamp, - feedback.interval)); + painter_->SetTimebaseAndInterval(feedback.timestamp, feedback.interval); } } // namespace ash
diff --git a/ash/fast_ink/cursor/cursor_view.h b/ash/fast_ink/cursor/cursor_view.h index 5a97e9ede..9341d1c 100644 --- a/ash/fast_ink/cursor/cursor_view.h +++ b/ash/fast_ink/cursor/cursor_view.h
@@ -5,6 +5,8 @@ #ifndef ASH_FAST_INK_CURSOR_CURSOR_VIEW_H_ #define ASH_FAST_INK_CURSOR_CURSOR_VIEW_H_ +#include <memory> + #include "ash/fast_ink/fast_ink_view.h" #include "base/memory/raw_ptr.h" #include "base/sequence_checker.h" @@ -14,10 +16,6 @@ #include "ui/events/ozone/chromeos/cursor_controller.h" #include "ui/views/widget/unique_widget_ptr.h" -namespace base { -class SingleThreadTaskRunner; -} // namespace base - namespace gfx { struct PresentationFeedback; } @@ -27,7 +25,6 @@ // CursorView class can be used to display a cursor image with minimal // latency/jank and optional motion blur. class CursorView : public FastInkView, - public viz::DelayBasedTimeSourceClient, public ui::CursorController::CursorObserver { public: CursorView(const CursorView&) = delete; @@ -39,7 +36,6 @@ bool is_motion_blur_enabled, aura::Window* container); - void SetCursorLocation(const gfx::Point& new_location); void SetCursorImage(const gfx::ImageSkia& cursor_image, const gfx::Size& cursor_size, const gfx::Point& cursor_hotspot); @@ -47,59 +43,30 @@ // ui::CursorController::CursorObserver overrides: void OnCursorLocationChanged(const gfx::PointF& location) override; - // viz::DelayBasedTimeSourceClient overrides: - void OnTimerTick() override; - protected: - // FastInkView override. + // ash::FastInkView overrides: FastInkHost::PresentationCallback GetPresentationCallback() override; + // views::View overrides: + void AddedToWidget() override; + private: + // Paints cursor on the paint thread. + class Painter; + CursorView(const gfx::Point& initial_location, bool is_motion_blur_enabled); - void StationaryOnPaintThread(); - gfx::Rect CalculateCursorRectOnPaintThread() const; - void SetActiveOnPaintThread(bool active); - void SetTimebaseAndIntervalOnPaintThread(base::TimeTicks timebase, - base::TimeDelta interval); void DidPresentCompositorFrame(const gfx::PresentationFeedback& feedback); // Constants that can be used on any thread. - const bool is_motion_blur_enabled_; - const scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; - const scoped_refptr<base::SingleThreadTaskRunner> paint_task_runner_; - gfx::Transform buffer_to_screen_transform_; + absl::optional<gfx::Transform> buffer_to_screen_transform_; - base::Lock lock_; - // Shared state protected by |lock_|. - gfx::Point new_location_; - gfx::Size new_cursor_size_; - gfx::ImageSkia new_cursor_image_; - gfx::Point new_cursor_hotspot_; - - // Paint thread state. - gfx::Point location_; - gfx::ImageSkia cursor_image_; - gfx::Size cursor_size_; - gfx::Point cursor_hotspot_; - gfx::Rect cursor_rect_; - base::TimeTicks next_tick_time_; - gfx::Vector2dF velocity_; - gfx::Vector2dF responsive_velocity_; - gfx::Vector2dF smooth_velocity_; - sk_sp<cc::PaintFilter> motion_blur_filter_; - gfx::Vector2dF motion_blur_offset_; - SkMatrix motion_blur_matrix_; - SkMatrix motion_blur_inverse_matrix_; - std::unique_ptr<viz::DelayBasedTimeSource> time_source_; - base::RetainingOneShotTimer stationary_timer_; - base::RepeatingCallback<void(const gfx::Rect&, const gfx::Rect&, bool)> - update_surface_callback_; - SEQUENCE_CHECKER(paint_sequence_checker_); + std::unique_ptr<Painter> painter_; // UI thread state. raw_ptr<ui::Compositor, ExperimentalAsh> compositor_ = nullptr; SEQUENCE_CHECKER(ui_sequence_checker_); + const scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_; base::WeakPtrFactory<CursorView> weak_ptr_factory_{this}; };
diff --git a/base/allocator/partition_allocator/page_allocator_internals_fuchsia.h b/base/allocator/partition_allocator/page_allocator_internals_fuchsia.h index 76628953..6fa902a8 100644 --- a/base/allocator/partition_allocator/page_allocator_internals_fuchsia.h +++ b/base/allocator/partition_allocator/page_allocator_internals_fuchsia.h
@@ -44,7 +44,7 @@ auto result = sync_vmex_resource_client->Get(); if (result.is_error()) { PA_LOG(ERROR) << "VmexResource.Get():" - << result.error_value().FormatDescription(); + << result.error_value().FormatDescription().c_str(); return {}; }
diff --git a/base/allocator/partition_allocator/page_allocator_internals_posix.h b/base/allocator/partition_allocator/page_allocator_internals_posix.h index 531431de..906cdde 100644 --- a/base/allocator/partition_allocator/page_allocator_internals_posix.h +++ b/base/allocator/partition_allocator/page_allocator_internals_posix.h
@@ -116,7 +116,7 @@ // executable fails with EPERM. Although this is not enforced on x86_64, // MAP_JIT is harmless in that case. - base::ScopedCFTypeRef<SecTaskRef> task( + base::apple::ScopedCFTypeRef<SecTaskRef> task( SecTaskCreateFromSelf(kCFAllocatorDefault)); if (!task) { return true; @@ -134,7 +134,7 @@ // (EINVAL) to use MAP_JIT with the hardened runtime unless the JIT // entitlement is specified. - base::ScopedCFTypeRef<CFTypeRef> jit_entitlement( + base::apple::ScopedCFTypeRef<CFTypeRef> jit_entitlement( SecTaskCopyValueForEntitlement( task.get(), CFSTR("com.apple.security.cs.allow-jit"), nullptr)); if (!jit_entitlement) {
diff --git a/base/allocator/partition_allocator/partition_alloc_base/apple/mach_logging.cc b/base/allocator/partition_allocator/partition_alloc_base/apple/mach_logging.cc index 55b2ba1d..5bed623 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/apple/mach_logging.cc +++ b/base/allocator/partition_allocator/partition_alloc_base/apple/mach_logging.cc
@@ -35,7 +35,7 @@ MachLogMessage::~MachLogMessage() { stream() << ": " << mach_error_string(mach_err_) - << FormatMachErrorNumber(mach_err_); + << FormatMachErrorNumber(mach_err_).c_str(); } } // namespace partition_alloc::internal::logging
diff --git a/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_cftyperef.h b/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_cftyperef.h index b201b083..b8a7a09 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_cftyperef.h +++ b/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_cftyperef.h
@@ -9,7 +9,7 @@ #include "base/allocator/partition_allocator/partition_alloc_base/apple/scoped_typeref.h" -namespace partition_alloc::internal::base { +namespace partition_alloc::internal::base::apple { // ScopedCFTypeRef<> is patterned after std::unique_ptr<>, but maintains // ownership of a CoreFoundation object: any object that can be represented @@ -43,6 +43,6 @@ using ScopedCFTypeRef = ScopedTypeRef<CFT, internal::ScopedCFTypeRefTraits<CFT>>; -} // namespace partition_alloc::internal::base +} // namespace partition_alloc::internal::base::apple #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_APPLE_SCOPED_CFTYPEREF_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_typeref.h b/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_typeref.h index 5b49c71..aaa00276 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_typeref.h +++ b/base/allocator/partition_allocator/partition_alloc_base/apple/scoped_typeref.h
@@ -8,7 +8,7 @@ #include "base/allocator/partition_allocator/partition_alloc_base/check.h" #include "base/allocator/partition_allocator/partition_alloc_base/memory/scoped_policy.h" -namespace partition_alloc::internal::base { +namespace partition_alloc::internal::base::apple { // ScopedTypeRef<> is patterned after std::unique_ptr<>, but maintains ownership // of a reference to any type that is maintained by Retain and Release methods. @@ -33,7 +33,7 @@ // of ownership of the object. For example, continuing to use the above // CGLContextObj specialization: // -// base::ScopedTypeRef<CGLContextObj> context; +// base::apple::ScopedTypeRef<CGLContextObj> context; // CGLCreateContext(pixel_format, share_group, context.InitializeInto()); // // For initialization with an existing object, the caller may specify whether @@ -146,6 +146,6 @@ element_type object_; }; -} // namespace partition_alloc::internal::base +} // namespace partition_alloc::internal::base::apple #endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_ALLOC_BASE_APPLE_SCOPED_TYPEREF_H_
diff --git a/base/allocator/partition_allocator/partition_alloc_base/check.cc b/base/allocator/partition_allocator/partition_alloc_base/check.cc index 2ea3952..fb23410 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/check.cc +++ b/base/allocator/partition_allocator/partition_alloc_base/check.cc
@@ -69,7 +69,7 @@ return check_error; } -std::ostream& CheckError::stream() { +base::strings::CStringBuilder& CheckError::stream() { return log_message_->stream(); }
diff --git a/base/allocator/partition_allocator/partition_alloc_base/check.h b/base/allocator/partition_allocator/partition_alloc_base/check.h index 67437e3a..97b38a7 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/check.h +++ b/base/allocator/partition_allocator/partition_alloc_base/check.h
@@ -11,6 +11,7 @@ #include "base/allocator/partition_allocator/partition_alloc_base/component_export.h" #include "base/allocator/partition_allocator/partition_alloc_base/debug/debugging_buildflags.h" #include "base/allocator/partition_allocator/partition_alloc_base/immediate_crash.h" +#include "base/allocator/partition_allocator/partition_alloc_base/strings/cstring_builder.h" #define PA_STRINGIFY_IMPL(s) #s #define PA_STRINGIFY(s) PA_STRINGIFY_IMPL(s) @@ -50,7 +51,7 @@ explicit VoidifyStream(bool ignored) {} // This operator has lower precedence than << but higher than ?: - void operator&(std::ostream&) {} + void operator&(base::strings::CStringBuilder&) {} }; // Helper macro which avoids evaluating the arguments to a stream if the @@ -65,7 +66,8 @@ true ? (void)0 \ : ::partition_alloc::internal::logging::VoidifyStream(expr) & \ (*::partition_alloc::internal::logging::g_swallow_stream) -PA_COMPONENT_EXPORT(PARTITION_ALLOC) extern std::ostream* g_swallow_stream; +PA_COMPONENT_EXPORT(PARTITION_ALLOC) +extern base::strings::CStringBuilder* g_swallow_stream; class LogMessage; @@ -86,7 +88,7 @@ const char* function); // Stream for adding optional details to the error message. - std::ostream& stream(); + base::strings::CStringBuilder& stream(); PA_NOMERGE ~CheckError();
diff --git a/base/allocator/partition_allocator/partition_alloc_base/logging.cc b/base/allocator/partition_allocator/partition_alloc_base/logging.cc index ccfbc7b..a9640b3 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/logging.cc +++ b/base/allocator/partition_allocator/partition_alloc_base/logging.cc
@@ -112,7 +112,7 @@ // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have // an object of the correct type on the LHS of the unused part of the ternary // operator. -std::ostream* g_swallow_stream; +base::strings::CStringBuilder* g_swallow_stream; void SetMinLogLevel(int level) { g_min_log_level = std::min(LOGGING_FATAL, level); @@ -154,8 +154,8 @@ } LogMessage::~LogMessage() { - stream_ << std::endl; - std::string str_newline(stream_.str()); + stream_ << '\n'; + std::string str_newline(stream_.c_str()); // Give any log message handler first dibs on the message. if (g_log_message_handler && @@ -186,7 +186,7 @@ } stream_ << ":" << filename << "(" << line << ")] "; } - message_start_ = stream_.str().length(); + message_start_ = strlen(stream_.c_str()); } #if BUILDFLAG(IS_WIN) @@ -236,7 +236,7 @@ : LogMessage(file, line, severity), err_(err) {} Win32ErrorLogMessage::~Win32ErrorLogMessage() { - stream() << ": " << SystemErrorCodeToString(err_); + stream() << ": " << SystemErrorCodeToString(err_).c_str(); // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a // field) and use Alias in hopes that it makes it into crash dumps. DWORD last_error = err_; @@ -250,7 +250,7 @@ : LogMessage(file, line, severity), err_(err) {} ErrnoLogMessage::~ErrnoLogMessage() { - stream() << ": " << SystemErrorCodeToString(err_); + stream() << ": " << SystemErrorCodeToString(err_).c_str(); // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a // field) and use Alias in hopes that it makes it into crash dumps. int last_error = err_;
diff --git a/base/allocator/partition_allocator/partition_alloc_base/logging.h b/base/allocator/partition_allocator/partition_alloc_base/logging.h index 270d770..c618e1b 100644 --- a/base/allocator/partition_allocator/partition_alloc_base/logging.h +++ b/base/allocator/partition_allocator/partition_alloc_base/logging.h
@@ -16,6 +16,7 @@ #include "base/allocator/partition_allocator/partition_alloc_base/component_export.h" #include "base/allocator/partition_allocator/partition_alloc_base/debug/debugging_buildflags.h" #include "base/allocator/partition_allocator/partition_alloc_base/scoped_clear_last_error.h" +#include "base/allocator/partition_allocator/partition_alloc_base/strings/cstring_builder.h" #include "build/build_config.h" // TODO(1151236): Need to update the description, because logging for PA @@ -341,7 +342,8 @@ PA_LAZY_STREAM(PA_PLOG_STREAM(severity), \ PA_LOG_IS_ON(severity) && (condition)) -PA_COMPONENT_EXPORT(PARTITION_ALLOC) extern std::ostream* g_swallow_stream; +PA_COMPONENT_EXPORT(PARTITION_ALLOC) +extern base::strings::CStringBuilder* g_swallow_stream; // Note that g_swallow_stream is used instead of an arbitrary PA_LOG() stream to // avoid the creation of an object with a non-trivial destructor (LogMessage). @@ -429,16 +431,16 @@ LogMessage& operator=(const LogMessage&) = delete; virtual ~LogMessage(); - std::ostream& stream() { return stream_; } + base::strings::CStringBuilder& stream() { return stream_; } LogSeverity severity() { return severity_; } - std::string str() { return stream_.str(); } + const char* c_str() { return stream_.c_str(); } private: void Init(const char* file, int line); const LogSeverity severity_; - std::ostringstream stream_; + base::strings::CStringBuilder stream_; size_t message_start_; // Offset of the start of the message (past prefix // info). // The file and line information passed in to the constructor. @@ -459,7 +461,7 @@ LogMessageVoidify() = default; // This has to be an operator with a precedence lower than << but // higher than ?: - void operator&(std::ostream&) {} + void operator&(base::strings::CStringBuilder&) {} }; #if BUILDFLAG(IS_WIN)
diff --git a/base/apple/backup_util_unittest.mm b/base/apple/backup_util_unittest.mm index 13874dc..60f5c22 100644 --- a/base/apple/backup_util_unittest.mm +++ b/base/apple/backup_util_unittest.mm
@@ -44,7 +44,7 @@ ScopedTempDir temp_dir_; ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); FilePath excluded_file_path = temp_dir_.GetPath().Append("excluded"); - base::ScopedCFTypeRef<CFURLRef> excluded_url = + ScopedCFTypeRef<CFURLRef> excluded_url = apple::FilePathToCFURL(excluded_file_path); constexpr char placeholder_data[] = "All your base are belong to us!";
diff --git a/base/apple/bridging.h b/base/apple/bridging.h index 18bfec0..19911dce 100644 --- a/base/apple/bridging.h +++ b/base/apple/bridging.h
@@ -144,7 +144,7 @@ namespace base::apple { template <typename CFT> -id _Nullable CFToNSOwnershipCast(base::ScopedCFTypeRef<CFT>) { +id _Nullable CFToNSOwnershipCast(ScopedCFTypeRef<CFT>) { static_assert( AlwaysFalse<CFT>, "Error: Do not pass a ScopedCFTypeRef to CFToNSOwnershipCast. "
diff --git a/base/apple/foundation_util.mm b/base/apple/foundation_util.mm index a4936c9..4d7cd17f 100644 --- a/base/apple/foundation_util.mm +++ b/base/apple/foundation_util.mm
@@ -432,8 +432,9 @@ } std::ostream& operator<<(std::ostream& o, const CFErrorRef err) { - base::ScopedCFTypeRef<CFStringRef> desc(CFErrorCopyDescription(err)); - base::ScopedCFTypeRef<CFDictionaryRef> user_info(CFErrorCopyUserInfo(err)); + base::apple::ScopedCFTypeRef<CFStringRef> desc(CFErrorCopyDescription(err)); + base::apple::ScopedCFTypeRef<CFDictionaryRef> user_info( + CFErrorCopyUserInfo(err)); CFStringRef errorDesc = nullptr; if (user_info.get()) { errorDesc = reinterpret_cast<CFStringRef>(
diff --git a/base/apple/scoped_cftyperef.h b/base/apple/scoped_cftyperef.h index fa275e9e..4fa1901 100644 --- a/base/apple/scoped_cftyperef.h +++ b/base/apple/scoped_cftyperef.h
@@ -9,7 +9,7 @@ #include "base/apple/scoped_typeref.h" -namespace base { +namespace base::apple { // ScopedCFTypeRef<> is patterned after std::unique_ptr<>, but maintains // ownership of a CoreFoundation object: any object that can be represented @@ -43,6 +43,6 @@ using ScopedCFTypeRef = ScopedTypeRef<CFT, internal::ScopedCFTypeRefTraits<CFT>>; -} // namespace base +} // namespace base::apple #endif // BASE_APPLE_SCOPED_CFTYPEREF_H_
diff --git a/base/apple/scoped_typeref.h b/base/apple/scoped_typeref.h index 04778e3..0699059b 100644 --- a/base/apple/scoped_typeref.h +++ b/base/apple/scoped_typeref.h
@@ -8,7 +8,7 @@ #include "base/check.h" #include "base/memory/scoped_policy.h" -namespace base { +namespace base::apple { // ScopedTypeRef<> is patterned after std::unique_ptr<>, but maintains ownership // of a reference to any type that is maintained by Retain and Release methods. @@ -33,7 +33,7 @@ // of ownership of the object. For example, continuing to use the above // CGLContextObj specialization: // -// base::ScopedTypeRef<CGLContextObj> context; +// base::apple::ScopedTypeRef<CGLContextObj> context; // CGLCreateContext(pixel_format, share_group, context.InitializeInto()); // // For initialization with an existing object, the caller may specify whether @@ -146,6 +146,6 @@ element_type object_; }; -} // namespace base +} // namespace base::apple #endif // BASE_APPLE_SCOPED_TYPEREF_H_
diff --git a/base/files/file_path.cc b/base/files/file_path.cc index 786ea8fb..032899a 100644 --- a/base/files/file_path.cc +++ b/base/files/file_path.cc
@@ -1267,7 +1267,7 @@ StringType FilePath::GetHFSDecomposedForm(StringPieceType string) { StringType result; - ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy( + apple::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy( NULL, reinterpret_cast<const UInt8*>(string.data()), checked_cast<CFIndex>(string.length()), kCFStringEncodingUTF8, false, kCFAllocatorNull)); @@ -1310,11 +1310,11 @@ // GetHFSDecomposedForm() returns an empty string in an error case. if (hfs1.empty() || hfs2.empty()) { - ScopedCFTypeRef<CFStringRef> cfstring1(CFStringCreateWithBytesNoCopy( + apple::ScopedCFTypeRef<CFStringRef> cfstring1(CFStringCreateWithBytesNoCopy( NULL, reinterpret_cast<const UInt8*>(string1.data()), checked_cast<CFIndex>(string1.length()), kCFStringEncodingUTF8, false, kCFAllocatorNull)); - ScopedCFTypeRef<CFStringRef> cfstring2(CFStringCreateWithBytesNoCopy( + apple::ScopedCFTypeRef<CFStringRef> cfstring2(CFStringCreateWithBytesNoCopy( NULL, reinterpret_cast<const UInt8*>(string2.data()), checked_cast<CFIndex>(string2.length()), kCFStringEncodingUTF8, false, kCFAllocatorNull));
diff --git a/base/files/file_path_watcher_fsevents.cc b/base/files/file_path_watcher_fsevents.cc index 2c5419fd..0a38fb79 100644 --- a/base/files/file_path_watcher_fsevents.cc +++ b/base/files/file_path_watcher_fsevents.cc
@@ -213,13 +213,13 @@ if (fsevent_stream_) DestroyEventStream(); - ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString( + apple::ScopedCFTypeRef<CFStringRef> cf_path(CFStringCreateWithCString( NULL, resolved_target_.value().c_str(), kCFStringEncodingMacHFS)); - ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString( + apple::ScopedCFTypeRef<CFStringRef> cf_dir_path(CFStringCreateWithCString( NULL, resolved_target_.DirName().value().c_str(), kCFStringEncodingMacHFS)); CFStringRef paths_array[] = { cf_path.get(), cf_dir_path.get() }; - ScopedCFTypeRef<CFArrayRef> watched_paths( + apple::ScopedCFTypeRef<CFArrayRef> watched_paths( CFArrayCreate(NULL, reinterpret_cast<const void**>(paths_array), std::size(paths_array), &kCFTypeArrayCallBacks));
diff --git a/base/ios/device_util.mm b/base/ios/device_util.mm index 4488344d1..e3ea4786 100644 --- a/base/ios/device_util.mm +++ b/base/ios/device_util.mm
@@ -129,9 +129,9 @@ } std::string GetRandomId() { - base::ScopedCFTypeRef<CFUUIDRef> uuid_object( + base::apple::ScopedCFTypeRef<CFUUIDRef> uuid_object( CFUUIDCreate(kCFAllocatorDefault)); - base::ScopedCFTypeRef<CFStringRef> uuid_string( + base::apple::ScopedCFTypeRef<CFStringRef> uuid_string( CFUUIDCreateString(kCFAllocatorDefault, uuid_object)); return base::SysCFStringRefToUTF8(uuid_string); } @@ -177,9 +177,9 @@ hash); CFUUIDBytes* uuid_bytes = reinterpret_cast<CFUUIDBytes*>(hash); - base::ScopedCFTypeRef<CFUUIDRef> uuid_object( + base::apple::ScopedCFTypeRef<CFUUIDRef> uuid_object( CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, *uuid_bytes)); - base::ScopedCFTypeRef<CFStringRef> device_id( + base::apple::ScopedCFTypeRef<CFStringRef> device_id( CFUUIDCreateString(kCFAllocatorDefault, uuid_object)); return base::SysCFStringRefToUTF8(device_id); }
diff --git a/base/mac/mac_util.mm b/base/mac/mac_util.mm index b7dcee4..1da035e 100644 --- a/base/mac/mac_util.mm +++ b/base/mac/mac_util.mm
@@ -65,12 +65,13 @@ // representing the specified bundle. If such an item is found, returns a // retained reference to it. Caller is responsible for releasing the // reference. - ScopedCFTypeRef<LSSharedFileListItemRef> GetLoginItemForApp(NSURL* url) { + apple::ScopedCFTypeRef<LSSharedFileListItemRef> GetLoginItemForApp( + NSURL* url) { DCHECK(login_items_.get()) << "Initialize() failed or not called."; #pragma clang diagnostic push // https://crbug.com/1154377 #pragma clang diagnostic ignored "-Wdeprecated-declarations" - ScopedCFTypeRef<CFArrayRef> login_items_array( + apple::ScopedCFTypeRef<CFArrayRef> login_items_array( LSSharedFileListCopySnapshot(login_items_, /*inList=*/nullptr)); #pragma clang diagnostic pop @@ -88,27 +89,27 @@ #pragma clang diagnostic pop if (item_url && [item_url isEqual:url]) { - return ScopedCFTypeRef<LSSharedFileListItemRef>( + return apple::ScopedCFTypeRef<LSSharedFileListItemRef>( item, base::scoped_policy::RETAIN); } } - return ScopedCFTypeRef<LSSharedFileListItemRef>(); + return apple::ScopedCFTypeRef<LSSharedFileListItemRef>(); } - ScopedCFTypeRef<LSSharedFileListItemRef> GetLoginItemForMainApp() { + apple::ScopedCFTypeRef<LSSharedFileListItemRef> GetLoginItemForMainApp() { NSURL* url = [NSURL fileURLWithPath:base::apple::MainBundle().bundlePath]; return GetLoginItemForApp(url); } private: - ScopedCFTypeRef<LSSharedFileListRef> login_items_; + apple::ScopedCFTypeRef<LSSharedFileListRef> login_items_; }; bool IsHiddenLoginItem(LSSharedFileListItemRef item) { #pragma clang diagnostic push // https://crbug.com/1154377 #pragma clang diagnostic ignored "-Wdeprecated-declarations" - ScopedCFTypeRef<CFBooleanRef> hidden( + apple::ScopedCFTypeRef<CFBooleanRef> hidden( reinterpret_cast<CFBooleanRef>(LSSharedFileListItemCopyProperty( item, kLSSharedFileListLoginItemHidden))); #pragma clang diagnostic pop @@ -164,7 +165,7 @@ } NSURL* app_bundle_url = base::apple::FilePathToNSURL(app_bundle_file_path); - base::ScopedCFTypeRef<LSSharedFileListItemRef> item = + apple::ScopedCFTypeRef<LSSharedFileListItemRef> item = login_items.GetLoginItemForApp(app_bundle_url); if (item.get() && (IsHiddenLoginItem(item) == hide_on_startup)) { @@ -185,7 +186,7 @@ NSDictionary* properties = @{apple::CFToNSPtrCast(kLSSharedFileListLoginItemHidden) : @(hide)}; - ScopedCFTypeRef<LSSharedFileListItemRef> new_item( + apple::ScopedCFTypeRef<LSSharedFileListItemRef> new_item( LSSharedFileListInsertItemURL( login_items.GetLoginFileList(), kLSSharedFileListItemLast, /*inDisplayName=*/nullptr, @@ -205,7 +206,7 @@ } NSURL* app_bundle_url = base::apple::FilePathToNSURL(app_bundle_file_path); - base::ScopedCFTypeRef<LSSharedFileListItemRef> item = + apple::ScopedCFTypeRef<LSSharedFileListItemRef> item = login_items.GetLoginItemForApp(app_bundle_url); if (!item.get()) { return; @@ -250,7 +251,7 @@ CFStringRef app = CFSTR("com.apple.loginwindow"); CFStringRef save_state = CFSTR("TALLogoutSavesState"); - ScopedCFTypeRef<CFPropertyListRef> plist( + apple::ScopedCFTypeRef<CFPropertyListRef> plist( CFPreferencesCopyAppValue(save_state, app)); // According to documentation, com.apple.loginwindow.plist does not exist on a // fresh installation until the user changes a login window setting. The @@ -278,7 +279,7 @@ return false; } - base::ScopedCFTypeRef<LSSharedFileListItemRef> item( + apple::ScopedCFTypeRef<LSSharedFileListItemRef> item( login_items.GetLoginItemForMainApp()); if (!item.get()) { // The OS itself can launch items, usually for the resume feature. @@ -407,7 +408,7 @@ ScopedIOObject<io_service_t> platform_expert(IOServiceGetMatchingService( kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"))); if (platform_expert) { - ScopedCFTypeRef<CFDataRef> model_data( + apple::ScopedCFTypeRef<CFDataRef> model_data( static_cast<CFDataRef>(IORegistryEntryCreateCFProperty( platform_expert, CFSTR("model"), kCFAllocatorDefault, 0))); if (model_data) { @@ -462,7 +463,7 @@ return std::string(); } - base::ScopedCFTypeRef<CFTypeRef> serial_number( + apple::ScopedCFTypeRef<CFTypeRef> serial_number( IORegistryEntryCreateCFProperty(expert_device, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0));
diff --git a/base/mac/scoped_ioobject.h b/base/mac/scoped_ioobject.h index bd59e6b..67d5370 100644 --- a/base/mac/scoped_ioobject.h +++ b/base/mac/scoped_ioobject.h
@@ -27,7 +27,8 @@ // Just like ScopedCFTypeRef but for io_object_t and subclasses. template <typename IOT> -using ScopedIOObject = ScopedTypeRef<IOT, internal::ScopedIOObjectTraits<IOT>>; +using ScopedIOObject = + apple::ScopedTypeRef<IOT, internal::ScopedIOObjectTraits<IOT>>; } // namespace base::mac
diff --git a/base/mac/scoped_ioplugininterface.h b/base/mac/scoped_ioplugininterface.h index 6fea9d44..4770d88 100644 --- a/base/mac/scoped_ioplugininterface.h +++ b/base/mac/scoped_ioplugininterface.h
@@ -29,7 +29,7 @@ // (IOUSBInterfaceStruct and IOUSBDeviceStruct320 in particular). template <typename T> using ScopedIOPluginInterface = - ScopedTypeRef<T**, internal::ScopedIOPluginInterfaceTraits<T**>>; + apple::ScopedTypeRef<T**, internal::ScopedIOPluginInterfaceTraits<T**>>; } // namespace base::mac
diff --git a/base/message_loop/message_pump_apple.h b/base/message_loop/message_pump_apple.h index 4037a93..3b64ef7 100644 --- a/base/message_loop/message_pump_apple.h +++ b/base/message_loop/message_pump_apple.h
@@ -219,20 +219,20 @@ void PushWorkItemScope(); // The thread's run loop. - base::ScopedCFTypeRef<CFRunLoopRef> run_loop_; + apple::ScopedCFTypeRef<CFRunLoopRef> run_loop_; // The enabled modes. Posted tasks may run in any non-null entry. std::unique_ptr<ScopedModeEnabler> enabled_modes_[kNumModes]; // The timer, sources, and observers are described above alongside their // callbacks. - base::ScopedCFTypeRef<CFRunLoopTimerRef> delayed_work_timer_; - base::ScopedCFTypeRef<CFRunLoopSourceRef> work_source_; - base::ScopedCFTypeRef<CFRunLoopSourceRef> nesting_deferred_work_source_; - base::ScopedCFTypeRef<CFRunLoopObserverRef> pre_wait_observer_; - base::ScopedCFTypeRef<CFRunLoopObserverRef> after_wait_observer_; - base::ScopedCFTypeRef<CFRunLoopObserverRef> pre_source_observer_; - base::ScopedCFTypeRef<CFRunLoopObserverRef> enter_exit_observer_; + apple::ScopedCFTypeRef<CFRunLoopTimerRef> delayed_work_timer_; + apple::ScopedCFTypeRef<CFRunLoopSourceRef> work_source_; + apple::ScopedCFTypeRef<CFRunLoopSourceRef> nesting_deferred_work_source_; + apple::ScopedCFTypeRef<CFRunLoopObserverRef> pre_wait_observer_; + apple::ScopedCFTypeRef<CFRunLoopObserverRef> after_wait_observer_; + apple::ScopedCFTypeRef<CFRunLoopObserverRef> pre_source_observer_; + apple::ScopedCFTypeRef<CFRunLoopObserverRef> enter_exit_observer_; // (weak) Delegate passed as an argument to the innermost Run call. raw_ptr<Delegate> delegate_ = nullptr; @@ -310,7 +310,7 @@ // A source that doesn't do anything but provide something signalable // attached to the run loop. This source will be signalled when Quit // is called, to cause the loop to wake up so that it can stop. - base::ScopedCFTypeRef<CFRunLoopSourceRef> quit_source_; + apple::ScopedCFTypeRef<CFRunLoopSourceRef> quit_source_; }; #if BUILDFLAG(IS_IOS)
diff --git a/base/message_loop/message_pump_io_ios.cc b/base/message_loop/message_pump_io_ios.cc index 1ce11b5a..999a929 100644 --- a/base/message_loop/message_pump_io_ios.cc +++ b/base/message_loop/message_pump_io_ios.cc
@@ -91,9 +91,9 @@ CFFileDescriptorRef fdref = controller->fdref_.get(); if (fdref == NULL) { - base::ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref( - CFFileDescriptorCreate( - kCFAllocatorDefault, fd, false, HandleFdIOEvent, &source_context)); + apple::ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref( + CFFileDescriptorCreate(kCFAllocatorDefault, fd, false, HandleFdIOEvent, + &source_context)); if (scoped_fdref == NULL) { NOTREACHED() << "CFFileDescriptorCreate failed"; return false; @@ -102,9 +102,9 @@ CFFileDescriptorEnableCallBacks(scoped_fdref, callback_types); // TODO(wtc): what should the 'order' argument be? - base::ScopedCFTypeRef<CFRunLoopSourceRef> scoped_fd_source( - CFFileDescriptorCreateRunLoopSource( - kCFAllocatorDefault, scoped_fdref, 0)); + apple::ScopedCFTypeRef<CFRunLoopSourceRef> scoped_fd_source( + CFFileDescriptorCreateRunLoopSource(kCFAllocatorDefault, scoped_fdref, + 0)); if (scoped_fd_source == NULL) { NOTREACHED() << "CFFileDescriptorCreateRunLoopSource failed"; return false; @@ -154,7 +154,7 @@ // Ensure that |fdref| will remain live for the duration of this function // call even if |controller| is deleted or |StopWatchingFileDescriptor()| is // called, either of which will cause |fdref| to be released. - ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref( + apple::ScopedCFTypeRef<CFFileDescriptorRef> scoped_fdref( fdref, base::scoped_policy::RETAIN); int fd = CFFileDescriptorGetNativeDescriptor(fdref);
diff --git a/base/message_loop/message_pump_io_ios.h b/base/message_loop/message_pump_io_ios.h index b55b196..806ed24f 100644 --- a/base/message_loop/message_pump_io_ios.h +++ b/base/message_loop/message_pump_io_ios.h
@@ -53,10 +53,10 @@ void OnFileCanWriteWithoutBlocking(int fd, MessagePumpIOSForIO* pump); bool is_persistent_ = false; // false if this event is one-shot. - base::apple::ScopedCFFileDescriptorRef fdref_; + apple::ScopedCFFileDescriptorRef fdref_; CFOptionFlags callback_types_ = 0; - base::ScopedCFTypeRef<CFRunLoopSourceRef> fd_source_; - base::WeakPtr<MessagePumpIOSForIO> pump_; + apple::ScopedCFTypeRef<CFRunLoopSourceRef> fd_source_; + WeakPtr<MessagePumpIOSForIO> pump_; FdWatcher* watcher_ = nullptr; };
diff --git a/base/native_library_mac.mm b/base/native_library_mac.mm index 41cc130a..7859ebd7 100644 --- a/base/native_library_mac.mm +++ b/base/native_library_mac.mm
@@ -64,7 +64,7 @@ native_lib->objc_status = OBJC_UNKNOWN; return native_lib; } - ScopedCFTypeRef<CFURLRef> url(CFURLCreateFromFileSystemRepresentation( + apple::ScopedCFTypeRef<CFURLRef> url(CFURLCreateFromFileSystemRepresentation( kCFAllocatorDefault, (const UInt8*)library_path.value().c_str(), checked_cast<CFIndex>(library_path.value().length()), true)); if (!url) @@ -103,7 +103,7 @@ // Get the function pointer using the right API for the type. if (library->type == BUNDLE) { - ScopedCFTypeRef<CFStringRef> symbol_name(CFStringCreateWithCString( + apple::ScopedCFTypeRef<CFStringRef> symbol_name(CFStringCreateWithCString( kCFAllocatorDefault, name, kCFStringEncodingUTF8)); function_pointer = CFBundleGetFunctionPointerForName(library->bundle, symbol_name);
diff --git a/base/power_monitor/battery_level_provider_mac.mm b/base/power_monitor/battery_level_provider_mac.mm index 76e7bb5..ab91ab0 100644 --- a/base/power_monitor/battery_level_provider_mac.mm +++ b/base/power_monitor/battery_level_provider_mac.mm
@@ -71,7 +71,7 @@ return MakeBatteryState(/* battery_details=*/{}); } - base::ScopedCFTypeRef<CFMutableDictionaryRef> dict; + apple::ScopedCFTypeRef<CFMutableDictionaryRef> dict; kern_return_t result = IORegistryEntryCreateCFProperties(service.get(), dict.InitializeInto(), /*allocator=*/nullptr, /*options=*/0);
diff --git a/base/power_monitor/thermal_state_observer_mac.mm b/base/power_monitor/thermal_state_observer_mac.mm index a1daf362..44f2a65 100644 --- a/base/power_monitor/thermal_state_observer_mac.mm +++ b/base/power_monitor/thermal_state_observer_mac.mm
@@ -111,7 +111,7 @@ } int ThermalStateObserverMac::GetCurrentSpeedLimit() { - base::ScopedCFTypeRef<CFDictionaryRef> dictionary; + apple::ScopedCFTypeRef<CFDictionaryRef> dictionary; IOReturn result = IOPMCopyCPUPowerStatus(dictionary.InitializeInto()); if (result != kIOReturnSuccess) { DVLOG(1) << __func__
diff --git a/base/strings/sys_string_conversions.h b/base/strings/sys_string_conversions.h index df6d2ce..006f2e3 100644 --- a/base/strings/sys_string_conversions.h +++ b/base/strings/sys_string_conversions.h
@@ -63,10 +63,10 @@ // Converts between strings and CFStringRefs/NSStrings. // Converts a string to a CFStringRef. Returns null on failure. -[[nodiscard]] BASE_EXPORT ScopedCFTypeRef<CFStringRef> SysUTF8ToCFStringRef( - StringPiece utf8); -[[nodiscard]] BASE_EXPORT ScopedCFTypeRef<CFStringRef> SysUTF16ToCFStringRef( - StringPiece16 utf16); +[[nodiscard]] BASE_EXPORT apple::ScopedCFTypeRef<CFStringRef> +SysUTF8ToCFStringRef(StringPiece utf8); +[[nodiscard]] BASE_EXPORT apple::ScopedCFTypeRef<CFStringRef> +SysUTF16ToCFStringRef(StringPiece16 utf16); // Converts a CFStringRef to a string. Returns an empty string on failure. It is // not valid to call these with a null `ref`.
diff --git a/base/strings/sys_string_conversions_apple.mm b/base/strings/sys_string_conversions_apple.mm index 0ec86e4..132380b 100644 --- a/base/strings/sys_string_conversions_apple.mm +++ b/base/strings/sys_string_conversions_apple.mm
@@ -81,7 +81,7 @@ return OutStringType(); } - base::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy( + apple::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(in.data()), checked_cast<CFIndex>(in_length * sizeof(typename InStringType::value_type)), @@ -97,15 +97,16 @@ // Given a StringPiece `in` with an encoding specified by `in_encoding`, returns // it as a CFStringRef. Returns null on failure. template <typename CharT> -ScopedCFTypeRef<CFStringRef> StringPieceToCFStringWithEncodingsT( +apple::ScopedCFTypeRef<CFStringRef> StringPieceToCFStringWithEncodingsT( BasicStringPiece<CharT> in, CFStringEncoding in_encoding) { const auto in_length = in.length(); if (in_length == 0) { - return ScopedCFTypeRef<CFStringRef>(CFSTR(""), base::scoped_policy::RETAIN); + return apple::ScopedCFTypeRef<CFStringRef>(CFSTR(""), + base::scoped_policy::RETAIN); } - return ScopedCFTypeRef<CFStringRef>(CFStringCreateWithBytes( + return apple::ScopedCFTypeRef<CFStringRef>(CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(in.data()), checked_cast<CFIndex>(in_length * sizeof(CharT)), in_encoding, false)); } @@ -136,11 +137,11 @@ return SysUTF8ToWide(native_mb); } -ScopedCFTypeRef<CFStringRef> SysUTF8ToCFStringRef(StringPiece utf8) { +apple::ScopedCFTypeRef<CFStringRef> SysUTF8ToCFStringRef(StringPiece utf8) { return StringPieceToCFStringWithEncodingsT(utf8, kCFStringEncodingUTF8); } -ScopedCFTypeRef<CFStringRef> SysUTF16ToCFStringRef(StringPiece16 utf16) { +apple::ScopedCFTypeRef<CFStringRef> SysUTF16ToCFStringRef(StringPiece16 utf16) { return StringPieceToCFStringWithEncodingsT(utf16, kCFStringEncodingUTF16LE); }
diff --git a/base/time/time_exploded_ios.cc b/base/time/time_exploded_ios.cc index dbb17ed..1e04e9f 100644 --- a/base/time/time_exploded_ios.cc +++ b/base/time/time_exploded_ios.cc
@@ -26,11 +26,11 @@ // static bool Time::FromExploded(bool is_local, const Exploded& exploded, Time* time) { - base::ScopedCFTypeRef<CFTimeZoneRef> time_zone( + ScopedCFTypeRef<CFTimeZoneRef> time_zone( is_local ? CFTimeZoneCopySystem() : CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, 0)); - base::ScopedCFTypeRef<CFCalendarRef> gregorian(CFCalendarCreateWithIdentifier( + ScopedCFTypeRef<CFCalendarRef> gregorian(CFCalendarCreateWithIdentifier( kCFAllocatorDefault, kCFGregorianCalendar)); CFCalendarSetTimeZone(gregorian, time_zone); CFAbsoluteTime absolute_time; @@ -83,11 +83,11 @@ kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970; - base::ScopedCFTypeRef<CFTimeZoneRef> time_zone( + ScopedCFTypeRef<CFTimeZoneRef> time_zone( is_local ? CFTimeZoneCopySystem() : CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, 0)); - base::ScopedCFTypeRef<CFCalendarRef> gregorian(CFCalendarCreateWithIdentifier( + ScopedCFTypeRef<CFCalendarRef> gregorian(CFCalendarCreateWithIdentifier( kCFAllocatorDefault, kCFGregorianCalendar)); CFCalendarSetTimeZone(gregorian, time_zone); int second, day_of_week;
diff --git a/chrome/VERSION b/chrome/VERSION index 81cf1c4..fc3d735 100644 --- a/chrome/VERSION +++ b/chrome/VERSION
@@ -1,4 +1,4 @@ MAJOR=118 MINOR=0 -BUILD=5963 +BUILD=5964 PATCH=0
diff --git a/chrome/android/BUILD.gn b/chrome/android/BUILD.gn index 1fb0b830..7c0956d 100644 --- a/chrome/android/BUILD.gn +++ b/chrome/android/BUILD.gn
@@ -417,7 +417,6 @@ "//chrome/browser/ui/android/favicon:java", "//chrome/browser/ui/android/hats:factory_java", "//chrome/browser/ui/android/hats:java", - "//chrome/browser/ui/android/hats/internal:controller_java", "//chrome/browser/ui/android/layouts:java", "//chrome/browser/ui/android/layouts/glue:java", "//chrome/browser/ui/android/logo:java",
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java b/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java index 51b9af62..33483b9b 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/AppHooks.java
@@ -113,7 +113,7 @@ * @return The created {@link SurveyController}. */ public SurveyController createSurveyController() { - return null; + return new SurveyController(); } /**
diff --git a/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java b/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java index 53f29c48..62e3387 100644 --- a/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java +++ b/chrome/android/java/src/org/chromium/chrome/browser/survey/SurveyController.java
@@ -10,8 +10,8 @@ import androidx.annotation.Nullable; import org.chromium.base.ResettersForTesting; +import org.chromium.chrome.browser.AppHooks; import org.chromium.chrome.browser.lifecycle.ActivityLifecycleDispatcher; -import org.chromium.chrome.browser.ui.hats.SurveyControllerProvider; import java.util.Map; @@ -23,12 +23,6 @@ public class SurveyController { private static SurveyController sTestInstance; - private final org.chromium.chrome.browser.ui.hats.SurveyController mDelegate; - - public SurveyController() { - mDelegate = SurveyControllerProvider.create(); - } - /** * @return The SurveyController to use during the lifetime of the browser process. */ @@ -36,7 +30,7 @@ if (sTestInstance != null) { return sTestInstance; } - return new SurveyController(); + return AppHooks.get().createSurveyController(); } /** Set the instance to use for survey related tests. Reset back to null after tests. */ @@ -54,9 +48,7 @@ * survey does not exist. */ protected void downloadSurvey(Context context, String triggerId, Runnable onSuccessRunnable, - Runnable onFailureRunnable) { - mDelegate.downloadSurvey(context, triggerId, onSuccessRunnable, onFailureRunnable); - } + Runnable onFailureRunnable) {} /** * Show the survey. @@ -73,10 +65,7 @@ @Deprecated protected void showSurveyIfAvailable(Activity activity, String siteId, boolean showAsBottomSheet, int displayLogoResId, - @Nullable ActivityLifecycleDispatcher lifecycleDispatcher) { - mDelegate.showSurveyIfAvailable( - activity, siteId, displayLogoResId, lifecycleDispatcher, null); - } + @Nullable ActivityLifecycleDispatcher lifecycleDispatcher) {} /** * Show the survey. @@ -90,8 +79,7 @@ protected void showSurveyIfAvailable(Activity activity, String triggerId, int displayLogoResId, @Nullable ActivityLifecycleDispatcher lifecycleDispatcher, @Nullable Map<String, String> psd) { - mDelegate.showSurveyIfAvailable( - activity, triggerId, displayLogoResId, lifecycleDispatcher, psd); + throw new UnsupportedOperationException(); } /** @@ -100,6 +88,6 @@ * @return true if the survey has expired, false if the survey is valid. */ protected boolean isSurveyExpired(String triggerId) { - return mDelegate.isSurveyExpired(triggerId); + return false; } }
diff --git a/chrome/app/chrome_crash_reporter_client_mac.mm b/chrome/app/chrome_crash_reporter_client_mac.mm index 718be0b..97d1355 100644 --- a/chrome/app/chrome_crash_reporter_client_mac.mm +++ b/chrome/app/chrome_crash_reporter_client_mac.mm
@@ -17,7 +17,7 @@ bool ChromeCrashReporterClient::ReportingIsEnforcedByPolicy( bool* breakpad_enabled) { - base::ScopedCFTypeRef<CFStringRef> key = + base::apple::ScopedCFTypeRef<CFStringRef> key = base::SysUTF8ToCFStringRef(policy::key::kMetricsReportingEnabled); Boolean key_valid; Boolean metrics_reporting_enabled = CFPreferencesGetAppBooleanValue(key,
diff --git a/chrome/app/generated_resources.grd b/chrome/app/generated_resources.grd index 21f4619..66a295e 100644 --- a/chrome/app/generated_resources.grd +++ b/chrome/app/generated_resources.grd
@@ -7693,6 +7693,9 @@ <message name="IDS_NTP_MODULES_DISABLE_TOAST_MESSAGE" desc="Text shown in the toast confirming a module has been disabled."> You won't see <ph name="MODULE_NAME">$1<ex>shopping suggestions</ex></ph> on this page again </message> + <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_MESSAGE" desc="Text shown in the toast confirming the NTP History Clusters module has been disabled."> + You won't see <ph name="MODULE_NAME">$1<ex>this type of card</ex></ph> again + </message> <message name="IDS_NTP_MODULES_DISMISS_BUTTON_TEXT" desc="Text shown on the disable button of an NTP module."> Hide <ph name="MODULE_TITLE">$1<ex>Office Chairs</ex></ph> </message> @@ -8009,6 +8012,9 @@ <message name="IDS_NTP_MODULES_RESUME_YOUR_JOURNEY" desc="A label for the title in NTP Quests Module."> Resume your journey for <ph name="MODULE_TITLE">$1<ex>Office Chairs</ex></ph> </message> + <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_RESUME_BROWSING" desc="A label for the title in NTP History Clusters Module in sentence case."> + Resume browsing for <ph name="MODULE_TITLE">$1<ex>Office Chairs</ex></ph> + </message> <message name="IDS_NTP_MODULES_SHOW_ALL" desc="A label for the show all button in NTP Quests Module."> Show all </message> @@ -8021,6 +8027,12 @@ <ph name="BREAK"><br></ph> You can manage settings from the card menu or see more options in Customize Chrome. </message> + <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_INFO2" desc="Text shown in the body of the info dialog of the NTP History Clusters module."> + You’re seeing pages you've visited and suggested searches to help you easily get back to your most recent activity. + <ph name="BREAK"><br></ph> + <ph name="BREAK"><br></ph> + You can manage settings from the card menu or see more options in Customize Chrome. + </message> <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_WITH_DISCOUNT_INFO" desc="Text shown in the body of the info dialog of the history clusters module when the cluster has available discount."> You’re seeing suggested searches and shopping discounts that might interest you based on your recent activity. <ph name="BREAK"><br></ph> @@ -8030,12 +8042,18 @@ <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_SENTENCE2" desc="Variant of the name of the History Clusters module in sentence case shown in various UIs."> Journeys </message> + <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_NAME" desc="Variant of the name of the History Clusters module shown in the toast confirming it has been disabled."> + this type of card + </message> <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_DISMISS_BUTTON" desc="A label for the dismiss button in the dropdown."> No longer interested </message> <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TEXT" desc="A label to append to the disable text in the dropdown."> Journeys card </message> + <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_DROPDOWN_TEXT" desc="A label to append to the disable text in the dropdown."> + this card + </message> <message name="IDS_NTP_MODULES_HISTORY_CLUSTERS_DONE_BUTTON" desc="A label for the done button in the dropdown."> Mark as done and hide </message>
diff --git a/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_DROPDOWN_TEXT.png.sha1 b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_DROPDOWN_TEXT.png.sha1 new file mode 100644 index 0000000..603f3518 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_DROPDOWN_TEXT.png.sha1
@@ -0,0 +1 @@ +3663fd0fbf7164c7c6e73b070f40611fba45930c \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_MESSAGE.png.sha1 b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_MESSAGE.png.sha1 new file mode 100644 index 0000000..2b1f463 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_MESSAGE.png.sha1
@@ -0,0 +1 @@ +a362433093621e90bbef43255b0fb94100c38ac1 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_NAME.png.sha1 b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_NAME.png.sha1 new file mode 100644 index 0000000..38b23051 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_NAME.png.sha1
@@ -0,0 +1 @@ +ad9742b814fa3852966b4e6d159ed4da83f86fe8 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_INFO2.png.sha1 b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_INFO2.png.sha1 new file mode 100644 index 0000000..5fbfaa9 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_INFO2.png.sha1
@@ -0,0 +1 @@ +b6a96118410cedd6ff3eec739ab180318cad0b82 \ No newline at end of file
diff --git a/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_RESUME_BROWSING.png.sha1 b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_RESUME_BROWSING.png.sha1 new file mode 100644 index 0000000..c0968c2 --- /dev/null +++ b/chrome/app/generated_resources_grd/IDS_NTP_MODULES_HISTORY_CLUSTERS_RESUME_BROWSING.png.sha1
@@ -0,0 +1 @@ +1bf982b29b3846a037248a57b9cd77fff5835f7b \ No newline at end of file
diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn index 712a89e7..e9e06da8 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn
@@ -4750,20 +4750,6 @@ if (is_chromeos_ash) { assert(enable_system_notifications) sources += [ - "apps/app_deduplication_service/app_deduplication_cache.cc", - "apps/app_deduplication_service/app_deduplication_cache.h", - "apps/app_deduplication_service/app_deduplication_mapper.cc", - "apps/app_deduplication_service/app_deduplication_mapper.h", - "apps/app_deduplication_service/app_deduplication_server_connector.cc", - "apps/app_deduplication_service/app_deduplication_server_connector.h", - "apps/app_deduplication_service/app_deduplication_service.cc", - "apps/app_deduplication_service/app_deduplication_service.h", - "apps/app_deduplication_service/app_deduplication_service_factory.cc", - "apps/app_deduplication_service/app_deduplication_service_factory.h", - "apps/app_deduplication_service/duplicate_group.cc", - "apps/app_deduplication_service/duplicate_group.h", - "apps/app_deduplication_service/entry_types.cc", - "apps/app_deduplication_service/entry_types.h", "apps/app_discovery_service/app_discovery_service.cc", "apps/app_discovery_service/app_discovery_service.h", "apps/app_discovery_service/app_discovery_service_factory.cc", @@ -4783,8 +4769,6 @@ "apps/app_discovery_service/result.h", "apps/app_discovery_service/test_fetcher.cc", "apps/app_discovery_service/test_fetcher.h", - "apps/app_provisioning_service/app_provisioning_data_manager.cc", - "apps/app_provisioning_service/app_provisioning_data_manager.h", "apps/digital_goods/digital_goods_ash.cc", "apps/digital_goods/digital_goods_ash.h", "apps/digital_goods/digital_goods_factory_impl.cc", @@ -5184,9 +5168,9 @@ "//ash/webui/system_extensions_internals_ui/mojom", "//build:chromeos_buildflags", "//chrome/app/theme:chrome_unscaled_resources_grit", - "//chrome/browser/apps/app_deduplication_service/proto", + "//chrome/browser/apps/app_deduplication_service", "//chrome/browser/apps/app_preload_service", - "//chrome/browser/apps/app_provisioning_service/proto", + "//chrome/browser/apps/app_provisioning_service", "//chrome/browser/ash", "//chrome/browser/ash/crosapi", "//chrome/browser/ash/power/ml/smart_dim",
diff --git a/chrome/browser/about_flags.cc b/chrome/browser/about_flags.cc index 256ed7b..7554463 100644 --- a/chrome/browser/about_flags.cc +++ b/chrome/browser/about_flags.cc
@@ -6292,6 +6292,10 @@ kJourneysVariations, "HistoryJourneys")}, + {"rename-history-journeys", flag_descriptions::kRenameJourneysName, + flag_descriptions::kRenameJourneysDescription, kOsDesktop | kOsAndroid, + FEATURE_VALUE_TYPE(history_clusters::kRenameJourneys)}, + {"history-journeys-content-clustering", flag_descriptions::kJourneysContentClusteringName, flag_descriptions::kJourneysContentClusteringDescription,
diff --git a/chrome/browser/app_controller_mac.mm b/chrome/browser/app_controller_mac.mm index 1346412..db6cf13 100644 --- a/chrome/browser/app_controller_mac.mm +++ b/chrome/browser/app_controller_mac.mm
@@ -271,7 +271,7 @@ .DirName() .DirName() .DirName(); - base::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring = + base::apple::ScopedCFTypeRef<CFStringRef> app_bundle_path_cfstring = base::SysUTF8ToCFStringRef(app_bundle_path.value()); CFPreferencesSetAppValue( base::apple::NSToCFPtrCast(app_mode::kLastRunAppBundlePathPrefsKey),
diff --git a/chrome/browser/apps/app_deduplication_service/BUILD.gn b/chrome/browser/apps/app_deduplication_service/BUILD.gn new file mode 100644 index 0000000..d5f5b9e --- /dev/null +++ b/chrome/browser/apps/app_deduplication_service/BUILD.gn
@@ -0,0 +1,73 @@ +# Copyright 2023 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/chromeos/ui_mode.gni") + +# App Deduplication Service is Ash-only. +assert(is_chromeos_ash) + +source_set("app_deduplication_service") { + sources = [ + "app_deduplication_cache.cc", + "app_deduplication_cache.h", + "app_deduplication_mapper.cc", + "app_deduplication_mapper.h", + "app_deduplication_server_connector.cc", + "app_deduplication_server_connector.h", + "app_deduplication_service.cc", + "app_deduplication_service.h", + "app_deduplication_service_factory.cc", + "app_deduplication_service_factory.h", + "duplicate_group.cc", + "duplicate_group.h", + "entry_types.cc", + "entry_types.h", + ] + + public_deps = [ "//chrome/browser/apps/app_deduplication_service/proto" ] + + deps = [ + "//base", + "//chrome/browser/apps/almanac_api_client", + "//chrome/browser/apps/app_provisioning_service", + "//chrome/browser/apps/app_service", + "//chrome/browser/profiles", + "//chrome/browser/profiles:profile", + "//chrome/common:constants", + "//components/keyed_service/content", + "//components/pref_registry", + "//components/prefs", + "//components/services/app_service", + "//google_apis:google_apis", + "//services/network/public/cpp", + "//url", + ] +} + +source_set("unit_tests") { + testonly = true + + sources = [ + "app_deduplication_cache_unittest.cc", + "app_deduplication_mapper_unittest.cc", + "app_deduplication_server_connector_unittest.cc", + "app_deduplication_service_unittest.cc", + ] + + deps = [ + ":app_deduplication_service", + "//base", + "//base/test:test_support", + "//chrome/browser/apps/almanac_api_client", + "//chrome/browser/apps/app_provisioning_service", + "//chrome/browser/apps/app_service", + "//chrome/common:constants", + "//chrome/test:test_support", + "//components/version_info:channel", + "//content/test:test_support", + "//net", + "//services/network:test_support", + "//services/network/public/cpp", + ] +}
diff --git a/chrome/browser/apps/app_deduplication_service/app_deduplication_service.cc b/chrome/browser/apps/app_deduplication_service/app_deduplication_service.cc index e675533..75d8765 100644 --- a/chrome/browser/apps/app_deduplication_service/app_deduplication_service.cc +++ b/chrome/browser/apps/app_deduplication_service/app_deduplication_service.cc
@@ -23,7 +23,6 @@ #include "components/prefs/pref_service.h" #include "components/services/app_service/public/cpp/app_types.h" #include "components/services/app_service/public/cpp/types_util.h" -#include "third_party/crashpad/crashpad/util/string/split_string.h" namespace { // Folder path to where the deduplication data will be stored on disk.
diff --git a/chrome/browser/apps/app_deduplication_service/app_deduplication_service_factory.cc b/chrome/browser/apps/app_deduplication_service/app_deduplication_service_factory.cc index 17a3ce0..888eed3 100644 --- a/chrome/browser/apps/app_deduplication_service/app_deduplication_service_factory.cc +++ b/chrome/browser/apps/app_deduplication_service/app_deduplication_service_factory.cc
@@ -8,7 +8,6 @@ #include "chrome/browser/apps/app_deduplication_service/app_deduplication_service.h" #include "chrome/browser/apps/app_deduplication_service/app_deduplication_service_factory.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" -#include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_features.h"
diff --git a/chrome/browser/apps/app_provisioning_service/BUILD.gn b/chrome/browser/apps/app_provisioning_service/BUILD.gn new file mode 100644 index 0000000..8cc1b6ff --- /dev/null +++ b/chrome/browser/apps/app_provisioning_service/BUILD.gn
@@ -0,0 +1,19 @@ +# Copyright 2023 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import("//build/config/chromeos/ui_mode.gni") + +# App Provisioning Service is Ash-only. +assert(is_chromeos_ash) + +source_set("app_provisioning_service") { + sources = [ + "app_provisioning_data_manager.cc", + "app_provisioning_data_manager.h", + ] + + public_deps = [ "//chrome/browser/apps/app_provisioning_service/proto" ] + + deps = [ "//base" ] +}
diff --git a/chrome/browser/apps/app_provisioning_service/app_provisioning_data_manager.cc b/chrome/browser/apps/app_provisioning_service/app_provisioning_data_manager.cc index a31a9a4b..a510c14 100644 --- a/chrome/browser/apps/app_provisioning_service/app_provisioning_data_manager.cc +++ b/chrome/browser/apps/app_provisioning_service/app_provisioning_data_manager.cc
@@ -6,10 +6,8 @@ #include <memory> -#include "base/feature_list.h" #include "base/logging.h" #include "chrome/browser/apps/app_provisioning_service/proto/app_data.pb.h" -#include "chrome/common/chrome_features.h" namespace apps {
diff --git a/chrome/browser/apps/app_service/app_service_proxy_lacros.cc b/chrome/browser/apps/app_service/app_service_proxy_lacros.cc index 905027f9..9da2638 100644 --- a/chrome/browser/apps/app_service/app_service_proxy_lacros.cc +++ b/chrome/browser/apps/app_service/app_service_proxy_lacros.cc
@@ -327,45 +327,42 @@ return intent_launch_info; } - if (crosapi_receiver_.is_bound()) { - app_registry_cache_.ForEachApp( - [&intent_launch_info, &intent, &exclude_browsers, - &exclude_browser_tab_apps](const apps::AppUpdate& update) { - if (!apps_util::IsInstalled(update.Readiness()) || - !update.ShowInLauncher().value_or(false)) { - return; - } - if (exclude_browser_tab_apps && - update.WindowMode() == WindowMode::kBrowser) { - return; - } - std::set<std::string> existing_activities; - for (const auto& filter : update.IntentFilters()) { - DCHECK(filter); - if (exclude_browsers && filter->IsBrowserFilter()) { - continue; - } - if (intent->MatchFilter(filter)) { - IntentLaunchInfo entry; - entry.app_id = update.AppId(); - std::string activity_label; - if (filter->activity_label && - !filter->activity_label.value().empty()) { - activity_label = filter->activity_label.value(); - } else { - activity_label = update.Name(); - } - if (base::Contains(existing_activities, activity_label)) { - continue; - } - existing_activities.insert(activity_label); - entry.activity_label = activity_label; - entry.activity_name = filter->activity_name.value_or(""); - intent_launch_info.push_back(entry); - } - } - }); - } + app_registry_cache_.ForEachApp([&intent_launch_info, &intent, + &exclude_browsers, &exclude_browser_tab_apps]( + const apps::AppUpdate& update) { + if (!apps_util::IsInstalled(update.Readiness()) || + !update.ShowInLauncher().value_or(false)) { + return; + } + if (exclude_browser_tab_apps && + update.WindowMode() == WindowMode::kBrowser) { + return; + } + std::set<std::string> existing_activities; + for (const auto& filter : update.IntentFilters()) { + DCHECK(filter); + if (exclude_browsers && filter->IsBrowserFilter()) { + continue; + } + if (intent->MatchFilter(filter)) { + IntentLaunchInfo entry; + entry.app_id = update.AppId(); + std::string activity_label; + if (filter->activity_label && !filter->activity_label.value().empty()) { + activity_label = filter->activity_label.value(); + } else { + activity_label = update.Name(); + } + if (base::Contains(existing_activities, activity_label)) { + continue; + } + existing_activities.insert(activity_label); + entry.activity_label = activity_label; + entry.activity_name = filter->activity_name.value_or(""); + intent_launch_info.push_back(entry); + } + } + }); return intent_launch_info; }
diff --git a/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.cc b/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.cc index 92a774b..28c6e36 100644 --- a/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.cc +++ b/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.cc
@@ -48,10 +48,10 @@ DependsOn(AppServiceProxyFactory::GetInstance()); } -KeyedService* -StandaloneBrowserExtensionAppsFactoryForApp::BuildServiceInstanceFor( - content::BrowserContext* context) const { - return new StandaloneBrowserExtensionApps( +std::unique_ptr<KeyedService> StandaloneBrowserExtensionAppsFactoryForApp:: + BuildServiceInstanceForBrowserContext( + content::BrowserContext* context) const { + return std::make_unique<StandaloneBrowserExtensionApps>( AppServiceProxyFactory::GetForProfile( Profile::FromBrowserContext(context)), AppType::kStandaloneBrowserChromeApp);
diff --git a/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.h b/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.h index d8876785..926f0da 100644 --- a/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.h +++ b/chrome/browser/apps/app_service/publishers/standalone_browser_extension_apps_factory.h
@@ -36,7 +36,7 @@ ~StandaloneBrowserExtensionAppsFactoryForApp() override = default; // BrowserContextKeyedServiceFactory overrides. - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/apps/app_shim/app_shim_host_bootstrap_mac.cc b/chrome/browser/apps/app_shim/app_shim_host_bootstrap_mac.cc index 65a4d41..5b77854 100644 --- a/chrome/browser/apps/app_shim/app_shim_host_bootstrap_mac.cc +++ b/chrome/browser/apps/app_shim/app_shim_host_bootstrap_mac.cc
@@ -28,7 +28,7 @@ // TODO(https://crbug.com/1052131): Remove NSLog logging, and move to an // internal debugging URL. void LogToNSLog(std::string format, ...) { - base::ScopedCFTypeRef<CFStringRef> cf_format( + base::apple::ScopedCFTypeRef<CFStringRef> cf_format( base::SysUTF8ToCFStringRef(format)); va_list arguments;
diff --git a/chrome/browser/apps/app_shim/app_shim_manager_mac.cc b/chrome/browser/apps/app_shim/app_shim_manager_mac.cc index 7ba3278..5936af9 100644 --- a/chrome/browser/apps/app_shim/app_shim_manager_mac.cc +++ b/chrome/browser/apps/app_shim/app_shim_manager_mac.cc
@@ -109,14 +109,14 @@ // * "has_value() == true" app shim validation should occur. // * "has_value() == false" app shim validation should be skipped. // * "has_value() == true && value() == null" validation should always fail. -absl::optional<base::ScopedCFTypeRef<SecRequirementRef>> +absl::optional<base::apple::ScopedCFTypeRef<SecRequirementRef>> CreateAppShimRequirement() { // Note: Don't validate |framework_code|: We don't need to waste time // validating. We are only interested in discovering if the framework bundle // is code-signed, and if so what the designated requirement is. - base::ScopedCFTypeRef<CFURLRef> framework_url = + base::apple::ScopedCFTypeRef<CFURLRef> framework_url = base::apple::FilePathToCFURL(base::apple::FrameworkBundlePath()); - base::ScopedCFTypeRef<SecStaticCodeRef> framework_code; + base::apple::ScopedCFTypeRef<SecStaticCodeRef> framework_code; OSStatus status = SecStaticCodeCreateWithPath( framework_url, kSecCSDefaultFlags, framework_code.InitializeInto()); @@ -132,18 +132,18 @@ if (status != errSecSuccess) { DumpOSStatusError(status, "SecStaticCodeCreateWithPath"); // has_value() == true - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } // Copy the signing info from the SecStaticCodeRef. - base::ScopedCFTypeRef<CFDictionaryRef> framework_signing_info; + base::apple::ScopedCFTypeRef<CFDictionaryRef> framework_signing_info; status = SecCodeCopySigningInformation( framework_code.get(), kSecCSSigningInformation, framework_signing_info.InitializeInto()); if (status != errSecSuccess) { DumpOSStatusError(status, "SecCodeCopySigningInformation"); // has_value() == true - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } // Look up the code signing flags. If the flags are absent treat this as @@ -168,7 +168,7 @@ &flags)) { DumpError("CFNumberGetValue"); // has_value() == true - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } if (static_cast<uint32_t>(flags) & kSecCodeSignatureAdhoc) { return absl::nullopt; // has_value() == false @@ -178,24 +178,24 @@ // validate the app shim's code signature. First let's get the framework // bundle requirement. We will build a suitable requirement for the app shim // based off that. - base::ScopedCFTypeRef<SecRequirementRef> framework_requirement; + base::apple::ScopedCFTypeRef<SecRequirementRef> framework_requirement; status = SecCodeCopyDesignatedRequirement(framework_code, kSecCSDefaultFlags, framework_requirement.InitializeInto()); if (status != errSecSuccess) { DumpOSStatusError(status, "SecCodeCopyDesignatedRequirement"); // has_value() == true - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } - base::ScopedCFTypeRef<CFStringRef> framework_requirement_string; + base::apple::ScopedCFTypeRef<CFStringRef> framework_requirement_string; status = SecRequirementCopyString(framework_requirement, kSecCSDefaultFlags, framework_requirement_string.InitializeInto()); if (status != errSecSuccess) { DumpOSStatusError(status, "SecRequirementCopyString"); // has_value() == true - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } // Always returns has_value() == true. @@ -212,7 +212,7 @@ // requirement). bool IsAcceptablyCodeSignedInternal(pid_t app_shim_pid) { static base::NoDestructor< - absl::optional<base::ScopedCFTypeRef<SecRequirementRef>>> + absl::optional<base::apple::ScopedCFTypeRef<SecRequirementRef>>> app_shim_requirement(CreateAppShimRequirement()); if (!app_shim_requirement->has_value()) { // App shim validation is not required because framework bundle is not @@ -229,15 +229,16 @@ } // Verify the app shim. - base::ScopedCFTypeRef<CFNumberRef> app_shim_pid_cf( + base::apple::ScopedCFTypeRef<CFNumberRef> app_shim_pid_cf( CFNumberCreate(nullptr, kCFNumberIntType, &app_shim_pid)); const void* app_shim_attribute_keys[] = {kSecGuestAttributePid}; const void* app_shim_attribute_values[] = {app_shim_pid_cf}; - base::ScopedCFTypeRef<CFDictionaryRef> app_shim_attributes(CFDictionaryCreate( - nullptr, app_shim_attribute_keys, app_shim_attribute_values, - std::size(app_shim_attribute_keys), &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); - base::ScopedCFTypeRef<SecCodeRef> app_shim_code; + base::apple::ScopedCFTypeRef<CFDictionaryRef> app_shim_attributes( + CFDictionaryCreate( + nullptr, app_shim_attribute_keys, app_shim_attribute_values, + std::size(app_shim_attribute_keys), &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<SecCodeRef> app_shim_code; OSStatus status = SecCodeCopyGuestWithAttributes( nullptr, app_shim_attributes, kSecCSDefaultFlags, app_shim_code.InitializeInto()); @@ -1667,7 +1668,7 @@ return !files.empty() || !urls.empty() || !override_url.is_empty(); } -base::ScopedCFTypeRef<SecRequirementRef> +base::apple::ScopedCFTypeRef<SecRequirementRef> AppShimManager::BuildAppShimRequirementFromFrameworkRequirementString( CFStringRef framwork_requirement) { // Make sure the framework bundle requirement is in the expected format. @@ -1676,13 +1677,13 @@ // we can swap in the desired app shim identifier leaving rest of the // requirement unmodified. CFIndex len = CFStringGetLength(framwork_requirement); - base::ScopedCFTypeRef<CFArrayRef> quote_ranges( + base::apple::ScopedCFTypeRef<CFArrayRef> quote_ranges( CFStringCreateArrayWithFindResults(nullptr, framwork_requirement, CFSTR("\""), CFRangeMake(0, len), 0)); if (!CFStringHasPrefix(framwork_requirement, CFSTR("identifier \"")) || !quote_ranges || CFArrayGetCount(quote_ranges) < 2) { DumpError("Framework bundle requirement is malformed."); - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } // Get the index of the second quote. @@ -1693,22 +1694,22 @@ // Make sure there is something to read after the second quote. if (second_quote_index + 1 >= len) { DumpError("Framework bundle requirement is too short"); - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } // Build the app shim requirement. Keep the data from the framework bundle // requirement starting after second quote. - base::ScopedCFTypeRef<CFStringRef> right_of_second_quote( + base::apple::ScopedCFTypeRef<CFStringRef> right_of_second_quote( CFStringCreateWithSubstring( nullptr, framwork_requirement, CFRangeMake(second_quote_index + 1, len - second_quote_index - 1))); - base::ScopedCFTypeRef<CFMutableStringRef> shim_requirement_string( + base::apple::ScopedCFTypeRef<CFMutableStringRef> shim_requirement_string( CFStringCreateMutableCopy(nullptr, 0, CFSTR("identifier \"app_mode_loader\""))); CFStringAppend(shim_requirement_string, right_of_second_quote); // Parse the requirement. - base::ScopedCFTypeRef<SecRequirementRef> shim_requirement; + base::apple::ScopedCFTypeRef<SecRequirementRef> shim_requirement; OSStatus status = SecRequirementCreateWithString( shim_requirement_string, kSecCSDefaultFlags, shim_requirement.InitializeInto()); @@ -1716,7 +1717,7 @@ DumpOSStatusError(status, std::string("SecRequirementCreateWithString: ") + base::SysCFStringRefToUTF8(shim_requirement_string)); - return base::ScopedCFTypeRef<SecRequirementRef>(nullptr); + return base::apple::ScopedCFTypeRef<SecRequirementRef>(nullptr); } return shim_requirement; }
diff --git a/chrome/browser/apps/app_shim/app_shim_manager_mac.h b/chrome/browser/apps/app_shim/app_shim_manager_mac.h index 72facbe..c92bd76 100644 --- a/chrome/browser/apps/app_shim/app_shim_manager_mac.h +++ b/chrome/browser/apps/app_shim/app_shim_manager_mac.h
@@ -231,7 +231,7 @@ // AvatarMenuObserver: void OnAvatarMenuChanged(AvatarMenu* menu) override; - static base::ScopedCFTypeRef<SecRequirementRef> + static base::apple::ScopedCFTypeRef<SecRequirementRef> BuildAppShimRequirementFromFrameworkRequirementString(CFStringRef); class AppShimObserver {
diff --git a/chrome/browser/apps/app_shim/app_shim_manager_mac_unittest.cc b/chrome/browser/apps/app_shim/app_shim_manager_mac_unittest.cc index 13a4864..0ef7def 100644 --- a/chrome/browser/apps/app_shim/app_shim_manager_mac_unittest.cc +++ b/chrome/browser/apps/app_shim/app_shim_manager_mac_unittest.cc
@@ -1790,11 +1790,11 @@ "apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] /* " "exists */ and certificate leaf[field.1.2.840.113635.100.6.1.13] " "/* exists */ and certificate leaf[subject.OU] = EQHXZ8M8AV"); - base::ScopedCFTypeRef<SecRequirementRef> got_req( + base::apple::ScopedCFTypeRef<SecRequirementRef> got_req( manager_->BuildAppShimRequirementFromFrameworkRequirementString( framework_req_string)); ASSERT_TRUE(got_req); - base::ScopedCFTypeRef<CFStringRef> got_req_string; + base::apple::ScopedCFTypeRef<CFStringRef> got_req_string; ASSERT_EQ(SecRequirementCopyString(got_req, kSecCSDefaultFlags, got_req_string.InitializeInto()), errSecSuccess);
diff --git a/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc b/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc index a417e52..ae897de9 100644 --- a/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc +++ b/chrome/browser/ash/accessibility/spoken_feedback_browsertest.cc
@@ -16,7 +16,6 @@ #include "ash/public/cpp/event_rewriter_controller.h" #include "ash/public/cpp/screen_backlight.h" #include "ash/public/cpp/shelf_model.h" -#include "ash/public/cpp/shell_window_ids.h" #include "ash/public/cpp/test/shell_test_api.h" #include "ash/public/cpp/test/test_shelf_item_delegate.h" #include "ash/root_window_controller.h" @@ -30,7 +29,6 @@ #include "ash/system/status_area_widget_test_helper.h" #include "ash/system/unified/unified_system_tray.h" #include "ash/wm/desks/templates/saved_desk_util.h" -#include "base/allocator/partition_allocator/pointers/raw_ptr.h" #include "base/command_line.h" #include "base/functional/bind.h" #include "base/test/scoped_feature_list.h" @@ -41,7 +39,6 @@ #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/ash/accessibility/accessibility_manager.h" #include "chrome/browser/ash/accessibility/html_test_utils.h" -#include "chrome/browser/ash/input_method/ui/candidate_window_view.h" #include "chrome/browser/ash/login/test/device_state_mixin.h" #include "chrome/browser/ash/login/test/login_manager_mixin.h" #include "chrome/browser/ash/login/test/oobe_base_test.h" @@ -68,7 +65,6 @@ #include "extensions/common/constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/accessibility/accessibility_features.h" -#include "ui/base/ime/candidate_window.h" #include "ui/base/ui_base_features.h" #include "ui/display/manager/display_manager.h" #include "ui/display/screen.h" @@ -2372,84 +2368,4 @@ sm_.ExpectSpeech("row 1 column 1"); sm_.Replay(); } - -class SpokenFeedbackWithCandidateWindowTest - : public LoggedInSpokenFeedbackTest { - public: - SpokenFeedbackWithCandidateWindowTest() = default; - SpokenFeedbackWithCandidateWindowTest( - const SpokenFeedbackWithCandidateWindowTest&) = delete; - SpokenFeedbackWithCandidateWindowTest& operator=( - const SpokenFeedbackWithCandidateWindowTest&) = delete; - ~SpokenFeedbackWithCandidateWindowTest() override = default; - - void SetUpOnMainThread() override { - LoggedInSpokenFeedbackTest::SetUpOnMainThread(); - - aura::Window* parent = - ash::Shell::GetContainer(Shell::Get()->GetPrimaryRootWindow(), - ash::kShellWindowId_MenuContainer); - - candidate_window_view_ = new ui::ime::CandidateWindowView(parent); - candidate_window_view_->InitWidget(); - } - void TearDownOnMainThread() override { - candidate_window_view_.ExtractAsDangling()->GetWidget()->CloseNow(); - LoggedInSpokenFeedbackTest::TearDownOnMainThread(); - } - - raw_ptr<ui::ime::CandidateWindowView> candidate_window_view_; -}; - -IN_PROC_BROWSER_TEST_F(SpokenFeedbackWithCandidateWindowTest, - SpeakSelectedItem) { - EnableChromeVox(); - - ui::CandidateWindow candidate_window; - candidate_window.set_cursor_position(0); - candidate_window.set_page_size(2); - candidate_window.mutable_candidates()->clear(); - candidate_window.set_orientation(ui::CandidateWindow::VERTICAL); - for (size_t i = 0; i < 2; ++i) { - ui::CandidateWindow::Entry entry; - entry.value = u"value " + base::NumberToString16(i); - entry.label = u"label " + base::NumberToString16(i); - candidate_window.mutable_candidates()->push_back(entry); - } - - sm_.Call([this, &candidate_window]() { - candidate_window_view_->GetWidget()->Show(); - candidate_window_view_->UpdateCandidates(candidate_window); - candidate_window_view_->ShowLookupTable(); - }); - sm_.ExpectSpeech("value 0"); - - // Move selection to another item. - sm_.Call([this, &candidate_window]() { - candidate_window.set_cursor_position(1); - candidate_window_view_->UpdateCandidates(candidate_window); - }); - sm_.ExpectSpeech("value 1"); - - // Simulate pagination. - sm_.Call([this, &candidate_window]() { - candidate_window.set_cursor_position(0); - candidate_window.mutable_candidates()->at(0).value = u"value 2"; - candidate_window.mutable_candidates()->at(0).label = u"label 2"; - candidate_window.mutable_candidates()->at(1).value = u"value 3"; - candidate_window.mutable_candidates()->at(1).label = u"label 3"; - candidate_window_view_->UpdateCandidates(candidate_window); - }); - // TODO(hirokisato): We should check unexpected utterances are not skipped - // when consuming "value 2", otherwise there's a race between when we check - // "NextSpeechIsNot" and when speech is created, and test may pass - // unexpectedly. - sm_.ExpectNextSpeechIsNot("value 0"); - sm_.ExpectNextSpeechIsNot("value 1"); - sm_.ExpectNextSpeechIsNot("value 3"); - sm_.ExpectSpeech("value 2"); - - sm_.Replay(); -} - } // namespace ash
diff --git a/chrome/browser/ash/arc/accessibility/arc_accessibility_helper_bridge.cc b/chrome/browser/ash/arc/accessibility/arc_accessibility_helper_bridge.cc index 77db121..0214b614 100644 --- a/chrome/browser/ash/arc/accessibility/arc_accessibility_helper_bridge.cc +++ b/chrome/browser/ash/arc/accessibility/arc_accessibility_helper_bridge.cc
@@ -475,6 +475,8 @@ return ax::android::mojom::AccessibilityFilterType::OFF; } +// TODO(b/177979962): Remove after Android starts accepting CaptionStyle from +// arc_intent_helper. void ArcAccessibilityHelperBridge::UpdateCaptionSettings() const { ax::android::mojom::CaptionStylePtr caption_style = GetCaptionStyleFromPrefs(profile_->GetPrefs());
diff --git a/chrome/browser/ash/arc/intent_helper/arc_settings_service.cc b/chrome/browser/ash/arc/intent_helper/arc_settings_service.cc index 1ed105f..11f7dfe 100644 --- a/chrome/browser/ash/arc/intent_helper/arc_settings_service.cc +++ b/chrome/browser/ash/arc/intent_helper/arc_settings_service.cc
@@ -11,6 +11,7 @@ #include "ash/components/arc/arc_prefs.h" #include "ash/components/arc/arc_util.h" #include "ash/components/arc/mojom/backup_settings.mojom.h" +#include "ash/components/arc/mojom/intent_helper.mojom.h" #include "ash/components/arc/mojom/pip.mojom.h" #include "ash/components/arc/session/arc_bridge_service.h" #include "ash/constants/ash_features.h" @@ -22,9 +23,11 @@ #include "base/memory/raw_ptr.h" #include "base/memory/singleton.h" #include "base/scoped_observation.h" +#include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/ash/app_list/arc/arc_app_utils.h" #include "chrome/browser/ash/arc/arc_util.h" @@ -47,6 +50,7 @@ #include "components/arc/common/intent_helper/arc_intent_helper_package.h" #include "components/arc/intent_helper/arc_intent_helper_bridge.h" #include "components/language/core/browser/pref_names.h" +#include "components/live_caption/pref_names.h" #include "components/onc/onc_pref_names.h" #include "components/prefs/pref_change_registrar.h" #include "components/prefs/pref_service.h" @@ -58,6 +62,8 @@ #include "net/proxy_resolution/proxy_bypass_rules.h" #include "net/proxy_resolution/proxy_config.h" #include "third_party/blink/public/common/page/page_zoom.h" +#include "third_party/skia/include/core/SkColor.h" +#include "ui/base/metadata/base_type_conversion.h" // Enable VLOG level 1. #undef ENABLED_VLOG_LEVEL @@ -77,6 +83,88 @@ constexpr float kAndroidFontScaleNormal = 1; +// These values are based on +// https://source.chromium.org/chromium/chromium/src/+/main:chrome/browser/resources/ash/settings/os_a11y_page/captions_subpage.ts;l=142;drc=0918c7f73782a9575396f0c6b80a722b5a3d255a +constexpr char kTextShadowRaised[] = "-2px -2px 4px rgba(0, 0, 0, 0.5)"; +constexpr char kTextShadowDepressed[] = "2px 2px 4px rgba(0, 0, 0, 0.5)"; +constexpr char kTextShadowUniform[] = + "-1px 0px 0px black, 0px -1px 0px black, 1px 0px 0px black, 0px 1px 0px " + "black"; +constexpr char kTextShadowDropShadow[] = + "0px 0px 2px rgba(0, 0, 0, 0.5), 2px 2px 2px black"; + +arc::mojom::CaptionColorPtr GetCaptionColorFromPrefs( + const PrefService* prefs, + const char* color_pref_name, + const char* opacity_pref_name) { + const std::string rgb = prefs->GetString(color_pref_name); + if (rgb.empty()) { + return nullptr; + } + const int opacity = prefs->GetInteger(opacity_pref_name); + std::string color_str = + base::StringPrintf("rgba(%s,%s)", rgb.c_str(), + base::NumberToString(opacity / 100.0).c_str()); + + // Validate color value is correct by converting it to SkColor and retrieve + // the values if it's valid. The caveat is due to the method being very + // generic, it does some redundant stuffs (like utf16 conversion, removing rgb + // prefix). But since this path is frequently used, the benefit of reusing + // method outweighs the cons. + absl::optional<SkColor> sk_color = + ui::metadata::SkColorConverter::FromString(base::UTF8ToUTF16(color_str)); + if (!sk_color) { + return nullptr; + } + SkColor color = sk_color.value(); + return arc::mojom::CaptionColor::New(SkColorGetA(color), SkColorGetR(color), + SkColorGetG(color), SkColorGetB(color)); +} + +float GetFontScaleFromPref(const PrefService* prefs) { + std::string text_size = + prefs->GetString(::prefs::kAccessibilityCaptionsTextSize); + if (text_size.empty()) { + return 1.0f; + } + CHECK(text_size[text_size.size() - 1] == '%'); + text_size = text_size.substr(0, text_size.size() - 1); + int font_scale; + CHECK(base::StringToInt(text_size, &font_scale)); + return font_scale / 100.0f; +} + +arc::mojom::CaptionStylePtr GetCaptionStyleFromPrefs(const PrefService* prefs) { + CHECK(prefs); + + arc::mojom::CaptionStylePtr style = arc::mojom::CaptionStyle::New(); + + style->font_scale = GetFontScaleFromPref(prefs); + style->text_color = + GetCaptionColorFromPrefs(prefs, ::prefs::kAccessibilityCaptionsTextColor, + ::prefs::kAccessibilityCaptionsTextOpacity); + style->background_color = GetCaptionColorFromPrefs( + prefs, ::prefs::kAccessibilityCaptionsBackgroundColor, + ::prefs::kAccessibilityCaptionsBackgroundOpacity); + style->user_locale = prefs->GetString(::language::prefs::kApplicationLocale); + + const std::string text_shadow = + prefs->GetString(::prefs::kAccessibilityCaptionsTextShadow); + if (text_shadow == kTextShadowRaised) { + style->text_shadow_type = arc::mojom::CaptionTextShadowType::kRaised; + } else if (text_shadow == kTextShadowDepressed) { + style->text_shadow_type = arc::mojom::CaptionTextShadowType::kDepressed; + } else if (text_shadow == kTextShadowUniform) { + style->text_shadow_type = arc::mojom::CaptionTextShadowType::kUniform; + } else if (text_shadow == kTextShadowDropShadow) { + style->text_shadow_type = arc::mojom::CaptionTextShadowType::kDropShadow; + } else { + style->text_shadow_type = arc::mojom::CaptionTextShadowType::kNone; + } + + return style; +} + bool GetHttpProxyServer(const ProxyConfigDictionary* proxy_config_dict, std::string* host, int* port) { @@ -186,6 +274,7 @@ void SyncAccessibilityLargeMouseCursorEnabled() const; void SyncAccessibilityVirtualKeyboardEnabled() const; void SyncBackupEnabled() const; + void SyncCaptionStyle() const; void SyncConsumerAutoUpdateToggle() const; void SyncDockedMagnifierEnabled() const; void SyncFocusHighlightEnabled() const; @@ -306,6 +395,14 @@ return; } SyncProxySettings(); + } else if (pref_name == ::prefs::kAccessibilityCaptionsBackgroundColor || + pref_name == ::prefs::kAccessibilityCaptionsBackgroundOpacity || + pref_name == ::prefs::kAccessibilityCaptionsTextColor || + pref_name == ::prefs::kAccessibilityCaptionsTextFont || + pref_name == ::prefs::kAccessibilityCaptionsTextOpacity || + pref_name == ::prefs::kAccessibilityCaptionsTextShadow || + pref_name == ::prefs::kAccessibilityCaptionsTextSize) { + SyncCaptionStyle(); } else if (pref_name == ash::prefs::kAccessibilityFocusHighlightEnabled) { SyncFocusHighlightEnabled(); } else if (pref_name == ash::prefs::kAccessibilityLargeCursorEnabled) { @@ -327,6 +424,12 @@ } else if (pref_name == ::language::prefs::kApplicationLocale || pref_name == ::language::prefs::kPreferredLanguages) { SyncLocale(); + // Android separates locale settings for system language and caption + // language, meanwhile ChromeOS settings treat it as one, hence we use + // this same setting to update Android's caption locale. + if (pref_name == ::language::prefs::kApplicationLocale) { + SyncCaptionStyle(); + } } else if (pref_name == ::prefs::kConsumerAutoUpdateToggle) { SyncConsumerAutoUpdateToggle(); } else if (pref_name == ::prefs::kUse24HourClock) { @@ -420,6 +523,16 @@ local_state_registrar_.Init(g_browser_process->local_state()); // Keep these lines ordered lexicographically. + AddPrefToObserve(::prefs::kAccessibilityCaptionsBackgroundColor); + AddPrefToObserve(::prefs::kAccessibilityCaptionsBackgroundOpacity); + AddPrefToObserve(::prefs::kAccessibilityCaptionsTextColor); + AddPrefToObserve(::prefs::kAccessibilityCaptionsTextFont); + AddPrefToObserve(::prefs::kAccessibilityCaptionsTextOpacity); + AddPrefToObserve(::prefs::kAccessibilityCaptionsTextShadow); + AddPrefToObserve(::prefs::kAccessibilityCaptionsTextSize); + AddPrefToObserve(::prefs::kResolveTimezoneByGeolocationMethod); + AddPrefToObserve(::prefs::kSystemProxyUserTrafficHostAndPort); + AddPrefToObserve(::prefs::kUse24HourClock); AddPrefToObserve(ash::prefs::kAccessibilityFocusHighlightEnabled); AddPrefToObserve(ash::prefs::kAccessibilityLargeCursorEnabled); AddPrefToObserve(ash::prefs::kAccessibilityScreenMagnifierEnabled); @@ -429,12 +542,9 @@ AddPrefToObserve(ash::prefs::kAccessibilityVirtualKeyboardEnabled); AddPrefToObserve(ash::prefs::kDockedMagnifierEnabled); AddPrefToObserve(ash::prefs::kUserGeolocationAllowed); - AddPrefToObserve(::prefs::kResolveTimezoneByGeolocationMethod); - AddPrefToObserve(::prefs::kSystemProxyUserTrafficHostAndPort); - AddPrefToObserve(::prefs::kUse24HourClock); - AddPrefToObserve(proxy_config::prefs::kProxy); AddPrefToObserve(onc::prefs::kDeviceOpenNetworkConfiguration); AddPrefToObserve(onc::prefs::kOpenNetworkConfiguration); + AddPrefToObserve(proxy_config::prefs::kProxy); // Keep these lines ordered lexicographically. AddLocalStatePrefToObserve(::prefs::kConsumerAutoUpdateToggle); @@ -474,6 +584,7 @@ // Keep these lines ordered lexicographically. SyncAccessibilityLargeMouseCursorEnabled(); SyncAccessibilityVirtualKeyboardEnabled(); + SyncCaptionStyle(); SyncConsumerAutoUpdateToggle(); SyncDockedMagnifierEnabled(); SyncFocusHighlightEnabled(); @@ -539,6 +650,22 @@ } } +void ArcSettingsServiceImpl::SyncCaptionStyle() const { + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_bridge_service_->intent_helper(), SetCaptionStyle); + if (!instance) { + return; + } + + const PrefService* pref_service = registrar_.prefs(); + CHECK(pref_service); + arc::mojom::CaptionStylePtr caption_style = + GetCaptionStyleFromPrefs(pref_service); + CHECK(caption_style); + + instance->SetCaptionStyle(std::move(caption_style)); +} + void ArcSettingsServiceImpl::SyncFocusHighlightEnabled() const { SendBoolPrefSettingsBroadcast( ash::prefs::kAccessibilityFocusHighlightEnabled,
diff --git a/chrome/browser/ash/arc/intent_helper/arc_settings_service_unittest.cc b/chrome/browser/ash/arc/intent_helper/arc_settings_service_unittest.cc index b8527a4d..3e4676f0 100644 --- a/chrome/browser/ash/arc/intent_helper/arc_settings_service_unittest.cc +++ b/chrome/browser/ash/arc/intent_helper/arc_settings_service_unittest.cc
@@ -14,6 +14,8 @@ #include "ash/components/arc/session/arc_service_manager.h" #include "ash/components/arc/test/arc_util_test_support.h" #include "ash/components/arc/test/connection_holder_util.h" +#include "ash/components/arc/test/fake_app_host.h" +#include "ash/components/arc/test/fake_app_instance.h" #include "ash/components/arc/test/fake_arc_session.h" #include "ash/components/arc/test/fake_backup_settings_instance.h" #include "base/command_line.h" @@ -34,10 +36,13 @@ #include "chromeos/ash/services/network_config/public/cpp/cros_network_config_test_helper.h" #include "components/arc/test/fake_intent_helper_host.h" #include "components/arc/test/fake_intent_helper_instance.h" +#include "components/language/core/browser/pref_names.h" +#include "components/live_caption/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_store.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user_manager.h" +#include "testing/gmock/include/gmock/gmock.h" namespace arc { @@ -46,6 +51,15 @@ constexpr char kActionLocaionEnabled[] = "org.chromium.arc.intent_helper.SET_LOCATION_SERVICE_ENABLED"; +bool IsSameCaptionColor(const arc::mojom::CaptionColor* l, + const arc::mojom::CaptionColor* r) { + return l->red == r->red && l->blue == r->blue && l->green == r->green && + l->alpha == r->alpha; +} +MATCHER_P(VerifyCaptionColor, color, "") { + return IsSameCaptionColor(arg.get(), color); +} + class ArcSettingsServiceTest : public BrowserWithTestWindowTest { public: ArcSettingsServiceTest() @@ -96,6 +110,8 @@ intent_helper_host_ = std::make_unique<FakeIntentHelperHost>( arc_bridge_service()->intent_helper()); + app_host_ = std::make_unique<FakeAppHost>(arc_bridge_service()->app()); + app_instance_ = std::make_unique<FakeAppInstance>(app_host_.get()); ArcSettingsService* arc_settings_service = ArcSettingsService::GetForBrowserContext(profile()); DCHECK(arc_settings_service); @@ -111,6 +127,9 @@ &intent_helper_instance_); arc_bridge_service()->backup_settings()->CloseInstance( &backup_settings_instance_); + arc_bridge_service()->app()->CloseInstance(app_instance_.get()); + app_instance_.reset(); + app_host_.reset(); intent_helper_host_.reset(); arc_session_manager()->Shutdown(); @@ -134,6 +153,9 @@ arc_bridge_service()->intent_helper()->SetInstance( &intent_helper_instance_); WaitForInstanceReady(arc_bridge_service()->intent_helper()); + + arc_bridge_service()->app()->SetInstance(app_instance_.get()); + WaitForInstanceReady(arc_bridge_service()->app()); } ash::FakeChromeUserManager* user_manager() { @@ -164,6 +186,8 @@ std::unique_ptr<ArcServiceManager> arc_service_manager_; FakeIntentHelperInstance intent_helper_instance_; FakeBackupSettingsInstance backup_settings_instance_; + std::unique_ptr<FakeAppHost> app_host_; + std::unique_ptr<FakeAppInstance> app_instance_; }; } // namespace @@ -305,4 +329,51 @@ EXPECT_EQ(0U, intent_helper->GetBroadcastsForAction(kSetPageZoom).size()); } +TEST_F(ArcSettingsServiceTest, SetCaptionStyle) { + arc_session_manager()->RequestEnable(); + SetInstances(); + FakeIntentHelperInstance* intent_helper = intent_helper_instance(); + + PrefService* pref_service = profile()->GetPrefs(); + pref_service->SetString(::prefs::kAccessibilityCaptionsTextSize, "200%"); + pref_service->SetString(::prefs::kAccessibilityCaptionsTextColor, "10,20,30"); + pref_service->SetInteger(::prefs::kAccessibilityCaptionsTextOpacity, 90); + pref_service->SetString(::prefs::kAccessibilityCaptionsBackgroundColor, + "40,50,60"); + pref_service->SetInteger(::prefs::kAccessibilityCaptionsBackgroundOpacity, + 80); + pref_service->SetString(::prefs::kAccessibilityCaptionsTextShadow, + "-2px -2px 4px rgba(0, 0, 0, 0.5)"); + pref_service->SetString(::language::prefs::kApplicationLocale, "my_locale"); + + auto style = intent_helper->GetCaptionStyle(); + + ASSERT_TRUE(style); + EXPECT_EQ(2.0f, style->font_scale); + // Alpha value from 0.9 * 255. + EXPECT_THAT(arc::mojom::CaptionColor::New(230, 10, 20, 30), + VerifyCaptionColor(style->text_color.get())); + // Alpha value from 0.8 * 255. + EXPECT_THAT(arc::mojom::CaptionColor::New(204, 40, 50, 60), + VerifyCaptionColor(style->background_color.get())); + EXPECT_EQ("my_locale", style->user_locale); + EXPECT_EQ(arc::mojom::CaptionTextShadowType::kRaised, + style->text_shadow_type); +} + +TEST_F(ArcSettingsServiceTest, CaptionStyleNotSetReturnEmpty) { + arc_session_manager()->RequestEnable(); + SetInstances(); + FakeIntentHelperInstance* intent_helper = intent_helper_instance(); + + auto style = intent_helper->GetCaptionStyle(); + + ASSERT_TRUE(style); + EXPECT_EQ(1.0f, style->font_scale); + EXPECT_EQ(nullptr, style->text_color.get()); + EXPECT_EQ(nullptr, style->background_color.get()); + EXPECT_EQ("", style->user_locale); + EXPECT_EQ(arc::mojom::CaptionTextShadowType::kNone, style->text_shadow_type); +} + } // namespace arc
diff --git a/chrome/browser/ash/bruschetta/bruschetta_service_factory.cc b/chrome/browser/ash/bruschetta/bruschetta_service_factory.cc index 9e1ac22..f353493 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_service_factory.cc +++ b/chrome/browser/ash/bruschetta/bruschetta_service_factory.cc
@@ -40,10 +40,11 @@ BruschettaServiceFactory::~BruschettaServiceFactory() = default; -KeyedService* BruschettaServiceFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +BruschettaServiceFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { auto* profile = Profile::FromBrowserContext(context); - return new BruschettaService(profile); + return std::make_unique<BruschettaService>(profile); } // Force BruschettaService to be set up when a BrowserContext is
diff --git a/chrome/browser/ash/bruschetta/bruschetta_service_factory.h b/chrome/browser/ash/bruschetta/bruschetta_service_factory.h index e5998e6..8ad6048 100644 --- a/chrome/browser/ash/bruschetta/bruschetta_service_factory.h +++ b/chrome/browser/ash/bruschetta/bruschetta_service_factory.h
@@ -29,7 +29,7 @@ ~BruschettaServiceFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override;
diff --git a/chrome/browser/ash/crosapi/crosapi_util.cc b/chrome/browser/ash/crosapi/crosapi_util.cc index 70797d2..f537ac69 100644 --- a/chrome/browser/ash/crosapi/crosapi_util.cc +++ b/chrome/browser/ash/crosapi/crosapi_util.cc
@@ -21,6 +21,7 @@ #include "chrome/browser/ash/crosapi/idle_service_ash.h" #include "chrome/browser/ash/crosapi/native_theme_service_ash.h" #include "chrome/browser/ash/crosapi/resource_manager_ash.h" +#include "chrome/browser/ash/drive/file_system_util.h" #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" #include "chrome/browser/ash/policy/handlers/device_name_policy_handler.h" #include "chrome/browser/ash/settings/cros_settings.h" @@ -657,7 +658,7 @@ params->is_pdf_ocr_enabled = ::features::IsPdfOcrEnabled(); params->is_drivefs_bulk_pinning_enabled = - ash::features::IsDriveFsBulkPinningEnabled(); + drive::util::IsDriveFsBulkPinningEnabled(); params->is_sys_ui_downloads_integration_v2_enabled = ash::features::IsSysUiDownloadsIntegrationV2Enabled();
diff --git a/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.cc b/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.cc index 3b430de..42a9728 100644 --- a/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.cc +++ b/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.cc
@@ -106,9 +106,9 @@ PersistentForcedExtensionKeepAliveFactory:: ~PersistentForcedExtensionKeepAliveFactory() = default; -KeyedService* -PersistentForcedExtensionKeepAliveFactory::BuildServiceInstanceFor( - content::BrowserContext* context) const { +std::unique_ptr<KeyedService> PersistentForcedExtensionKeepAliveFactory:: + BuildServiceInstanceForBrowserContext( + content::BrowserContext* context) const { if (!browser_util::IsLacrosEnabled()) return nullptr; Profile* profile = Profile::FromBrowserContext(context); @@ -118,7 +118,7 @@ // Does not have to be registered on the sign-in profile. return nullptr; } - return new PersistentForcedExtensionKeepAlive( + return std::make_unique<PersistentForcedExtensionKeepAlive>( user_prefs::UserPrefs::Get(context)); }
diff --git a/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.h b/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.h index 3b2647b..8d37ca7 100644 --- a/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.h +++ b/chrome/browser/ash/crosapi/persistent_forced_extension_keep_alive.h
@@ -58,7 +58,7 @@ ~PersistentForcedExtensionKeepAliveFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override; };
diff --git a/chrome/browser/ash/crostini/crostini_manager_factory.cc b/chrome/browser/ash/crostini/crostini_manager_factory.cc index deea778..d5e69d1c 100644 --- a/chrome/browser/ash/crostini/crostini_manager_factory.cc +++ b/chrome/browser/ash/crostini/crostini_manager_factory.cc
@@ -34,10 +34,11 @@ CrostiniManagerFactory::~CrostiniManagerFactory() = default; -KeyedService* CrostiniManagerFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +CrostiniManagerFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - return new CrostiniManager(profile); + return std::make_unique<CrostiniManager>(profile); } } // namespace crostini
diff --git a/chrome/browser/ash/crostini/crostini_manager_factory.h b/chrome/browser/ash/crostini/crostini_manager_factory.h index 4bab885f..13e06f1 100644 --- a/chrome/browser/ash/crostini/crostini_manager_factory.h +++ b/chrome/browser/ash/crostini/crostini_manager_factory.h
@@ -29,7 +29,7 @@ ~CrostiniManagerFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/ash/crostini/crostini_metrics_service.cc b/chrome/browser/ash/crostini/crostini_metrics_service.cc index b3903d0..699f1ca 100644 --- a/chrome/browser/ash/crostini/crostini_metrics_service.cc +++ b/chrome/browser/ash/crostini/crostini_metrics_service.cc
@@ -42,10 +42,11 @@ CrostiniMetricsService::Factory::~Factory() = default; -KeyedService* CrostiniMetricsService::Factory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +CrostiniMetricsService::Factory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); - return new CrostiniMetricsService(profile); + return std::make_unique<CrostiniMetricsService>(profile); } bool CrostiniMetricsService::Factory::ServiceIsCreatedWithBrowserContext()
diff --git a/chrome/browser/ash/crostini/crostini_metrics_service.h b/chrome/browser/ash/crostini/crostini_metrics_service.h index 16812f62..9405d2b 100644 --- a/chrome/browser/ash/crostini/crostini_metrics_service.h +++ b/chrome/browser/ash/crostini/crostini_metrics_service.h
@@ -31,7 +31,7 @@ ~Factory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override; bool ServiceIsNULLWhileTesting() const override;
diff --git a/chrome/browser/ash/drive/file_system_util.cc b/chrome/browser/ash/drive/file_system_util.cc index 77da20aa..856e051 100644 --- a/chrome/browser/ash/drive/file_system_util.cc +++ b/chrome/browser/ash/drive/file_system_util.cc
@@ -119,8 +119,6 @@ } bool IsDriveFsBulkPinningEnabled(const Profile* const profile) { - DCHECK(profile); - // Check the "DriveFsBulkPinning" Chrome feature. If this feature is disabled, // then it probably means that the kill switch has been activated, and the // bulk-pinning feature should not be available. @@ -131,12 +129,13 @@ // Check the "drivefs.bulk_pinning.visible" boolean pref. If this pref is // false, then it probably means that it has been turned down by an enterprise // policy, and the bulk-pinning feature should not be available. - if (!profile->GetPrefs()->GetBoolean(prefs::kDriveFsBulkPinningVisible)) { + if (profile && + !profile->GetPrefs()->GetBoolean(prefs::kDriveFsBulkPinningVisible)) { return false; } // Does the user profile belong to a managed user or not? - if (!profile->GetProfilePolicyConnector()->IsManaged()) { + if (!profile || !profile->GetProfilePolicyConnector()->IsManaged()) { // Not a managed user. The bulk-pinning feature is available on suitable // devices, as controlled by the "FeatureManagementDriveFsBulkPinning" // Chrome feature. @@ -160,6 +159,12 @@ user->GetAccountId().GetUserEmail()); } +bool IsOobeDrivePinningEnabled(const Profile* const profile) { + return base::FeatureList::IsEnabled(ash::features::kOobeDrivePinning) && + ash::features::IsOobeChoobeEnabled() && + IsDriveFsBulkPinningEnabled(profile); +} + ConnectionStatusType GetDriveConnectionStatus(Profile* profile) { auto* drive_integration_service = GetIntegrationServiceByProfile(profile); if (!drive_integration_service) {
diff --git a/chrome/browser/ash/drive/file_system_util.h b/chrome/browser/ash/drive/file_system_util.h index 0bcf8c79..a3b7eecc 100644 --- a/chrome/browser/ash/drive/file_system_util.h +++ b/chrome/browser/ash/drive/file_system_util.h
@@ -40,7 +40,8 @@ // feature has been activated (turned on) by the user. It merely indicates // whether the bulk-pinning feature is available and can be turned on by the // user if they choose to. -bool IsDriveFsBulkPinningEnabled(const Profile* profile); +bool IsDriveFsBulkPinningEnabled(const Profile* profile = nullptr); +bool IsOobeDrivePinningEnabled(const Profile* profile = nullptr); // Enum type for describing the current connection status to Drive. enum ConnectionStatusType {
diff --git a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc index 19ab344a..605dd5294 100644 --- a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc +++ b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_impl.cc
@@ -458,6 +458,11 @@ } if (settings_.empty() || report_only_scans_) { + // Re-enter state progress if needed. + if (progress_->state != State::kInProgress) { + progress_->state = State::kInProgress; + progress_callback_.Run(*progress_); + } // Don't do any scans. It's either dlp-only restrictions (if `settings_` is // empty), or the scans will performed after the copy/move is completed // (report_only_scans_ is true).
diff --git a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc index 047cf58..5b3879e 100644 --- a/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc +++ b/chrome/browser/ash/file_manager/copy_or_move_io_task_policy_unittest.cc
@@ -1681,6 +1681,13 @@ Field(&ProgressStatus::sources, EntryStatusUrls(source_urls)), Property(&ProgressStatus::GetDestinationFolder, dest), Field(&ProgressStatus::state, State::kInProgress), + Field(&ProgressStatus::bytes_transferred, 0)))); + EXPECT_CALL( + progress_callback, + Run(AllOf(Field(&ProgressStatus::type, OperationType::kCopy), + Field(&ProgressStatus::sources, EntryStatusUrls(source_urls)), + Property(&ProgressStatus::GetDestinationFolder, dest), + Field(&ProgressStatus::state, State::kInProgress), Field(&ProgressStatus::bytes_transferred, 1 * kTestFileSize)))); // Task is completed. EXPECT_CALL(
diff --git a/chrome/browser/ash/file_manager/file_manager_jstest.cc b/chrome/browser/ash/file_manager/file_manager_jstest.cc index 65c540b..2c95f19 100644 --- a/chrome/browser/ash/file_manager/file_manager_jstest.cc +++ b/chrome/browser/ash/file_manager/file_manager_jstest.cc
@@ -348,7 +348,7 @@ } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, ReducerSearch) { - RunTestURL("state/reducers/search_unittest.js"); + RunTestURL("state/ducks/search_unittest.js"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, ReducerUiEntries) { @@ -356,11 +356,11 @@ } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, ReducerVolumes) { - RunTestURL("state/reducers/volumes_unittest.js"); + RunTestURL("state/ducks/volumes_unittest.js"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, ReducerBulkPinning) { - RunTestURL("state/reducers/bulk_pinning_unittest.js"); + RunTestURL("state/ducks/bulk_pinning_unittest.js"); } IN_PROC_BROWSER_TEST_F(FileManagerJsTest, ReducerPreferences) {
diff --git a/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc b/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc index 42af07c5..32ec1abe 100644 --- a/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc +++ b/chrome/browser/ash/file_manager/restore_to_destination_io_task_unittest.cc
@@ -321,9 +321,8 @@ EXPECT_CALL(progress_callback, Run(Field(&ProgressStatus::state, State::kPaused))); - // // TODO(b/295887686): Uncomment when fixed. - // EXPECT_CALL(progress_callback, - // Run(Field(&ProgressStatus::state, State::kInProgress))); + EXPECT_CALL(progress_callback, + Run(Field(&ProgressStatus::state, State::kInProgress))); EXPECT_CALL(complete_callback, Run(Field(&ProgressStatus::state, State::kSuccess))) .WillOnce(RunClosure(run_loop.QuitClosure())); @@ -353,6 +352,9 @@ base::DoNothing(), task_id, std::move(warning_files), policy::DlpFileDestination(), policy::dlp::FileAction::kMove); + auto* move_task = task->GetMoveTaskForTesting(); + ASSERT_TRUE(move_task); + EXPECT_TRUE(move_task->progress().IsPaused()); EXPECT_TRUE(task->progress().IsPaused()); // Resume. ResumeParams params; @@ -362,8 +364,8 @@ // start the transfer and set the correct state. std::move(result_callback).Run({}); - // TODO(b/295887686): Uncomment when fixed. - // EXPECT_FALSE(task->progress().IsPaused()); + EXPECT_FALSE(move_task->progress().IsPaused()); + EXPECT_FALSE(task->progress().IsPaused()); })); task->Execute(progress_callback.Get(), complete_callback.Get());
diff --git a/chrome/browser/ash/file_manager/volume.cc b/chrome/browser/ash/file_manager/volume.cc index b8f11494..b075ac1 100644 --- a/chrome/browser/ash/file_manager/volume.cc +++ b/chrome/browser/ash/file_manager/volume.cc
@@ -18,16 +18,12 @@ using l10n_util::GetStringUTF8; const char kMtpVolumeIdPrefix[] = "mtp:"; -// Registers |path| as the "Downloads" folder to the FileSystem API backend. -// If another folder is already mounted. It revokes and overrides the old one. -// Registers a mount point for Android files to ExternalMountPoints. VolumeType MountTypeToVolumeType(ash::MountType type) { switch (type) { case ash::MountType::kInvalid: - // We don't expect this value, but list here, so that when any value - // is added to the enum definition but this is not edited, the compiler - // warns it. - break; + // A zip mount with an invalid path will return type kInvalid. We can use + // a default VolumeType in this case. + return VOLUME_TYPE_DOWNLOADS_DIRECTORY; case ash::MountType::kDevice: return VOLUME_TYPE_REMOVABLE_DISK_PARTITION; case ash::MountType::kArchive:
diff --git a/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.cc b/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.cc index 40e12ff..9adbcf5 100644 --- a/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.cc +++ b/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.cc
@@ -42,7 +42,8 @@ PasswordSyncTokenVerifierFactory::~PasswordSyncTokenVerifierFactory() = default; -KeyedService* PasswordSyncTokenVerifierFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +PasswordSyncTokenVerifierFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); user_manager::User* user = ProfileHelper::Get()->GetUserByProfile(profile); @@ -52,7 +53,7 @@ !user->using_saml()) { return nullptr; } - return new PasswordSyncTokenVerifier(profile); + return std::make_unique<PasswordSyncTokenVerifier>(profile); } } // namespace ash
diff --git a/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.h b/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.h index 54a8146..933cd90 100644 --- a/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.h +++ b/chrome/browser/ash/login/saml/password_sync_token_verifier_factory.h
@@ -28,7 +28,7 @@ ~PasswordSyncTokenVerifierFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/ash/login/session/user_session_manager.cc b/chrome/browser/ash/login/session/user_session_manager.cc index cb6cec8..a9fd14d5 100644 --- a/chrome/browser/ash/login/session/user_session_manager.cc +++ b/chrome/browser/ash/login/session/user_session_manager.cc
@@ -51,6 +51,7 @@ #include "chrome/browser/ash/child_accounts/child_policy_observer.h" #include "chrome/browser/ash/crosapi/browser_data_back_migrator.h" #include "chrome/browser/ash/crosapi/browser_data_migrator.h" +#include "chrome/browser/ash/drive/file_system_util.h" #include "chrome/browser/ash/eol_notification.h" #include "chrome/browser/ash/first_run/first_run.h" #include "chrome/browser/ash/floating_workspace/floating_workspace_service.h" @@ -2150,7 +2151,7 @@ if (features::IsOobeDisplaySizeEnabled()) { DisplaySizeScreen::MaybeUpdateZoomFactor(profile); } - if (features::IsOobeDrivePinningEnabled()) { + if (drive::util::IsOobeDrivePinningEnabled(profile)) { DrivePinningScreen::ApplyDrivePinningPref(profile); } }
diff --git a/chrome/browser/ash/login/startup_utils.cc b/chrome/browser/ash/login/startup_utils.cc index eae9c94b..0fd6295 100644 --- a/chrome/browser/ash/login/startup_utils.cc +++ b/chrome/browser/ash/login/startup_utils.cc
@@ -18,6 +18,7 @@ #include "base/task/thread_pool.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" +#include "chrome/browser/ash/drive/file_system_util.h" #include "chrome/browser/ash/login/login_pref_names.h" #include "chrome/browser/ash/login/onboarding_user_activity_counter.h" #include "chrome/browser/ash/login/oobe_quick_start/oobe_quick_start_pref_names.h" @@ -147,7 +148,7 @@ registry->RegisterListPref(prefs::kChoobeCompletedScreens); } - if (features::IsOobeDrivePinningEnabled()) { + if (drive::util::IsOobeDrivePinningEnabled()) { registry->RegisterBooleanPref(prefs::kOobeDrivePinningEnabledDeferred, false); }
diff --git a/chrome/browser/ash/login/wizard_controller.cc b/chrome/browser/ash/login/wizard_controller.cc index 9ed340f..8be7dd0 100644 --- a/chrome/browser/ash/login/wizard_controller.cc +++ b/chrome/browser/ash/login/wizard_controller.cc
@@ -39,6 +39,7 @@ #include "chrome/browser/ash/app_mode/web_app/web_kiosk_app_manager.h" #include "chrome/browser/ash/arc/arc_util.h" #include "chrome/browser/ash/customization/customization_document.h" +#include "chrome/browser/ash/drive/file_system_util.h" #include "chrome/browser/ash/login/choobe_flow_controller.h" #include "chrome/browser/ash/login/configuration_keys.h" #include "chrome/browser/ash/login/demo_mode/demo_session.h" @@ -871,7 +872,7 @@ weak_factory_.GetWeakPtr()))); } - if (features::IsOobeDrivePinningEnabled()) { + if (drive::util::IsOobeDrivePinningEnabled()) { append(std::make_unique<DrivePinningScreen>( oobe_ui->GetView<DrivePinningScreenHandler>()->AsWeakPtr(), base::BindRepeating(&WizardController::OnDrivePinningScreenExit, @@ -1012,7 +1013,7 @@ } void WizardController::ShowDrivePinningScreen() { - if (features::IsOobeDrivePinningEnabled()) { + if (drive::util::IsOobeDrivePinningEnabled()) { SetCurrentScreen(GetScreen(DrivePinningScreenView::kScreenId)); } else { OnDrivePinningScreenExit(DrivePinningScreen::Result::NOT_APPLICABLE); @@ -1507,7 +1508,7 @@ OnScreenExit(ConsolidatedConsentScreenView::kScreenId, ConsolidatedConsentScreen::GetResultString(result)); - if (features::IsOobeDrivePinningEnabled() && + if (drive::util::IsOobeDrivePinningEnabled() && !GetScreen<DrivePinningScreen>()->CalculateRequiredSpace()) { LOG(ERROR) << "DriveFS bulk-pinning manager cannot calculate the required space";
diff --git a/chrome/browser/ash/sync/sync_error_notifier_factory.cc b/chrome/browser/ash/sync/sync_error_notifier_factory.cc index 63c2ea0..6ef7c0d89 100644 --- a/chrome/browser/ash/sync/sync_error_notifier_factory.cc +++ b/chrome/browser/ash/sync/sync_error_notifier_factory.cc
@@ -37,7 +37,8 @@ return instance.get(); } -KeyedService* SyncErrorNotifierFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +SyncErrorNotifierFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = static_cast<Profile*>(context); syncer::SyncService* sync_service = @@ -47,7 +48,7 @@ return nullptr; } - return new SyncErrorNotifier(sync_service, profile); + return std::make_unique<SyncErrorNotifier>(sync_service, profile); } } // namespace ash
diff --git a/chrome/browser/ash/sync/sync_error_notifier_factory.h b/chrome/browser/ash/sync/sync_error_notifier_factory.h index 42009f6..d5afeae 100644 --- a/chrome/browser/ash/sync/sync_error_notifier_factory.h +++ b/chrome/browser/ash/sync/sync_error_notifier_factory.h
@@ -36,7 +36,7 @@ ~SyncErrorNotifierFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const override; };
diff --git a/chrome/browser/cart/cart_service_factory.cc b/chrome/browser/cart/cart_service_factory.cc index 2887fa84..236aa6a 100644 --- a/chrome/browser/cart/cart_service_factory.cc +++ b/chrome/browser/cart/cart_service_factory.cc
@@ -55,7 +55,8 @@ CartServiceFactory::~CartServiceFactory() = default; -KeyedService* CartServiceFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +CartServiceFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { - return BuildCartService(context).release(); + return BuildCartService(context); }
diff --git a/chrome/browser/cart/cart_service_factory.h b/chrome/browser/cart/cart_service_factory.h index 8a0ae78..35d68b5 100644 --- a/chrome/browser/cart/cart_service_factory.h +++ b/chrome/browser/cart/cart_service_factory.h
@@ -30,7 +30,7 @@ CartServiceFactory(); ~CartServiceFactory() override; - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/drive/drive_notification_manager_factory.cc b/chrome/browser/drive/drive_notification_manager_factory.cc index 8e1649b..4bd2cb0 100644 --- a/chrome/browser/drive/drive_notification_manager_factory.cc +++ b/chrome/browser/drive/drive_notification_manager_factory.cc
@@ -72,9 +72,10 @@ DriveNotificationManagerFactory::~DriveNotificationManagerFactory() = default; -KeyedService* DriveNotificationManagerFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +DriveNotificationManagerFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { - return new DriveNotificationManager( + return std::make_unique<DriveNotificationManager>( GetInvalidationService(Profile::FromBrowserContext(context))); }
diff --git a/chrome/browser/drive/drive_notification_manager_factory.h b/chrome/browser/drive/drive_notification_manager_factory.h index db80c31..5c1be0f 100644 --- a/chrome/browser/drive/drive_notification_manager_factory.h +++ b/chrome/browser/drive/drive_notification_manager_factory.h
@@ -39,7 +39,7 @@ ~DriveNotificationManagerFactory() override; // BrowserContextKeyedServiceFactory implementation. - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_client.h b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_client.h index 0a02dfa..184b20c 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_client.h +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_client.h
@@ -24,11 +24,11 @@ MockSecureEnclaveClient(); ~MockSecureEnclaveClient() override; - MOCK_METHOD(base::ScopedCFTypeRef<SecKeyRef>, + MOCK_METHOD(base::apple::ScopedCFTypeRef<SecKeyRef>, CreatePermanentKey, (), (override)); - MOCK_METHOD(base::ScopedCFTypeRef<SecKeyRef>, + MOCK_METHOD(base::apple::ScopedCFTypeRef<SecKeyRef>, CopyStoredKey, (KeyType), (override));
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_helper.h b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_helper.h index b928846..5830d02 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_helper.h +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/mock_secure_enclave_helper.h
@@ -21,11 +21,11 @@ MockSecureEnclaveHelper(); ~MockSecureEnclaveHelper() override; - MOCK_METHOD(base::ScopedCFTypeRef<SecKeyRef>, + MOCK_METHOD(base::apple::ScopedCFTypeRef<SecKeyRef>, CreateSecureKey, (CFDictionaryRef, OSStatus*), (override)); - MOCK_METHOD(base::ScopedCFTypeRef<SecKeyRef>, + MOCK_METHOD(base::apple::ScopedCFTypeRef<SecKeyRef>, CopyKey, (CFDictionaryRef, OSStatus*), (override));
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client.h b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client.h index c8df020..f55c886 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client.h +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client.h
@@ -43,11 +43,12 @@ base::span<const uint8_t> wrapped_key_label); // Creates a new Secure Enclave private key with a permanent key label. - virtual base::ScopedCFTypeRef<SecKeyRef> CreatePermanentKey() = 0; + virtual base::apple::ScopedCFTypeRef<SecKeyRef> CreatePermanentKey() = 0; // Queries for the secure key using its label determined by the key `type`. // Returns the secure key reference or a nullptr if no key was found. - virtual base::ScopedCFTypeRef<SecKeyRef> CopyStoredKey(KeyType type) = 0; + virtual base::apple::ScopedCFTypeRef<SecKeyRef> CopyStoredKey( + KeyType type) = 0; // Deletes any key stored in `new_key_type` and updates the private key // storage in `current_key_type` to `new_key_type` and modifies the key label
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.h b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.h index 7283b99..c9c7c3e 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.h +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.h
@@ -27,8 +27,8 @@ ~SecureEnclaveClientImpl() override; // SecureEnclaveClient: - base::ScopedCFTypeRef<SecKeyRef> CreatePermanentKey() override; - base::ScopedCFTypeRef<SecKeyRef> CopyStoredKey(KeyType type) override; + base::apple::ScopedCFTypeRef<SecKeyRef> CreatePermanentKey() override; + base::apple::ScopedCFTypeRef<SecKeyRef> CopyStoredKey(KeyType type) override; bool UpdateStoredKeyLabel(KeyType current_key_type, KeyType new_key_type) override; bool DeleteKey(KeyType type) override;
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.mm b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.mm index 2c96783..7f7aadb 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.mm +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_impl.mm
@@ -56,8 +56,8 @@ // Creates and returns the secure enclave private key attributes used // for key creation. These key attributes represent the key created in // the permanent key location. -base::ScopedCFTypeRef<CFMutableDictionaryRef> CreateAttributesForKey() { - base::ScopedCFTypeRef<CFMutableDictionaryRef> attributes( +base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> CreateAttributesForKey() { + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> attributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -75,13 +75,13 @@ attributes, kSecAttrLabel, base::SysUTF8ToCFStringRef(constants::kDeviceTrustSigningKeyLabel)); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue(attributes, kSecPrivateKeyAttrs, private_key_params); CFDictionarySetValue(private_key_params, kSecAttrIsPermanent, kCFBooleanTrue); - base::ScopedCFTypeRef<SecAccessControlRef> access_control( + base::apple::ScopedCFTypeRef<SecAccessControlRef> access_control( SecAccessControlCreateWithFlags( kCFAllocatorDefault, // Private key can only be used when the device is unlocked. @@ -95,11 +95,12 @@ // Creates the query used for querying the keychain for the secure key // reference. -base::ScopedCFTypeRef<CFMutableDictionaryRef> CreateQueryForKey( +base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> CreateQueryForKey( SecureEnclaveClient::KeyType type) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> query(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue(query, kSecClass, kSecClassKey); CFDictionarySetValue(query, kSecAttrKeyType, kSecAttrKeyTypeECSECPrimeRandom); CFDictionarySetValue(query, kSecAttrLabel, @@ -118,10 +119,11 @@ SecureEnclaveClientImpl::~SecureEnclaveClientImpl() = default; -base::ScopedCFTypeRef<SecKeyRef> SecureEnclaveClientImpl::CreatePermanentKey() { +base::apple::ScopedCFTypeRef<SecKeyRef> +SecureEnclaveClientImpl::CreatePermanentKey() { auto attributes = CreateAttributesForKey(); if (!attributes) - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); // Deletes a permanent Secure Enclave key if it exists from a previous // key rotation. @@ -137,7 +139,7 @@ return key; } -base::ScopedCFTypeRef<SecKeyRef> SecureEnclaveClientImpl::CopyStoredKey( +base::apple::ScopedCFTypeRef<SecKeyRef> SecureEnclaveClientImpl::CopyStoredKey( KeyType type) { OSStatus status; auto key_ref = helper_->CopyKey(CreateQueryForKey(type), &status); @@ -153,7 +155,7 @@ // Deletes the `new_key_type` label if it exists in the keychain. DeleteKey(new_key_type); - base::ScopedCFTypeRef<CFMutableDictionaryRef> attributes_to_update( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> attributes_to_update( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -202,10 +204,10 @@ bool SecureEnclaveClientImpl::ExportPublicKey(SecKeyRef key, std::vector<uint8_t>& output) { - base::ScopedCFTypeRef<SecKeyRef> public_key = - base::ScopedCFTypeRef<SecKeyRef>(SecKeyCopyPublicKey(key)); - base::ScopedCFTypeRef<CFErrorRef> error; - base::ScopedCFTypeRef<CFDataRef> data_ref( + base::apple::ScopedCFTypeRef<SecKeyRef> public_key = + base::apple::ScopedCFTypeRef<SecKeyRef>(SecKeyCopyPublicKey(key)); + base::apple::ScopedCFTypeRef<CFErrorRef> error; + base::apple::ScopedCFTypeRef<CFDataRef> data_ref( SecKeyCopyExternalRepresentation(public_key, error.InitializeInto())); if (!data_ref) @@ -244,12 +246,12 @@ bool SecureEnclaveClientImpl::SignDataWithKey(SecKeyRef key, base::span<const uint8_t> data, std::vector<uint8_t>& output) { - base::ScopedCFTypeRef<CFDataRef> data_ref( + base::apple::ScopedCFTypeRef<CFDataRef> data_ref( CFDataCreate(kCFAllocatorDefault, data.data(), base::checked_cast<CFIndex>(data.size()))); - base::ScopedCFTypeRef<CFErrorRef> error; - base::ScopedCFTypeRef<CFDataRef> signature(SecKeyCreateSignature( + base::apple::ScopedCFTypeRef<CFErrorRef> error; + base::apple::ScopedCFTypeRef<CFDataRef> signature(SecKeyCreateSignature( key, kSecKeyAlgorithmECDSASignatureMessageX962SHA256, data_ref, error.InitializeInto()));
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_unittest.mm b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_unittest.mm index e114aae..1eb7f1b 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_unittest.mm +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_client_unittest.mm
@@ -65,7 +65,7 @@ // Creates a test key. void CreateAndSetTestKey() { - base::ScopedCFTypeRef<CFMutableDictionaryRef> test_attributes( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> test_attributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -75,7 +75,7 @@ kSecAttrKeyTypeECSECPrimeRandom); CFDictionarySetValue(test_attributes, kSecAttrKeySizeInBits, base::apple::NSToCFPtrCast(@256)); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -83,7 +83,7 @@ kCFBooleanFalse); CFDictionarySetValue(test_attributes, kSecPrivateKeyAttrs, private_key_params); - test_key_ = base::ScopedCFTypeRef<SecKeyRef>( + test_key_ = base::apple::ScopedCFTypeRef<SecKeyRef>( SecKeyCreateRandomKey(test_attributes, nullptr)); } @@ -99,7 +99,7 @@ raw_ptr<MockSecureEnclaveHelper, DanglingUntriaged> mock_secure_enclave_helper_ = nullptr; std::unique_ptr<SecureEnclaveClient> secure_enclave_client_; - base::ScopedCFTypeRef<SecKeyRef> test_key_; + base::apple::ScopedCFTypeRef<SecKeyRef> test_key_; }; // Tests that the CreatePermanentKey method invokes both the SE helper's @@ -165,7 +165,7 @@ .Times(1) .WillOnce([](CFDictionaryRef attributes, OSStatus* status) { *status = errSecItemNotFound; - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); }); EXPECT_FALSE(secure_enclave_client_->CreatePermanentKey()); @@ -214,7 +214,7 @@ .Times(2) .WillRepeatedly([](CFDictionaryRef query, OSStatus* status) { *status = errSecItemNotFound; - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); }); EXPECT_FALSE(secure_enclave_client_->CopyStoredKey( SecureEnclaveClient::KeyType::kPermanent)); @@ -506,7 +506,7 @@ .Times(1) .WillOnce([](CFDictionaryRef query, OSStatus* status) { *status = errSecItemNotFound; - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); }); EXPECT_FALSE(secure_enclave_client_->GetStoredKeyLabel( SecureEnclaveClient::KeyType::kTemporary, output)); @@ -565,7 +565,7 @@ .Times(1) .WillOnce([](CFDictionaryRef query, OSStatus* status) { *status = errSecItemNotFound; - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); }); EXPECT_FALSE(secure_enclave_client_->GetStoredKeyLabel( SecureEnclaveClient::KeyType::kPermanent, output));
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper.h b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper.h index f4b9e41b..34d4b0d 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper.h +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper.h
@@ -29,7 +29,7 @@ // `attributes`. Returns the key or a nullptr on failure. If an `error` // pointer is given, its value will be set to the OSStatus returned by the // Keychain API call. - virtual base::ScopedCFTypeRef<SecKeyRef> CreateSecureKey( + virtual base::apple::ScopedCFTypeRef<SecKeyRef> CreateSecureKey( CFDictionaryRef attributes, OSStatus* error) = 0; @@ -38,8 +38,8 @@ // if the key is not found. If an `error` pointer // is given, its value will be set to the OSStatus returned by the Keychain // API call. - virtual base::ScopedCFTypeRef<SecKeyRef> CopyKey(CFDictionaryRef query, - OSStatus* error) = 0; + virtual base::apple::ScopedCFTypeRef<SecKeyRef> CopyKey(CFDictionaryRef query, + OSStatus* error) = 0; // Uses the SecItemUpdate API to update the the key retrieved with the // `query` with its `attributes_to_update`. Returns the OSStatus value
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.h b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.h index 3d005c7..289bba1 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.h +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.h
@@ -20,10 +20,11 @@ ~SecureEnclaveHelperImpl() override; // SecureEnclaveHelper: - base::ScopedCFTypeRef<SecKeyRef> CreateSecureKey(CFDictionaryRef attributes, - OSStatus* error) override; - base::ScopedCFTypeRef<SecKeyRef> CopyKey(CFDictionaryRef query, - OSStatus* error) override; + base::apple::ScopedCFTypeRef<SecKeyRef> CreateSecureKey( + CFDictionaryRef attributes, + OSStatus* error) override; + base::apple::ScopedCFTypeRef<SecKeyRef> CopyKey(CFDictionaryRef query, + OSStatus* error) override; OSStatus Update(CFDictionaryRef query, CFDictionaryRef attributes_to_update) override; OSStatus Delete(CFDictionaryRef query) override;
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.mm b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.mm index aebac0b..170a852 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.mm +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_helper_impl.mm
@@ -17,11 +17,11 @@ SecureEnclaveHelperImpl::~SecureEnclaveHelperImpl() = default; -base::ScopedCFTypeRef<SecKeyRef> SecureEnclaveHelperImpl::CreateSecureKey( - CFDictionaryRef attributes, - OSStatus* error) { - base::ScopedCFTypeRef<CFErrorRef> error_ref; - base::ScopedCFTypeRef<SecKeyRef> key( +base::apple::ScopedCFTypeRef<SecKeyRef> +SecureEnclaveHelperImpl::CreateSecureKey(CFDictionaryRef attributes, + OSStatus* error) { + base::apple::ScopedCFTypeRef<CFErrorRef> error_ref; + base::apple::ScopedCFTypeRef<SecKeyRef> key( SecKeyCreateRandomKey(attributes, error_ref.InitializeInto())); if (error && error_ref) { @@ -31,10 +31,10 @@ return key; } -base::ScopedCFTypeRef<SecKeyRef> SecureEnclaveHelperImpl::CopyKey( +base::apple::ScopedCFTypeRef<SecKeyRef> SecureEnclaveHelperImpl::CopyKey( CFDictionaryRef query, OSStatus* error) { - base::ScopedCFTypeRef<SecKeyRef> key; + base::apple::ScopedCFTypeRef<SecKeyRef> key; OSStatus status = SecItemCopyMatching( query, const_cast<CFTypeRef*>( reinterpret_cast<const CFTypeRef*>(key.InitializeInto())));
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key.cc b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key.cc index 4d06cdd8..6c383cfb 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key.cc +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key.cc
@@ -23,7 +23,7 @@ // An implementation of crypto::UnexportableSigningKey. class SecureEnclaveSigningKey : public crypto::UnexportableSigningKey { public: - SecureEnclaveSigningKey(base::ScopedCFTypeRef<SecKeyRef> key, + SecureEnclaveSigningKey(base::apple::ScopedCFTypeRef<SecKeyRef> key, std::unique_ptr<SecureEnclaveClient> client, SecureEnclaveClient::KeyType type); ~SecureEnclaveSigningKey() override; @@ -36,13 +36,13 @@ base::span<const uint8_t> data) override; private: - base::ScopedCFTypeRef<SecKeyRef> key_; + base::apple::ScopedCFTypeRef<SecKeyRef> key_; std::unique_ptr<SecureEnclaveClient> client_; SecureEnclaveClient::KeyType key_type_; }; SecureEnclaveSigningKey::SecureEnclaveSigningKey( - base::ScopedCFTypeRef<SecKeyRef> key, + base::apple::ScopedCFTypeRef<SecKeyRef> key, std::unique_ptr<SecureEnclaveClient> client, SecureEnclaveClient::KeyType type) : key_(std::move(key)), client_(std::move(client)), key_type_(type) {
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key_unittest.mm b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key_unittest.mm index 96e59b6..62743f4 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key_unittest.mm +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/mac/secure_enclave_signing_key_unittest.mm
@@ -43,7 +43,7 @@ protected: // Creates a test key. void CreateTestKey() { - base::ScopedCFTypeRef<CFMutableDictionaryRef> test_attributes( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> test_attributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -52,7 +52,7 @@ kSecAttrKeyTypeECSECPrimeRandom); CFDictionarySetValue(test_attributes, kSecAttrKeySizeInBits, base::apple::NSToCFPtrCast(@256)); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -60,7 +60,7 @@ kCFBooleanFalse); CFDictionarySetValue(test_attributes, kSecPrivateKeyAttrs, private_key_params); - test_key_ = base::ScopedCFTypeRef<SecKeyRef>( + test_key_ = base::apple::ScopedCFTypeRef<SecKeyRef>( SecKeyCreateRandomKey(test_attributes, nullptr)); } @@ -78,7 +78,7 @@ raw_ptr<MockSecureEnclaveClient, DanglingUntriaged> mock_secure_enclave_client_ = nullptr; std::unique_ptr<crypto::UnexportableSigningKey> key_; - base::ScopedCFTypeRef<SecKeyRef> test_key_; + base::apple::ScopedCFTypeRef<SecKeyRef> test_key_; }; // Tests that the GenerateSigningKeySlowly method invokes the SE client's
diff --git a/chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/mac_key_persistence_delegate_unittest.mm b/chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/mac_key_persistence_delegate_unittest.mm index b7c6ff74..26f47f47 100644 --- a/chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/mac_key_persistence_delegate_unittest.mm +++ b/chrome/browser/enterprise/connectors/device_trust/key_management/core/persistence/mac_key_persistence_delegate_unittest.mm
@@ -53,8 +53,8 @@ } // Creates a test key. - base::ScopedCFTypeRef<SecKeyRef> CreateTestKey() { - base::ScopedCFTypeRef<CFMutableDictionaryRef> test_attributes( + base::apple::ScopedCFTypeRef<SecKeyRef> CreateTestKey() { + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> test_attributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -63,7 +63,7 @@ kSecAttrKeyTypeECSECPrimeRandom); CFDictionarySetValue(test_attributes, kSecAttrKeySizeInBits, base::apple::NSToCFPtrCast(@256)); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -71,7 +71,7 @@ kCFBooleanFalse); CFDictionarySetValue(test_attributes, kSecPrivateKeyAttrs, private_key_params); - return base::ScopedCFTypeRef<SecKeyRef>( + return base::apple::ScopedCFTypeRef<SecKeyRef>( SecKeyCreateRandomKey(test_attributes, nullptr)); } @@ -227,7 +227,7 @@ SetMockClient(); EXPECT_CALL(*mock_secure_enclave_client_, CreatePermanentKey()) - .WillOnce([]() { return base::ScopedCFTypeRef<SecKeyRef>(); }); + .WillOnce([]() { return base::apple::ScopedCFTypeRef<SecKeyRef>(); }); EXPECT_FALSE(persistence_delegate_->CreateKeyPair()); }
diff --git a/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc b/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc index b15829b..d652d41 100644 --- a/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc +++ b/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc
@@ -170,7 +170,7 @@ crypto::AppleKeychain keychain; UInt32 password_length = 0; void* password_data = nullptr; - base::ScopedCFTypeRef<SecKeychainItemRef> item_ref; + base::apple::ScopedCFTypeRef<SecKeychainItemRef> item_ref; status = keychain.FindGenericPassword( strlen(kServiceName), kServiceName, strlen(kAccountName), kAccountName, &password_length, &password_data, item_ref.InitializeInto());
diff --git a/chrome/browser/extensions/api/enterprise_reporting_private/keychain_data_helper_mac.cc b/chrome/browser/extensions/api/enterprise_reporting_private/keychain_data_helper_mac.cc index 12f6e1b..d09fabd 100644 --- a/chrome/browser/extensions/api/enterprise_reporting_private/keychain_data_helper_mac.cc +++ b/chrome/browser/extensions/api/enterprise_reporting_private/keychain_data_helper_mac.cc
@@ -30,7 +30,7 @@ return status; } - base::ScopedCFTypeRef<CFArrayRef> acl_list; + base::apple::ScopedCFTypeRef<CFArrayRef> acl_list; status = SecAccessCopyACLList(*access_ref, acl_list.InitializeInto()); if (status != noErr) { return status; @@ -39,8 +39,8 @@ for (CFIndex i = 0; i < CFArrayGetCount(acl_list); ++i) { SecACLRef acl = (SecACLRef)CFArrayGetValueAtIndex(acl_list, i); - base::ScopedCFTypeRef<CFArrayRef> app_list; - base::ScopedCFTypeRef<CFStringRef> description; + base::apple::ScopedCFTypeRef<CFArrayRef> app_list; + base::apple::ScopedCFTypeRef<CFStringRef> description; SecKeychainPromptSelector dummy_prompt_selector; status = SecACLCopyContents(acl, app_list.InitializeInto(), description.InitializeInto(), @@ -93,7 +93,7 @@ const_cast<char*>(account_name.data())}}; SecKeychainAttributeList attribute_list = {std::size(attributes), attributes}; - base::ScopedCFTypeRef<SecAccessRef> access_ref; + base::apple::ScopedCFTypeRef<SecAccessRef> access_ref; OSStatus status = CreateTargetAccess(base::SysUTF8ToCFStringRef(service_name), access_ref.InitializeInto()); if (status != noErr) { @@ -107,7 +107,7 @@ OSStatus VerifyKeychainForItemUnlocked(SecKeychainItemRef item_ref, bool* unlocked) { - base::ScopedCFTypeRef<SecKeychainRef> keychain; + base::apple::ScopedCFTypeRef<SecKeychainRef> keychain; OSStatus status = SecKeychainItemCopyKeychain(item_ref, keychain.InitializeInto()); if (status != noErr) { @@ -118,7 +118,7 @@ } OSStatus VerifyDefaultKeychainUnlocked(bool* unlocked) { - base::ScopedCFTypeRef<SecKeychainRef> keychain; + base::apple::ScopedCFTypeRef<SecKeychainRef> keychain; OSStatus status = SecKeychainCopyDefault(keychain.InitializeInto()); if (status != noErr) { return status;
diff --git a/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc b/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc index e69e9e7d..1ed76b2 100644 --- a/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc +++ b/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc
@@ -27,7 +27,7 @@ base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); // Match only writable whole-disks. - base::ScopedCFTypeRef<CFMutableDictionaryRef> matching( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> matching( IOServiceMatching(kIOMediaClass)); CFDictionaryAddValue(matching, CFSTR(kIOMediaWholeKey), kCFBooleanTrue); CFDictionaryAddValue(matching, CFSTR(kIOMediaWritableKey), kCFBooleanTrue); @@ -54,7 +54,7 @@ if (!is_suitable) continue; - base::ScopedCFTypeRef<CFMutableDictionaryRef> dict; + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> dict; if (IORegistryEntryCreateCFProperties(disk_obj, dict.InitializeInto(), kCFAllocatorDefault, 0) != KERN_SUCCESS) { @@ -62,12 +62,10 @@ continue; } - base::ScopedCFTypeRef<CFDictionaryRef> characteristics( + base::apple::ScopedCFTypeRef<CFDictionaryRef> characteristics( static_cast<CFDictionaryRef>(IORegistryEntrySearchCFProperty( - disk_obj, - kIOServicePlane, - CFSTR(kIOPropertyDeviceCharacteristicsKey), - kCFAllocatorDefault, + disk_obj, kIOServicePlane, + CFSTR(kIOPropertyDeviceCharacteristicsKey), kCFAllocatorDefault, kIORegistryIterateParents | kIORegistryIterateRecursively))); if (!characteristics) {
diff --git a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.cc b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.cc index 2891aad..399c04f1 100644 --- a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.cc +++ b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.cc
@@ -92,9 +92,10 @@ PasswordsPrivateDelegateFactory::~PasswordsPrivateDelegateFactory() = default; -KeyedService* PasswordsPrivateDelegateFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +PasswordsPrivateDelegateFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const { - return new PasswordsPrivateDelegateProxy(profile); + return std::make_unique<PasswordsPrivateDelegateProxy>(profile); } } // namespace extensions
diff --git a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.h b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.h index 2282426..49e0e0f 100644 --- a/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.h +++ b/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_factory.h
@@ -62,7 +62,7 @@ ~PasswordsPrivateDelegateFactory() override; // BrowserContextKeyedServiceFactory implementation. - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const override; };
diff --git a/chrome/browser/extensions/extension_garbage_collector_factory.cc b/chrome/browser/extensions/extension_garbage_collector_factory.cc index e550c68..b0253bf 100644 --- a/chrome/browser/extensions/extension_garbage_collector_factory.cc +++ b/chrome/browser/extensions/extension_garbage_collector_factory.cc
@@ -61,9 +61,10 @@ #endif } -KeyedService* ExtensionGarbageCollectorFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +ExtensionGarbageCollectorFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { - return BuildInstanceFor(context).release(); + return BuildInstanceFor(context); } bool ExtensionGarbageCollectorFactory::ServiceIsCreatedWithBrowserContext()
diff --git a/chrome/browser/extensions/extension_garbage_collector_factory.h b/chrome/browser/extensions/extension_garbage_collector_factory.h index c9f1cb4..0158e4f 100644 --- a/chrome/browser/extensions/extension_garbage_collector_factory.h +++ b/chrome/browser/extensions/extension_garbage_collector_factory.h
@@ -38,7 +38,7 @@ ~ExtensionGarbageCollectorFactory() override; // BrowserContextKeyedServiceFactory overrides: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override;
diff --git a/chrome/browser/extensions/extension_management.cc b/chrome/browser/extensions/extension_management.cc index 632f7a2b..cc2802df 100644 --- a/chrome/browser/extensions/extension_management.cc +++ b/chrome/browser/extensions/extension_management.cc
@@ -934,11 +934,13 @@ ExtensionManagementFactory::~ExtensionManagementFactory() {} -KeyedService* ExtensionManagementFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +ExtensionManagementFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { TRACE_EVENT0("browser,startup", "ExtensionManagementFactory::BuildServiceInstanceFor"); - return new ExtensionManagement(Profile::FromBrowserContext(context)); + return std::make_unique<ExtensionManagement>( + Profile::FromBrowserContext(context)); } void ExtensionManagementFactory::RegisterProfilePrefs(
diff --git a/chrome/browser/extensions/extension_management.h b/chrome/browser/extensions/extension_management.h index c5d648921..b568856 100644 --- a/chrome/browser/extensions/extension_management.h +++ b/chrome/browser/extensions/extension_management.h
@@ -364,7 +364,7 @@ ~ExtensionManagementFactory() override; // BrowserContextKeyedServiceExtensionManagementFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; void RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) override;
diff --git a/chrome/browser/extensions/extension_util.cc b/chrome/browser/extensions/extension_util.cc index 2d0a7b6c..522ad04 100644 --- a/chrome/browser/extensions/extension_util.cc +++ b/chrome/browser/extensions/extension_util.cc
@@ -71,6 +71,7 @@ return ReloadExtension(extension_id, context); } +#if BUILDFLAG(IS_CHROMEOS_ASH) // Returns true if the extension ID is found in the InstallForceList policy. Is // checked by HasIsolatedStorage() when the extension is not found in the // registry. @@ -91,6 +92,7 @@ } return false; } +#endif // BUILDFLAG(IS_CHROMEOS_ASH) // Returns true if the profile is a sign-in profile and the extension is policy // installed. `is_policy_installed` can be passed to the method if its value is
diff --git a/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.cc b/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.cc index d67bb262..725395c7 100644 --- a/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.cc +++ b/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.cc
@@ -40,9 +40,10 @@ GetInstance()->GetServiceForBrowserContext(browser_context, true)); } -KeyedService* FastCheckoutCapabilitiesFetcherFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +FastCheckoutCapabilitiesFetcherFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* browser_context) const { - return new FastCheckoutCapabilitiesFetcherImpl( + return std::make_unique<FastCheckoutCapabilitiesFetcherImpl>( browser_context->GetDefaultStoragePartition() ->GetURLLoaderFactoryForBrowserProcess()); }
diff --git a/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.h b/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.h index 2e7d8e26..84088c6 100644 --- a/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.h +++ b/chrome/browser/fast_checkout/fast_checkout_capabilities_fetcher_factory.h
@@ -27,7 +27,7 @@ content::BrowserContext* browser_context); private: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* browser_context) const override; };
diff --git a/chrome/browser/flag-metadata.json b/chrome/browser/flag-metadata.json index dcc54ed..5017eae 100644 --- a/chrome/browser/flag-metadata.json +++ b/chrome/browser/flag-metadata.json
@@ -6983,6 +6983,11 @@ "expiry_milestone": -1 }, { + "name": "rename-history-journeys", + "owners": [ "mahmadi", "chrome-journeys@google.com" ], + "expiry_milestone": 120 + }, + { "name": "render-arc-notifications-by-chrome", "owners": [ "shuminghao", "arc-framework@google.com" ], "expiry_milestone": 118
diff --git a/chrome/browser/flag_descriptions.cc b/chrome/browser/flag_descriptions.cc index cd2105e75..b0ffb65 100644 --- a/chrome/browser/flag_descriptions.cc +++ b/chrome/browser/flag_descriptions.cc
@@ -2035,6 +2035,9 @@ const char kJourneysName[] = "History Journeys"; const char kJourneysDescription[] = "Enables the History Journeys UI."; +const char kRenameJourneysName[] = "Rename History Journeys"; +const char kRenameJourneysDescription[] = "Renames History Journeys in the UI."; + const char kJourneysContentClusteringName[] = "History Journeys Content Clustering"; const char kJourneysContentClusteringDescription[] =
diff --git a/chrome/browser/flag_descriptions.h b/chrome/browser/flag_descriptions.h index b93dd2c..edd26ac 100644 --- a/chrome/browser/flag_descriptions.h +++ b/chrome/browser/flag_descriptions.h
@@ -1146,6 +1146,9 @@ extern const char kJourneysName[]; extern const char kJourneysDescription[]; +extern const char kRenameJourneysName[]; +extern const char kRenameJourneysDescription[]; + extern const char kJourneysContentClusteringName[]; extern const char kJourneysContentClusteringDescription[];
diff --git a/chrome/browser/history_clusters/history_clusters_internals_browsertest.cc b/chrome/browser/history_clusters/history_clusters_internals_browsertest.cc index e9b202bb7..81ad9e28 100644 --- a/chrome/browser/history_clusters/history_clusters_internals_browsertest.cc +++ b/chrome/browser/history_clusters/history_clusters_internals_browsertest.cc
@@ -111,7 +111,7 @@ // Trigger the debug messages to be added to the internals page. EXPECT_TRUE(ui_test_utils::NavigateToURL( - browser(), GURL(history_clusters::kChromeUIHistoryClustersURL))); + browser(), GURL(history_clusters::GetChromeUIHistoryClustersURL()))); // Verify that log messages are not added to the UI. There are still two // entries in the UI - the table header and the feature disabled message. @@ -150,7 +150,7 @@ // Trigger the debug messages to be added to the internals page. EXPECT_TRUE(ui_test_utils::NavigateToURL( - browser(), GURL(history_clusters::kChromeUIHistoryClustersURL))); + browser(), GURL(history_clusters::GetChromeUIHistoryClustersURL()))); // Verify that log messages are added to the UI. EXPECT_EQ(true, EvalJs(internals_page_web_contents, R"(
diff --git a/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc b/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc index b9bd4fe..ca0148c4 100644 --- a/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc +++ b/chrome/browser/history_clusters/history_clusters_metrics_browsertest.cc
@@ -113,7 +113,7 @@ // Navigates to the history clusters UI with `PAGE_TRANSITION_RELOAD`. Assumes // the current URL is also the history clusters UI. void RefreshHistoryClusters() { - NavigateParams params(browser(), GURL(kChromeUIHistoryClustersURL), + NavigateParams params(browser(), GURL(GetChromeUIHistoryClustersURL()), ui::PAGE_TRANSITION_RELOAD); ui_test_utils::NavigateToURL(¶ms); } @@ -150,8 +150,8 @@ MAYBE_DirectNavigationNoInteraction) { base::HistogramTester histogram_tester; ukm::TestAutoSetUkmRecorder ukm_recorder; - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), - GURL(kChromeUIHistoryClustersURL))); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(GetChromeUIHistoryClustersURL()))); EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("https://foo.com"))); auto entries = ukm_recorder.GetEntriesByName(ukm::builders::HistoryClusters::kEntryName); @@ -179,8 +179,8 @@ base::HistogramTester histogram_tester; ukm::TestAutoSetUkmRecorder ukm_recorder; - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), - GURL(kChromeUIHistoryClustersURL))); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(GetChromeUIHistoryClustersURL()))); EXPECT_TRUE(content::WaitForLoadStop( browser()->tab_strip_model()->GetActiveWebContents())); history_clusters::HistoryClustersHandler* page_handler = @@ -226,8 +226,8 @@ base::HistogramTester histogram_tester; ukm::TestAutoSetUkmRecorder ukm_recorder; - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), - GURL(kChromeUIHistoryClustersURL))); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(GetChromeUIHistoryClustersURL()))); ToggleToUi(UiTab::kBasicHistory); EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("https://foo.com"))); @@ -251,8 +251,8 @@ base::HistogramTester histogram_tester; ukm::TestAutoSetUkmRecorder ukm_recorder; - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), - GURL(kChromeUIHistoryClustersURL))); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(GetChromeUIHistoryClustersURL()))); ToggleToUi(UiTab::kBasicHistory); ToggleToUi(UiTab::kClustersUi);
diff --git a/chrome/browser/history_clusters/history_clusters_tab_helper.cc b/chrome/browser/history_clusters/history_clusters_tab_helper.cc index 2d2f5f3a..4beac89 100644 --- a/chrome/browser/history_clusters/history_clusters_tab_helper.cc +++ b/chrome/browser/history_clusters/history_clusters_tab_helper.cc
@@ -299,7 +299,7 @@ // The remaining logic only pertains to if the previously committed navigation // was the HistoryClusters UI. if (!IsHistoryPage(navigation_handle->GetWebContents()->GetLastCommittedURL(), - GURL(history_clusters::kChromeUIHistoryClustersURL))) { + GURL(history_clusters::GetChromeUIHistoryClustersURL()))) { return; } @@ -332,7 +332,7 @@ } if (!IsHistoryPage(navigation_handle->GetURL(), - GURL(history_clusters::kChromeUIHistoryClustersURL))) { + GURL(history_clusters::GetChromeUIHistoryClustersURL()))) { return; }
diff --git a/chrome/browser/icon_loader_mac.mm b/chrome/browser/icon_loader_mac.mm index 1f9067b..313d753 100644 --- a/chrome/browser/icon_loader_mac.mm +++ b/chrome/browser/icon_loader_mac.mm
@@ -62,9 +62,9 @@ // Remove the leading dot. extension_string.erase(extension_string.begin()); - base::ScopedCFTypeRef<CFStringRef> extension_cf = + base::apple::ScopedCFTypeRef<CFStringRef> extension_cf = base::SysUTF8ToCFStringRef(extension_string); - base::ScopedCFTypeRef<CFStringRef> cftype( + base::apple::ScopedCFTypeRef<CFStringRef> cftype( UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension_cf, /*inConformingToUTI=*/nullptr));
diff --git a/chrome/browser/mac/bluetooth_utility.mm b/chrome/browser/mac/bluetooth_utility.mm index b053c51a..d103ddc 100644 --- a/chrome/browser/mac/bluetooth_utility.mm +++ b/chrome/browser/mac/bluetooth_utility.mm
@@ -16,7 +16,7 @@ namespace bluetooth_utility { BluetoothAvailability GetBluetoothAvailability() { - base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( IOServiceMatching("IOBluetoothHCIController")); if (!matching_dict) return BLUETOOTH_AVAILABILITY_ERROR; @@ -34,7 +34,7 @@ while (device.reset(IOIteratorNext(scoped_iter.get())), device) { bluetooth_available = true; - base::ScopedCFTypeRef<CFMutableDictionaryRef> dict; + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> dict; kr = IORegistryEntryCreateCFProperties(device, dict.InitializeInto(), kCFAllocatorDefault, kNilOptions); if (kr != KERN_SUCCESS)
diff --git a/chrome/browser/mac/dock.mm b/chrome/browser/mac/dock.mm index cbf20386..14275d20 100644 --- a/chrome/browser/mac/dock.mm +++ b/chrome/browser/mac/dock.mm
@@ -50,7 +50,7 @@ // A wrapper around _CFURLCopyPropertyListRepresentation that operates on // Foundation data types and returns an autoreleased NSDictionary. NSDictionary* DockFileDataDictionaryForURL(NSURL* url) { - base::ScopedCFTypeRef<CFPropertyListRef> property_list( + base::apple::ScopedCFTypeRef<CFPropertyListRef> property_list( _CFURLCopyPropertyListRepresentation(base::apple::NSToCFPtrCast(url))); CFDictionaryRef dictionary = base::apple::CFCast<CFDictionaryRef>(property_list); @@ -64,7 +64,7 @@ // A wrapper around _CFURLCreateFromPropertyListRepresentation that operates // on Foundation data types and returns an autoreleased NSURL. NSURL* URLFromDockFileDataDictionary(NSDictionary* dictionary) { - base::ScopedCFTypeRef<CFURLRef> url( + base::apple::ScopedCFTypeRef<CFURLRef> url( _CFURLCreateFromPropertyListRepresentation( kCFAllocatorDefault, base::apple::NSToCFPtrCast(dictionary))); if (!url)
diff --git a/chrome/browser/mac/install_from_dmg.mm b/chrome/browser/mac/install_from_dmg.mm index 2f2d138f..1427a04 100644 --- a/chrome/browser/mac/install_from_dmg.mm +++ b/chrome/browser/mac/install_from_dmg.mm
@@ -125,7 +125,7 @@ GetDiskImageAncestorForMedia("AppleDiskImageDevice", media); if (di_device) { if (image_path) { - base::ScopedCFTypeRef<CFTypeRef> disk_image_url_cftyperef( + base::apple::ScopedCFTypeRef<CFTypeRef> disk_image_url_cftyperef( IORegistryEntryCreateCFProperty(di_device, CFSTR("DiskImageURL"), /*allocator=*/nullptr, /*options=*/0)); @@ -138,21 +138,23 @@ CFStringRef disk_image_url_string = base::apple::CFCast<CFStringRef>(disk_image_url_cftyperef.get()); if (!disk_image_url_string) { - base::ScopedCFTypeRef<CFStringRef> observed_type_cf( + base::apple::ScopedCFTypeRef<CFStringRef> observed_type_cf( CFCopyTypeIDDescription(CFGetTypeID(disk_image_url_cftyperef))); LOG(ERROR) << "DiskImageURL: expected CFString, observed " << base::SysCFStringRefToUTF8(observed_type_cf); return true; } - base::ScopedCFTypeRef<CFURLRef> disk_image_url(CFURLCreateWithString( - /*allocator=*/nullptr, disk_image_url_string, /*baseURL=*/nullptr)); + base::apple::ScopedCFTypeRef<CFURLRef> disk_image_url( + CFURLCreateWithString( + /*allocator=*/nullptr, disk_image_url_string, + /*baseURL=*/nullptr)); if (!disk_image_url) { LOG(ERROR) << "CFURLCreateWithString failed"; return true; } - base::ScopedCFTypeRef<CFStringRef> disk_image_path( + base::apple::ScopedCFTypeRef<CFStringRef> disk_image_path( CFURLCopyFileSystemPath(disk_image_url, kCFURLPOSIXPathStyle)); if (!disk_image_path) { LOG(ERROR) << "CFURLCopyFileSystemPath failed"; @@ -173,7 +175,7 @@ GetDiskImageAncestorForMedia("IOHDIXHDDrive", media); if (hdix_drive) { if (image_path) { - base::ScopedCFTypeRef<CFTypeRef> image_path_cftyperef( + base::apple::ScopedCFTypeRef<CFTypeRef> image_path_cftyperef( IORegistryEntryCreateCFProperty(hdix_drive, CFSTR("image-path"), /*allocator=*/nullptr, /*options=*/0)); @@ -185,7 +187,7 @@ CFDataRef image_path_data = base::apple::CFCast<CFDataRef>(image_path_cftyperef.get()); if (!image_path_data) { - base::ScopedCFTypeRef<CFStringRef> observed_type_cf( + base::apple::ScopedCFTypeRef<CFStringRef> observed_type_cf( CFCopyTypeIDDescription(CFGetTypeID(image_path_cftyperef))); LOG(ERROR) << "image-path: expected CFData, observed " << base::SysCFStringRefToUTF8(observed_type_cf); @@ -244,8 +246,9 @@ out_dmg_bsd_device_name->assign(dmg_bsd_device_name); } - base::ScopedCFTypeRef<CFMutableDictionaryRef> match_dict(IOBSDNameMatching( - kIOMasterPortDefault, /*options=*/0, dmg_bsd_device_name)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> match_dict( + IOBSDNameMatching(kIOMasterPortDefault, /*options=*/0, + dmg_bsd_device_name)); if (!match_dict) { LOG(ERROR) << "IOBSDNameMatching " << dmg_bsd_device_name; return DiskImageStatusFailure; @@ -554,7 +557,7 @@ // A small structure used to ferry data between SynchronousDAOperation and // SynchronousDACallbackAdapter. struct SynchronousDACallbackData { - base::ScopedCFTypeRef<DADissenterRef> dissenter; + base::apple::ScopedCFTypeRef<DADissenterRef> dissenter; bool callback_called = false; bool run_loop_running = false; bool can_log = true; @@ -645,14 +648,14 @@ } // namespace void EjectAndTrashDiskImage(const std::string& dmg_bsd_device_name) { - base::ScopedCFTypeRef<DASessionRef> session( + base::apple::ScopedCFTypeRef<DASessionRef> session( DASessionCreate(/*allocator=*/nullptr)); if (!session.get()) { LOG(ERROR) << "DASessionCreate"; return; } - base::ScopedCFTypeRef<DADiskRef> disk(DADiskCreateFromBSDName( + base::apple::ScopedCFTypeRef<DADiskRef> disk(DADiskCreateFromBSDName( /*allocator=*/nullptr, session, dmg_bsd_device_name.c_str())); if (!disk.get()) { LOG(ERROR) << "DADiskCreateFromBSDName";
diff --git a/chrome/browser/media/webrtc/window_icon_util_mac.mm b/chrome/browser/media/webrtc/window_icon_util_mac.mm index 7838237..dc28e45 100644 --- a/chrome/browser/media/webrtc/window_icon_util_mac.mm +++ b/chrome/browser/media/webrtc/window_icon_util_mac.mm
@@ -16,9 +16,9 @@ CGWindowID ids[1]; ids[0] = id.id; - base::ScopedCFTypeRef<CFArrayRef> window_id_array(CFArrayCreate( + base::apple::ScopedCFTypeRef<CFArrayRef> window_id_array(CFArrayCreate( nullptr, reinterpret_cast<const void**>(&ids), std::size(ids), nullptr)); - base::ScopedCFTypeRef<CFArrayRef> window_array( + base::apple::ScopedCFTypeRef<CFArrayRef> window_array( CGWindowListCreateDescriptionFromArray(window_id_array)); if (!window_array || 0 == CFArrayGetCount(window_array)) { return gfx::ImageSkia(); @@ -59,7 +59,8 @@ } CGDataProviderRef provider = CGImageGetDataProvider(cg_icon_image); - base::ScopedCFTypeRef<CFDataRef> cf_data(CGDataProviderCopyData(provider)); + base::apple::ScopedCFTypeRef<CFDataRef> cf_data( + CGDataProviderCopyData(provider)); int width = CGImageGetWidth(cg_icon_image); int height = CGImageGetHeight(cg_icon_image);
diff --git a/chrome/browser/net/profile_network_context_service_factory.cc b/chrome/browser/net/profile_network_context_service_factory.cc index 6ac83fcc6..14ac2ce 100644 --- a/chrome/browser/net/profile_network_context_service_factory.cc +++ b/chrome/browser/net/profile_network_context_service_factory.cc
@@ -61,9 +61,11 @@ ProfileNetworkContextServiceFactory::~ProfileNetworkContextServiceFactory() = default; -KeyedService* ProfileNetworkContextServiceFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +ProfileNetworkContextServiceFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const { - return new ProfileNetworkContextService(Profile::FromBrowserContext(profile)); + return std::make_unique<ProfileNetworkContextService>( + Profile::FromBrowserContext(profile)); } bool ProfileNetworkContextServiceFactory::ServiceIsNULLWhileTesting() const {
diff --git a/chrome/browser/net/profile_network_context_service_factory.h b/chrome/browser/net/profile_network_context_service_factory.h index 0ab8e15..6348cde 100644 --- a/chrome/browser/net/profile_network_context_service_factory.h +++ b/chrome/browser/net/profile_network_context_service_factory.h
@@ -37,7 +37,7 @@ ~ProfileNetworkContextServiceFactory() override; // BrowserContextKeyedServiceFactory implementation: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const override; bool ServiceIsNULLWhileTesting() const override; };
diff --git a/chrome/browser/net/sandboxed_network_change_notifier_win_browsertest.cc b/chrome/browser/net/sandboxed_network_change_notifier_win_browsertest.cc new file mode 100644 index 0000000..173ea4d --- /dev/null +++ b/chrome/browser/net/sandboxed_network_change_notifier_win_browsertest.cc
@@ -0,0 +1,203 @@ +// 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 "services/network/public/mojom/network_service.mojom.h" + +#include <windows.h> // Must be in front of other Windows header files. + +#include <initguid.h> // Must be in front of devpkey.h. + +// Must be in front of Windows includes because they define LogSeverity and this +// breaks gmock. +#include "testing/gmock/include/gmock/gmock.h" + +#include <cfgmgr32.h> +#include <devpkey.h> +#include <newdev.h> +#include <ntddser.h> +#include <setupapi.h> +#include <shlobj.h> +#include <stdint.h> + +#include "base/base_paths_win.h" +#include "base/files/file_path.h" +#include "base/functional/callback_helpers.h" +#include "base/path_service.h" +#include "base/run_loop.h" +#include "base/test/bind.h" +#include "base/test/scoped_feature_list.h" +#include "base/win/scoped_devinfo.h" +#include "base/win/win_util.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "content/public/browser/network_service_instance.h" +#include "content/public/common/content_features.h" +#include "content/public/test/browser_test.h" +#include "sandbox/policy/features.h" +#include "services/network/public/mojom/network_change_manager.mojom.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +namespace content { + +namespace { + +absl::optional<base::ScopedClosureRunner> InstallAdapter( + const base::FilePath& inf, + const std::wstring hwid) { + GUID guid; + wchar_t className[MAX_CLASS_NAME_LEN]; + + if (!::SetupDiGetINFClass(inf.value().c_str(), &guid, className, + MAX_CLASS_NAME_LEN, 0)) { + PLOG(ERROR) << "Unable to create SetupDiGetINFClass."; + return absl::nullopt; + } + + base::win::ScopedDevInfo dev_info( + ::SetupDiCreateDeviceInfoList(&guid, nullptr)); + if (!dev_info.is_valid()) { + PLOG(ERROR) << "Unable to call SetupDiCreateDeviceInfoList."; + return absl::nullopt; + } + + SP_DEVINFO_DATA deviceInfoData = {}; + deviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); + + if (!::SetupDiCreateDeviceInfo(dev_info.get(), className, &guid, nullptr, + nullptr, DICD_GENERATE_ID, &deviceInfoData)) { + PLOG(ERROR) << "Unable to call SetupDiCreateDeviceInfo"; + return absl::nullopt; + } + + if (!::SetupDiSetDeviceRegistryProperty( + dev_info.get(), &deviceInfoData, SPDRP_HARDWAREID, + reinterpret_cast<const BYTE*>(hwid.c_str()), + (hwid.length() + 1) * sizeof(wchar_t))) { + PLOG(ERROR) << "Unable to call SetupDiSetDeviceRegistryProperty."; + return absl::nullopt; + } + + if (!::SetupDiCallClassInstaller(DIF_REGISTERDEVICE, dev_info.get(), + &deviceInfoData)) { + PLOG(ERROR) << "Unable to call SetupDiCallClassInstaller."; + return absl::nullopt; + } + + BOOL reboot_required = FALSE; + if (!::UpdateDriverForPlugAndPlayDevices( + nullptr, hwid.c_str(), inf.value().c_str(), 0, &reboot_required)) { + PLOG(ERROR) << "Unable to call UpdateDriverForPlugAndPlayDevices."; + return absl::nullopt; + } + + return base::ScopedClosureRunner(base::BindOnce( + [](DEVINST devinst) { std::ignore = ::CM_Uninstall_DevNode(devinst, 0); }, + deviceInfoData.DevInst)); +} + +class MockNetworkChangeManagerClient + : public network::mojom::NetworkChangeManagerClient { + public: + MockNetworkChangeManagerClient( + network::mojom::NetworkChangeManager* network_change_manager) { + mojo::PendingRemote<network::mojom::NetworkChangeManagerClient> + client_remote; + receiver_.Bind(client_remote.InitWithNewPipeAndPassReceiver()); + network_change_manager->RequestNotifications(std::move(client_remote)); + } + + MockNetworkChangeManagerClient(const MockNetworkChangeManagerClient&) = + delete; + MockNetworkChangeManagerClient& operator=( + const MockNetworkChangeManagerClient&) = delete; + + ~MockNetworkChangeManagerClient() override {} + + // NetworkChangeManagerClient implementation: + MOCK_METHOD(void, + OnInitialConnectionType, + (network::mojom::ConnectionType type), + (override)); + MOCK_METHOD(void, + OnNetworkChanged, + (network::mojom::ConnectionType type), + (override)); + + private: + mojo::Receiver<network::mojom::NetworkChangeManagerClient> receiver_{this}; +}; + +} // namespace + +class SandboxedNetworkChangeNotifierBrowserTest + : public InProcessBrowserTest, + public ::testing::WithParamInterface</*sandboxed=*/bool> { + public: + SandboxedNetworkChangeNotifierBrowserTest() { + if (GetParam()) { + scoped_feature_list_.InitWithFeatures( + {sandbox::policy::features::kNetworkServiceSandbox}, + {features::kNetworkServiceInProcess}); + } else { + scoped_feature_list_.InitWithFeatures( + {}, {features::kNetworkServiceInProcess, + sandbox::policy::features::kNetworkServiceSandbox}); + } + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; +}; + +// Test that dynamically adds a new adapter to the host, and verifies that a +// network change notification is sent from the network service to the browser +// process. +// The network service is able to see these network adapter changes, as it is +// created with the LPAC "internetClient" capability. See +// https://learn.microsoft.com/en-us/windows/uwp/packaging/app-capability-declarations +IN_PROC_BROWSER_TEST_P(SandboxedNetworkChangeNotifierBrowserTest, + AddNetworkAdapter) { + if (!::IsUserAnAdmin()) { + GTEST_SKIP() << "This test requires running elevated."; + } + mojo::Remote<network::mojom::NetworkChangeManager> network_change_manager; + GetNetworkService()->GetNetworkChangeManager( + network_change_manager.BindNewPipeAndPassReceiver()); + base::RunLoop run_loop; + + ::testing::StrictMock<MockNetworkChangeManagerClient> mock( + network_change_manager.get()); + + ::testing::InSequence order; + // OnInitialConnectionType can be called with CONNECTION_UNKNOWN or + // CONNECTION_ETHERNET. + EXPECT_CALL(mock, OnInitialConnectionType(::testing::AnyOf( + network::mojom::ConnectionType::CONNECTION_UNKNOWN, + network::mojom::ConnectionType::CONNECTION_ETHERNET))); + // NetworkChangeManager sends two notifications, the first is always + // CONNECTION_NONE, followed by the actual ConnectionType. See + // `network_change_manager.mojom`. + EXPECT_CALL( + mock, OnNetworkChanged(network::mojom::ConnectionType::CONNECTION_NONE)); + EXPECT_CALL(mock, OnNetworkChanged( + network::mojom::ConnectionType::CONNECTION_ETHERNET)) + .WillOnce([&run_loop]() { run_loop.Quit(); }); + + // Install a new network card. + base::FilePath dir_windows; + ASSERT_TRUE(base::PathService::Get(base::DIR_WINDOWS, &dir_windows)); + auto inst = InstallAdapter( + dir_windows.AppendASCII("Inf").AppendASCII("netloop.inf"), L"*MSLOOP"); + ASSERT_TRUE(inst); + + run_loop.Run(); +} + +INSTANTIATE_TEST_SUITE_P(, + SandboxedNetworkChangeNotifierBrowserTest, + ::testing::Bool(), + [](const auto& info) { + return info.param ? "Sandboxed" : "Unsandboxed"; + }); +} // namespace content
diff --git a/chrome/browser/new_tab_page/modules/new_tab_page_modules.cc b/chrome/browser/new_tab_page/modules/new_tab_page_modules.cc index 8485511..4e25f05 100644 --- a/chrome/browser/new_tab_page/modules/new_tab_page_modules.cc +++ b/chrome/browser/new_tab_page/modules/new_tab_page_modules.cc
@@ -15,6 +15,7 @@ #include "chrome/browser/new_tab_page/new_tab_page_util.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/grit/generated_resources.h" +#include "components/history_clusters/core/features.h" #include "components/page_image_service/features.h" #include "components/search/ntp_features.h" #include "components/signin/public/identity_manager/accounts_in_cookie_jar_info.h" @@ -29,8 +30,11 @@ if (base::FeatureList::IsEnabled(ntp_features::kNtpHistoryClustersModule) && base::FeatureList::IsEnabled(page_image_service::kImageService)) { - details.emplace_back("history_clusters", - IDS_HISTORY_CLUSTERS_JOURNEYS_TAB_LABEL); + details.emplace_back( + "history_clusters", + base::FeatureList::IsEnabled(history_clusters::kRenameJourneys) + ? IDS_OMNIBOX_HISTORY_CLUSTERS_SEARCH_HINT + : IDS_HISTORY_CLUSTERS_JOURNEYS_TAB_LABEL); } if (IsRecipeTasksModuleEnabled()) {
diff --git a/chrome/browser/password_manager/password_manager_util_mac.mm b/chrome/browser/password_manager/password_manager_util_mac.mm index d27cbf7..a7d80905 100644 --- a/chrome/browser/password_manager/password_manager_util_mac.mm +++ b/chrome/browser/password_manager/password_manager_util_mac.mm
@@ -70,7 +70,7 @@ AuthorizationItem right_items[] = {{rightName.UTF8String, 0, nullptr, 0}}; AuthorizationRights rights = {std::size(right_items), right_items}; - base::ScopedCFTypeRef<CFStringRef> prompt = + base::apple::ScopedCFTypeRef<CFStringRef> prompt = base::SysUTF16ToCFStringRef(prompt_string); // Pass kAuthorizationFlagDestroyRights to prevent the OS from saving the
diff --git a/chrome/browser/policy/browser_dm_token_storage_mac.mm b/chrome/browser/policy/browser_dm_token_storage_mac.mm index 7598e551..22fdb0e 100644 --- a/chrome/browser/policy/browser_dm_token_storage_mac.mm +++ b/chrome/browser/policy/browser_dm_token_storage_mac.mm
@@ -106,7 +106,7 @@ bool GetEnrollmentTokenFromPolicy(std::string* enrollment_token) { // Since the configuration management infrastructure is not initialized when // this code runs, read the policy preference directly. - base::ScopedCFTypeRef<CFPropertyListRef> value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( CFPreferencesCopyAppValue(kEnrollmentTokenPolicyName, kBundleId)); // Read the enrollment token from the new location. If that fails, try the old @@ -138,8 +138,9 @@ } absl::optional<bool> IsEnrollmentMandatoryByPolicy() { - base::ScopedCFTypeRef<CFPropertyListRef> value(CFPreferencesCopyAppValue( - kEnrollmentMandatoryOptionPolicyName, kBundleId)); + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( + CFPreferencesCopyAppValue(kEnrollmentMandatoryOptionPolicyName, + kBundleId)); if (!value || !CFPreferencesAppValueIsForced( kEnrollmentMandatoryOptionPolicyName, kBundleId)) {
diff --git a/chrome/browser/policy/chrome_browser_policy_connector.cc b/chrome/browser/policy/chrome_browser_policy_connector.cc index 941b9a4f..bf03f3d 100644 --- a/chrome/browser/policy/chrome_browser_policy_connector.cc +++ b/chrome/browser/policy/chrome_browser_policy_connector.cc
@@ -323,7 +323,7 @@ // policies. CFStringRef bundle_id = CFSTR("com.google.Chrome"); #else - base::ScopedCFTypeRef<CFStringRef> bundle_id( + base::apple::ScopedCFTypeRef<CFStringRef> bundle_id( base::SysUTF8ToCFStringRef(base::apple::BaseBundleID())); #endif auto loader = std::make_unique<PolicyLoaderMac>(
diff --git a/chrome/browser/policy/policy_path_parser_mac.mm b/chrome/browser/policy/policy_path_parser_mac.mm index d374ab3a..44a46c9 100644 --- a/chrome/browser/policy/policy_path_parser_mac.mm +++ b/chrome/browser/policy/policy_path_parser_mac.mm
@@ -76,9 +76,9 @@ position = result.find(kMachineNamePolicyVarName); if (position != std::string::npos) { SCDynamicStoreContext context = {0, nullptr, nullptr, nullptr}; - base::ScopedCFTypeRef<SCDynamicStoreRef> store(SCDynamicStoreCreate( + base::apple::ScopedCFTypeRef<SCDynamicStoreRef> store(SCDynamicStoreCreate( kCFAllocatorDefault, CFSTR("policy_subsystem"), nullptr, &context)); - base::ScopedCFTypeRef<CFStringRef> machine_name( + base::apple::ScopedCFTypeRef<CFStringRef> machine_name( SCDynamicStoreCopyLocalHostName(store)); if (machine_name) { result.replace(position, strlen(kMachineNamePolicyVarName), @@ -103,13 +103,13 @@ // policies. CFStringRef bundle_id = CFSTR("com.google.Chrome"); #else - base::ScopedCFTypeRef<CFStringRef> bundle_id( + base::apple::ScopedCFTypeRef<CFStringRef> bundle_id( base::SysUTF8ToCFStringRef(base::apple::BaseBundleID())); #endif - base::ScopedCFTypeRef<CFStringRef> key( + base::apple::ScopedCFTypeRef<CFStringRef> key( base::SysUTF8ToCFStringRef(policy::key::kUserDataDir)); - base::ScopedCFTypeRef<CFPropertyListRef> value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( CFPreferencesCopyAppValue(key, bundle_id)); if (!value || !CFPreferencesAppValueIsForced(key, bundle_id))
diff --git a/chrome/browser/policy/test/history_clusters_policy_browsertest.cc b/chrome/browser/policy/test/history_clusters_policy_browsertest.cc new file mode 100644 index 0000000..5a84d1e --- /dev/null +++ b/chrome/browser/policy/test/history_clusters_policy_browsertest.cc
@@ -0,0 +1,106 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/scoped_feature_list.h" +#include "chrome/browser/history_clusters/history_clusters_service_factory.h" +#include "chrome/browser/policy/policy_test_utils.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "components/history_clusters/core/config.h" +#include "components/history_clusters/core/features.h" +#include "components/history_clusters/core/history_clusters_prefs.h" +#include "components/history_clusters/core/history_clusters_service.h" +#include "components/policy/core/common/policy_map.h" +#include "components/policy/core/common/policy_types.h" +#include "components/policy/policy_constants.h" +#include "components/prefs/pref_service.h" +#include "content/public/test/browser_test.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace policy { + +// Tests setting the visibility of the History Clusters by policy. +class HistoryClustersPolicyTest : public PolicyTest, + public testing::WithParamInterface<bool> { + public: + HistoryClustersPolicyTest() { + if (GetParam()) { + scoped_feature_list_.InitAndEnableFeature( + history_clusters::kRenameJourneys); + } else { + scoped_feature_list_.InitAndDisableFeature( + history_clusters::kRenameJourneys); + } + } + + void SetUp() override { + PolicyTest::SetUp(); + + config_.is_journeys_enabled_no_locale_check = true; + history_clusters::SetConfigForTesting(config_); + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; + history_clusters::Config config_; +}; + +INSTANTIATE_TEST_SUITE_P(RenameJourneys, + HistoryClustersPolicyTest, + testing::Bool()); + +IN_PROC_BROWSER_TEST_P(HistoryClustersPolicyTest, HistoryClustersVisible) { + auto* history_clusters_service = + HistoryClustersServiceFactory::GetForBrowserContext(browser()->profile()); + PrefService* prefs = browser()->profile()->GetPrefs(); + PolicyMap policies; + + // Verify that history clusters are visible by default. + EXPECT_TRUE(prefs->GetBoolean(history_clusters::prefs::kVisible)); + EXPECT_FALSE(prefs->IsManagedPreference(history_clusters::prefs::kVisible)); + EXPECT_TRUE(history_clusters_service->IsJourneysEnabledAndVisible()); + + // Verify that history clusters can be hidden by prefs. + prefs->SetBoolean(history_clusters::prefs::kVisible, false); + + EXPECT_FALSE(prefs->GetBoolean(history_clusters::prefs::kVisible)); + EXPECT_FALSE(prefs->IsManagedPreference(history_clusters::prefs::kVisible)); + // When history_clusters::kRenameJourneys is enabled, history clusters are + // always visible unless the visibility prefs is set to false by policy. + EXPECT_EQ(history_clusters_service->IsJourneysEnabledAndVisible(), + GetParam()); + + // Verify that history clusters can be hidden by policy. + policies.Set(key::kHistoryClustersVisible, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(false), + nullptr); + UpdateProviderPolicy(policies); + + EXPECT_FALSE(prefs->GetBoolean(history_clusters::prefs::kVisible)); + EXPECT_TRUE(prefs->IsManagedPreference(history_clusters::prefs::kVisible)); + EXPECT_FALSE(history_clusters_service->IsJourneysEnabledAndVisible()); + + // Verify that history clusters can be made visible by policy. + policies.Set(key::kHistoryClustersVisible, POLICY_LEVEL_MANDATORY, + POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD, base::Value(true), + nullptr); + UpdateProviderPolicy(policies); + + EXPECT_TRUE(prefs->GetBoolean(history_clusters::prefs::kVisible)); + EXPECT_TRUE(prefs->IsManagedPreference(history_clusters::prefs::kVisible)); + EXPECT_TRUE(history_clusters_service->IsJourneysEnabledAndVisible()); + + // Verify that clearing the policy restores the original prefs. + policies.Clear(); + UpdateProviderPolicy(policies); + + EXPECT_FALSE(prefs->GetBoolean(history_clusters::prefs::kVisible)); + EXPECT_FALSE(prefs->IsManagedPreference(history_clusters::prefs::kVisible)); + // When history_clusters::kRenameJourneys is enabled, history clusters are + // always visible unless the visibility prefs is set to false by policy. + EXPECT_EQ(history_clusters_service->IsJourneysEnabledAndVisible(), + GetParam()); +} + +} // namespace policy
diff --git a/chrome/browser/predictors/loading_predictor_factory.cc b/chrome/browser/predictors/loading_predictor_factory.cc index 7458409b..34c088a 100644 --- a/chrome/browser/predictors/loading_predictor_factory.cc +++ b/chrome/browser/predictors/loading_predictor_factory.cc
@@ -38,14 +38,15 @@ LoadingPredictorFactory::~LoadingPredictorFactory() = default; -KeyedService* LoadingPredictorFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +LoadingPredictorFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); if (!IsLoadingPredictorEnabled(profile)) return nullptr; - return new LoadingPredictor(LoadingPredictorConfig(), profile); + return std::make_unique<LoadingPredictor>(LoadingPredictorConfig(), profile); } } // namespace predictors
diff --git a/chrome/browser/predictors/loading_predictor_factory.h b/chrome/browser/predictors/loading_predictor_factory.h index d02b8e1..d771aa6 100644 --- a/chrome/browser/predictors/loading_predictor_factory.h +++ b/chrome/browser/predictors/loading_predictor_factory.h
@@ -29,7 +29,7 @@ ~LoadingPredictorFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/profiles/renderer_updater_factory.cc b/chrome/browser/profiles/renderer_updater_factory.cc index 711f4493..ed5b366 100644 --- a/chrome/browser/profiles/renderer_updater_factory.cc +++ b/chrome/browser/profiles/renderer_updater_factory.cc
@@ -43,9 +43,10 @@ GetInstance()->GetServiceForBrowserContext(profile, true)); } -KeyedService* RendererUpdaterFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +RendererUpdaterFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { - return new RendererUpdater(static_cast<Profile*>(context)); + return std::make_unique<RendererUpdater>(static_cast<Profile*>(context)); } bool RendererUpdaterFactory::ServiceIsCreatedWithBrowserContext() const {
diff --git a/chrome/browser/profiles/renderer_updater_factory.h b/chrome/browser/profiles/renderer_updater_factory.h index e6ee310..2ff4a96 100644 --- a/chrome/browser/profiles/renderer_updater_factory.h +++ b/chrome/browser/profiles/renderer_updater_factory.h
@@ -26,7 +26,7 @@ protected: // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const override; bool ServiceIsCreatedWithBrowserContext() const override;
diff --git a/chrome/browser/push_messaging/push_messaging_service_factory.cc b/chrome/browser/push_messaging/push_messaging_service_factory.cc index f57f55d..ab9113f 100644 --- a/chrome/browser/push_messaging/push_messaging_service_factory.cc +++ b/chrome/browser/push_messaging/push_messaging_service_factory.cc
@@ -72,9 +72,10 @@ })); } -KeyedService* PushMessagingServiceFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +PushMessagingServiceFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); CHECK(!profile->IsOffTheRecord()); - return new PushMessagingServiceImpl(profile); + return std::make_unique<PushMessagingServiceImpl>(profile); }
diff --git a/chrome/browser/push_messaging/push_messaging_service_factory.h b/chrome/browser/push_messaging/push_messaging_service_factory.h index ab903ac..9e4298e 100644 --- a/chrome/browser/push_messaging/push_messaging_service_factory.h +++ b/chrome/browser/push_messaging/push_messaging_service_factory.h
@@ -31,7 +31,7 @@ ~PushMessagingServiceFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* profile) const override; };
diff --git a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm index e83fd1af..688573dd 100644 --- a/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm +++ b/chrome/browser/renderer_host/chrome_render_widget_host_view_mac_history_swiper_browsertest.mm
@@ -146,8 +146,9 @@ // Creates a mock scroll wheel event that is backed by a real CGEvent. id MockScrollWheelEvent(NSPoint delta, NSEventType type) { - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateScrollWheelEvent( - nullptr, kCGScrollEventUnitLine, 2, 0, 0)); + base::apple::ScopedCFTypeRef<CGEventRef> cg_event( + CGEventCreateScrollWheelEvent(nullptr, kCGScrollEventUnitLine, 2, 0, + 0)); CGEventSetIntegerValueField(cg_event, kCGScrollWheelEventIsContinuous, 1); CGEventSetIntegerValueField( cg_event, kCGScrollWheelEventPointDeltaAxis2, delta.x);
diff --git a/chrome/browser/resources/chromeos/accessibility/chromevox/background/event/range_automation_handler.js b/chrome/browser/resources/chromeos/accessibility/chromevox/background/event/range_automation_handler.js index cd0f207..88b17c59 100644 --- a/chrome/browser/resources/chromeos/accessibility/chromevox/background/event/range_automation_handler.js +++ b/chrome/browser/resources/chromeos/accessibility/chromevox/background/event/range_automation_handler.js
@@ -173,12 +173,6 @@ return; } - // To avoid output of stale information, don't report changes in IME - // candidates. IME candidate output is handled during selection events. - if (evt.target.role === RoleType.IME_CANDIDATE) { - return; - } - // Report attribute changes for specific generated events. if (evt.type === chrome.automation.EventType.SORT_CHANGED) { let msgId;
diff --git a/chrome/browser/resources/history/app.html b/chrome/browser/resources/history/app.html index 013cda62..a810828d 100644 --- a/chrome/browser/resources/history/app.html +++ b/chrome/browser/resources/history/app.html
@@ -110,7 +110,7 @@ if="[[historyClustersSelected_(selectedPage_, showHistoryClusters_)]]"> <history-clusters id="history-clusters" query="[[queryState_.searchTerm]]" - path="journeys"> + path="[[historyClustersPath_]]"> </history-clusters> </template> </iron-pages>
diff --git a/chrome/browser/resources/history/app.ts b/chrome/browser/resources/history/app.ts index 945c55e1..7a162bf 100644 --- a/chrome/browser/resources/history/app.ts +++ b/chrome/browser/resources/history/app.ts
@@ -197,6 +197,12 @@ value: () => loadTimeData.getBoolean('isHistoryClustersVisible'), }, + historyClustersPath_: { + type: Boolean, + value: () => + loadTimeData.getBoolean('renameJourneys') ? '2' : 'journeys', + }, + showHistoryClusters_: { type: Boolean, computed: @@ -238,7 +244,7 @@ private pendingDelete_: boolean; private queryResult_: QueryResult; private queryState_: QueryState; - private selectedPage_: Page; + private selectedPage_: string; private selectedTab_: number; private showHistoryClusters_: boolean; private tabsIcons_: string[]; @@ -308,7 +314,7 @@ } private historyClustersSelected_( - _selectedPage: Page, _showHistoryClusters: boolean): boolean { + _selectedPage: string, _showHistoryClusters: boolean): boolean { return this.selectedPage_ === Page.HISTORY_CLUSTERS && this.showHistoryClusters_; } @@ -469,7 +475,7 @@ this.set('footerInfo.otherFormsOfHistory', hasOtherForms); } - private syncedTabsSelected_(_selectedPage: Page): boolean { + private syncedTabsSelected_(_selectedPage: string): boolean { return this.selectedPage_ === Page.SYNCED_TABS; } @@ -482,7 +488,7 @@ return querying && !incremental && searchTerm !== ''; } - private selectedPageChanged_(newPage: Page, oldPage: Page) { + private selectedPageChanged_(newPage: string, oldPage: string) { this.unselectAll(); this.historyViewChanged_(); this.maybeUpdateSelectedHistoryTab_();
diff --git a/chrome/browser/resources/history/router.ts b/chrome/browser/resources/history/router.ts index b5e0f383..1c0c7f5585 100644 --- a/chrome/browser/resources/history/router.ts +++ b/chrome/browser/resources/history/router.ts
@@ -5,17 +5,21 @@ import 'chrome://resources/polymer/v3_0/iron-location/iron-location.js'; import 'chrome://resources/polymer/v3_0/iron-location/iron-query-params.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.js'; import {Debouncer, microTask, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {QueryState} from './externs.js'; import {getTemplate} from './router.html.js'; // All valid pages. -export enum Page { - HISTORY = 'history', - HISTORY_CLUSTERS = 'journeys', - SYNCED_TABS = 'syncedTabs', -} +// TODO(crbug.com/1473855): Change this to an enum and use that type for holding +// these values for better type check when `loadTimeData` is no longer needed. +export const Page = { + HISTORY: 'history', + HISTORY_CLUSTERS: loadTimeData.getBoolean('renameJourneys') ? '2' : + 'journeys', + SYNCED_TABS: 'syncedTabs', +}; // The ids of pages with corresponding tabs in the order of their tab indices. export const TABBED_PAGES = [Page.HISTORY, Page.HISTORY_CLUSTERS];
diff --git a/chrome/browser/resources/history/side_bar.ts b/chrome/browser/resources/history/side_bar.ts index c2fe87e..cc0e3c9 100644 --- a/chrome/browser/resources/history/side_bar.ts +++ b/chrome/browser/resources/history/side_bar.ts
@@ -85,6 +85,11 @@ }, }, + renameJourneys_: { + type: Boolean, + value: () => loadTimeData.getBoolean('renameJourneys'), + }, + /** * Used to display notices for profile sign-in status and managed status. */ @@ -103,7 +108,8 @@ showToggleHistoryClusters_: { type: Boolean, computed: 'computeShowToggleHistoryClusters_(' + - 'historyClustersEnabled, historyClustersVisibleManagedByPolicy_)', + 'historyClustersEnabled, historyClustersVisibleManagedByPolicy_, ' + + 'renameJourneys_)', }, }; } @@ -111,10 +117,11 @@ footerInfo: FooterInfo; historyClustersEnabled: boolean; historyClustersVisible: boolean; - selectedPage: Page; + selectedPage: string; selectedTab: number; private guestSession_ = loadTimeData.getBoolean('isGuestSession'); private historyClustersVisibleManagedByPolicy_: boolean; + private renameJourneys_: boolean; private showFooter_: boolean; private showHistoryClusters_: boolean; @@ -227,7 +234,7 @@ private computeShowToggleHistoryClusters_(): boolean { return this.historyClustersEnabled && - !this.historyClustersVisibleManagedByPolicy_; + !this.historyClustersVisibleManagedByPolicy_ && !this.renameJourneys_; } }
diff --git a/chrome/browser/resources/new_tab_page/modules/history_clusters/module.ts b/chrome/browser/resources/new_tab_page/modules/history_clusters/module.ts index 7a8474b..c8404f6 100644 --- a/chrome/browser/resources/new_tab_page/modules/history_clusters/module.ts +++ b/chrome/browser/resources/new_tab_page/modules/history_clusters/module.ts
@@ -200,8 +200,8 @@ composed: true, detail: { message: loadTimeData.getStringF( - 'disableModuleToastMessage', - loadTimeData.getString('modulesJourneysSentence2')), + 'disableQuestsModuleToastMessage', + loadTimeData.getString('disableQuestsModuleToastName')), }, }); this.dispatchEvent(disableEvent);
diff --git a/chrome/browser/resources/new_tab_page/modules/v2/history_clusters/module.ts b/chrome/browser/resources/new_tab_page/modules/v2/history_clusters/module.ts index 082eac3..19900004 100644 --- a/chrome/browser/resources/new_tab_page/modules/v2/history_clusters/module.ts +++ b/chrome/browser/resources/new_tab_page/modules/v2/history_clusters/module.ts
@@ -127,8 +127,8 @@ composed: true, detail: { message: loadTimeData.getStringF( - 'disableModuleToastMessage', - loadTimeData.getString('modulesJourneysSentence2')), + 'disableQuestsModuleToastMessage', + loadTimeData.getString('disableQuestsModuleToastName')), }, }); this.dispatchEvent(disableEvent);
diff --git a/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc b/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc index e24103f4..7f492817 100644 --- a/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc +++ b/chrome/browser/safe_browsing/incident_reporting/binary_integrity_analyzer_mac_unittest.cc
@@ -106,7 +106,7 @@ EXPECT_EQ(paths_and_requirements[i].requirement, paths_and_requirements_expected[i].requirement); - base::ScopedCFTypeRef<SecRequirementRef> requirement; + base::apple::ScopedCFTypeRef<SecRequirementRef> requirement; EXPECT_EQ( errSecSuccess, SecRequirementCreateWithString(
diff --git a/chrome/browser/safe_browsing/signature_evaluator_mac.h b/chrome/browser/safe_browsing/signature_evaluator_mac.h index fd824134..19b8c016 100644 --- a/chrome/browser/safe_browsing/signature_evaluator_mac.h +++ b/chrome/browser/safe_browsing/signature_evaluator_mac.h
@@ -59,10 +59,10 @@ bool has_requirement_; // The static code object constructed from the code object on disk. - base::ScopedCFTypeRef<SecStaticCodeRef> code_; + base::apple::ScopedCFTypeRef<SecStaticCodeRef> code_; // The requirement object constructed from the requirement string. - base::ScopedCFTypeRef<SecRequirementRef> requirement_; + base::apple::ScopedCFTypeRef<SecRequirementRef> requirement_; }; } // namespace safe_browsing
diff --git a/chrome/browser/safe_browsing/signature_evaluator_mac.mm b/chrome/browser/safe_browsing/signature_evaluator_mac.mm index 7cd25b8..6a2269e2 100644 --- a/chrome/browser/safe_browsing/signature_evaluator_mac.mm +++ b/chrome/browser/safe_browsing/signature_evaluator_mac.mm
@@ -176,7 +176,7 @@ } bool MacSignatureEvaluator::Initialize() { - base::ScopedCFTypeRef<CFURLRef> code_url = + base::apple::ScopedCFTypeRef<CFURLRef> code_url = base::apple::FilePathToCFURL(path_); if (!code_url) return false; @@ -199,7 +199,7 @@ bool MacSignatureEvaluator::PerformEvaluation( ClientIncidentReport_IncidentData_BinaryIntegrityIncident* incident) { DCHECK(incident->contained_file_size() == 0); - base::ScopedCFTypeRef<CFErrorRef> errors; + base::apple::ScopedCFTypeRef<CFErrorRef> errors; OSStatus err = SecStaticCodeCheckValidityWithErrors( code_, kSecCSCheckAllArchitectures, requirement_, errors.InitializeInto()); @@ -210,7 +210,7 @@ incident->set_sec_error(err); // We heuristically detect if we are in a bundle or not by checking if // the main executable is different from the path_. - base::ScopedCFTypeRef<CFDictionaryRef> info_dict; + base::apple::ScopedCFTypeRef<CFDictionaryRef> info_dict; base::FilePath exec_path; if (SecCodeCopySigningInformation(code_, kSecCSDefaultFlags, info_dict.InitializeInto()) == @@ -232,7 +232,8 @@ } if (errors) { - base::ScopedCFTypeRef<CFDictionaryRef> info(CFErrorCopyUserInfo(errors)); + base::apple::ScopedCFTypeRef<CFDictionaryRef> info( + CFErrorCopyUserInfo(errors)); static const CFStringRef keys[] = { kSecCFErrorResourceAltered, kSecCFErrorResourceMissing, };
diff --git a/chrome/browser/screen_ai/screen_ai_service_router_factory.cc b/chrome/browser/screen_ai/screen_ai_service_router_factory.cc index 9173591..f1eb85f 100644 --- a/chrome/browser/screen_ai/screen_ai_service_router_factory.cc +++ b/chrome/browser/screen_ai/screen_ai_service_router_factory.cc
@@ -35,9 +35,10 @@ ScreenAIServiceRouterFactory::~ScreenAIServiceRouterFactory() = default; -KeyedService* ScreenAIServiceRouterFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +ScreenAIServiceRouterFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* /*context*/) const { - return new screen_ai::ScreenAIServiceRouter(); + return std::make_unique<screen_ai::ScreenAIServiceRouter>(); } // static
diff --git a/chrome/browser/screen_ai/screen_ai_service_router_factory.h b/chrome/browser/screen_ai/screen_ai_service_router_factory.h index 2e30f2e..f43c6e3 100644 --- a/chrome/browser/screen_ai/screen_ai_service_router_factory.h +++ b/chrome/browser/screen_ai/screen_ai_service_router_factory.h
@@ -33,7 +33,7 @@ ~ScreenAIServiceRouterFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; };
diff --git a/chrome/browser/search_engine_choice/search_engine_choice_service_factory.cc b/chrome/browser/search_engine_choice/search_engine_choice_service_factory.cc index 5aa96032..23390cc 100644 --- a/chrome/browser/search_engine_choice/search_engine_choice_service_factory.cc +++ b/chrome/browser/search_engine_choice/search_engine_choice_service_factory.cc
@@ -82,7 +82,8 @@ .pref_service = profile.GetPrefs()}); } -KeyedService* SearchEngineChoiceServiceFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +SearchEngineChoiceServiceFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { if (!g_is_chrome_build) { return nullptr; @@ -93,5 +94,5 @@ CHECK_DEREF(g_browser_process->policy_service()), profile)) { return nullptr; } - return new SearchEngineChoiceService(); + return std::make_unique<SearchEngineChoiceService>(); }
diff --git a/chrome/browser/search_engine_choice/search_engine_choice_service_factory.h b/chrome/browser/search_engine_choice/search_engine_choice_service_factory.h index dde953ad..60b1ea0e 100644 --- a/chrome/browser/search_engine_choice/search_engine_choice_service_factory.h +++ b/chrome/browser/search_engine_choice/search_engine_choice_service_factory.h
@@ -39,7 +39,7 @@ ~SearchEngineChoiceServiceFactory() override; // BrowserContextKeyedServiceFactory: - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; // Returns whether the profile is eligible for the Search Engine Choice dialog
diff --git a/chrome/browser/sharesheet/sharesheet_service_factory.cc b/chrome/browser/sharesheet/sharesheet_service_factory.cc index 71e8767..3081a78 100644 --- a/chrome/browser/sharesheet/sharesheet_service_factory.cc +++ b/chrome/browser/sharesheet/sharesheet_service_factory.cc
@@ -43,7 +43,8 @@ SharesheetServiceFactory::~SharesheetServiceFactory() = default; -KeyedService* SharesheetServiceFactory::BuildServiceInstanceFor( +std::unique_ptr<KeyedService> +SharesheetServiceFactory::BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const { Profile* profile = Profile::FromBrowserContext(context); @@ -57,7 +58,7 @@ return nullptr; } - return new SharesheetService(profile); + return std::make_unique<SharesheetService>(profile); } bool SharesheetServiceFactory::ServiceIsCreatedWithBrowserContext() const {
diff --git a/chrome/browser/sharesheet/sharesheet_service_factory.h b/chrome/browser/sharesheet/sharesheet_service_factory.h index f64584da..fd7f4d8 100644 --- a/chrome/browser/sharesheet/sharesheet_service_factory.h +++ b/chrome/browser/sharesheet/sharesheet_service_factory.h
@@ -31,7 +31,7 @@ ~SharesheetServiceFactory() override; // BrowserContextKeyedServiceFactory overrides. - KeyedService* BuildServiceInstanceFor( + std::unique_ptr<KeyedService> BuildServiceInstanceForBrowserContext( content::BrowserContext* context) const override; bool ServiceIsCreatedWithBrowserContext() const override; };
diff --git a/chrome/browser/ui/android/hats/internal/java/src/org/chromium/chrome/browser/ui/hats/SurveyControllerProvider.java b/chrome/browser/ui/android/hats/internal/java/src/org/chromium/chrome/browser/ui/hats/SurveyControllerProvider.java index f5658be8..d3255dba 100644 --- a/chrome/browser/ui/android/hats/internal/java/src/org/chromium/chrome/browser/ui/hats/SurveyControllerProvider.java +++ b/chrome/browser/ui/android/hats/internal/java/src/org/chromium/chrome/browser/ui/hats/SurveyControllerProvider.java
@@ -7,14 +7,13 @@ /** * Util class that creates a new SurveyController. */ -// TODO(crbug/1400731): Change to package private once public references are removed. -public class SurveyControllerProvider { +class SurveyControllerProvider { private SurveyControllerProvider() {} /** * @return A new instance of survey controller. */ - public static SurveyController create() { + static SurveyController create() { return new SurveyController() {}; } }
diff --git a/chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc b/chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc index d14dd08..130389d 100644 --- a/chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc +++ b/chrome/browser/ui/autofill/payments/autofill_progress_dialog_controller_impl.cc
@@ -79,6 +79,7 @@ return l10n_util::GetStringUTF16( IDS_AUTOFILL_FIDO_AUTHENTICATION_PROMPT_TITLE); case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: + case AutofillProgressDialogType::kServerCardUnmaskProgressDialog: return l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_PROGRESS_DIALOG_TITLE); case AutofillProgressDialogType::kUnspecified: @@ -92,6 +93,7 @@ switch (autofill_progress_dialog_type_) { case AutofillProgressDialogType::kAndroidFIDOProgressDialog: case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: + case AutofillProgressDialogType::kServerCardUnmaskProgressDialog: return l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_CONFIRMATION_DIALOG_TITLE); case AutofillProgressDialogType::kUnspecified: @@ -106,6 +108,7 @@ case AutofillProgressDialogType::kAndroidFIDOProgressDialog: return l10n_util::GetStringUTF16(IDS_CANCEL); case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: + case AutofillProgressDialogType::kServerCardUnmaskProgressDialog: return l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_CANCEL_BUTTON_LABEL); case AutofillProgressDialogType::kUnspecified: @@ -121,6 +124,9 @@ case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: return l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_PROGRESS_BAR_MESSAGE); + case AutofillProgressDialogType::kServerCardUnmaskProgressDialog: + return l10n_util::GetStringUTF16( + IDS_AUTOFILL_MASKED_SERVER_CARD_RISK_BASED_UNMASK_PROGRESS_BAR_MESSAGE); case AutofillProgressDialogType::kUnspecified: NOTREACHED(); return std::u16string(); @@ -133,6 +139,7 @@ case AutofillProgressDialogType::kAndroidFIDOProgressDialog: return std::u16string(); case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: + case AutofillProgressDialogType::kServerCardUnmaskProgressDialog: return l10n_util::GetStringUTF16( IDS_AUTOFILL_CARD_UNMASK_CONFIRMATION_MESSAGE); case AutofillProgressDialogType::kUnspecified:
diff --git a/chrome/browser/ui/browser_navigator.cc b/chrome/browser/ui/browser_navigator.cc index 2810e6e..3b7f96e 100644 --- a/chrome/browser/ui/browser_navigator.cc +++ b/chrome/browser/ui/browser_navigator.cc
@@ -658,10 +658,19 @@ return nullptr; } - // If no source WebContents was specified, we use the selected one from - // the target browser. This must happen first, before - // GetBrowserAndTabForDisposition() has a chance to replace |params->browser| - // with another one. +#if BUILDFLAG(IS_CHROMEOS_LACROS) + const GURL& source_url = + params->source_contents ? params->source_contents->GetURL() : GURL(); + if (lacros_url_handling::IsNavigationInterceptable(*params, source_url) && + lacros_url_handling::MaybeInterceptNavigation(params->url)) { + return nullptr; + } +#endif + + // If no source WebContents was specified, we use the selected one from the + // target browser. This must happen before GetBrowserAndTabForDisposition() + // has a chance to replace |params->browser| with another one, but after the + // above check that relies on the original source_contents value. if (!params->source_contents && params->browser) { params->source_contents = params->browser->tab_strip_model()->GetActiveWebContents(); @@ -740,14 +749,8 @@ } #endif #if BUILDFLAG(IS_CHROMEOS_LACROS) - const GURL& source_url = - params->source_contents ? params->source_contents->GetURL() : GURL(); - if (lacros_url_handling::IsNavigationInterceptable(*params, source_url) && - lacros_url_handling::MaybeInterceptNavigation(params->url)) { - return nullptr; - } - // If Lacros comes here with an internal os:// redirect scheme to Ash, and Ash - // does not accept the URL, we convert it into a blocked url instead. + // If Lacros gets here with an internal os:// redirect scheme to Ash, Ash + // did not accept the URL. Convert it into a blocked URL instead. if (crosapi::gurl_os_handler_utils::IsAshOsUrl(params->url)) { params->url = GURL(content::kBlockedURL); }
diff --git a/chrome/browser/ui/cocoa/history_overlay_controller.mm b/chrome/browser/ui/cocoa/history_overlay_controller.mm index ac68a5da..62a22298 100644 --- a/chrome/browser/ui/cocoa/history_overlay_controller.mm +++ b/chrome/browser/ui/cocoa/history_overlay_controller.mm
@@ -74,7 +74,7 @@ [super setFrameSize:newSize]; if (!_shapeLayer.path || !NSEqualSizes(oldSize, newSize)) { - base::ScopedCFTypeRef<CGMutablePathRef> oval(CGPathCreateMutable()); + base::apple::ScopedCFTypeRef<CGMutablePathRef> oval(CGPathCreateMutable()); CGRect ovalRect = CGRectMake(0, 0, newSize.width, newSize.height); CGPathAddEllipseInRect(oval, nullptr, ovalRect); _shapeLayer.path = oval; @@ -84,7 +84,7 @@ - (void)setShieldAlpha:(CGFloat)shieldAlpha { if (shieldAlpha != _shieldAlpha) { _shieldAlpha = shieldAlpha; - base::ScopedCFTypeRef<CGColorRef> fillColor( + base::apple::ScopedCFTypeRef<CGColorRef> fillColor( CGColorCreateGenericGray(0, shieldAlpha)); _shapeLayer.fillColor = fillColor; }
diff --git a/chrome/browser/ui/views/autofill/payments/autofill_progress_dialog_views_browsertest.cc b/chrome/browser/ui/views/autofill/payments/autofill_progress_dialog_views_browsertest.cc index 8dc198b..79391bb 100644 --- a/chrome/browser/ui/views/autofill/payments/autofill_progress_dialog_views_browsertest.cc +++ b/chrome/browser/ui/views/autofill/payments/autofill_progress_dialog_views_browsertest.cc
@@ -20,7 +20,9 @@ namespace autofill { -class AutofillProgressDialogViewsBrowserTest : public DialogBrowserTest { +class AutofillProgressDialogViewsBrowserTest + : public DialogBrowserTest, + public testing::WithParamInterface<std::string> { public: AutofillProgressDialogViewsBrowserTest() = default; ~AutofillProgressDialogViewsBrowserTest() override = default; @@ -29,12 +31,22 @@ AutofillProgressDialogViewsBrowserTest& operator=( const AutofillProgressDialogViewsBrowserTest&) = delete; + AutofillProgressDialogType GetDialogType() const { + if (GetParam() == "VirtualCardUnmask") { + return AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog; + } else if (GetParam() == "ServerCardUnmask") { + return AutofillProgressDialogType::kServerCardUnmaskProgressDialog; + } + NOTREACHED_NORETURN(); + } + + std::string GetDialogTypeStringForLogging() const { + return std::string( + AutofillMetrics::GetDialogTypeStringForLogging(GetDialogType())); + } + void ShowUi(const std::string& name) override { - AutofillProgressDialogType autofill_progress_dialog_type_; - CHECK_EQ(name, "VirtualCardUnmask"); - autofill_progress_dialog_type_ = - AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog; - controller()->ShowDialog(autofill_progress_dialog_type_, base::DoNothing()); + controller()->ShowDialog(GetDialogType(), base::DoNothing()); } AutofillProgressDialogViews* GetDialogViews() { @@ -55,49 +67,59 @@ } }; -IN_PROC_BROWSER_TEST_F(AutofillProgressDialogViewsBrowserTest, +IN_PROC_BROWSER_TEST_P(AutofillProgressDialogViewsBrowserTest, InvokeUi_VirtualCardUnmask) { base::HistogramTester histogram_tester; ShowAndVerifyUi(); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Shown", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Shown"}), + true, 1); } // Ensures closing current tab while dialog being visible is correctly handle // and the browser won't crash. -IN_PROC_BROWSER_TEST_F(AutofillProgressDialogViewsBrowserTest, +IN_PROC_BROWSER_TEST_P(AutofillProgressDialogViewsBrowserTest, CloseTabWhileDialogShowing) { base::HistogramTester histogram_tester; - ShowUi("VirtualCardUnmask"); + ShowUi(GetDialogTypeStringForLogging()); VerifyUi(); browser()->tab_strip_model()->GetActiveWebContents()->Close(); base::RunLoop().RunUntilIdle(); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Shown", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Shown"}), + true, 1); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Result", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Result"}), + true, 1); } // Ensures closing browser while dialog being visible is correctly handled and // the browser won't crash. -IN_PROC_BROWSER_TEST_F(AutofillProgressDialogViewsBrowserTest, +IN_PROC_BROWSER_TEST_P(AutofillProgressDialogViewsBrowserTest, CloseBrowserWhileDialogShowing) { base::HistogramTester histogram_tester; - ShowUi("VirtualCardUnmask"); + ShowUi(GetDialogTypeStringForLogging()); VerifyUi(); browser()->window()->Close(); base::RunLoop().RunUntilIdle(); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Shown", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Shown"}), + true, 1); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Result", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Result"}), + true, 1); } // Ensures clicking on the cancel button is correctly handled. -IN_PROC_BROWSER_TEST_F(AutofillProgressDialogViewsBrowserTest, +IN_PROC_BROWSER_TEST_P(AutofillProgressDialogViewsBrowserTest, ClickCancelButton) { base::HistogramTester histogram_tester; - ShowUi("VirtualCardUnmask"); + ShowUi(GetDialogTypeStringForLogging()); VerifyUi(); auto* dialog_views = GetDialogViews(); ASSERT_TRUE(dialog_views); @@ -107,16 +129,20 @@ destroyed_waiter.Wait(); EXPECT_FALSE(GetDialogViews()); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Shown", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Shown"}), + true, 1); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Result", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Result"}), + true, 1); } // Ensures the dialog closing with confirmation works properly. -IN_PROC_BROWSER_TEST_F(AutofillProgressDialogViewsBrowserTest, +IN_PROC_BROWSER_TEST_P(AutofillProgressDialogViewsBrowserTest, CloseDialogWithConfirmation) { base::HistogramTester histogram_tester; - ShowUi("VirtualCardUnmask"); + ShowUi(GetDialogTypeStringForLogging()); VerifyUi(); auto* dialog_views = GetDialogViews(); ASSERT_TRUE(dialog_views); @@ -133,9 +159,18 @@ testing::Mock::VerifyAndClearExpectations( &no_interactive_authentication_callback); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Shown", true, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Shown"}), + true, 1); histogram_tester.ExpectUniqueSample( - "Autofill.ProgressDialog.CardUnmask.Result", false, 1); + base::StrCat({"Autofill.ProgressDialog.", GetDialogTypeStringForLogging(), + ".Result"}), + false, 1); } +INSTANTIATE_TEST_SUITE_P(, + AutofillProgressDialogViewsBrowserTest, + testing::Values("VirtualCardUnmask", + "ServerCardUnmask")); + } // namespace autofill
diff --git a/chrome/browser/ui/views/editor_menu/BUILD.gn b/chrome/browser/ui/views/editor_menu/BUILD.gn index 87d8b30..b2391af 100644 --- a/chrome/browser/ui/views/editor_menu/BUILD.gn +++ b/chrome/browser/ui/views/editor_menu/BUILD.gn
@@ -23,6 +23,8 @@ sources = [ "editor_menu_chip_view.cc", "editor_menu_chip_view.h", + "editor_menu_promo_card_view.cc", + "editor_menu_promo_card_view.h", "editor_menu_textfield_view.cc", "editor_menu_textfield_view.h", "editor_menu_view.cc",
diff --git a/chrome/browser/ui/views/editor_menu/editor_menu_controller_impl.cc b/chrome/browser/ui/views/editor_menu/editor_menu_controller_impl.cc index e6851b7..c2c9d19b 100644 --- a/chrome/browser/ui/views/editor_menu/editor_menu_controller_impl.cc +++ b/chrome/browser/ui/views/editor_menu/editor_menu_controller_impl.cc
@@ -4,6 +4,7 @@ #include "chrome/browser/ui/views/editor_menu/editor_menu_controller_impl.h" +#include "chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.h" #include "chrome/browser/ui/views/editor_menu/editor_menu_view.h" #include "ui/gfx/geometry/rect.h" @@ -32,7 +33,8 @@ } if (status == ConsentStatus::kPending) { - // TODO(b/295061567): Implement the consent view. + editor_menu_widget_ = EditorMenuPromoCardView::CreateWidget(anchor_bounds); + editor_menu_widget_->ShowInactive(); return; }
diff --git a/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.cc b/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.cc new file mode 100644 index 0000000..a63a0aef --- /dev/null +++ b/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.cc
@@ -0,0 +1,94 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.h" + +#include "ui/base/metadata/metadata_impl_macros.h" +#include "ui/display/screen.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/views/accessibility/view_accessibility.h" +#include "ui/views/controls/label.h" +#include "ui/views/layout/flex_layout.h" +#include "ui/views/style/typography.h" +#include "ui/views/view.h" +#include "ui/views/view_class_properties.h" +#include "ui/views/widget/widget.h" + +namespace chromeos::editor_menu { + +namespace { + +constexpr char kWidgetName[] = "EditorMenuPromoCardViewWidget"; +constexpr char16_t kTitleTextPlaceholder[] = + u"Editor menu title text placeholder"; + +constexpr int kContainerMinWidthDip = 368; + +// Spacing between this view and the anchor view (context menu). +constexpr int kMarginDip = 8; + +} // namespace + +EditorMenuPromoCardView::EditorMenuPromoCardView( + const gfx::Rect& anchor_view_bounds) { + InitLayout(); +} + +EditorMenuPromoCardView::~EditorMenuPromoCardView() = default; + +// static +views::UniqueWidgetPtr EditorMenuPromoCardView::CreateWidget( + const gfx::Rect& anchor_view_bounds) { + views::Widget::InitParams params; + params.activatable = views::Widget::InitParams::Activatable::kYes; + params.shadow_elevation = 2; + params.shadow_type = views::Widget::InitParams::ShadowType::kDrop; + params.type = views::Widget::InitParams::TYPE_POPUP; + params.z_order = ui::ZOrderLevel::kFloatingUIElement; + params.name = kWidgetName; + + views::UniqueWidgetPtr widget = + std::make_unique<views::Widget>(std::move(params)); + EditorMenuPromoCardView* editor_menu_promo_card_view = + widget->SetContentsView( + std::make_unique<EditorMenuPromoCardView>(anchor_view_bounds)); + editor_menu_promo_card_view->UpdateBounds(anchor_view_bounds); + + return widget; +} + +void EditorMenuPromoCardView::UpdateBounds( + const gfx::Rect& anchor_view_bounds) { + const int height = GetHeightForWidth(anchor_view_bounds.width()); + int y = anchor_view_bounds.y() - kMarginDip - height; + + // The Editor Menu view will be off screen if showing above the anchor. + // Show below the anchor instead. + if (y < display::Screen::GetScreen() + ->GetDisplayMatching(anchor_view_bounds) + .work_area() + .y()) { + y = anchor_view_bounds.bottom() + kMarginDip; + } + + const gfx::Rect bounds = {{anchor_view_bounds.x(), y}, + {kContainerMinWidthDip, height}}; + GetWidget()->SetBounds(bounds); +} + +void EditorMenuPromoCardView::GetAccessibleNodeData(ui::AXNodeData* node_data) { + node_data->role = ax::mojom::Role::kDialog; + node_data->SetName(kTitleTextPlaceholder); +} + +void EditorMenuPromoCardView::InitLayout() { + SetLayoutManager(std::make_unique<views::FlexLayout>()); + AddChildView(std::make_unique<views::Label>( + kTitleTextPlaceholder, views::style::CONTEXT_DIALOG_TITLE)); +} + +BEGIN_METADATA(EditorMenuPromoCardView, views::View) +END_METADATA + +} // namespace chromeos::editor_menu
diff --git a/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.h b/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.h new file mode 100644 index 0000000..95fd104 --- /dev/null +++ b/chrome/browser/ui/views/editor_menu/editor_menu_promo_card_view.h
@@ -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. + +#ifndef CHROME_BROWSER_UI_VIEWS_EDITOR_MENU_EDITOR_MENU_PROMO_CARD_VIEW_H_ +#define CHROME_BROWSER_UI_VIEWS_EDITOR_MENU_EDITOR_MENU_PROMO_CARD_VIEW_H_ + +#include "ui/base/metadata/metadata_header_macros.h" +#include "ui/views/widget/unique_widget_ptr.h" + +namespace chromeos::editor_menu { + +// A view which shows a promo card to introduce the Editor Menu feature. +class EditorMenuPromoCardView : public views::View { + public: + METADATA_HEADER(EditorMenuPromoCardView); + + explicit EditorMenuPromoCardView(const gfx::Rect& anchor_view_bounds); + + EditorMenuPromoCardView(const EditorMenuPromoCardView&) = delete; + EditorMenuPromoCardView& operator=(const EditorMenuPromoCardView&) = delete; + + ~EditorMenuPromoCardView() override; + + static views::UniqueWidgetPtr CreateWidget( + const gfx::Rect& anchor_view_bounds); + + // views::View: + void GetAccessibleNodeData(ui::AXNodeData* node_data) override; + + void UpdateBounds(const gfx::Rect& anchor_view_bounds); + + private: + void InitLayout(); +}; + +} // namespace chromeos::editor_menu + +#endif // CHROME_BROWSER_UI_VIEWS_EDITOR_MENU_EDITOR_MENU_PROMO_CARD_VIEW_H_
diff --git a/chrome/browser/ui/views/frame/browser_frame.cc b/chrome/browser/ui/views/frame/browser_frame.cc index 40fc0ef6..be8a546 100644 --- a/chrome/browser/ui/views/frame/browser_frame.cc +++ b/chrome/browser/ui/views/frame/browser_frame.cc
@@ -437,16 +437,17 @@ } #endif // BUILDFLAG(IS_CHROMEOS_ASH) + const auto* theme_service = + ThemeServiceFactory::GetForProfile(browser_view_->browser()->profile()); + // color_mode. - [this, &key]() { + [this, &key, theme_service]() { // Currently the incognito browser is implemented as unthemed dark mode. if (IsIncognitoBrowser()) { key.color_mode = ui::ColorProviderKey::ColorMode::kDark; return; } - const auto* theme_service = - ThemeServiceFactory::GetForProfile(browser_view_->browser()->profile()); const auto browser_color_scheme = theme_service->GetBrowserColorScheme(); if (browser_color_scheme != ThemeService::BrowserColorScheme::kSystem) { @@ -457,9 +458,6 @@ } }(); - const auto* theme_service = - ThemeServiceFactory::GetForProfile(browser_view_->browser()->profile()); - // is_grayscale. // Incognito mode browser should be forced to grayscale. key.is_grayscale = IsIncognitoBrowser() || @@ -467,7 +465,7 @@ theme_service->GetIsGrayscale()); // user_color. - [this, &key]() { + [&key, theme_service]() { // The grayscale theme also assumes that the baseline palette is used. if (key.is_grayscale) { // Baseline palette is used when `ColorProviderKey::user_color` is empty. @@ -475,8 +473,6 @@ return; } - const auto* theme_service = - ThemeServiceFactory::GetForProfile(browser_view_->browser()->profile()); if (!theme_service) { return; }
diff --git a/chrome/browser/ui/views/side_panel/history_clusters/history_clusters_side_panel_coordinator.cc b/chrome/browser/ui/views/side_panel/history_clusters/history_clusters_side_panel_coordinator.cc index 06bac14..68a2aeb 100644 --- a/chrome/browser/ui/views/side_panel/history_clusters/history_clusters_side_panel_coordinator.cc +++ b/chrome/browser/ui/views/side_panel/history_clusters/history_clusters_side_panel_coordinator.cc
@@ -55,11 +55,16 @@ void HistoryClustersSidePanelCoordinator::CreateAndRegisterEntry( SidePanelRegistry* global_registry) { + const bool rename_journeys = + base::FeatureList::IsEnabled(history_clusters::kRenameJourneys); global_registry->Register(std::make_unique<SidePanelEntry>( SidePanelEntry::Id::kHistoryClusters, - l10n_util::GetStringUTF16(IDS_HISTORY_CLUSTERS_JOURNEYS_TAB_LABEL), - ui::ImageModel::FromVectorIcon(kJourneysIcon, ui::kColorIcon, - /*icon_size=*/16), + l10n_util::GetStringUTF16(rename_journeys + ? IDS_HISTORY_TITLE + : IDS_HISTORY_CLUSTERS_JOURNEYS_TAB_LABEL), + ui::ImageModel::FromVectorIcon( + rename_journeys ? kHistoryIcon : kJourneysIcon, ui::kColorIcon, + /*icon_size=*/16), base::BindRepeating( &HistoryClustersSidePanelCoordinator::CreateHistoryClustersWebView, base::Unretained(this)), @@ -115,12 +120,9 @@ auto* browser = &GetBrowser(); auto* global_registry = SidePanelCoordinator::GetGlobalSidePanelRegistry(browser); - if (browser->profile()->GetPrefs()->GetBoolean( - history_clusters::prefs::kVisible)) { - if (IsSupported(browser->profile())) { - HistoryClustersSidePanelCoordinator::GetOrCreateForBrowser(browser) - ->CreateAndRegisterEntry(global_registry); - } + if (IsSupported(browser->profile())) { + HistoryClustersSidePanelCoordinator::GetOrCreateForBrowser(browser) + ->CreateAndRegisterEntry(global_registry); } else { global_registry->Deregister( SidePanelEntry::Key(SidePanelEntry::Id::kHistoryClusters)); @@ -152,7 +154,7 @@ if (history_clusters_ui_) query = history_clusters_ui_->GetLastQueryIssued(); - return query.empty() ? GURL(history_clusters::kChromeUIHistoryClustersURL) + return query.empty() ? GURL(history_clusters::GetChromeUIHistoryClustersURL()) : history_clusters::GetFullJourneysUrlForQuery(query); }
diff --git a/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.cc b/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.cc index 9258069..7b9d997 100644 --- a/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.cc +++ b/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.cc
@@ -124,7 +124,7 @@ } // static -void WebAppNavigationBrowserTest::ClickLinkWithModifiersAndWaitForURL( +void WebAppNavigationBrowserTest::ClickLink( content::WebContents* web_contents, const GURL& link_url, const GURL& target_url, @@ -132,7 +132,6 @@ const std::string& rel, int modifiers, blink::WebMouseEvent::Button button) { - auto observer = GetTestNavigationObserver(target_url); std::string script = base::StringPrintf( "(() => {" "const link = document.createElement('a');" @@ -154,7 +153,19 @@ ASSERT_TRUE(content::ExecJs(web_contents, script)); content::SimulateMouseClick(web_contents, modifiers, button); +} +// static +void WebAppNavigationBrowserTest::ClickLinkWithModifiersAndWaitForURL( + content::WebContents* web_contents, + const GURL& link_url, + const GURL& target_url, + WebAppNavigationBrowserTest::LinkTarget target, + const std::string& rel, + int modifiers, + blink::WebMouseEvent::Button button) { + auto observer = GetTestNavigationObserver(target_url); + ClickLink(web_contents, link_url, target_url, target, rel, modifiers, button); observer->Wait(); }
diff --git a/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.h b/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.h index cc4d9e6..e9edb9f 100644 --- a/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.h +++ b/chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.h
@@ -56,6 +56,16 @@ // respectively, adds it to the DOM, and clicks on it with |modifiers|. // Returns once |target_url| has loaded. |modifiers| should be based on // blink::WebInputEvent::Modifiers. + static void ClickLink( + content::WebContents* web_contents, + const GURL& link_url, + const GURL& target_url, + LinkTarget target = LinkTarget::SELF, + const std::string& rel = "", + int modifiers = blink::WebInputEvent::Modifiers::kNoModifiers, + blink::WebMouseEvent::Button button = + blink::WebMouseEvent::Button::kLeft); + static void ClickLinkWithModifiersAndWaitForURL( content::WebContents* web_contents, const GURL& link_url,
diff --git a/chrome/browser/ui/web_applications/web_app_launch_process.cc b/chrome/browser/ui/web_applications/web_app_launch_process.cc index da054bcf..2ae43531 100644 --- a/chrome/browser/ui/web_applications/web_app_launch_process.cc +++ b/chrome/browser/ui/web_applications/web_app_launch_process.cc
@@ -126,12 +126,12 @@ ->GetSystemApp( *ash::GetSystemWebAppTypeForAppId(&*profile_, params_->app_id)) ->IsUrlInSystemAppScope(launch_url); - DCHECK(registrar_->IsUrlInAppScope(launch_url, params_->app_id) || - is_url_in_system_web_app_sccope) + CHECK(registrar_->IsUrlInAppExtendedScope(launch_url, params_->app_id) || + is_url_in_system_web_app_sccope) << "Url " << launch_url.spec() << " not in scope for app " << params_->app_id; #else - DCHECK(registrar_->IsUrlInAppScope(launch_url, params_->app_id)); + CHECK(registrar_->IsUrlInAppExtendedScope(launch_url, params_->app_id)); #endif #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -360,8 +360,8 @@ return {.web_contents = existing_tab, .did_navigate = false}; } - if (registrar_->IsUrlInAppScope(existing_tab->GetLastCommittedURL(), - params_->app_id)) { + if (registrar_->IsUrlInAppExtendedScope(existing_tab->GetLastCommittedURL(), + params_->app_id)) { // If the web contents is currently navigating then interrupt it. The // current page is now being used for this app launch. existing_tab->Stop();
diff --git a/chrome/browser/ui/webui/ash/login/oobe_ui.cc b/chrome/browser/ui/webui/ash/login/oobe_ui.cc index 1ee4ae4..2d246f0 100644 --- a/chrome/browser/ui/webui/ash/login/oobe_ui.cc +++ b/chrome/browser/ui/webui/ash/login/oobe_ui.cc
@@ -26,6 +26,7 @@ #include "base/values.h" #include "build/branding_buildflags.h" #include "chrome/browser/ash/boot_times_recorder_tab_helper.h" +#include "chrome/browser/ash/drive/file_system_util.h" #include "chrome/browser/ash/login/enrollment/auto_enrollment_check_screen_view.h" #include "chrome/browser/ash/login/enrollment/enrollment_screen_view.h" #include "chrome/browser/ash/login/quick_unlock/pin_backend.h" @@ -324,7 +325,7 @@ features::IsOobeTouchpadScrollEnabled()); source->AddBoolean("isDrivePinningEnabled", - features::IsOobeDrivePinningEnabled()); + drive::util::IsOobeDrivePinningEnabled(profile)); // Whether the timings in oobe_trace.js will be output to the console. source->AddBoolean( @@ -548,7 +549,8 @@ AddScreenHandler(std::make_unique<AddChildScreenHandler>()); - if (features::IsOobeDrivePinningEnabled()) { + Profile* const profile = Profile::FromWebUI(web_ui()); + if (drive::util::IsOobeDrivePinningEnabled(profile)) { AddScreenHandler(std::make_unique<DrivePinningScreenHandler>()); } @@ -556,7 +558,6 @@ AddScreenHandler(std::make_unique<CryptohomeRecoveryScreenHandler>()); - Profile* profile = Profile::FromWebUI(web_ui()); // Set up the chrome://theme/ source, for Chrome logo. content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
diff --git a/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.cc b/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.cc index b69822c1..8032a3f0 100644 --- a/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.cc +++ b/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.cc
@@ -11,6 +11,7 @@ #include "chrome/grit/generated_resources.h" #include "components/history/core/common/pref_names.h" #include "components/history_clusters/core/config.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_prefs.h" #include "components/history_clusters/core/history_clusters_service.h" #include "components/page_image_service/features.h" @@ -33,11 +34,18 @@ "isHistoryClustersEnabled", history_clusters_service && history_clusters_service->is_journeys_feature_flag_enabled()); + const bool rename_journeys = + base::FeatureList::IsEnabled(history_clusters::kRenameJourneys); + source->AddBoolean(kRenameJourneysKey, rename_journeys); + const bool journeys_is_managed = + prefs->IsManagedPreference(history_clusters::prefs::kVisible); + // When history_clusters::kRenameJourneys is enabled, history clusters are + // always visible unless the visibility prefs is set to false by policy. source->AddBoolean(kIsHistoryClustersVisibleKey, - prefs->GetBoolean(history_clusters::prefs::kVisible)); - source->AddBoolean( - kIsHistoryClustersVisibleManagedByPolicyKey, - prefs->IsManagedPreference(history_clusters::prefs::kVisible)); + prefs->GetBoolean(history_clusters::prefs::kVisible) || + (rename_journeys && !journeys_is_managed)); + source->AddBoolean(kIsHistoryClustersVisibleManagedByPolicyKey, + journeys_is_managed); source->AddBoolean("isHistoryClustersDebug", history_clusters::GetConfig().user_visible_debug); source->AddBoolean( @@ -78,5 +86,15 @@ {"toggleButtonLabelMore", IDS_HISTORY_CLUSTERS_SHOW_MORE_BUTTON_LABEL}, }; source->AddLocalizedStrings(kHistoryClustersStrings); + + if (rename_journeys) { + source->AddLocalizedString("historyClustersSearchPrompt", + IDS_HISTORY_SEARCH_PROMPT); + source->AddLocalizedString("historyClustersTabLabel", + IDS_HISTORY_CLUSTERS_BY_GROUP_TAB_LABEL); + source->AddLocalizedString("historyListTabLabel", + IDS_HISTORY_CLUSTERS_BY_DATE_TAB_LABEL); + } + return; }
diff --git a/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.h b/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.h index 0e18a85..18354cd 100644 --- a/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.h +++ b/chrome/browser/ui/webui/cr_components/history_clusters/history_clusters_util.h
@@ -8,6 +8,7 @@ constexpr char kIsHistoryClustersVisibleKey[] = "isHistoryClustersVisible"; constexpr char kIsHistoryClustersVisibleManagedByPolicyKey[] = "isHistoryClustersVisibleManagedByPolicy"; +constexpr char kRenameJourneysKey[] = "renameJourneys"; class Profile;
diff --git a/chrome/browser/ui/webui/history/history_ui.cc b/chrome/browser/ui/webui/history/history_ui.cc index 14db0f47..af184ef 100644 --- a/chrome/browser/ui/webui/history/history_ui.cc +++ b/chrome/browser/ui/webui/history/history_ui.cc
@@ -218,12 +218,18 @@ base::Value::Dict update; update.Set(kIsUserSignedInKey, IsUserSignedIn(profile)); + + const bool rename_journeys = + base::FeatureList::IsEnabled(history_clusters::kRenameJourneys); + const bool is_managed = profile->GetPrefs()->IsManagedPreference( + history_clusters::prefs::kVisible); + // When history_clusters::kRenameJourneys is enabled, history clusters are + // always visible unless the visibility prefs is set to false by policy. update.Set( kIsHistoryClustersVisibleKey, - profile->GetPrefs()->GetBoolean(history_clusters::prefs::kVisible)); - update.Set(kIsHistoryClustersVisibleManagedByPolicyKey, - profile->GetPrefs()->IsManagedPreference( - history_clusters::prefs::kVisible)); + profile->GetPrefs()->GetBoolean(history_clusters::prefs::kVisible) || + (rename_journeys && !is_managed)); + update.Set(kIsHistoryClustersVisibleManagedByPolicyKey, is_managed); content::WebUIDataSource::Update(profile, chrome::kChromeUIHistoryHost, std::move(update));
diff --git a/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc b/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc index f542a2c..504d0ad 100644 --- a/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc +++ b/chrome/browser/ui/webui/history_clusters/history_clusters_handler_browsertest.cc
@@ -31,7 +31,7 @@ void SetUpOnMainThread() override { EXPECT_TRUE(ui_test_utils::NavigateToURL( - browser(), GURL(kChromeUIHistoryClustersURL))); + browser(), GURL(GetChromeUIHistoryClustersURL()))); EXPECT_TRUE(content::WaitForLoadStop( browser()->tab_strip_model()->GetActiveWebContents())); handler_ = browser()
diff --git a/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc b/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc index 96858ada..2b9e769 100644 --- a/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc +++ b/chrome/browser/ui/webui/new_tab_page/new_tab_page_ui.cc
@@ -66,6 +66,7 @@ #include "components/feed/feed_feature_list.h" #include "components/google/core/common/google_util.h" #include "components/grit/components_scaled_resources.h" +#include "components/history_clusters/core/features.h" #include "components/page_image_service/image_service.h" #include "components/page_image_service/image_service_handler.h" #include "components/prefs/pref_registry_simple.h" @@ -493,7 +494,10 @@ {"modulesJourneysResumeJourney", IDS_NTP_MODULES_RESUME_YOUR_JOURNEY}, {"modulesJourneysShowAll", IDS_NTP_MODULES_SHOW_ALL}, {"modulesJourneysInfo", IDS_NTP_MODULES_HISTORY_CLUSTERS_INFO}, - {"modulesJourneysSentence2", IDS_NTP_MODULES_HISTORY_CLUSTERS_SENTENCE2}, + {"disableQuestsModuleToastName", + IDS_NTP_MODULES_HISTORY_CLUSTERS_SENTENCE2}, + {"disableQuestsModuleToastMessage", + IDS_NTP_MODULES_DISABLE_TOAST_MESSAGE}, {"modulesJourneyDisable", IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TEXT}, {"modulesJourneysDismissButton", IDS_NTP_MODULES_HISTORY_CLUSTERS_DISMISS_BUTTON}, @@ -528,6 +532,23 @@ source->AddBoolean("wideModulesEnabled", base::FeatureList::IsEnabled( ntp_features::kNtpWideModules)); + if (base::FeatureList::IsEnabled(history_clusters::kRenameJourneys)) { + source->AddLocalizedString( + "modulesJourneysResumeJourney", + IDS_NTP_MODULES_HISTORY_CLUSTERS_RESUME_BROWSING); + source->AddLocalizedString("modulesJourneysInfo", + IDS_NTP_MODULES_HISTORY_CLUSTERS_INFO2); + source->AddLocalizedString( + "disableQuestsModuleToastName", + IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_NAME); + source->AddLocalizedString( + "disableQuestsModuleToastMessage", + IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_TOAST_MESSAGE); + source->AddLocalizedString( + "modulesJourneyDisable", + IDS_NTP_MODULES_HISTORY_CLUSTERS_DISABLE_DROPDOWN_TEXT); + } + source->AddBoolean( "modulesHeaderIconEnabled", base::FeatureList::IsEnabled(ntp_features::kNtpModulesHeaderIcon));
diff --git a/chrome/browser/updater/browser_updater_client_util_mac.mm b/chrome/browser/updater/browser_updater_client_util_mac.mm index b18b55d1..b1db0af 100644 --- a/chrome/browser/updater/browser_updater_client_util_mac.mm +++ b/chrome/browser/updater/browser_updater_client_util_mac.mm
@@ -275,12 +275,13 @@ return; } - base::ScopedCFTypeRef<CFErrorRef> error; + base::apple::ScopedCFTypeRef<CFErrorRef> error; Boolean result = SMJobBless(kSMDomainSystemLaunchd, base::SysUTF8ToCFStringRef(kPrivilegedHelperName), authorization, error.InitializeInto()); if (!result) { - base::ScopedCFTypeRef<CFStringRef> desc(CFErrorCopyDescription(error)); + base::apple::ScopedCFTypeRef<CFStringRef> desc( + CFErrorCopyDescription(error)); VLOG(0) << "Could not bless the privileged helper. Resulting error: " << base::SysCFStringRefToUTF8(desc); }
diff --git a/chrome/browser/web_applications/BUILD.gn b/chrome/browser/web_applications/BUILD.gn index e26be30..479c993c 100644 --- a/chrome/browser/web_applications/BUILD.gn +++ b/chrome/browser/web_applications/BUILD.gn
@@ -863,6 +863,7 @@ "web_app_internals_browsertest.cc", "web_app_origin_association_manager_browsertest.cc", "web_app_pref_migration_browsertest.cc", + "web_app_scope_extensions_browsertest.cc", "web_contents/web_app_url_loader_browsertest.cc", ] @@ -925,6 +926,7 @@ if (is_chromeos_lacros) { deps += [ + "//chrome/browser/web_applications/app_service:test_support", "//chromeos/constants", "//chromeos/startup", ]
diff --git a/chrome/browser/web_applications/app_service/lacros_web_apps_controller.h b/chrome/browser/web_applications/app_service/lacros_web_apps_controller.h index 0f05bb2..acc90b0 100644 --- a/chrome/browser/web_applications/app_service/lacros_web_apps_controller.h +++ b/chrome/browser/web_applications/app_service/lacros_web_apps_controller.h
@@ -58,19 +58,6 @@ void SetPublisherForTesting(crosapi::mojom::AppPublisher* publisher); - private: - void OnReady(); - void ExecuteContextMenuCommandInternal( - const std::string& app_id, - const std::string& id, - base::OnceCallback<void(const std::vector<content::WebContents*>&)> - launch_finished_callback); - void LaunchInternal( - const std::string& app_id, - apps::AppLaunchParams params, - base::OnceCallback<void(const std::vector<content::WebContents*>&)> - launch_finished_callback); - // crosapi::mojom::AppController: void Uninstall(const std::string& app_id, apps::UninstallSource uninstall_source, @@ -102,6 +89,19 @@ void SetPermission(const std::string& app_id, apps::PermissionPtr permission) override; + private: + void OnReady(); + void ExecuteContextMenuCommandInternal( + const std::string& app_id, + const std::string& id, + base::OnceCallback<void(const std::vector<content::WebContents*>&)> + launch_finished_callback); + void LaunchInternal( + const std::string& app_id, + apps::AppLaunchParams params, + base::OnceCallback<void(const std::vector<content::WebContents*>&)> + launch_finished_callback); + // WebAppPublisherHelper::Delegate: void PublishWebApps(std::vector<apps::AppPtr> apps) override; void PublishWebApp(apps::AppPtr app) override;
diff --git a/chrome/browser/web_applications/app_service/test/loopback_crosapi_app_service_proxy.cc b/chrome/browser/web_applications/app_service/test/loopback_crosapi_app_service_proxy.cc index e32bbb8c..4a0d45a 100644 --- a/chrome/browser/web_applications/app_service/test/loopback_crosapi_app_service_proxy.cc +++ b/chrome/browser/web_applications/app_service/test/loopback_crosapi_app_service_proxy.cc
@@ -67,15 +67,15 @@ } void LoopbackCrosapiAppServiceProxy::Launch( crosapi::mojom::LaunchParamsPtr launch_params) { - // Implement this if needed. - NOTIMPLEMENTED(); + app_service_->LacrosWebAppsControllerForTesting()->Launch( + std::move(launch_params), base::DoNothing()); } void LoopbackCrosapiAppServiceProxy::LaunchWithResult( crosapi::mojom::LaunchParamsPtr launch_params, LaunchWithResultCallback callback) { - // Implement this if needed. - NOTIMPLEMENTED(); + app_service_->LacrosWebAppsControllerForTesting()->Launch( + std::move(launch_params), std::move(callback)); } void LoopbackCrosapiAppServiceProxy::LoadIcon(const std::string& app_id,
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 8871ae9..415c6fa 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
@@ -344,6 +344,33 @@ return intent_filter; } +apps::IntentFilterPtr CreateIntentFilterFromScopeExtensionInfo( + const web_app::ScopeExtensionInfo& scope_extension_info) { + CHECK(!scope_extension_info.origin.opaque()); + + auto intent_filter = std::make_unique<apps::IntentFilter>(); + + intent_filter->AddSingleValueCondition(apps::ConditionType::kAction, + apps_util::kIntentActionView, + apps::PatternMatchType::kLiteral); + + intent_filter->AddSingleValueCondition(apps::ConditionType::kScheme, + scope_extension_info.origin.scheme(), + apps::PatternMatchType::kLiteral); + + intent_filter->AddSingleValueCondition( + apps::ConditionType::kAuthority, + apps_util::AuthorityView::Encode(scope_extension_info.origin), + scope_extension_info.has_origin_wildcard + ? apps::PatternMatchType::kSuffix + : apps::PatternMatchType::kLiteral); + + intent_filter->AddSingleValueCondition(apps::ConditionType::kPath, "", + apps::PatternMatchType::kPrefix); + + return intent_filter; +} + apps::IntentFilters CreateShareIntentFiltersFromShareTarget( const apps::ShareTarget& share_target) { apps::IntentFilters filters; @@ -611,6 +638,12 @@ filters.push_back(apps_util::MakeIntentFilterForUrlScope(app_scope)); } + for (const ScopeExtensionInfo& scope_extension_info : + app.validated_scope_extensions()) { + filters.push_back( + CreateIntentFilterFromScopeExtensionInfo(scope_extension_info)); + } + #if BUILDFLAG(IS_CHROMEOS) if (chromeos::features::IsUploadOfficeToCloudEnabled()) { for (const char* scope_extension :
diff --git a/chrome/browser/web_applications/os_integration/icns_encoder_unittest.cc b/chrome/browser/web_applications/os_integration/icns_encoder_unittest.cc index b50ebb2..0d55f977 100644 --- a/chrome/browser/web_applications/os_integration/icns_encoder_unittest.cc +++ b/chrome/browser/web_applications/os_integration/icns_encoder_unittest.cc
@@ -111,16 +111,17 @@ EXPECT_TRUE(encoder.WriteToFile(icon_path)); // Now use Image I/O methods to load the .icns file back in. - base::ScopedCFTypeRef<CFDictionaryRef> empty_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> empty_dict( CFDictionaryCreate(nullptr, nullptr, nullptr, 0, nullptr, nullptr)); - base::ScopedCFTypeRef<CFURLRef> url = base::apple::FilePathToCFURL(icon_path); - base::ScopedCFTypeRef<CGImageSourceRef> source( + base::apple::ScopedCFTypeRef<CFURLRef> url = + base::apple::FilePathToCFURL(icon_path); + base::apple::ScopedCFTypeRef<CGImageSourceRef> source( CGImageSourceCreateWithURL(url, nullptr)); // And make sure we got back the same images that were written to the file. EXPECT_EQ(3u, CGImageSourceGetCount(source)); for (size_t i = 0; i < CGImageSourceGetCount(source); ++i) { - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGImageSourceCreateImageAtIndex(source, i, empty_dict)); SkBitmap bitmap = skia::CGImageToSkBitmap(cg_image); EXPECT_EQ(bitmap.width(), bitmap.height());
diff --git a/chrome/browser/web_applications/preinstalled_web_apps/google_docs.cc b/chrome/browser/web_applications/preinstalled_web_apps/google_docs.cc index eaea467..39927ec 100644 --- a/chrome/browser/web_applications/preinstalled_web_apps/google_docs.cc +++ b/chrome/browser/web_applications/preinstalled_web_apps/google_docs.cc
@@ -20,10 +20,10 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_features.h" +#include "chrome/browser/ash/drive/file_system_util.h" #endif // BUILDFLAG(IS_CHROMEOS_ASH) namespace web_app { - namespace { // clang-format off @@ -111,7 +111,7 @@ #if BUILDFLAG(IS_CHROMEOS_LACROS) return chromeos::BrowserParamsProxy::Get()->IsDriveFsBulkPinningEnabled(); #elif BUILDFLAG(IS_CHROMEOS_ASH) - return ash::features::IsDriveFsBulkPinningEnabled(); + return drive::util::IsDriveFsBulkPinningEnabled(); #endif // BUILDFLAG(IS_CHROMEOS_ASH) } #endif // BUILDFLAG(IS_CHROMEOS)
diff --git a/chrome/browser/web_applications/test/os_integration_test_override_impl.cc b/chrome/browser/web_applications/test/os_integration_test_override_impl.cc index ae8cc50..2dd5745 100644 --- a/chrome/browser/web_applications/test/os_integration_test_override_impl.cc +++ b/chrome/browser/web_applications/test/os_integration_test_override_impl.cc
@@ -785,16 +785,17 @@ #if BUILDFLAG(IS_MAC) base::FilePath icon_path = shortcut_path.AppendASCII("Contents/Resources/app.icns"); - base::ScopedCFTypeRef<CFDictionaryRef> empty_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> empty_dict( CFDictionaryCreate(nullptr, nullptr, nullptr, 0, nullptr, nullptr)); - base::ScopedCFTypeRef<CFURLRef> url = base::apple::FilePathToCFURL(icon_path); - base::ScopedCFTypeRef<CGImageSourceRef> source( + base::apple::ScopedCFTypeRef<CFURLRef> url = + base::apple::FilePathToCFURL(icon_path); + base::apple::ScopedCFTypeRef<CGImageSourceRef> source( CGImageSourceCreateWithURL(url, nullptr)); if (!source) { return 0; } // Get the first icon in the .icns file (index 0) - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGImageSourceCreateImageAtIndex(source, 0, empty_dict)); if (!cg_image) { return 0;
diff --git a/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc b/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc index a69677d..9f99331 100644 --- a/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc +++ b/chrome/browser/web_applications/web_app_install_finalizer_unittest.cc
@@ -505,8 +505,9 @@ webapps::WebappInstallSource::INTERNAL_DEFAULT); ScopeExtensionInfo scope_extension = - ScopeExtensionInfo(url::Origin::Create(GURL("htps://foo.example")), + ScopeExtensionInfo(url::Origin::Create(GURL("https://foo.example")), /*has_origin_wildcard=*/true); + CHECK(!scope_extension.origin.opaque()); info->scope_extensions = {scope_extension}; // Set data such that scope_extension will be returned in validated data. @@ -533,7 +534,7 @@ webapps::WebappInstallSource::INTERNAL_DEFAULT); ScopeExtensionInfo scope_extension = - ScopeExtensionInfo(url::Origin::Create(GURL("htps://foo.example")), + ScopeExtensionInfo(url::Origin::Create(GURL("https://foo.example")), /*has_origin_wildcard=*/true); info->scope_extensions = {scope_extension};
diff --git a/chrome/browser/web_applications/web_app_launch_queue.cc b/chrome/browser/web_applications/web_app_launch_queue.cc index d7a7890..0c0b284 100644 --- a/chrome/browser/web_applications/web_app_launch_queue.cc +++ b/chrome/browser/web_applications/web_app_launch_queue.cc
@@ -114,8 +114,8 @@ // App scope is a web app concept that is not applicable for extensions. // Therefore this check will be skipped when launching an extension URL. if (!IsExtensionURL(launch_params.target_url)) { - DCHECK(registrar_->IsUrlInAppScope(launch_params.target_url, - launch_params.app_id)); + CHECK(registrar_->IsUrlInAppExtendedScope(launch_params.target_url, + launch_params.app_id)); } DCHECK(launch_params.dir.empty() || @@ -162,7 +162,8 @@ // App scope is a web app concept that is not applicable for extensions. // Therefore this check will be skipped when launching an extension URL. if (!IsExtensionURL(handle->GetURL()) && - !registrar_->IsUrlInAppScope(handle->GetURL(), queue_.front().app_id)) { + !registrar_->IsUrlInAppExtendedScope(handle->GetURL(), + queue_.front().app_id)) { Reset(); return; } @@ -198,8 +199,8 @@ void WebAppLaunchQueue::SendLaunchParams(WebAppLaunchParams launch_params, const GURL& current_url) { // App scope is a web app concept that is not applicable for extensions. - DCHECK(IsExtensionURL(current_url) || - registrar_->IsUrlInAppScope(current_url, launch_params.app_id)); + CHECK(IsExtensionURL(current_url) || + registrar_->IsUrlInAppExtendedScope(current_url, launch_params.app_id)); mojo::AssociatedRemote<blink::mojom::WebLaunchService> launch_service; web_contents() ->GetPrimaryMainFrame()
diff --git a/chrome/browser/web_applications/web_app_registrar.cc b/chrome/browser/web_applications/web_app_registrar.cc index 684cb30..d62b02dc 100644 --- a/chrome/browser/web_applications/web_app_registrar.cc +++ b/chrome/browser/web_applications/web_app_registrar.cc
@@ -320,11 +320,6 @@ size_t WebAppRegistrar::GetAppExtendedScopeScore(const GURL& url, const AppId& app_id) const { - if (!base::FeatureList::IsEnabled( - blink::features::kWebAppEnableScopeExtensions)) { - return 0; - } - if (!url.is_valid()) { return 0; } @@ -334,6 +329,16 @@ return app_scope; } + if (!base::FeatureList::IsEnabled( + blink::features::kWebAppEnableScopeExtensions)) { + return 0; + } + + const WebApp* app = GetAppById(app_id); + if (!app || app->validated_scope_extensions().empty()) { + return 0; + } + url::Origin origin = url::Origin::Create(url); if (origin.opaque() || origin.scheme() != url::kHttpsScheme) { return 0; @@ -370,6 +375,11 @@ return GetUrlInAppScopeScore(url.spec(), app_id) > 0; } +bool WebAppRegistrar::IsUrlInAppExtendedScope(const GURL& url, + const AppId& app_id) const { + return GetAppExtendedScopeScore(url, app_id) > 0; +} + size_t WebAppRegistrar::GetUrlInAppScopeScore(const std::string& url_spec, const AppId& app_id) const { std::string app_scope = GetAppScope(app_id).spec();
diff --git a/chrome/browser/web_applications/web_app_registrar.h b/chrome/browser/web_applications/web_app_registrar.h index f1fffbb..11a7cffa 100644 --- a/chrome/browser/web_applications/web_app_registrar.h +++ b/chrome/browser/web_applications/web_app_registrar.h
@@ -298,8 +298,13 @@ // Returns whether |url| is in the scope of |app_id|. bool IsUrlInAppScope(const GURL& url, const AppId& app_id) const; - // Returns the strength of matching |url| to the extended & regular scope of - // |app_id|. Returns 0 if not in extended scope. + // Returns whether |url| is in scope or scope_extensions of |app_id|. + // Only checks scope if scope_extensions is disabled. + bool IsUrlInAppExtendedScope(const GURL& url, const AppId& app_id) const; + + // Returns the strength of matching |url| to the scope and scope_extensions of + // |app_id|. Returns 0 if not in either. + // Only checks scope if scope_extensions is disabled. size_t GetAppExtendedScopeScore(const GURL& url, const AppId& app_id) const; // Returns the strength of matching |url_spec| to the scope of |app_id|,
diff --git a/chrome/browser/web_applications/web_app_scope_extensions_browsertest.cc b/chrome/browser/web_applications/web_app_scope_extensions_browsertest.cc new file mode 100644 index 0000000..78c0407 --- /dev/null +++ b/chrome/browser/web_applications/web_app_scope_extensions_browsertest.cc
@@ -0,0 +1,347 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/strings/string_util.h" +#include "base/test/scoped_feature_list.h" +#include "chrome/browser/apps/app_service/app_service_proxy.h" +#include "chrome/browser/apps/app_service/app_service_proxy_factory.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_commands.h" +#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h" +#include "chrome/browser/ui/web_applications/test/web_app_navigation_browsertest.h" +#include "chrome/browser/web_applications/os_integration/os_integration_manager.h" +#include "chrome/browser/web_applications/web_app.h" +#include "chrome/browser/web_applications/web_app_provider.h" +#include "chrome/browser/web_applications/web_app_registrar.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/content_mock_cert_verifier.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" +#include "third_party/blink/public/common/features.h" + +#if BUILDFLAG(IS_CHROMEOS) +#include "chrome/browser/apps/intent_helper/preferred_apps_test_util.h" +#include "chrome/browser/web_applications/test/app_registry_cache_waiter.h" +#endif + +#if BUILDFLAG(IS_CHROMEOS_LACROS) +#include "chrome/browser/extensions/extension_keeplist_chromeos.h" +#include "chrome/browser/web_applications/app_service/test/loopback_crosapi_app_service_proxy.h" +#endif + +namespace web_app { + +#if BUILDFLAG(IS_CHROMEOS) + +class WebAppScopeExtensionsBrowserTest : public WebAppNavigationBrowserTest { + public: + WebAppScopeExtensionsBrowserTest() + : WebAppScopeExtensionsBrowserTest(/*enabled=*/true) {} + explicit WebAppScopeExtensionsBrowserTest(bool enabled) + : primary_server_(net::EmbeddedTestServer::TYPE_HTTPS), + secondary_server_(net::EmbeddedTestServer::TYPE_HTTPS) { + feature_list_.InitWithFeatureState( + blink::features::kWebAppEnableScopeExtensions, enabled); + } + ~WebAppScopeExtensionsBrowserTest() override = default; + + void SetUpOnMainThread() override { + WebAppNavigationBrowserTest::SetUpOnMainThread(); + +#if BUILDFLAG(IS_CHROMEOS_LACROS) + extensions::SetEmptyAshKeeplistForTest(); + loopback_crosapi_.emplace(browser()->profile()); +#endif + + primary_server_.AddDefaultHandlers(GetChromeTestDataDir()); + primary_server_.RegisterRequestHandler( + base::BindRepeating(&WebAppScopeExtensionsBrowserTest::RequestHandler, + base::Unretained(this))); + ASSERT_TRUE(primary_server_.Start()); + primary_origin_ = primary_server_.GetOrigin(); + + secondary_server_.AddDefaultHandlers(GetChromeTestDataDir()); + secondary_server_.RegisterRequestHandler( + base::BindRepeating(&WebAppScopeExtensionsBrowserTest::RequestHandler, + base::Unretained(this))); + ASSERT_TRUE(secondary_server_.Start()); + secondary_origin_ = secondary_server_.GetOrigin(); + + unrelated_server_.AddDefaultHandlers(GetChromeTestDataDir()); + ASSERT_TRUE(unrelated_server_.Start()); + unrelated_url_ = unrelated_server_.GetURL("/simple.html"); + } + + void TearDownOnMainThread() override { +#if BUILDFLAG(IS_CHROMEOS_LACROS) + loopback_crosapi_.reset(); +#endif + + app_ = nullptr; + } + + std::unique_ptr<net::test_server::HttpResponse> RequestHandler( + const net::test_server::HttpRequest& request) { + auto it = url_overrides_.find(request.GetURL()); + if (it == url_overrides_.end()) { + return nullptr; + } + auto http_response = + std::make_unique<net::test_server::BasicHttpResponse>(); + http_response->set_code(net::HTTP_OK); + http_response->set_content(it->second); + return http_response; + } + + WebAppProvider& provider() { + return *WebAppProvider::GetForTest(browser()->profile()); + } + + void InstallScopeExtendedWebApp(std::string manifest_file, + std::string association_file) { + GURL manifest_url = primary_server_.GetURL("/web_apps/manifest.json"); + GURL association_url = + secondary_server_.GetURL("/.well-known/web-app-origin-association"); + + url_overrides_[manifest_url] = manifest_file; + url_overrides_[association_url] = association_file; + + AppId app_id = InstallWebAppFromPageAndCloseAppBrowser( + browser(), + primary_server_.GetURL("/web_apps/get_manifest.html?manifest.json")); + + app_ = provider().registrar_unsafe().GetAppById(app_id); + + // Turn on link capturing. +#if BUILDFLAG(IS_CHROMEOS) + AppReadinessWaiter(browser()->profile(), app_id).Await(); + apps_util::SetSupportedLinksPreferenceAndWait(browser()->profile(), app_id); +#else + static_assert( + false, + "Support WML scope_extensions link capturing once it's implemented"); +#endif + } + + bool WebAppCapturesUrl(const GURL& url) { + CHECK_NE(url, unrelated_url_); + NavigateToURLAndWait(browser(), unrelated_url_); + + ui_test_utils::BrowserChangeObserver browser_observer( + /*browser=*/nullptr, + ui_test_utils::BrowserChangeObserver::ChangeType::kAdded); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + WebAppNavigationBrowserTest::ClickLinkAndWaitForURL( + web_contents, + /*link_url=*/url, + /*target_url=*/url, WebAppNavigationBrowserTest::LinkTarget::SELF, + /*rel=*/""); + + // Navigation happened in the browser tab instead of being link captured. + if (web_contents->GetVisibleURL() == url) { + return false; + } + + Browser* app_browser = browser_observer.Wait(); + EXPECT_EQ( + app_browser->tab_strip_model()->GetActiveWebContents()->GetVisibleURL(), + url); + chrome::CloseWindow(app_browser); + return true; + } + + protected: +#if BUILDFLAG(IS_CHROMEOS_LACROS) + absl::optional<LoopbackCrosapiAppServiceProxy> loopback_crosapi_; +#endif + + net::EmbeddedTestServer primary_server_; + url::Origin primary_origin_; + + net::EmbeddedTestServer secondary_server_; + url::Origin secondary_origin_; + + net::EmbeddedTestServer unrelated_server_; + GURL unrelated_url_; + + std::map<GURL, std::string> url_overrides_; + + raw_ptr<const WebApp> app_ = nullptr; + + base::test::ScopedFeatureList feature_list_; + content::ContentMockCertVerifier cert_verifier_; + OsIntegrationManager::ScopedSuppressForTesting os_hooks_supress_; +}; + +IN_PROC_BROWSER_TEST_F(WebAppScopeExtensionsBrowserTest, + ExtendedLinkCapturingBasic) { + InstallScopeExtendedWebApp( + /*manifest_file=*/base::ReplaceStringPlaceholders( + R"( + { + "Name": "Test app", + "start_url": "/", + "scope": "/", + "scope_extensions": [{ + "origin": "$1" + }] + })", + {secondary_origin_.Serialize()}, nullptr), + /*association_file=*/base::ReplaceStringPlaceholders( + R"( + { + "web_apps": [{ + "web_app_identity": "$1" + }] + })", + {primary_origin_.Serialize()}, nullptr)); + + EXPECT_THAT( + app_->scope_extensions(), + testing::ElementsAre(ScopeExtensionInfo{.origin = secondary_origin_})); + EXPECT_EQ(app_->scope_extensions(), app_->validated_scope_extensions()); + + ASSERT_TRUE( + WebAppCapturesUrl(primary_server_.GetURL("/web_apps/basic.html"))); + EXPECT_TRUE( + WebAppCapturesUrl(secondary_server_.GetURL("/web_apps/basic.html"))); +} + +IN_PROC_BROWSER_TEST_F(WebAppScopeExtensionsBrowserTest, + ExtendedLinkCapturingFocusExisting) { + InstallScopeExtendedWebApp( + /*manifest_file=*/base::ReplaceStringPlaceholders( + R"( + { + "Name": "Test app", + "start_url": "/simple.html", + "scope": "/", + "scope_extensions": [{ + "origin": "$1" + }], + "launch_handler": { + "client_mode": "focus-existing" + } + })", + {secondary_origin_.Serialize()}, nullptr), + /*association_file=*/base::ReplaceStringPlaceholders( + R"( + { + "web_apps": [{ + "web_app_identity": "$1" + }] + })", + {primary_server_.GetURL("/simple.html").spec()}, nullptr)); + + Browser* app_browser = LaunchWebAppBrowserAndWait(app_->app_id()); + content::WebContents* app_web_contents = + app_browser->tab_strip_model()->GetActiveWebContents(); + + // Await the first LaunchParams. + const char* script = R"( + window.launchParamsPromise = new Promise(resolve => { + window.resolveLaunchParamsPromise = resolve; + }); + launchQueue.setConsumer(launchParams => { + window.resolveLaunchParamsPromise(launchParams.targetURL); + window.resolveLaunchParamsPromise = null; + }); + window.launchParamsPromise; + )"; + EXPECT_EQ(EvalJs(app_web_contents, script).ExtractString(), + app_->start_url().spec()); + + // Set up the next LaunchParams promise. + script = R"( + window.launchParamsPromise = new Promise(resolve => { + window.resolveLaunchParamsPromise = resolve; + }); + true; + )"; + EXPECT_TRUE(EvalJs(app_web_contents, script).ExtractBool()); + + // Link capture an extended scope URL. + GURL extended_scope_url = + secondary_server_.GetURL("/url/that/does/not/get/navigated/to"); + ClickLink(browser()->tab_strip_model()->GetActiveWebContents(), + /*link_url=*/extended_scope_url, + /*target_url=*/extended_scope_url); + + // Await the second LaunchParams in the same app document. + EXPECT_EQ( + EvalJs(app_web_contents, "window.launchParamsPromise").ExtractString(), + extended_scope_url.spec()); + // The document should not have navigated due to "focus-existing". + EXPECT_EQ(app_web_contents->GetVisibleURL(), app_->start_url().spec()); +} + +IN_PROC_BROWSER_TEST_F(WebAppScopeExtensionsBrowserTest, + ExtendedLinkCapturingBadAssociationFile) { + InstallScopeExtendedWebApp( + /*manifest_file=*/base::ReplaceStringPlaceholders( + R"( + { + "Name": "Test app", + "start_url": "/", + "scope": "/", + "scope_extensions": [{ + "origin": "$1" + }] + })", + {secondary_origin_.Serialize()}, nullptr), + /*association_file=*/"garbage"); + + EXPECT_TRUE( + WebAppCapturesUrl(primary_server_.GetURL("/web_apps/basic.html"))); + EXPECT_FALSE( + WebAppCapturesUrl(secondary_server_.GetURL("/web_apps/basic.html"))); +} + +class WebAppScopeExtensionsDisabledBrowserTest + : public WebAppScopeExtensionsBrowserTest { + public: + WebAppScopeExtensionsDisabledBrowserTest() + : WebAppScopeExtensionsBrowserTest(/*enabled=*/false) {} +}; + +IN_PROC_BROWSER_TEST_F(WebAppScopeExtensionsDisabledBrowserTest, + NoExtendedLinkCapturing) { + InstallScopeExtendedWebApp( + /*manifest_file=*/base::ReplaceStringPlaceholders( + R"( + { + "Name": "Test app", + "start_url": "/", + "scope": "/", + "scope_extensions": [{ + "origin": "$1" + }] + })", + {secondary_origin_.Serialize()}, nullptr), + /*association_file=*/base::ReplaceStringPlaceholders( + R"( + { + "web_apps": [{ + "web_app_identity": "$1" + }] + })", + {primary_origin_.Serialize()}, nullptr)); + + EXPECT_TRUE(app_->scope_extensions().empty()); + EXPECT_TRUE(app_->validated_scope_extensions().empty()); + + ASSERT_TRUE( + WebAppCapturesUrl(primary_server_.GetURL("/web_apps/basic.html"))); + EXPECT_FALSE( + WebAppCapturesUrl(secondary_server_.GetURL("/web_apps/basic.html"))); +} + +#endif // BUILDFLAG(IS_CHROMEOS) + +} // namespace web_app
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model.cc b/chrome/browser/webauthn/authenticator_request_dialog_model.cc index f4027af..cd3fa61 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model.cc
@@ -383,7 +383,10 @@ } } else if (priority_mechanism_index_) { Mechanism& mechanism = mechanisms_[*priority_mechanism_index_]; - if (absl::holds_alternative<Mechanism::Credential>(mechanism.type)) { + const Mechanism::Credential* cred = + absl::get_if<Mechanism::Credential>(&mechanism.type); + if (cred != nullptr && + cred->value().source != device::AuthenticatorType::kICloudKeychain) { SetCurrentStep(Step::kSelectPriorityMechanism); } else { mechanism.callback.Run();
diff --git a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc index a227baa9..66c0741 100644 --- a/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc +++ b/chrome/browser/webauthn/authenticator_request_dialog_model_unittest.cc
@@ -309,8 +309,8 @@ const auto plat_ui = Step::kNotStarted; const auto cable_ui = Step::kCableActivate; [[maybe_unused]] const auto create_pk = Step::kCreatePasskey; - const auto use_pk = Step::kPreSelectSingleAccount; - const auto use_pk_multi = Step::kPreSelectAccount; + [[maybe_unused]] const auto use_pk = Step::kPreSelectSingleAccount; + [[maybe_unused]] const auto use_pk_multi = Step::kPreSelectAccount; const auto qr = Step::kCableV2QRCode; const auto pconf = Step::kPhoneConfirmationSheet; const auto hero = Step::kSelectPriorityMechanism; @@ -335,11 +335,36 @@ // If there's only a single mechanism, it should activate. {L, mc, {usb}, {}, {}, {t(usb)}, usb_ui}, {L, ga, {usb}, {}, {}, {t(usb)}, usb_ui}, - // ... otherwise should the selection sheet. +#if defined(NEW_UI) + {L, ga, {usb, cable}, {}, {}, {add}, qr}, + {L, ga, {usb, cable}, {}, {}, {add}, qr}, +#else + // ... otherwise show the selection sheet. {L, ga, {usb, cable}, {}, {}, {add, t(usb)}, mss}, {L, ga, {usb, cable}, {}, {}, {add, t(usb)}, mss}, +#endif // If the platform authenticator has a credential it should activate. +#if defined(NEW_UI) + {L, ga, {usb, internal}, {has_plat, one_cred}, {}, {c(cred1), t(usb)}, + hero}, + // Even with an empty allow list. + {L, + ga, + {usb, internal}, + {has_plat, one_cred, empty_al}, + {}, + {c(cred1), t(usb)}, + hero}, + // Two credentials shows mechanism selection. + {L, + ga, + {usb, internal}, + {has_plat, two_cred, empty_al}, + {}, + {c(cred1), c(cred2), t(usb)}, + mss}, +#else {L, ga, {usb, internal}, {has_plat}, {}, {t(internal), t(usb)}, plat_ui}, // ... but with an empty allow list the user should be prompted first. {L, @@ -356,6 +381,7 @@ {}, {t(internal), t(usb)}, use_pk_multi}, +#endif // MakeCredential with attachment=platform shows the 'Create a passkey' // step, but only on macOS. On other OSes, we defer to the platform. @@ -391,9 +417,27 @@ {L, ga, {}, {has_winapi}, {}, {winapi}, plat_ui}, // ... even if, somehow, there's another transport. {L, mc, {usb}, {has_winapi}, {}, {winapi, t(usb)}, plat_ui}, +#if defined(NEW_UI) + // TODO(NEWUI): This is seemingly broken with the new UI, but we've not + // enabled that on Windows yet. + {L, ga, {usb}, {has_winapi}, {}, {winapi, t(usb)}, mss}, +#else {L, ga, {usb}, {has_winapi}, {}, {winapi, t(usb)}, plat_ui}, +#endif // A caBLEv1 extension should cause us to go directly to caBLE. +#if defined(NEW_UI) + {L, ga, {usb, cable}, {v1}, {}, {t(cable), t(usb)}, cable_ui}, + // A caBLEv2 extension should cause us to go directly to caBLE, but also + // show the AOA option. + {L, + ga, + {usb, aoa, cable}, + {v2}, + {}, + {t(aoa), t(cable), t(usb)}, + cable_ui}, +#else {L, ga, {usb, cable}, {v1}, {}, {t(usb), t(cable)}, cable_ui}, // A caBLEv2 extension should cause us to go directly to caBLE, but also // show the AOA option. @@ -404,7 +448,26 @@ {}, {t(usb), t(aoa), t(cable)}, cable_ui}, +#endif +#if defined(NEW_UI) + // If there are linked phones then AOA doesn't show up, but the phones do, + // and sorted. The selection sheet should show. + {L, + mc, + {usb, aoa, cable}, + {}, + {pqr("a"), pqr("b")}, + {p("a"), p("b"), add}, + mss}, + {L, + ga, + {usb, aoa, cable}, + {}, + {pqr("a"), pqr("b")}, + {p("a"), p("b"), add}, + mss}, +#else // If there are linked phones then AOA doesn't show up, but the phones do, // and sorted. The selection sheet should show. {L, @@ -421,10 +484,20 @@ {pqr("a"), pqr("b")}, {p("a"), p("b"), add, t(usb)}, mss}, +#endif // If this is a Conditional UI request, don't offer the platform // authenticator. {L, ga, {usb, internal}, {c_ui}, {}, {t(usb)}, usb_ui}, +#if defined(NEW_UI) + {L, + ga, + {usb, internal, cable}, + {c_ui}, + {pqr("a")}, + {p("a"), add}, + mss}, +#else {L, ga, {usb, internal, cable}, @@ -432,6 +505,7 @@ {pqr("a")}, {p("a"), add, t(usb)}, mss}, +#endif // On Windows, mc with rk=required jumps to the platform UI when caBLE // isn't an option. The case where caBLE is possible is tested below. @@ -443,9 +517,16 @@ // On Windows, ga with an empty allow list goes to the platform UI unless // caBLE is an option and resident-key is required, which is tested below. {L, ga, {}, {has_winapi, empty_al}, {}, {winapi}, plat_ui}, +#if defined(NEW_UI) + // With a non-empty allow list containing non phone credentials, always + // jump to Windows UI. + // TODO(NEWUI): we should maintain this behaviour on Windows. + {L, ga, {cable}, {has_winapi}, {}, {winapi, add}, mss}, +#else // With a non-empty allow list containing non phone credentials, always // jump to Windows UI. {L, ga, {cable}, {has_winapi}, {}, {winapi, add}, plat_ui}, +#endif {L, ga, {}, {has_winapi}, {}, {winapi}, plat_ui}, // Except when the request is legacy cable. {L, ga, {cable, aoa}, {has_winapi, v1}, {}, {winapi, t(cable)}, cable_ui}, @@ -457,6 +538,43 @@ {winapi, t(aoa), t(cable)}, cable_ui}, +#if defined(NEW_UI) + // QR code first: Make credential should jump to the QR code with + // RK=true. + {L, + mc, + {usb, internal, cable}, + {rk, att_xplat}, + {}, + {add, t(internal)}, + qr}, + // Unless there is a phone paired already. + {L, + mc, + {usb, internal, cable}, + {rk, att_xplat}, + {pqr("a")}, + {p("a"), add, t(internal)}, + mss}, + // Or if attachment=any + {L, + mc, + {usb, internal, cable}, + {rk, att_any}, + {}, + {add, t(internal)}, + mss}, + // If RK=false, go to the default for the platform instead. + { + L, + mc, + {usb, internal, cable}, + {}, + {}, + {add, t(internal)}, + create_pk, + }, +#else // QR code first: Make credential should jump to the QR code with // RK=true. {L, @@ -496,9 +614,66 @@ mss, #endif }, +#endif // Windows should also jump to the QR code first. {L, mc, {cable}, {rk, has_winapi}, {}, {winapi, add}, qr}, +#if defined(NEW_UI) + // QR code first: Get assertion should jump to the QR code with empty + // allow-list. + {L, + ga, + {usb, internal, cable}, + {empty_al}, + {}, + {add}, + qr}, + // And if the allow list only contains phones. + {L, + ga, + {internal, cable}, + {only_hybrid_or_internal}, + {}, + {add}, + qr}, + // Unless there is a phone paired already. + {L, + ga, + {usb, internal, cable}, + {empty_al}, + {pqr("a")}, + {p("a"), add}, + mss}, + // Or a recognized platform credential. + {L, + ga, + {usb, internal, cable}, + {empty_al, has_plat, one_cred}, + {}, + {c(cred1), add}, + mss}, + // Ignore the platform credential for conditional ui requests + {L, + ga, + {usb, internal, cable}, + {c_ui, empty_al, has_plat, one_cred}, + {}, + {c(cred1), add}, + qr}, + // If there is an allow-list containing USB, go to QR code as well. + {L, ga, {usb, internal, cable}, {}, {}, {add}, qr}, + // Windows should also jump to the QR code first. + // TODO: the expectation here (mss) doesn't match the comment. + {L, ga, {cable}, {empty_al, has_winapi}, {}, {winapi, add}, mss}, + // Unless there is a recognized platform credential. + {L, + ga, + {cable}, + {empty_al, has_winapi, has_plat, one_cred}, + {}, + {c(cred1), winapi, add}, + hero}, +#else // QR code first: Get assertion should jump to the QR code with empty // allow-list. {L, @@ -553,6 +728,7 @@ {}, {winapi, add}, plat_ui}, +#endif // For <=Win 10, we can't tell if there is a credential or not. Show the // mechanism selection screen instead. {L, @@ -563,9 +739,43 @@ {winapi, add}, mss}, +#if defined(NEW_UI) // Phone confirmation sheet: Get assertion should jump to it if there is - // a - // single phone paired. + // a single phone paired. + {L, + ga, + {cable, internal}, + {only_hybrid_or_internal}, + {pqr("a")}, + {p("a"), add}, + pconf}, + // Even on Windows. + {L, + ga, + {cable}, + {only_hybrid_or_internal, has_winapi}, + {pqr("a")}, + {p("a"), add}, + pconf}, + // Unless there is a recognized platform credential. + // Or a USB credential. + {L, + ga, + {cable, internal}, + {only_hybrid_or_internal, has_plat}, + {pqr("a")}, + {p("a"), add}, + mss}, + {L, + ga, + {usb, cable, internal}, + {}, + {pqr("a")}, + {p("a"), add}, + mss}, +#else + // Phone confirmation sheet: Get assertion should jump to it if there is + // a single phone paired. {L, ga, {cable, internal}, @@ -597,6 +807,7 @@ {pqr("a")}, {p("a"), add, t(internal), t(usb)}, mss}, +#endif // Or this is a conditional UI request. {L, ga, @@ -605,6 +816,16 @@ {pqr("a")}, {p("a"), add}, mss}, +#if defined(NEW_UI) + // Go to the mechanism selection screen if there are more phones paired. + {L, + ga, + {cable, internal}, + {only_hybrid_or_internal}, + {pqr("a"), pqr("b")}, + {p("a"), p("b"), add}, + mss}, +#else // Go to the mechanism selection screen if there are more phones paired. {L, ga, @@ -613,6 +834,7 @@ {pqr("a"), pqr("b")}, {p("a"), p("b"), add, t(internal)}, mss}, +#endif }; // Tests for the new UI that lists synced passkeys mixed with local @@ -1175,13 +1397,19 @@ model.AddObserver(&mock_observer); TransportAvailabilityInfo transports_info; - transports_info.request_type = RequestType::kGetAssertion; + transports_info.request_type = RequestType::kMakeCredential; + transports_info.make_credential_attachment = + device::AuthenticatorAttachment::kAny; transports_info.available_transports = kAllTransportsWithoutCable; EXPECT_CALL(mock_observer, OnStepTransition()); model.StartFlow(std::move(transports_info), /*is_conditional_mediation=*/false); +#if BUILDFLAG(IS_MAC) + EXPECT_EQ(Step::kCreatePasskey, model.current_step()); +#else EXPECT_EQ(Step::kMechanismSelection, model.current_step()); +#endif testing::Mock::VerifyAndClearExpectations(&mock_observer); EXPECT_CALL(mock_observer, OnStepTransition()); @@ -1305,12 +1533,19 @@ } } +#if !defined(NEW_UI) + +// TODO: reenable this test. I'm not sure that the intended behaviour on +// Windows will be. + TEST_F(AuthenticatorRequestDialogModelTest, RequestCallbackForWindowsAuthenticatorIsInvokedAutomatically) { constexpr char kWinAuthenticatorId[] = "some_authenticator_id"; ::device::FidoRequestHandlerBase::TransportAvailabilityInfo transports_info; transports_info.request_type = RequestType::kMakeCredential; + transports_info.make_credential_attachment = + device::AuthenticatorAttachment::kPlatform; transports_info.available_transports = {}; transports_info.has_win_native_api_authenticator = true; @@ -1333,6 +1568,8 @@ EXPECT_THAT(dispatched_authenticator_ids, ElementsAre(kWinAuthenticatorId)); } +#endif + TEST_F(AuthenticatorRequestDialogModelTest, ConditionalUINoRecognizedCredential) { AuthenticatorRequestDialogModel model(main_rfh()); @@ -1626,7 +1863,11 @@ transports_info.recognized_credentials = {kCred1, kCred2}; model.StartFlow(std::move(transports_info), /*is_conditional_mediation=*/false); +#if defined(NEW_UI) + EXPECT_EQ(model.current_step(), Step::kMechanismSelection); +#else EXPECT_EQ(model.current_step(), Step::kPreSelectAccount); +#endif EXPECT_EQ(request_num_called, 0); // After preselecting an account, the request should be dispatched to the @@ -1793,6 +2034,32 @@ base::WeakPtrFactory<RequestCallbackReceiver> weak_factory_{this}; }; +template <class Value> +class RepeatingValueCallbackReceiver { + public: + base::RepeatingCallback<void(Value)> Callback() { + return base::BindRepeating(&RepeatingValueCallbackReceiver::OnCallback, + base::Unretained(this)); + } + + Value WaitForResult() { + if (!value_) { + run_loop_->Run(); + } + Value ret = std::move(*value_); + run_loop_ = std::make_unique<base::RunLoop>(); + return ret; + } + + private: + void OnCallback(Value value) { + value_ = std::move(value); + run_loop_->Quit(); + } + absl::optional<Value> value_; + std::unique_ptr<base::RunLoop> run_loop_ = std::make_unique<base::RunLoop>(); +}; + TEST_F(MultiplePlatformAuthenticatorsTest, DeduplicateAccounts) { using Mechanism = AuthenticatorRequestDialogModel::Mechanism; const struct { @@ -1815,6 +2082,10 @@ AuthenticatorRequestDialogModel model(main_rfh()); model.set_allow_icloud_keychain(true); + RepeatingValueCallbackReceiver<device::PublicKeyCredentialDescriptor> + account_preselected_callback; + model.SetAccountPreselectedCallback( + account_preselected_callback.Callback()); model.StartFlow(std::move(transports_info), /*is_conditional_mediation=*/false); ASSERT_EQ(model.priority_mechanism_index_.has_value(), @@ -1924,6 +2195,55 @@ } } +TEST_F(MultiplePlatformAuthenticatorsTest, + OnlyShowConfirmationSheetForProfileAuthenticator) { + base::test::ScopedFeatureList scoped_feature_list_{ + device::kWebAuthnICloudKeychain}; + + for (const auto credential_source : + {device::AuthenticatorType::kTouchID, + device::AuthenticatorType::kICloudKeychain}) { + SCOPED_TRACE(static_cast<int>(credential_source)); + + TransportAvailabilityInfo transports_info; + transports_info.has_icloud_keychain = true; + transports_info.available_transports = {AuthenticatorTransport::kInternal}; + transports_info.request_type = device::FidoRequestType::kGetAssertion; + transports_info.has_empty_allow_list = false; + + if (credential_source == device::AuthenticatorType::kTouchID) { + transports_info.recognized_credentials = {kCred2}; + transports_info.has_platform_authenticator_credential = + device::FidoRequestHandlerBase::RecognizedCredential:: + kHasRecognizedCredential; + } else { + transports_info.recognized_credentials = {kCred1FromICloudKeychain}; + transports_info.has_icloud_keychain_credential = + device::FidoRequestHandlerBase::RecognizedCredential:: + kHasRecognizedCredential; + } + + AuthenticatorRequestDialogModel model(main_rfh()); + model.set_allow_icloud_keychain(true); + RepeatingValueCallbackReceiver<device::PublicKeyCredentialDescriptor> + account_preselected_callback; + model.SetAccountPreselectedCallback( + account_preselected_callback.Callback()); + + model.StartFlow(std::move(transports_info), + /*is_conditional_mediation=*/false); + + if (credential_source == device::AuthenticatorType::kTouchID) { + EXPECT_EQ(model.current_step(), Step::kSelectPriorityMechanism); + } else { + EXPECT_EQ(model.current_step(), Step::kNotStarted); + device::PublicKeyCredentialDescriptor descriptor = + account_preselected_callback.WaitForResult(); + EXPECT_EQ(descriptor.id, kCred1FromICloudKeychain.cred_id); + } + } +} + #endif class ListPasskeysFromSyncTest : public AuthenticatorRequestDialogModelTest { @@ -1932,32 +2252,6 @@ device::kWebAuthnNewPasskeyUI}; }; -template <class Value> -class RepeatingValueCallbackReceiver { - public: - base::RepeatingCallback<void(Value)> Callback() { - return base::BindRepeating(&RepeatingValueCallbackReceiver::OnCallback, - base::Unretained(this)); - } - - Value WaitForResult() { - if (!value_) { - run_loop_->Run(); - } - Value ret = std::move(*value_); - run_loop_ = std::make_unique<base::RunLoop>(); - return ret; - } - - private: - void OnCallback(Value value) { - value_ = std::move(value); - run_loop_->Quit(); - } - absl::optional<Value> value_; - std::unique_ptr<base::RunLoop> run_loop_ = std::make_unique<base::RunLoop>(); -}; - TEST_F(ListPasskeysFromSyncTest, MechanismsFromUserAccounts) { // Set up a model with two local passkeys and a GPM passkey. AuthenticatorRequestDialogModel model(main_rfh()); @@ -1984,7 +2278,7 @@ const std::string kLocalAuthenticatorId = "local-authenticator"; model.saved_authenticators().AddAuthenticator(AuthenticatorReference( kLocalAuthenticatorId, AuthenticatorTransport::kInternal, - device::AuthenticatorType::kWinNative)); + device::AuthenticatorType::kOther)); model.StartFlow(std::move(transports_info), /*is_conditional_mediation=*/false); @@ -2010,7 +2304,7 @@ model.StartOver(); model.saved_authenticators().AddAuthenticator(AuthenticatorReference( kLocalAuthenticatorId, AuthenticatorTransport::kInternal, - device::AuthenticatorType::kWinNative)); + device::AuthenticatorType::kOther)); // The second entry will be `kCred2`. const AuthenticatorRequestDialogModel::Mechanism& mech2 = @@ -2030,7 +2324,7 @@ model.StartOver(); model.saved_authenticators().AddAuthenticator(AuthenticatorReference( kLocalAuthenticatorId, AuthenticatorTransport::kInternal, - device::AuthenticatorType::kWinNative)); + device::AuthenticatorType::kOther)); // The third entry should correspond to `kPhoneCred1`. const AuthenticatorRequestDialogModel::Mechanism& mech3 =
diff --git a/chrome/build/android-arm32.pgo.txt b/chrome/build/android-arm32.pgo.txt index 137fd4c..b58bf7d 100644 --- a/chrome/build/android-arm32.pgo.txt +++ b/chrome/build/android-arm32.pgo.txt
@@ -1 +1 @@ -chrome-android32-main-1692618364-ace317e23b123701b7ed2602e5c7e8dcbc3ede3a.profdata +chrome-android32-main-1692683753-5368635162c2abe76bf2adcf2e964a93ba22475e.profdata
diff --git a/chrome/build/android-arm64.pgo.txt b/chrome/build/android-arm64.pgo.txt index 298ff28..6ea05c0 100644 --- a/chrome/build/android-arm64.pgo.txt +++ b/chrome/build/android-arm64.pgo.txt
@@ -1 +1 @@ -chrome-android64-main-1692618364-f69a95af5428fc8605ae5367cc00256c30e30550.profdata +chrome-android64-main-1692683753-e0dc4b06aee43e9978b941a8bd28c54972d57de7.profdata
diff --git a/chrome/build/lacros64.pgo.txt b/chrome/build/lacros64.pgo.txt index c72fbd5..74ce7627 100644 --- a/chrome/build/lacros64.pgo.txt +++ b/chrome/build/lacros64.pgo.txt
@@ -1 +1 @@ -chrome-chromeos-amd64-generic-main-1692618364-a02bf6b412a1fcb23c2b63629bf3f1b3d9b11b5e.profdata +chrome-chromeos-amd64-generic-main-1692662680-925b30d1cff012a6be74f5282d95e83c76a8c63b.profdata
diff --git a/chrome/build/linux.pgo.txt b/chrome/build/linux.pgo.txt index 9c6a2c9e..1ec78ea7 100644 --- a/chrome/build/linux.pgo.txt +++ b/chrome/build/linux.pgo.txt
@@ -1 +1 @@ -chrome-linux-main-1692618364-d08989b2e3ca7c08af8d8fbbd161e09baafd8b6f.profdata +chrome-linux-main-1692662376-442cc1d9806d2bf8bd022f6e2628edc6ab8ce603.profdata
diff --git a/chrome/build/mac-arm.pgo.txt b/chrome/build/mac-arm.pgo.txt index 108fad0..b4ecebd 100644 --- a/chrome/build/mac-arm.pgo.txt +++ b/chrome/build/mac-arm.pgo.txt
@@ -1 +1 @@ -chrome-mac-arm-main-1692647788-bf581906dfacaac623d842aaf6740a496ff616ce.profdata +chrome-mac-arm-main-1692683753-732c012083303bc4429e60756aef43f2e93358df.profdata
diff --git a/chrome/build/mac.pgo.txt b/chrome/build/mac.pgo.txt index 69ea016..9f48d67 100644 --- a/chrome/build/mac.pgo.txt +++ b/chrome/build/mac.pgo.txt
@@ -1 +1 @@ -chrome-mac-main-1692640759-ed1b8998a68bfb20647115222ba1948f12300023.profdata +chrome-mac-main-1692662376-47da963e461ae818ee9d7b822d54e5c47a9ae683.profdata
diff --git a/chrome/build/win32.pgo.txt b/chrome/build/win32.pgo.txt index e20327a..7701bde42 100644 --- a/chrome/build/win32.pgo.txt +++ b/chrome/build/win32.pgo.txt
@@ -1 +1 @@ -chrome-win32-main-1692651568-ec042f60246e27ad9e5302a3d83242f083405a61.profdata +chrome-win32-main-1692672821-a18b318e144b3cf5c8db04ed3c69c815053ae5fa.profdata
diff --git a/chrome/build/win64.pgo.txt b/chrome/build/win64.pgo.txt index 96d3be5..6f0b5918 100644 --- a/chrome/build/win64.pgo.txt +++ b/chrome/build/win64.pgo.txt
@@ -1 +1 @@ -chrome-win64-main-1692651568-19488fd7625f1a7ed98528e03f8aac9a687b6cd1.profdata +chrome-win64-main-1692672821-b70ecde1ad19c86b6651f00ee88a941386e583c1.profdata
diff --git a/chrome/common/extensions/image_writer/image_writer_util_mac.cc b/chrome/common/extensions/image_writer/image_writer_util_mac.cc index c40afa58..7f4da0b9 100644 --- a/chrome/common/extensions/image_writer/image_writer_util_mac.cc +++ b/chrome/common/extensions/image_writer/image_writer_util_mac.cc
@@ -30,7 +30,7 @@ current_obj = parent_obj; parent_obj_ref.reset(parent_obj); - base::ScopedCFTypeRef<CFStringRef> class_name( + base::apple::ScopedCFTypeRef<CFStringRef> class_name( IOObjectCopyClass(current_obj)); if (!class_name) { LOG(ERROR) << "Could not get object class of IO Registry Entry."; @@ -52,7 +52,7 @@ std::string* out_bsd_name, uint64_t* out_size_in_bytes, bool* out_removable) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> dict; + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> dict; kern_return_t result = IORegistryEntryCreateCFProperties( disk_obj, dict.InitializeInto(), kCFAllocatorDefault, 0); if (result != KERN_SUCCESS) {
diff --git a/chrome/installer/util/delete_reg_key_work_item_unittest.cc b/chrome/installer/util/delete_reg_key_work_item_unittest.cc index 2043d499..609131a 100644 --- a/chrome/installer/util/delete_reg_key_work_item_unittest.cc +++ b/chrome/installer/util/delete_reg_key_work_item_unittest.cc
@@ -4,15 +4,14 @@ #include "chrome/installer/util/delete_reg_key_work_item.h" -#include <windows.h> - -#include <atlsecurity.h> // NOLINT #include <stddef.h> +#include <windows.h> #include <memory> #include "base/logging.h" #include "base/win/registry.h" +#include "base/win/security_descriptor.h" #include "chrome/installer/util/registry_test_data.h" #include "chrome/installer/util/work_item.h" #include "testing/gtest/include/gtest/gtest.h" @@ -103,17 +102,21 @@ EXPECT_EQ(ERROR_SUCCESS, subkey2.Create(subkey.Handle(), L"Subkey2", KEY_WRITE | WRITE_DAC)); EXPECT_EQ(ERROR_SUCCESS, subkey2.WriteValue(L"", 2U)); - CSecurityDesc sec_desc; - sec_desc.FromString(L"D:PAI(A;OICI;KR;;;BU)"); // builtin users read - EXPECT_EQ(ERROR_SUCCESS, - RegSetKeySecurity(subkey.Handle(), DACL_SECURITY_INFORMATION, - const_cast<SECURITY_DESCRIPTOR*>( - sec_desc.GetPSECURITY_DESCRIPTOR()))); - sec_desc.FromString(L"D:PAI(A;OICI;KA;;;BU)"); // builtin users all access + // builtin users read. + auto sd = base::win::SecurityDescriptor::FromSddl(L"D:PAI(A;OICI;KR;;;BU)"); + ASSERT_TRUE(sd.has_value()); + SECURITY_DESCRIPTOR sec_desc; + sd->ToAbsolute(sec_desc); + EXPECT_EQ( + ERROR_SUCCESS, + RegSetKeySecurity(subkey.Handle(), DACL_SECURITY_INFORMATION, &sec_desc)); + // builtin users all access. + sd = base::win::SecurityDescriptor::FromSddl(L"D:PAI(A;OICI;KA;;;BU)"); + ASSERT_TRUE(sd.has_value()); + sd->ToAbsolute(sec_desc); EXPECT_EQ(ERROR_SUCCESS, RegSetKeySecurity(subkey2.Handle(), DACL_SECURITY_INFORMATION, - const_cast<SECURITY_DESCRIPTOR*>( - sec_desc.GetPSECURITY_DESCRIPTOR()))); + &sec_desc)); subkey2.Close(); subkey.Close(); key.Close(); @@ -135,10 +138,9 @@ EXPECT_EQ(ERROR_SUCCESS, key.ReadValueDW(L"SomeValue", &dw_value)); EXPECT_EQ(1U, dw_value); // Give users all access to the subkey so it can be deleted. - EXPECT_EQ(ERROR_SUCCESS, - RegSetKeySecurity(key.Handle(), DACL_SECURITY_INFORMATION, - const_cast<SECURITY_DESCRIPTOR*>( - sec_desc.GetPSECURITY_DESCRIPTOR()))); + EXPECT_EQ( + ERROR_SUCCESS, + RegSetKeySecurity(key.Handle(), DACL_SECURITY_INFORMATION, &sec_desc)); EXPECT_EQ(ERROR_SUCCESS, key.OpenKey(L"Subkey2", KEY_QUERY_VALUE)); EXPECT_EQ(ERROR_SUCCESS, key.ReadValueDW(L"", &dw_value)); EXPECT_EQ(2U, dw_value);
diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn index ebfea6f..35cfd4d 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn
@@ -2247,6 +2247,7 @@ "../browser/policy/test/content_settings_policy_browsertest.cc", "../browser/policy/test/default_search_provider_policy_browsertest.cc", "../browser/policy/test/force_google_safe_search_policy_browsertest.cc", + "../browser/policy/test/history_clusters_policy_browsertest.cc", "../browser/policy/test/jit_policy_browsertest.cc", "../browser/policy/test/platform_management_service_browsertest.cc", "../browser/policy/test/policy_browsertest.cc", @@ -7949,10 +7950,6 @@ "../browser/ui/window_sizer/window_sizer_unittest.cc", ] sources += [ - "../browser/apps/app_deduplication_service/app_deduplication_cache_unittest.cc", - "../browser/apps/app_deduplication_service/app_deduplication_mapper_unittest.cc", - "../browser/apps/app_deduplication_service/app_deduplication_server_connector_unittest.cc", - "../browser/apps/app_deduplication_service/app_deduplication_service_unittest.cc", "../browser/apps/app_discovery_service/app_discovery_service_unittest.cc", "../browser/apps/app_discovery_service/game_fetcher_unittest.cc", "../browser/apps/app_discovery_service/recommended_arc_app_fetcher_unittest.cc", @@ -8130,9 +8127,9 @@ "//ash/webui/scanning", "//ash/webui/settings/public/constants:mojom", "//chrome/browser/apps/almanac_api_client:unit_tests", - "//chrome/browser/apps/app_deduplication_service/proto", + "//chrome/browser/apps/app_deduplication_service:unit_tests", "//chrome/browser/apps/app_preload_service:unit_tests", - "//chrome/browser/apps/app_provisioning_service/proto", + "//chrome/browser/apps/app_provisioning_service", "//chrome/browser/apps/app_service/promise_apps/proto", "//chrome/browser/ash", "//chrome/browser/ash:arc_test_support", @@ -10723,6 +10720,7 @@ if (is_win) { sources += [ "../browser/downgrade/user_data_downgrade_browsertest.cc", + "../browser/net/sandboxed_network_change_notifier_win_browsertest.cc", "../browser/notifications/notification_platform_bridge_win_interactive_uitest.cc", "../browser/notifications/win/fake_itoastnotifier.cc", "../browser/notifications/win/fake_itoastnotifier.h", @@ -10754,6 +10752,7 @@ data_deps += [ "//chrome/elevation_service" ] libs = [ + "newdev.lib", "oleacc.lib", "runtimeobject.lib", ]
diff --git a/chrome/test/base/interactive_test_utils_mac.mm b/chrome/test/base/interactive_test_utils_mac.mm index 1c5fa9c..52681b0 100644 --- a/chrome/test/base/interactive_test_utils_mac.mm +++ b/chrome/test/base/interactive_test_utils_mac.mm
@@ -79,9 +79,10 @@ for (const auto& known_modifier : kKnownModifiers) { if (known_modifier.flag_mask & event_flags) { had_modifier = true; - CGEventPost(kCGSessionEventTap, - base::ScopedCFTypeRef<CGEventRef>(CGEventCreateKeyboardEvent( - nullptr, known_modifier.key_code, false))); + CGEventPost( + kCGSessionEventTap, + base::apple::ScopedCFTypeRef<CGEventRef>(CGEventCreateKeyboardEvent( + nullptr, known_modifier.key_code, false))); LOG(ERROR) << "Modifier " << known_modifier.name << " is hanging down, and may cause problems for any " "subsequent test.";
diff --git a/chrome/test/chromedriver/keycode_text_conversion_mac.mm b/chrome/test/chromedriver/keycode_text_conversion_mac.mm index c526ffa8..a0d22872 100644 --- a/chrome/test/chromedriver/keycode_text_conversion_mac.mm +++ b/chrome/test/chromedriver/keycode_text_conversion_mac.mm
@@ -19,7 +19,7 @@ UInt32 dead_key_state = 0; base::AutoLock lock(tis_lock_); - base::ScopedCFTypeRef<TISInputSourceRef> input_source( + base::apple::ScopedCFTypeRef<TISInputSourceRef> input_source( TISCopyCurrentKeyboardLayoutInputSource()); return ui::TranslatedUnicodeCharFromKeyCode( input_source.get(), mac_key_code, kUCKeyActionDown, modifier_key_state,
diff --git a/chrome/test/data/webui/history/history_metrics_test.ts b/chrome/test/data/webui/history/history_metrics_test.ts index f7ca6ae9..eeec40c 100644 --- a/chrome/test/data/webui/history/history_metrics_test.ts +++ b/chrome/test/data/webui/history/history_metrics_test.ts
@@ -7,6 +7,7 @@ import {BrowserServiceImpl, ensureLazyLoaded, HistoryAppElement, HistoryEntry, HistoryPageViewHistogram, SYNCED_TABS_HISTOGRAM_NAME, SyncedTabsHistogram} from 'chrome://history/history.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.js'; +import {loadTimeData} from 'chrome://resources/js/load_time_data.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js'; @@ -22,6 +23,9 @@ suiteSetup(function() { disableLinkClicks(); + loadTimeData.overrideValues({ + renameJourneys: false, + }); }); setup(async () => {
diff --git a/chrome/test/data/webui/history/history_routing_test.ts b/chrome/test/data/webui/history/history_routing_test.ts index 488d8c5..06d14d7 100644 --- a/chrome/test/data/webui/history/history_routing_test.ts +++ b/chrome/test/data/webui/history/history_routing_test.ts
@@ -28,6 +28,7 @@ enableHistoryClusters: 'Enable', isHistoryClustersEnabled, isHistoryClustersVisible: true, + renameJourneys: false, }); });
diff --git a/chrome/test/data/webui/history/history_ui_browsertest.cc b/chrome/test/data/webui/history/history_ui_browsertest.cc index bbb904e8..cad44a6 100644 --- a/chrome/test/data/webui/history/history_ui_browsertest.cc +++ b/chrome/test/data/webui/history/history_ui_browsertest.cc
@@ -3,13 +3,22 @@ // found in the LICENSE file. #include "base/strings/stringprintf.h" +#include "base/test/scoped_feature_list.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/web_ui_mocha_browser_test.h" +#include "components/history_clusters/core/features.h" #include "content/public/test/browser_test.h" class HistoryUIBrowserTest : public WebUIMochaBrowserTest { protected: - HistoryUIBrowserTest() { set_test_loader_host(chrome::kChromeUIHistoryHost); } + HistoryUIBrowserTest() { + scoped_feature_list_.InitAndDisableFeature( + history_clusters::kRenameJourneys); + set_test_loader_host(chrome::kChromeUIHistoryHost); + } + + private: + base::test::ScopedFeatureList scoped_feature_list_; }; using HistoryTest = HistoryUIBrowserTest;
diff --git a/chrome/test/data/webui/new_tab_page/new_tab_page_browsertest.cc b/chrome/test/data/webui/new_tab_page/new_tab_page_browsertest.cc index ec125fc..6cba8f3 100644 --- a/chrome/test/data/webui/new_tab_page/new_tab_page_browsertest.cc +++ b/chrome/test/data/webui/new_tab_page/new_tab_page_browsertest.cc
@@ -2,9 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "base/test/scoped_feature_list.h" #include "build/build_config.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/web_ui_mocha_browser_test.h" +#include "components/history_clusters/core/features.h" #include "components/search/ntp_features.h" #include "content/public/test/browser_test.h" @@ -222,9 +224,15 @@ class NewTabPageModulesHistoryClustersModuleTest : public NewTabPageBrowserTest { + protected: + NewTabPageModulesHistoryClustersModuleTest() { + scoped_feature_list_.InitWithFeatures( + /*enabled_features=*/{ntp_features::kNtpHistoryClustersModule}, + /*disabled_features=*/{history_clusters::kRenameJourneys}); + } + private: - base::test::ScopedFeatureList scoped_feature_list_{ - ntp_features::kNtpHistoryClustersModule}; + base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_F(NewTabPageModulesHistoryClustersModuleTest, Core) {
diff --git a/chrome/test/variations/drivers/chromeos.py b/chrome/test/variations/drivers/chromeos.py index 106065b..505453f5 100644 --- a/chrome/test/variations/drivers/chromeos.py +++ b/chrome/test/variations/drivers/chromeos.py
@@ -59,7 +59,7 @@ finder_options.CreateParser().parse_args(args=[]) b_options = finder_options.browser_options - b_options.browser_startup_timeout = 5 + b_options.browser_startup_timeout = 15 b_options.AppendExtraBrowserArgs(browser_args) device = cros_device.CrOSDevice(
diff --git a/chrome/updater/device_management/dm_storage_mac.mm b/chrome/updater/device_management/dm_storage_mac.mm index ecfaa54..6a5677d 100644 --- a/chrome/updater/device_management/dm_storage_mac.mm +++ b/chrome/updater/device_management/dm_storage_mac.mm
@@ -30,7 +30,7 @@ CFSTR(MAC_BROWSER_BUNDLE_IDENTIFIER_STRING); bool LoadEnrollmentTokenFromPolicy(std::string* enrollment_token) { - base::ScopedCFTypeRef<CFPropertyListRef> token_value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> token_value( CFPreferencesCopyAppValue(kEnrollmentTokenKey, kBrowserBundleId)); if (!token_value || CFGetTypeID(token_value) != CFStringGetTypeID() || !CFPreferencesAppValueIsForced(kEnrollmentTokenKey, kBrowserBundleId)) {
diff --git a/chrome/updater/mac/privileged_helper/service.mm b/chrome/updater/mac/privileged_helper/service.mm index c19528c..eb112d813 100644 --- a/chrome/updater/mac/privileged_helper/service.mm +++ b/chrome/updater/mac/privileged_helper/service.mm
@@ -189,9 +189,9 @@ } // namespace bool VerifyUpdaterSignature(const base::FilePath& updater_app_bundle) { - base::ScopedCFTypeRef<SecRequirementRef> requirement; - base::ScopedCFTypeRef<SecStaticCodeRef> code; - base::ScopedCFTypeRef<CFErrorRef> errors; + base::apple::ScopedCFTypeRef<SecRequirementRef> requirement; + base::apple::ScopedCFTypeRef<SecStaticCodeRef> code; + base::apple::ScopedCFTypeRef<CFErrorRef> errors; if (SecStaticCodeCreateWithPath( base::apple::FilePathToCFURL(updater_app_bundle), kSecCSDefaultFlags, code.InitializeInto()) != errSecSuccess) {
diff --git a/chrome/updater/policy/mac/managed_preference_policy_manager.mm b/chrome/updater/policy/mac/managed_preference_policy_manager.mm index d0cfe91a..5771f9ec 100644 --- a/chrome/updater/policy/mac/managed_preference_policy_manager.mm +++ b/chrome/updater/policy/mac/managed_preference_policy_manager.mm
@@ -206,9 +206,10 @@ } NSDictionary* ReadManagedPreferencePolicyDictionary() { - base::ScopedCFTypeRef<CFPropertyListRef> policies(CFPreferencesCopyAppValue( - base::apple::NSToCFPtrCast(kManagedPreferencesUpdatePolicies), - base::apple::NSToCFPtrCast(kKeystoneSharedPreferenceSuite))); + base::apple::ScopedCFTypeRef<CFPropertyListRef> policies( + CFPreferencesCopyAppValue( + base::apple::NSToCFPtrCast(kManagedPreferencesUpdatePolicies), + base::apple::NSToCFPtrCast(kKeystoneSharedPreferenceSuite))); if (!policies) return nil;
diff --git a/chrome/utility/image_writer/disk_unmounter_mac.h b/chrome/utility/image_writer/disk_unmounter_mac.h index 0303d71..96bb9b3 100644 --- a/chrome/utility/image_writer/disk_unmounter_mac.h +++ b/chrome/utility/image_writer/disk_unmounter_mac.h
@@ -58,8 +58,8 @@ base::OnceClosure success_continuation_; base::OnceClosure failure_continuation_; - base::ScopedCFTypeRef<DADiskRef> disk_; - base::ScopedCFTypeRef<DASessionRef> session_; + base::apple::ScopedCFTypeRef<DADiskRef> disk_; + base::apple::ScopedCFTypeRef<DASessionRef> session_; // Thread is last to ensure it is stopped before the data members are // destroyed.
diff --git a/chrome/utility/image_writer/image_writer_mac.cc b/chrome/utility/image_writer/image_writer_mac.cc index 0c01bb8..15c9c992 100644 --- a/chrome/utility/image_writer/image_writer_mac.cc +++ b/chrome/utility/image_writer/image_writer_mac.cc
@@ -33,9 +33,9 @@ static const char kAuthOpenPath[] = "/usr/libexec/authopen"; bool ImageWriter::IsValidDevice() { - base::ScopedCFTypeRef<CFStringRef> cf_bsd_name( + base::apple::ScopedCFTypeRef<CFStringRef> cf_bsd_name( base::SysUTF8ToCFStringRef(device_path_.value())); - base::ScopedCFTypeRef<CFMutableDictionaryRef> matching( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> matching( IOServiceMatching(kIOMediaClass)); CFDictionaryAddValue(matching, CFSTR(kIOMediaWholeKey), kCFBooleanTrue); CFDictionaryAddValue(matching, CFSTR(kIOMediaWritableKey), kCFBooleanTrue);
diff --git a/chrome/utility/safe_browsing/mac/udif.cc b/chrome/utility/safe_browsing/mac/udif.cc index 431d9f9b..fcbfad5 100644 --- a/chrome/utility/safe_browsing/mac/udif.cc +++ b/chrome/utility/safe_browsing/mac/udif.cc
@@ -457,7 +457,7 @@ return false; } - base::ScopedCFTypeRef<CFDataRef> plist_data( + base::apple::ScopedCFTypeRef<CFDataRef> plist_data( CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, plist_bytes.data(), plist_bytes.size(), kCFAllocatorNull)); if (!plist_data) { @@ -466,15 +466,15 @@ } CFErrorRef error = nullptr; - base::ScopedCFTypeRef<CFPropertyListRef> plist( + base::apple::ScopedCFTypeRef<CFPropertyListRef> plist( CFPropertyListCreateWithData(kCFAllocatorDefault, plist_data, kCFPropertyListImmutable, nullptr, &error)); CFDictionaryRef plist_dict = base::apple::CFCast<CFDictionaryRef>(plist.get()); - base::ScopedCFTypeRef<CFErrorRef> error_ref(error); + base::apple::ScopedCFTypeRef<CFErrorRef> error_ref(error); if (error) { - base::ScopedCFTypeRef<CFStringRef> error_string( + base::apple::ScopedCFTypeRef<CFStringRef> error_string( CFErrorCopyDescription(error)); DLOG(ERROR) << "Failed to parse XML plist: " << base::SysCFStringRefToUTF8(error_string);
diff --git a/components/BUILD.gn b/components/BUILD.gn index 1e9b121..5be5fe9 100644 --- a/components/BUILD.gn +++ b/components/BUILD.gn
@@ -397,6 +397,8 @@ "//components/reporting/resources:unit_tests", "//components/services/heap_profiling:unit_tests", "//components/services/storage:tests", + "//components/subresource_filter/content/common:unit_tests", + "//components/subresource_filter/content/renderer:unit_tests", "//components/tracing:unit_tests", "//components/translate/content/browser:unit_tests", "//components/translate/content/renderer:unit_tests", @@ -482,8 +484,6 @@ "//components/spellcheck/browser:unit_tests", "//components/spellcheck/renderer:unit_tests", "//components/subresource_filter/content/browser:unit_tests", - "//components/subresource_filter/content/common:unit_tests", - "//components/subresource_filter/content/renderer:unit_tests", "//components/web_package:unit_tests", "//components/web_package/test_support:unit_tests", "//components/webapps/browser:unit_tests",
diff --git a/components/arc/test/fake_intent_helper_instance.cc b/components/arc/test/fake_intent_helper_instance.cc index 979a61d8e..e3e72a4bd 100644 --- a/components/arc/test/fake_intent_helper_instance.cc +++ b/components/arc/test/fake_intent_helper_instance.cc
@@ -151,4 +151,9 @@ void FakeIntentHelperInstance::RequestDomainVerificationStatusUpdate() {} +void FakeIntentHelperInstance::SetCaptionStyle( + arc::mojom::CaptionStylePtr caption_style) { + caption_style_ = std::move(caption_style); +} + } // namespace arc
diff --git a/components/arc/test/fake_intent_helper_instance.h b/components/arc/test/fake_intent_helper_instance.h index 1b5db50..1946a73 100644 --- a/components/arc/test/fake_intent_helper_instance.h +++ b/components/arc/test/fake_intent_helper_instance.h
@@ -62,6 +62,10 @@ std::vector<Broadcast> GetBroadcastsForAction( const std::string& action) const; + arc::mojom::CaptionStylePtr GetCaptionStyle() const { + return caption_style_->Clone(); + } + // Sets a list of intent handlers to be returned in response to // RequestIntentHandlerList() calls with intents containing |action|. void SetIntentHandlers(const std::string& action, @@ -123,6 +127,8 @@ void RequestDomainVerificationStatusUpdate() override; + void SetCaptionStyle(arc::mojom::CaptionStylePtr caption_style) override; + private: std::vector<Broadcast> broadcasts_; @@ -139,6 +145,8 @@ // Keeps the binding alive so that calls to this class can be correctly // routed. mojo::Remote<mojom::IntentHelperHost> host_remote_; + + arc::mojom::CaptionStylePtr caption_style_; }; } // namespace arc
diff --git a/components/autofill/core/browser/autofill_progress_dialog_type.h b/components/autofill/core/browser/autofill_progress_dialog_type.h index 51d01bc0..991b672a 100644 --- a/components/autofill/core/browser/autofill_progress_dialog_type.h +++ b/components/autofill/core/browser/autofill_progress_dialog_type.h
@@ -15,7 +15,9 @@ // This progress dialog type applies to Android only. kAndroidFIDOProgressDialog = 1, // Used when unmasking virtual cards. - kVirtualCardUnmaskProgressDialog = 2 + kVirtualCardUnmaskProgressDialog = 2, + // Used when conducting a risk-based check for masked server card. + kServerCardUnmaskProgressDialog = 3 }; } // namespace autofill
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.cc b/components/autofill/core/browser/metrics/autofill_metrics.cc index fa5b8cc..4513e00 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.cc +++ b/components/autofill/core/browser/metrics/autofill_metrics.cc
@@ -906,39 +906,34 @@ void AutofillMetrics::LogProgressDialogResultMetric( bool is_canceled_by_user, AutofillProgressDialogType autofill_progress_dialog_type) { - std::string dialog_type; - switch (autofill_progress_dialog_type) { - case AutofillProgressDialogType::kAndroidFIDOProgressDialog: - dialog_type = "AndroidFIDO"; - break; - case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: - dialog_type = "CardUnmask"; - break; - case AutofillProgressDialogType::kUnspecified: - NOTREACHED(); - return; - } - base::UmaHistogramBoolean( - "Autofill.ProgressDialog." + dialog_type + ".Result", - is_canceled_by_user); + base::UmaHistogramBoolean(base::StrCat({"Autofill.ProgressDialog.", + GetDialogTypeStringForLogging( + autofill_progress_dialog_type), + ".Result"}), + is_canceled_by_user); } void AutofillMetrics::LogProgressDialogShown( AutofillProgressDialogType autofill_progress_dialog_type) { - std::string dialog_type; + base::UmaHistogramBoolean(base::StrCat({"Autofill.ProgressDialog.", + GetDialogTypeStringForLogging( + autofill_progress_dialog_type), + ".Shown"}), + true); +} + +std::string_view AutofillMetrics::GetDialogTypeStringForLogging( + AutofillProgressDialogType autofill_progress_dialog_type) { switch (autofill_progress_dialog_type) { case AutofillProgressDialogType::kAndroidFIDOProgressDialog: - dialog_type = "AndroidFIDO"; - break; + return "AndroidFIDO"; case AutofillProgressDialogType::kVirtualCardUnmaskProgressDialog: - dialog_type = "CardUnmask"; - break; - case AutofillProgressDialogType::kUnspecified: - NOTREACHED(); - return; + return "VirtualCardUnmask"; + case AutofillProgressDialogType::kServerCardUnmaskProgressDialog: + return "ServerCardUnmask"; + default: + NOTREACHED_NORETURN(); } - base::UmaHistogramBoolean("Autofill.ProgressDialog." + dialog_type + ".Shown", - true); } // static
diff --git a/components/autofill/core/browser/metrics/autofill_metrics.h b/components/autofill/core/browser/metrics/autofill_metrics.h index c507d6d..a6943bc 100644 --- a/components/autofill/core/browser/metrics/autofill_metrics.h +++ b/components/autofill/core/browser/metrics/autofill_metrics.h
@@ -912,6 +912,11 @@ static void LogProgressDialogShown( AutofillProgressDialogType autofill_progress_dialog_type); + // Returns a string representation of the given AutofillProgressDialogType for + // constructing subhistogram paths. + static std::string_view GetDialogTypeStringForLogging( + AutofillProgressDialogType autofill_progress_dialog_type); + // Should be called when credit card scan is finished. |duration| should be // the time elapsed between launching the credit card scanner and getting back // the result. |completed| should be true if a credit card was scanned, false
diff --git a/components/autofill_payments_strings.grdp b/components/autofill_payments_strings.grdp index 5a144b9130..823fc29 100644 --- a/components/autofill_payments_strings.grdp +++ b/components/autofill_payments_strings.grdp
@@ -459,10 +459,13 @@ <message name="IDS_AUTOFILL_CARD_UNMASK_PROGRESS_BAR_MESSAGE" desc="Message displayed after tapping a Virtual Card, and before any other verification steps."> Contacting your bank... </message> - <message name="IDS_AUTOFILL_CARD_UNMASK_CANCEL_BUTTON_LABEL" desc="Button that allows the user to cancel the Virtual Card unmasking process."> + <message name="IDS_AUTOFILL_MASKED_SERVER_CARD_RISK_BASED_UNMASK_PROGRESS_BAR_MESSAGE" desc="Loading message displayed after tapping a credit card entry in Autofill, before possibly showing the user any other verification steps."> + Using Google’s security technology to keep your payment info secure + </message> + <message name="IDS_AUTOFILL_CARD_UNMASK_CANCEL_BUTTON_LABEL" desc="Button that allows the user to cancel the card unmasking process."> Cancel </message> - <message name="IDS_AUTOFILL_CARD_UNMASK_CONFIRMATION_MESSAGE" desc="Message displayed after tapping a Virtual Card, and the response from the bank indicates that no further verification is required."> + <message name="IDS_AUTOFILL_CARD_UNMASK_CONFIRMATION_MESSAGE" desc="Message displayed after tapping a card, and the response from the bank indicates that no further verification is required."> Verified </message> <message name="IDS_AUTOFILL_FIDO_AUTHENTICATION_PROMPT_TITLE" desc="Title for FIDO authentication progress dialog">
diff --git a/components/autofill_payments_strings_grdp/IDS_AUTOFILL_MASKED_SERVER_CARD_RISK_BASED_UNMASK_PROGRESS_BAR_MESSAGE.png.sha1 b/components/autofill_payments_strings_grdp/IDS_AUTOFILL_MASKED_SERVER_CARD_RISK_BASED_UNMASK_PROGRESS_BAR_MESSAGE.png.sha1 new file mode 100644 index 0000000..b2dc2cf --- /dev/null +++ b/components/autofill_payments_strings_grdp/IDS_AUTOFILL_MASKED_SERVER_CARD_RISK_BASED_UNMASK_PROGRESS_BAR_MESSAGE.png.sha1
@@ -0,0 +1 @@ +45aa8be87548747f11121434c128ffee96868cf7 \ No newline at end of file
diff --git a/components/country_codes/country_codes.cc b/components/country_codes/country_codes.cc index f4e927b..d0eba16 100644 --- a/components/country_codes/country_codes.cc +++ b/components/country_codes/country_codes.cc
@@ -157,7 +157,7 @@ #elif BUILDFLAG(IS_APPLE) int GetCurrentCountryID() { - base::ScopedCFTypeRef<CFLocaleRef> locale(CFLocaleCopyCurrent()); + base::apple::ScopedCFTypeRef<CFLocaleRef> locale(CFLocaleCopyCurrent()); CFStringRef country = (CFStringRef)CFLocaleGetValue(locale.get(), kCFLocaleCountryCode); if (!country)
diff --git a/components/device_signals/core/system_signals/mac/mac_platform_delegate.mm b/components/device_signals/core/system_signals/mac/mac_platform_delegate.mm index 450dbd21..60e9885 100644 --- a/components/device_signals/core/system_signals/mac/mac_platform_delegate.mm +++ b/components/device_signals/core/system_signals/mac/mac_platform_delegate.mm
@@ -92,16 +92,16 @@ const base::FilePath& file_path) { SigningCertificatesPublicKeys public_keys; - base::ScopedCFTypeRef<CFURLRef> file_url = + base::apple::ScopedCFTypeRef<CFURLRef> file_url = base::apple::FilePathToCFURL(file_path); - base::ScopedCFTypeRef<SecStaticCodeRef> file_code; + base::apple::ScopedCFTypeRef<SecStaticCodeRef> file_code; if (SecStaticCodeCreateWithPath(file_url, kSecCSDefaultFlags, file_code.InitializeInto()) != errSecSuccess) { return public_keys; } - base::ScopedCFTypeRef<CFDictionaryRef> signing_information; + base::apple::ScopedCFTypeRef<CFDictionaryRef> signing_information; if (SecCodeCopySigningInformation(file_code, kSecCSSigningInformation, signing_information.InitializeInto()) != errSecSuccess) { @@ -123,7 +123,8 @@ SecCertificateRef leaf_cert = reinterpret_cast<SecCertificateRef>( const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, 0))); - base::ScopedCFTypeRef<CFDataRef> der_data(SecCertificateCopyData(leaf_cert)); + base::apple::ScopedCFTypeRef<CFDataRef> der_data( + SecCertificateCopyData(leaf_cert)); if (!der_data) { return public_keys; }
diff --git a/components/feed/core/v2/BUILD.gn b/components/feed/core/v2/BUILD.gn index 48e5621..cb95f39 100644 --- a/components/feed/core/v2/BUILD.gn +++ b/components/feed/core/v2/BUILD.gn
@@ -74,6 +74,8 @@ "public/web_feed_subscriptions.cc", "request_throttler.cc", "request_throttler.h", + "resource_fetcher.cc", + "resource_fetcher.h", "scheduling.cc", "scheduling.h", "stream/info_card_tracker.cc", @@ -219,6 +221,7 @@ "public/public_types_unittest.cc", "public/stream_type_unittest.cc", "request_throttler_unittest.cc", + "resource_fetcher_unittest.cc", "scheduling_unittest.cc", "stream/info_card_tracker_unittest.cc", "stream/privacy_notice_card_tracker_unittest.cc",
diff --git a/components/feed/core/v2/metrics_reporter.cc b/components/feed/core/v2/metrics_reporter.cc index 3a6eea6..57605fd 100644 --- a/components/feed/core/v2/metrics_reporter.cc +++ b/components/feed/core/v2/metrics_reporter.cc
@@ -1064,6 +1064,11 @@ net_error_or_http_status); } +void MetricsReporter::OnResourceFetched(int net_error_or_http_status) { + base::UmaHistogramSparse("ContentSuggestions.Feed.ResourceFetchStatus", + net_error_or_http_status); +} + void MetricsReporter::OnUploadActionsBatch(UploadActionsBatchStatus status) { VVLOG << "UploadActionsBatchStatus: " << status; base::UmaHistogramEnumeration(
diff --git a/components/feed/core/v2/metrics_reporter.h b/components/feed/core/v2/metrics_reporter.h index 67ed0a87..d016b36 100644 --- a/components/feed/core/v2/metrics_reporter.h +++ b/components/feed/core/v2/metrics_reporter.h
@@ -136,6 +136,7 @@ void OnEnterBackground(); static void OnImageFetched(const GURL& url, int net_error_or_http_status); + static void OnResourceFetched(int net_error_or_http_status); // Actions upload. static void OnUploadActionsBatch(UploadActionsBatchStatus status);
diff --git a/components/feed/core/v2/public/types.h b/components/feed/core/v2/public/types.h index 15795ffe..c1ba7e0 100644 --- a/components/feed/core/v2/public/types.h +++ b/components/feed/core/v2/public/types.h
@@ -98,10 +98,18 @@ std::ostream& operator<<(std::ostream& os, const NetworkResponseInfo& o); struct NetworkResponse { + NetworkResponse(); + NetworkResponse(const std::string& response_bytes, int status_code); + ~NetworkResponse(); + NetworkResponse(const NetworkResponse&); + NetworkResponse& operator=(const NetworkResponse&); + // HTTP response body. std::string response_bytes; // HTTP status code if available, or net::Error otherwise. int status_code; + // List of HTTP response header names and values. + std::vector<std::string> response_header_names_and_values; }; // For the snippets-internals page.
diff --git a/components/feed/core/v2/resource_fetcher.cc b/components/feed/core/v2/resource_fetcher.cc new file mode 100644 index 0000000..cb61e5c --- /dev/null +++ b/components/feed/core/v2/resource_fetcher.cc
@@ -0,0 +1,145 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/feed/core/v2/resource_fetcher.h" + +#include "components/feed/core/v2/metrics_reporter.h" +#include "components/feed/core/v2/public/types.h" +#include "net/base/net_errors.h" +#include "net/http/http_request_headers.h" +#include "services/network/public/cpp/resource_request.h" +#include "services/network/public/cpp/resource_request_body.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/simple_url_loader.h" +#include "services/network/public/mojom/url_response_head.mojom.h" + +namespace feed { + +namespace { + +bool IsSupportedHttpMethod(const std::string& method) { + return method == net::HttpRequestHeaders::kGetMethod || + method == net::HttpRequestHeaders::kPostMethod || + method == net::HttpRequestHeaders::kHeadMethod; +} + +} // namespace + +ResourceFetcher::ResourceFetcher( + scoped_refptr<::network::SharedURLLoaderFactory> url_loader_factory) + : url_loader_factory_(url_loader_factory) {} + +ResourceFetcher::~ResourceFetcher() = default; + +void ResourceFetcher::Fetch( + const GURL& url, + const std::string& method, + const std::vector<std::string>& header_names_and_values, + const std::string& post_data, + ResourceCallback callback) { + int status_code = net::OK; + if (!IsSupportedHttpMethod(method)) { + status_code = net::ERR_METHOD_NOT_SUPPORTED; + } else if ((header_names_and_values.size() % 2) > 0) { + status_code = net::ERR_INVALID_ARGUMENT; + } else if (!post_data.empty() && + method != net::HttpRequestHeaders::kPostMethod) { + status_code = net::ERR_INVALID_ARGUMENT; + } + if (status_code != net::OK) { + NetworkResponse response; + response.status_code = status_code; + std::move(callback).Run(std::move(response)); + return; + } + + net::NetworkTrafficAnnotationTag traffic_annotation = + net::DefineNetworkTrafficAnnotation("interest_feedv2_resource_send", R"( + semantics { + sender: "Feed Library" + description: + "Download resource data, like live sports or weather, that can be " + "used to provide additional information for the articles in the " + "feed." + trigger: "Triggered when viewing the feed on the NTP." + user_data { + type: NONE + } + data: + "The data to identify and render the additioal resource, like " + "sports game ID and language." + destination: GOOGLE_OWNED_SERVICE + internal { + contacts { + email: "chrome-feed-fundamentals@google.com" + } + } + last_reviewed: "2023-08-21" + } + policy { + cookies_allowed: NO + setting: "This can be disabled from the New Tab Page by collapsing " + "the articles section." + chrome_policy { + NTPContentSuggestionsEnabled { + policy_options {mode: MANDATORY} + NTPContentSuggestionsEnabled: false + } + } + })"); + auto resource_request = std::make_unique<::network::ResourceRequest>(); + resource_request->url = url; + resource_request->method = method; + if (!header_names_and_values.empty()) { + for (size_t i = 0; i < header_names_and_values.size(); i += 2) { + resource_request->headers.SetHeader(header_names_and_values[i], + header_names_and_values[i + 1]); + } + } + + resource_request->credentials_mode = network::mojom::CredentialsMode::kOmit; + + auto simple_loader = network::SimpleURLLoader::Create( + std::move(resource_request), traffic_annotation); + auto* const simple_loader_ptr = simple_loader.get(); + + if (!post_data.empty()) { + simple_loader->AttachStringForUpload(post_data); + } + + simple_loader_ptr->DownloadToString( + url_loader_factory_.get(), + base::BindOnce(&ResourceFetcher::OnFetchComplete, + weak_factory_.GetWeakPtr(), std::move(simple_loader), + std::move(callback)), + network::SimpleURLLoader::kMaxBoundedStringDownloadSize); +} + +void ResourceFetcher::OnFetchComplete( + std::unique_ptr<network::SimpleURLLoader> url_loader, + ResourceCallback callback, + std::unique_ptr<std::string> response_data) { + NetworkResponse response; + if (url_loader->ResponseInfo() && url_loader->ResponseInfo()->headers) { + response.status_code = url_loader->ResponseInfo()->headers->response_code(); + size_t iter = 0; + std::string name; + std::string value; + while (url_loader->ResponseInfo()->headers->EnumerateHeaderLines( + &iter, &name, &value)) { + response.response_header_names_and_values.push_back(std::move(name)); + response.response_header_names_and_values.push_back(std::move(value)); + } + } else { + response.status_code = url_loader->NetError(); + } + MetricsReporter::OnResourceFetched(response.status_code); + + if (response_data) { + response.response_bytes = std::move(*response_data); + } + std::move(callback).Run(std::move(response)); +} + +} // namespace feed
diff --git a/components/feed/core/v2/resource_fetcher.h b/components/feed/core/v2/resource_fetcher.h new file mode 100644 index 0000000..523f946 --- /dev/null +++ b/components/feed/core/v2/resource_fetcher.h
@@ -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. + +#ifndef COMPONENTS_FEED_CORE_V2_RESOURCE_FETCHER_H_ +#define COMPONENTS_FEED_CORE_V2_RESOURCE_FETCHER_H_ + +#include "base/functional/callback.h" +#include "base/memory/scoped_refptr.h" +#include "base/memory/weak_ptr.h" +#include "components/feed/core/v2/public/types.h" +#include "url/gurl.h" + +namespace network { +class SharedURLLoaderFactory; +class SimpleURLLoader; +} // namespace network + +namespace feed { + +struct NetworkResponse; + +// Fetcher object to retrieve a resource from a URL. +class ResourceFetcher { + public: + using ResourceCallback = base::OnceCallback<void(NetworkResponse)>; + explicit ResourceFetcher( + scoped_refptr<::network::SharedURLLoaderFactory> url_loader_factory); + ~ResourceFetcher(); + ResourceFetcher(const ResourceFetcher&) = delete; + ResourceFetcher& operator=(const ResourceFetcher&) = delete; + + void Fetch(const GURL& url, + const std::string& method, + const std::vector<std::string>& header_names_and_values, + const std::string& post_data, + ResourceCallback callback); + + private: + // Called when fetch request completes. + void OnFetchComplete(std::unique_ptr<network::SimpleURLLoader> url_loader, + ResourceCallback callback, + std::unique_ptr<std::string> response_data); + + const scoped_refptr<::network::SharedURLLoaderFactory> url_loader_factory_; + base::WeakPtrFactory<ResourceFetcher> weak_factory_{this}; +}; + +} // namespace feed + +#endif // COMPONENTS_FEED_CORE_V2_RESOURCE_FETCHER_H_
diff --git a/components/feed/core/v2/resource_fetcher_unittest.cc b/components/feed/core/v2/resource_fetcher_unittest.cc new file mode 100644 index 0000000..4e3b8184 --- /dev/null +++ b/components/feed/core/v2/resource_fetcher_unittest.cc
@@ -0,0 +1,302 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/feed/core/v2/resource_fetcher.h" + +#include <memory> +#include <utility> + +#include "base/functional/bind.h" +#include "base/strings/string_number_conversions.h" +#include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/task_environment.h" +#include "components/feed/core/v2/public/types.h" +#include "components/feed/core/v2/test/callback_receiver.h" +#include "net/http/http_request_headers.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_status_code.h" +#include "net/http/http_util.h" +#include "services/network/public/cpp/url_loader_completion_status.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "services/network/public/mojom/url_response_head.mojom.h" +#include "services/network/test/test_url_loader_factory.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "url/gurl.h" + +using ::testing::HasSubstr; + +namespace feed { +namespace { + +std::string GetStringFromDataElements( + const std::vector<network::DataElement>* data_elements) { + std::string result; + for (const network::DataElement& element : *data_elements) { + DCHECK_EQ(element.type(), network::DataElement::Tag::kBytes); + // Provide the length of the bytes explicitly, not to rely on the null + // termination. + const auto piece = element.As<network::DataElementBytes>().AsStringPiece(); + result.append(piece); + } + return result; +} + +class ResourceFetcherTest : public testing::Test { + public: + ResourceFetcherTest() = default; + ResourceFetcherTest(ResourceFetcherTest&) = delete; + ResourceFetcherTest& operator=(const ResourceFetcherTest&) = delete; + ~ResourceFetcherTest() override = default; + + void SetUp() override { + shared_url_loader_factory_ = + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( + &test_factory_); + resource_fetcher_ = + std::make_unique<ResourceFetcher>(shared_url_loader_factory_); + } + + ResourceFetcher* resource_fetcher() { return resource_fetcher_.get(); } + + network::ResourceRequest Respond( + const std::string& additional_response_headers, + const std::string& response_string, + int net_status_code, + int request_index = 0) { + network::URLLoaderCompletionStatus status; + + task_environment_.RunUntilIdle(); + network::TestURLLoaderFactory::PendingRequest* pending_request = + test_factory_.GetPendingRequest(request_index); + CHECK(pending_request); + network::ResourceRequest resource_request = pending_request->request; + auto head = network::mojom::URLResponseHead::New(); + if (net_status_code >= 0) { + std::string headers_str = + "HTTP/1.1 " + base::NumberToString(net_status_code); + if (!additional_response_headers.empty()) { + headers_str += "\n"; + headers_str += additional_response_headers; + } + headers_str + "\n"; + head->headers = base::MakeRefCounted<net::HttpResponseHeaders>( + net::HttpUtil::AssembleRawHeaders(headers_str)); + status.decoded_body_length = response_string.length(); + } else { + status.error_code = net_status_code; + } + + test_factory_.AddResponse(pending_request->request.url, std::move(head), + response_string, status); + task_environment_.FastForwardUntilNoTasksRemain(); + return resource_request; + } + + private: + std::unique_ptr<ResourceFetcher> resource_fetcher_; + network::TestURLLoaderFactory test_factory_; + scoped_refptr<network::SharedURLLoaderFactory> shared_url_loader_factory_; + base::test::TaskEnvironment task_environment_{ + base::test::TaskEnvironment::TimeSource::MOCK_TIME}; +}; + +TEST_F(ResourceFetcherTest, GetRequestWithEmptyResponse) { + base::HistogramTester histograms; + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver.Bind()); + network::ResourceRequest resource_request = Respond("", "", net::HTTP_OK); + + EXPECT_EQ(GURL("https://example.com"), resource_request.url); + EXPECT_EQ("GET", resource_request.method); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::HTTP_OK, receiver.GetResult()->status_code); + EXPECT_EQ("", receiver.GetResult()->response_bytes); + + EXPECT_EQ( + std::vector<base::Bucket>({{net::HTTP_OK, 1}}), + histograms.GetAllSamples("ContentSuggestions.Feed.ResourceFetchStatus")); +} + +TEST_F(ResourceFetcherTest, GetRequestWithCustomResponseHeader) { + base::HistogramTester histograms; + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver.Bind()); + Respond("Header1: Value1\nHeader2: Value2\n", "", net::HTTP_OK); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::HTTP_OK, receiver.GetResult()->status_code); + std::vector<std::string> expected_response_headers = {"Header1", "Value1", + "Header2", "Value2"}; + EXPECT_THAT(receiver.GetResult()->response_header_names_and_values, + expected_response_headers); +} + +TEST_F(ResourceFetcherTest, GetRequestWithNetError) { + base::HistogramTester histograms; + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver.Bind()); + Respond("", "", net::ERR_ACCESS_DENIED); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::ERR_ACCESS_DENIED, receiver.GetResult()->status_code); + + EXPECT_EQ( + std::vector<base::Bucket>({{net::ERR_ACCESS_DENIED, 1}}), + histograms.GetAllSamples("ContentSuggestions.Feed.ResourceFetchStatus")); +} + +TEST_F(ResourceFetcherTest, GetRequestWithHttpError) { + base::HistogramTester histograms; + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver.Bind()); + Respond("", "", 404); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(404, receiver.GetResult()->status_code); + + EXPECT_EQ( + std::vector<base::Bucket>({{404, 1}}), + histograms.GetAllSamples("ContentSuggestions.Feed.ResourceFetchStatus")); +} + +TEST_F(ResourceFetcherTest, GetRequestWithPostBody) { + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {}, + "post body", receiver.Bind()); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::ERR_INVALID_ARGUMENT, receiver.GetResult()->status_code); +} + +TEST_F(ResourceFetcherTest, GetRequestWithHeaders) { + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch( + GURL("https://example.com"), net::HttpRequestHeaders::kGetMethod, + {"Header1", "Value1", "Header2", "Value2"}, "", receiver.Bind()); + network::ResourceRequest resource_request = Respond("", "", net::HTTP_OK); + + EXPECT_EQ(GURL("https://example.com"), resource_request.url); + EXPECT_EQ("GET", resource_request.method); + + std::string value1; + EXPECT_TRUE(resource_request.headers.GetHeader("Header1", &value1)); + EXPECT_EQ("Value1", value1); + std::string value2; + EXPECT_TRUE(resource_request.headers.GetHeader("Header2", &value2)); + EXPECT_EQ("Value2", value2); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::HTTP_OK, receiver.GetResult()->status_code); +} + +TEST_F(ResourceFetcherTest, GetRequestWithIncompleteHeaders) { + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {"Header1"}, + "", receiver.Bind()); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::ERR_INVALID_ARGUMENT, receiver.GetResult()->status_code); +} + +TEST_F(ResourceFetcherTest, PostRequest) { + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kPostMethod, {}, + "post body", receiver.Bind()); + network::ResourceRequest resource_request = + Respond("", "example_response", net::HTTP_OK); + + EXPECT_EQ(GURL("https://example.com"), resource_request.url); + EXPECT_EQ("POST", resource_request.method); + EXPECT_EQ("post body", GetStringFromDataElements( + resource_request.request_body->elements())); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::HTTP_OK, receiver.GetResult()->status_code); + EXPECT_THAT(receiver.GetResult()->response_bytes, + HasSubstr("example_response")); +} + +TEST_F(ResourceFetcherTest, UnsupportedHttpMethods) { + std::string methods[] = {"CONNECT", "DELETE", "OPTIONS", "PATCH", + "PUT", "TRACE", "TRACK", "ZZZ"}; + + for (auto& method : methods) { + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), method, {}, "", + receiver.Bind()); + ASSERT_TRUE(receiver.GetResult()); + EXPECT_EQ(net::ERR_METHOD_NOT_SUPPORTED, receiver.GetResult()->status_code); + } +} + +TEST_F(ResourceFetcherTest, GetRequestWithResponse) { + CallbackReceiver<NetworkResponse> receiver; + resource_fetcher()->Fetch(GURL("https://example.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver.Bind()); + Respond("", "example_response", net::HTTP_OK); + + ASSERT_TRUE(receiver.GetResult()); + EXPECT_THAT(receiver.GetResult()->response_bytes, + HasSubstr("example_response")); + EXPECT_EQ(net::HTTP_OK, receiver.GetResult()->status_code); +} + +TEST_F(ResourceFetcherTest, SequentialRequests) { + CallbackReceiver<NetworkResponse> receiver1; + resource_fetcher()->Fetch(GURL("https://example1.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver1.Bind()); + Respond("", "example1_response", net::HTTP_OK); + + CallbackReceiver<NetworkResponse> receiver2; + resource_fetcher()->Fetch(GURL("https://example2.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver2.Bind()); + Respond("", "example2_response", net::HTTP_OK); + + ASSERT_TRUE(receiver1.GetResult()); + EXPECT_THAT(receiver1.GetResult()->response_bytes, + HasSubstr("example1_response")); + ASSERT_TRUE(receiver2.GetResult()); + EXPECT_THAT(receiver2.GetResult()->response_bytes, + HasSubstr("example2_response")); +} + +TEST_F(ResourceFetcherTest, ParallelRequests) { + CallbackReceiver<NetworkResponse> receiver1; + resource_fetcher()->Fetch(GURL("https://example1.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver1.Bind()); + CallbackReceiver<NetworkResponse> receiver2; + resource_fetcher()->Fetch(GURL("https://example2.com"), + net::HttpRequestHeaders::kGetMethod, {}, "", + receiver2.Bind()); + + Respond("", "example2_response", net::HTTP_OK, 1); + ASSERT_TRUE(receiver2.GetResult()); + EXPECT_THAT(receiver2.GetResult()->response_bytes, + HasSubstr("example2_response")); + + Respond("", "example1_response", net::HTTP_OK, 0); + ASSERT_TRUE(receiver1.GetResult()); + EXPECT_THAT(receiver1.GetResult()->response_bytes, + HasSubstr("example1_response")); +} + +} // namespace +} // namespace feed
diff --git a/components/feed/core/v2/types.cc b/components/feed/core/v2/types.cc index 78cf2229..bf07385 100644 --- a/components/feed/core/v2/types.cc +++ b/components/feed/core/v2/types.cc
@@ -121,6 +121,14 @@ NetworkResponseInfo& NetworkResponseInfo::operator=( const NetworkResponseInfo&) = default; +NetworkResponse::NetworkResponse() = default; +NetworkResponse::NetworkResponse(const std::string& response_bytes, + int status_code) + : response_bytes(response_bytes), status_code(status_code) {} +NetworkResponse::~NetworkResponse() = default; +NetworkResponse::NetworkResponse(const NetworkResponse&) = default; +NetworkResponse& NetworkResponse::operator=(const NetworkResponse&) = default; + std::string ToString(ContentRevision c) { // The 'c/' prefix is used to identify slices as content. Don't change this // without updating the Java side.
diff --git a/components/history_clusters/core/features.cc b/components/history_clusters/core/features.cc index bdea49d..539f7f8 100644 --- a/components/history_clusters/core/features.cc +++ b/components/history_clusters/core/features.cc
@@ -111,4 +111,8 @@ const base::FeatureParam<bool> kSidePanelJourneysOpensFromOmnibox{ &kSidePanelJourneys, "SidePanelJourneysOpensFromOmnibox", true}; +BASE_FEATURE(kRenameJourneys, + "RenameJourneys", + enabled_by_default_desktop_only); + } // namespace history_clusters
diff --git a/components/history_clusters/core/features.h b/components/history_clusters/core/features.h index a31a22a..00eae7c 100644 --- a/components/history_clusters/core/features.h +++ b/components/history_clusters/core/features.h
@@ -96,6 +96,9 @@ extern const base::FeatureParam<bool> kSidePanelJourneysOpensFromOmnibox; BASE_DECLARE_FEATURE(kSidePanelJourneysQueryless); +// Enables renaming Journeys in the UI. +BASE_DECLARE_FEATURE(kRenameJourneys); + } // namespace history_clusters #endif // COMPONENTS_HISTORY_CLUSTERS_CORE_FEATURES_H_
diff --git a/components/history_clusters/core/history_clusters_service.cc b/components/history_clusters/core/history_clusters_service.cc index 7a1663c..f59a026a 100644 --- a/components/history_clusters/core/history_clusters_service.cc +++ b/components/history_clusters/core/history_clusters_service.cc
@@ -9,6 +9,7 @@ #include <string> #include <utility> +#include "base/feature_list.h" #include "base/functional/bind.h" #include "base/i18n/case_conversion.h" #include "base/json/values_util.h" @@ -25,6 +26,7 @@ #include "components/history/core/browser/history_db_task.h" #include "components/history/core/browser/history_types.h" #include "components/history_clusters/core/config.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/file_clustering_backend.h" #include "components/history_clusters/core/history_clusters_debug_jsons.h" #include "components/history_clusters/core/history_clusters_prefs.h" @@ -169,8 +171,14 @@ void HistoryClustersService::Shutdown() {} bool HistoryClustersService::IsJourneysEnabledAndVisible() const { + const bool rename_journeys = base::FeatureList::IsEnabled(kRenameJourneys); + const bool journeys_is_managed = + pref_service_->IsManagedPreference(prefs::kVisible); + // When history_clusters::kRenameJourneys is enabled, history clusters are + // always visible unless the visibility prefs is set to false by policy. return is_journeys_feature_flag_enabled_ && - pref_service_->GetBoolean(prefs::kVisible); + (pref_service_->GetBoolean(prefs::kVisible) || + (rename_journeys && !journeys_is_managed)); } // static
diff --git a/components/history_clusters/core/url_constants.cc b/components/history_clusters/core/url_constants.cc index bc8290f..dfa17ec 100644 --- a/components/history_clusters/core/url_constants.cc +++ b/components/history_clusters/core/url_constants.cc
@@ -3,9 +3,15 @@ // found in the LICENSE file. #include "components/history_clusters/core/url_constants.h" +#include "base/feature_list.h" +#include "components/history_clusters/core/features.h" namespace history_clusters { -const char kChromeUIHistoryClustersURL[] = "chrome://history/journeys"; +const char* GetChromeUIHistoryClustersURL() { + return base::FeatureList::IsEnabled(history_clusters::kRenameJourneys) + ? "chrome://history/2" + : "chrome://history/journeys"; +} } // namespace history_clusters
diff --git a/components/history_clusters/core/url_constants.h b/components/history_clusters/core/url_constants.h index acb13f7..45b2b61 100644 --- a/components/history_clusters/core/url_constants.h +++ b/components/history_clusters/core/url_constants.h
@@ -7,8 +7,10 @@ namespace history_clusters { -// The main History Clusters WebUI URL. -extern const char kChromeUIHistoryClustersURL[]; +// Returns the main History Clusters WebUI URL. +// TODO(crbug.com/1473855): Change to a const char array when feature check is +// no longer needed. +const char* GetChromeUIHistoryClustersURL(); } // namespace history_clusters
diff --git a/components/history_clusters_strings.grdp b/components/history_clusters_strings.grdp index a916da88..f26df8c 100644 --- a/components/history_clusters_strings.grdp +++ b/components/history_clusters_strings.grdp
@@ -23,10 +23,16 @@ <message name="IDS_HISTORY_CLUSTERS_JOURNEYS_TAB_LABEL" desc="A label for the section in Chrome History (chrome://history) where Journeys are collected and shown to the user. See glossary entry for meaning of 'Journeys'." formatter_data="android_java"> Journeys </message> + <message name="IDS_HISTORY_CLUSTERS_BY_GROUP_TAB_LABEL" desc="A label for the section in Chrome History (chrome://history) where a list of history items organized into groups of pages are shown to the user."> + By group + </message> <message name="IDS_HISTORY_CLUSTERS_LIST_TAB_LABEL" desc="A label for the section in Chrome History (chrome://history) where a list of history items are shown to the user." formatter_data="android_java"> List </message> + <message name="IDS_HISTORY_CLUSTERS_BY_DATE_TAB_LABEL" desc="A label for the section in Chrome History (chrome://history) where a list of history items are shown to the user."> + By date + </message> <message name="IDS_HISTORY_CLUSTERS_CLUSTER_LABEL_SEARCH_TERMS" desc="The header used for Journeys that are anchored by search terms. The header is just the search terms in locale-specific quotation marks."> “<ph name="SEARCH_TERMS">$1<ex>flowers</ex></ph>” </message>
diff --git a/components/history_clusters_strings_grdp/IDS_HISTORY_CLUSTERS_BY_DATE_TAB_LABEL.png.sha1 b/components/history_clusters_strings_grdp/IDS_HISTORY_CLUSTERS_BY_DATE_TAB_LABEL.png.sha1 new file mode 100644 index 0000000..1adf428 --- /dev/null +++ b/components/history_clusters_strings_grdp/IDS_HISTORY_CLUSTERS_BY_DATE_TAB_LABEL.png.sha1
@@ -0,0 +1 @@ +5eb14a828f3365fdc0a30c03e5d6aa50a3f48145 \ No newline at end of file
diff --git a/components/history_clusters_strings_grdp/IDS_HISTORY_CLUSTERS_BY_GROUP_TAB_LABEL.png.sha1 b/components/history_clusters_strings_grdp/IDS_HISTORY_CLUSTERS_BY_GROUP_TAB_LABEL.png.sha1 new file mode 100644 index 0000000..e3b5f60 --- /dev/null +++ b/components/history_clusters_strings_grdp/IDS_HISTORY_CLUSTERS_BY_GROUP_TAB_LABEL.png.sha1
@@ -0,0 +1 @@ +6b6a348177560a4bd28325c068cf078c93a039ac \ No newline at end of file
diff --git a/components/metal_util/hdr_copier_layer.mm b/components/metal_util/hdr_copier_layer.mm index cf746b27..0271d1d4 100644 --- a/components/metal_util/hdr_copier_layer.mm +++ b/components/metal_util/hdr_copier_layer.mm
@@ -225,7 +225,7 @@ self.opaque = NO; self.presentsWithTransaction = YES; self.pixelFormat = MTLPixelFormatRGBA16Float; - base::ScopedCFTypeRef<CGColorSpaceRef> colorSpace( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> colorSpace( CGColorSpaceCreateWithName(kCGColorSpaceExtendedLinearSRGB)); self.colorspace = colorSpace; } @@ -251,9 +251,9 @@ CAEDRMetadata* edrMetadata = nil; switch (colorSpace.GetTransferID()) { case gfx::ColorSpace::TransferID::PQ: { - base::ScopedCFTypeRef<CFDataRef> display_info = + base::apple::ScopedCFTypeRef<CFDataRef> display_info = gfx::GenerateMasteringDisplayColorVolume(hdrMetadata); - base::ScopedCFTypeRef<CFDataRef> content_info = + base::apple::ScopedCFTypeRef<CFDataRef> content_info = gfx::GenerateContentLightLevelInfo(hdrMetadata); edrMetadata = [CAEDRMetadata HDR10MetadataWithDisplayInfo:base::apple::CFToNSPtrCast(
diff --git a/components/metrics/drive_metrics_provider_mac.mm b/components/metrics/drive_metrics_provider_mac.mm index 31345099..4133a56 100644 --- a/components/metrics/drive_metrics_provider_mac.mm +++ b/components/metrics/drive_metrics_provider_mac.mm
@@ -35,18 +35,18 @@ std::string bsd_name("/dev/"); bsd_name.append(dev_name); - base::ScopedCFTypeRef<DASessionRef> session( + base::apple::ScopedCFTypeRef<DASessionRef> session( DASessionCreate(kCFAllocatorDefault)); if (!session) return false; - base::ScopedCFTypeRef<DADiskRef> disk( + base::apple::ScopedCFTypeRef<DADiskRef> disk( DADiskCreateFromBSDName(kCFAllocatorDefault, session, bsd_name.c_str())); if (!disk) return false; base::mac::ScopedIOObject<io_object_t> io_media(DADiskCopyIOMedia(disk)); - base::ScopedCFTypeRef<CFDictionaryRef> characteristics( + base::apple::ScopedCFTypeRef<CFDictionaryRef> characteristics( static_cast<CFDictionaryRef>(IORegistryEntrySearchCFProperty( io_media, kIOServicePlane, CFSTR(kIOPropertyDeviceCharacteristicsKey), kCFAllocatorDefault,
diff --git a/components/omnibox/browser/actions/history_clusters_action.cc b/components/omnibox/browser/actions/history_clusters_action.cc index 9c91b5f5..87a2731 100644 --- a/components/omnibox/browser/actions/history_clusters_action.cc +++ b/components/omnibox/browser/actions/history_clusters_action.cc
@@ -91,8 +91,8 @@ } GURL GetFullJourneysUrlForQuery(const std::string& query) { - return net::AppendOrReplaceQueryParameter(GURL(kChromeUIHistoryClustersURL), - "q", query); + return net::AppendOrReplaceQueryParameter( + GURL(GetChromeUIHistoryClustersURL()), "q", query); } HistoryClustersAction::HistoryClustersAction(
diff --git a/components/omnibox/browser/actions/history_clusters_action_unittest.cc b/components/omnibox/browser/actions/history_clusters_action_unittest.cc index 77dbb68..1b3244ab 100644 --- a/components/omnibox/browser/actions/history_clusters_action_unittest.cc +++ b/components/omnibox/browser/actions/history_clusters_action_unittest.cc
@@ -9,10 +9,12 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_refptr.h" #include "base/ranges/algorithm.h" +#include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "components/history/core/browser/history_service.h" #include "components/history/core/test/history_service_test_util.h" #include "components/history_clusters/core/config.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_prefs.h" #include "components/history_clusters/core/history_clusters_service.h" #include "components/history_clusters/core/history_clusters_service_test_api.h" @@ -60,6 +62,9 @@ // `history_dir_` needs to be initialized once only. void SetUp() override { + scoped_feature_list_.InitAndDisableFeature( + history_clusters::kRenameJourneys); + CHECK(history_dir_.CreateUniqueTempDir()); history_service_ = history::CreateHistoryService(history_dir_.GetPath(), true); @@ -126,6 +131,8 @@ base::test::TaskEnvironment task_environment_; + base::test::ScopedFeatureList scoped_feature_list_; + base::ScopedTempDir history_dir_; std::unique_ptr<history::HistoryService> history_service_; std::unique_ptr<HistoryClustersService> history_clusters_service_;
diff --git a/components/omnibox/browser/history_cluster_provider.cc b/components/omnibox/browser/history_cluster_provider.cc index be469216..2f18b101 100644 --- a/components/omnibox/browser/history_cluster_provider.cc +++ b/components/omnibox/browser/history_cluster_provider.cc
@@ -4,10 +4,13 @@ #include "components/omnibox/browser/history_cluster_provider.h" +#include "base/feature_list.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "components/history_clusters/core/config.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_service.h" +#include "components/history_clusters/core/url_constants.h" #include "components/omnibox/browser/actions/history_clusters_action.h" #include "components/omnibox/browser/autocomplete_controller.h" #include "components/omnibox/browser/autocomplete_match.h" @@ -163,10 +166,12 @@ const auto& text = search_match.contents; - match.destination_url = GURL(base::UTF8ToUTF16(base::StringPrintf( - "chrome://history/journeys?q=%s", - base::EscapeQueryParamValue(base::UTF16ToUTF8(text), /*use_plus=*/false) - .c_str()))); + match.destination_url = GURL( + base::UTF8ToUTF16(history_clusters::GetChromeUIHistoryClustersURL() + + base::StringPrintf("?q=%s", base::EscapeQueryParamValue( + base::UTF16ToUTF8(text), + /*use_plus=*/false) + .c_str()))); match.fill_into_edit = text; @@ -176,7 +181,9 @@ ACMatchClassification::MATCH, ACMatchClassification::NONE); match.contents = l10n_util::GetStringUTF16( - IDS_OMNIBOX_ACTION_HISTORY_CLUSTERS_SEARCH_HINT); + base::FeatureList::IsEnabled(history_clusters::kRenameJourneys) + ? IDS_OMNIBOX_HISTORY_CLUSTERS_SEARCH_HINT + : IDS_OMNIBOX_ACTION_HISTORY_CLUSTERS_SEARCH_HINT); match.contents_class = {{0, ACMatchClassification::DIM}}; CompleteHistoryClustersMatch(base::UTF16ToUTF8(text),
diff --git a/components/omnibox/browser/history_cluster_provider_unittest.cc b/components/omnibox/browser/history_cluster_provider_unittest.cc index afa70ec..e17515eb 100644 --- a/components/omnibox/browser/history_cluster_provider_unittest.cc +++ b/components/omnibox/browser/history_cluster_provider_unittest.cc
@@ -8,9 +8,11 @@ #include "base/files/scoped_temp_dir.h" #include "base/memory/scoped_refptr.h" +#include "base/test/scoped_feature_list.h" #include "base/test/task_environment.h" #include "components/history/core/browser/history_service.h" #include "components/history_clusters/core/config.h" +#include "components/history_clusters/core/features.h" #include "components/history_clusters/core/history_clusters_prefs.h" #include "components/history_clusters/core/history_clusters_service.h" #include "components/history_clusters/core/history_clusters_service_test_api.h" @@ -43,6 +45,9 @@ public AutocompleteProviderListener { public: void SetUp() override { + scoped_feature_list_.InitAndDisableFeature( + history_clusters::kRenameJourneys); + config_.is_journeys_enabled_no_locale_check = true; config_.omnibox_history_cluster_provider = true; history_clusters::SetConfigForTesting(config_); @@ -117,6 +122,8 @@ base::test::TaskEnvironment task_environment_; + base::test::ScopedFeatureList scoped_feature_list_; + std::unique_ptr<FakeAutocompleteProviderClient> autocomplete_provider_client_; base::ScopedTempDir history_dir_;
diff --git a/components/omnibox_strings.grdp b/components/omnibox_strings.grdp index 8ad5f20..14b5b7f 100644 --- a/components/omnibox_strings.grdp +++ b/components/omnibox_strings.grdp
@@ -116,6 +116,9 @@ <!-- History Clusters Actions. --> + <message name="IDS_OMNIBOX_HISTORY_CLUSTERS_SEARCH_HINT" desc="The button text for the History Clusters omnibox suggestion in sentence case. Clicking this button takes users to a view of their browsing history related to the suggestion."> + Resume browsing + </message> <message name="IDS_OMNIBOX_ACTION_HISTORY_CLUSTERS_SEARCH_HINT" desc="The button text for the History Clusters omnibox action. Clicking this button takes users to a view of their browsing history related to the attached suggestion."> Resume your journey </message>
diff --git a/components/omnibox_strings_grdp/IDS_OMNIBOX_HISTORY_CLUSTERS_SEARCH_HINT.png.sha1 b/components/omnibox_strings_grdp/IDS_OMNIBOX_HISTORY_CLUSTERS_SEARCH_HINT.png.sha1 new file mode 100644 index 0000000..b9c4e48 --- /dev/null +++ b/components/omnibox_strings_grdp/IDS_OMNIBOX_HISTORY_CLUSTERS_SEARCH_HINT.png.sha1
@@ -0,0 +1 @@ +75912b568848ac9011f97ce7791f0fdc1c5fb670 \ No newline at end of file
diff --git a/components/password_manager/core/browser/login_database_ios.cc b/components/password_manager/core/browser/login_database_ios.cc index be73c00..99686963 100644 --- a/components/password_manager/core/browser/login_database_ios.cc +++ b/components/password_manager/core/browser/login_database_ios.cc
@@ -21,7 +21,7 @@ #include "components/password_manager/core/common/passwords_directory_util_ios.h" #include "sql/statement.h" -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; namespace password_manager {
diff --git a/components/password_manager/core/browser/login_database_ios_unittest.cc b/components/password_manager/core/browser/login_database_ios_unittest.cc index 9837c7b..132b32a6 100644 --- a/components/password_manager/core/browser/login_database_ios_unittest.cc +++ b/components/password_manager/core/browser/login_database_ios_unittest.cc
@@ -26,8 +26,8 @@ #include "testing/gtest/include/gtest/gtest.h" #include "testing/platform_test.h" -using base::ScopedCFTypeRef; using base::UTF16ToUTF8; +using base::apple::ScopedCFTypeRef; namespace password_manager {
diff --git a/components/policy/core/common/cloud/cloud_policy_util.cc b/components/policy/core/common/cloud/cloud_policy_util.cc index 13c6d66..f750ab0 100644 --- a/components/policy/core/common/cloud/cloud_policy_util.cc +++ b/components/policy/core/common/cloud/cloud_policy_util.cc
@@ -93,15 +93,15 @@ #elif BUILDFLAG(IS_MAC) // Do not use NSHost currentHost, as it's very slow. http://crbug.com/138570 SCDynamicStoreContext context = {0, NULL, NULL, NULL}; - base::ScopedCFTypeRef<SCDynamicStoreRef> store(SCDynamicStoreCreate( + base::apple::ScopedCFTypeRef<SCDynamicStoreRef> store(SCDynamicStoreCreate( kCFAllocatorDefault, CFSTR("chrome_sync"), NULL, &context)); - base::ScopedCFTypeRef<CFStringRef> machine_name( + base::apple::ScopedCFTypeRef<CFStringRef> machine_name( SCDynamicStoreCopyLocalHostName(store.get())); if (machine_name.get()) return base::SysCFStringRefToUTF8(machine_name.get()); // Fall back to get computer name. - base::ScopedCFTypeRef<CFStringRef> computer_name( + base::apple::ScopedCFTypeRef<CFStringRef> computer_name( SCDynamicStoreCopyComputerName(store.get(), NULL)); if (computer_name.get()) return base::SysCFStringRefToUTF8(computer_name.get());
diff --git a/components/policy/core/common/mac_util_unittest.cc b/components/policy/core/common/mac_util_unittest.cc index c3fda75..a34a98b4 100644 --- a/components/policy/core/common/mac_util_unittest.cc +++ b/components/policy/core/common/mac_util_unittest.cc
@@ -61,7 +61,8 @@ const base::Value root_val(std::move(root)); // base::Value -> property list -> base::Value. - base::ScopedCFTypeRef<CFPropertyListRef> property(ValueToProperty(root_val)); + base::apple::ScopedCFTypeRef<CFPropertyListRef> property( + ValueToProperty(root_val)); ASSERT_TRUE(property); std::unique_ptr<base::Value> value = PropertyToValue(property); ASSERT_TRUE(value);
diff --git a/components/policy/core/common/policy_loader_ios_unittest.mm b/components/policy/core/common/policy_loader_ios_unittest.mm index 7186fd6..c2de6fe 100644 --- a/components/policy/core/common/policy_loader_ios_unittest.mm +++ b/components/policy/core/common/policy_loader_ios_unittest.mm
@@ -132,7 +132,7 @@ const std::string& policy_name, const base::Value::List& policy_value) { NSString* key = base::SysUTF8ToNSString(policy_name); - base::ScopedCFTypeRef<CFPropertyListRef> value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( ValueToProperty(base::Value(policy_value.Clone()))); if (encode_complex_data_as_json_) { @@ -160,7 +160,7 @@ AddPolicies(@{key : base::SysUTF8ToNSString(json_string)}); } else { - base::ScopedCFTypeRef<CFPropertyListRef> value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( ValueToProperty(base::Value(policy_value.Clone()))); AddPolicies(@{key : (__bridge NSDictionary*)(value.get())}); }
diff --git a/components/policy/core/common/policy_loader_mac.h b/components/policy/core/common/policy_loader_mac.h index e107d20..bdc7197 100644 --- a/components/policy/core/common/policy_loader_mac.h +++ b/components/policy/core/common/policy_loader_mac.h
@@ -86,7 +86,7 @@ base::FilePathWatcher watcher_; // Application ID to pass into Mac's Preference Utilities API. - base::ScopedCFTypeRef<CFStringRef> application_id_; + base::apple::ScopedCFTypeRef<CFStringRef> application_id_; }; } // namespace policy
diff --git a/components/policy/core/common/policy_loader_mac.mm b/components/policy/core/common/policy_loader_mac.mm index 3e0d27a..e7b66ff 100644 --- a/components/policy/core/common/policy_loader_mac.mm +++ b/components/policy/core/common/policy_loader_mac.mm
@@ -111,9 +111,9 @@ schema_map()->GetSchema(PolicyNamespace(POLICY_DOMAIN_CHROME, "")); for (Schema::Iterator it = schema->GetPropertiesIterator(); !it.IsAtEnd(); it.Advance()) { - base::ScopedCFTypeRef<CFStringRef> name( + base::apple::ScopedCFTypeRef<CFStringRef> name( base::SysUTF8ToCFStringRef(it.key())); - base::ScopedCFTypeRef<CFPropertyListRef> value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( preferences_->CopyAppValue(name, application_id_)); if (!value) continue; @@ -204,15 +204,15 @@ if (!schema.valid()) return; - base::ScopedCFTypeRef<CFStringRef> bundle_id = + base::apple::ScopedCFTypeRef<CFStringRef> bundle_id = base::SysUTF8ToCFStringRef(bundle_id_string); preferences_->AppSynchronize(bundle_id); for (Schema::Iterator it = schema.GetPropertiesIterator(); !it.IsAtEnd(); it.Advance()) { - base::ScopedCFTypeRef<CFStringRef> pref_name = + base::apple::ScopedCFTypeRef<CFStringRef> pref_name = base::SysUTF8ToCFStringRef(it.key()); - base::ScopedCFTypeRef<CFPropertyListRef> value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> value( preferences_->CopyAppValue(pref_name, bundle_id)); if (!value) continue;
diff --git a/components/policy/core/common/policy_loader_mac_unittest.cc b/components/policy/core/common/policy_loader_mac_unittest.cc index f383147b..7a86fa64 100644 --- a/components/policy/core/common/policy_loader_mac_unittest.cc +++ b/components/policy/core/common/policy_loader_mac_unittest.cc
@@ -27,7 +27,7 @@ #include "components/policy/core/common/preferences_mock_mac.h" #include "testing/gtest/include/gtest/gtest.h" -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; namespace policy {
diff --git a/components/policy/core/common/policy_test_utils.cc b/components/policy/core/common/policy_test_utils.cc index acc1aee6..dcdd93b9 100644 --- a/components/policy/core/common/policy_test_utils.cc +++ b/components/policy/core/common/policy_test_utils.cc
@@ -91,9 +91,9 @@ for (const auto key_value_pair : value_dict) { // CFDictionaryAddValue() retains both |key| and |value|, so make sure // the references are balanced. - base::ScopedCFTypeRef<CFStringRef> key( + base::apple::ScopedCFTypeRef<CFStringRef> key( base::SysUTF8ToCFStringRef(key_value_pair.first)); - base::ScopedCFTypeRef<CFPropertyListRef> cf_value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> cf_value( ValueToProperty(key_value_pair.second)); if (cf_value) CFDictionaryAddValue(dict, key, cf_value); @@ -108,7 +108,7 @@ for (const base::Value& entry : list) { // CFArrayAppendValue() retains |cf_value|, so make sure the reference // created by ValueToProperty() is released. - base::ScopedCFTypeRef<CFPropertyListRef> cf_value( + base::apple::ScopedCFTypeRef<CFPropertyListRef> cf_value( ValueToProperty(entry)); if (cf_value) CFArrayAppendValue(array, cf_value);
diff --git a/components/policy/core/common/preferences_mock_mac.h b/components/policy/core/common/preferences_mock_mac.h index 0b4839de..fbeb4a70 100644 --- a/components/policy/core/common/preferences_mock_mac.h +++ b/components/policy/core/common/preferences_mock_mac.h
@@ -30,9 +30,9 @@ bool is_machine); private: - base::ScopedCFTypeRef<CFMutableDictionaryRef> values_; - base::ScopedCFTypeRef<CFMutableSetRef> forced_; - base::ScopedCFTypeRef<CFMutableSetRef> machine_; + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> values_; + base::apple::ScopedCFTypeRef<CFMutableSetRef> forced_; + base::apple::ScopedCFTypeRef<CFMutableSetRef> machine_; }; #endif // COMPONENTS_POLICY_CORE_COMMON_PREFERENCES_MOCK_MAC_H_
diff --git a/components/policy/resources/templates/policy_definitions/Miscellaneous/HistoryClustersVisible.yaml b/components/policy/resources/templates/policy_definitions/Miscellaneous/HistoryClustersVisible.yaml index fc65eeb..217cf15 100644 --- a/components/policy/resources/templates/policy_definitions/Miscellaneous/HistoryClustersVisible.yaml +++ b/components/policy/resources/templates/policy_definitions/Miscellaneous/HistoryClustersVisible.yaml
@@ -1,15 +1,14 @@ -caption: Show Journeys on the Chrome history page +caption: Show a view of Chrome history with groups of pages default: null -desc: "This policy controls the visibility of Journeys on the Chrome history page.\n\ - \n If the policy is set to Enabled, Journeys will be visible at chrome://history/journeys.\n\ - \n If the policy is set to Disabled, Journeys will not be visible at chrome://history/journeys.\n\ - \n If the policy is left unset, Journeys will be visible at chrome://history/journeys\ - \ by default and users can change the visibility of Journeys.\n\n Please note,\ +desc: "This policy controls the visibility of the Chrome history page organized into groups of pages.\n\ + \n If the policy is set to Enabled, a Chrome history page organized into groups will be visible at chrome://history/2.\n\ + \n If the policy is set to Disabled, a Chrome history page organized into groups will not be visible at chrome://history/2.\n\ + \n If the policy is left unset, a Chrome history page organized into groups will be visible at chrome://history/2\ + \ by default.\n\n Please note,\ \ if <ph name=\"COMPONENT_UPDATES_ENABLED_POLICY_NAME\">ComponentUpdatesEnabled</ph>\ \ policy is set to Disabled, but <ph name=\"HISTORY_CLUSTERS_VISIBLE_POLICY_NAME\"\ - >HistoryClustersVisible</ph> is set to Enabled or unset, Journeys will still be\ - \ available at chrome://history/journeys, but may be absent from the omnibox, and\ - \ less relevant to the user.\n " + >HistoryClustersVisible</ph> is set to Enabled or unset, a Chrome history page organized into groups will still be\ + \ available at chrome://history/2, but may be less relevant to the user.\n" example_value: false features: dynamic_refresh: true @@ -17,12 +16,11 @@ future_on: - fuchsia items: -- caption: Journeys will be visible at chrome://history/journeys. +- caption: Chrome history page organized into groups will be visible at chrome://history/2. value: true -- caption: Journeys will not be visible at chrome://history/journeys. +- caption: Chrome history page organized into groups will not be visible at chrome://history/2. value: false -- caption: Journeys will be visible at chrome://history/journeys by default and users - can change the visibility of Journeys. +- caption: Chrome history page organized into groups will be visible at chrome://history/2 by default. value: null owners: - file://components/history_clusters/OWNERS
diff --git a/components/power_metrics/energy_impact_mac.mm b/components/power_metrics/energy_impact_mac.mm index c4eddf9..51f6800 100644 --- a/components/power_metrics/energy_impact_mac.mm +++ b/components/power_metrics/energy_impact_mac.mm
@@ -182,7 +182,7 @@ // This is what libpmenergy is observed to do in order to retrieve the correct // coefficients file for the local computer. - base::ScopedCFTypeRef<CFDataRef> board_id_data( + base::apple::ScopedCFTypeRef<CFDataRef> board_id_data( base::apple::CFCast<CFDataRef>(IORegistryEntryCreateCFProperty( platform_expert, CFSTR("board-id"), kCFAllocatorDefault, 0)));
diff --git a/components/power_metrics/m1_sensors_mac.h b/components/power_metrics/m1_sensors_mac.h index f1d46da..e8a00a0 100644 --- a/components/power_metrics/m1_sensors_mac.h +++ b/components/power_metrics/m1_sensors_mac.h
@@ -38,10 +38,10 @@ protected: explicit M1SensorsReader( - base::ScopedCFTypeRef<IOHIDEventSystemClientRef> system); + base::apple::ScopedCFTypeRef<IOHIDEventSystemClientRef> system); private: - base::ScopedCFTypeRef<IOHIDEventSystemClientRef> system_; + base::apple::ScopedCFTypeRef<IOHIDEventSystemClientRef> system_; }; } // namespace power_metrics
diff --git a/components/power_metrics/m1_sensors_mac.mm b/components/power_metrics/m1_sensors_mac.mm index ff65ff9..d9ec55f6 100644 --- a/components/power_metrics/m1_sensors_mac.mm +++ b/components/power_metrics/m1_sensors_mac.mm
@@ -34,7 +34,7 @@ absl::optional<double> GetEventFloatValue(IOHIDServiceClientRef service, int64_t event_type) { - base::ScopedCFTypeRef<CFTypeRef> event( + base::apple::ScopedCFTypeRef<CFTypeRef> event( IOHIDServiceClientCopyEvent(service, event_type, 0, 0)); if (!event) return absl::nullopt; @@ -52,7 +52,7 @@ // static std::unique_ptr<M1SensorsReader> M1SensorsReader::Create() { - base::ScopedCFTypeRef<IOHIDEventSystemClientRef> system( + base::apple::ScopedCFTypeRef<IOHIDEventSystemClientRef> system( IOHIDEventSystemClientCreate(kCFAllocatorDefault)); if (system == nil) @@ -68,7 +68,7 @@ } M1SensorsReader::TemperaturesCelsius M1SensorsReader::ReadTemperatures() { - base::ScopedCFTypeRef<CFArrayRef> services( + base::apple::ScopedCFTypeRef<CFArrayRef> services( IOHIDEventSystemClientCopyServices(system_.get())); // There are multiple temperature sensors on P-Cores and E-Cores. Count and @@ -82,8 +82,9 @@ IOHIDServiceClientRef service = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(services, i); - base::ScopedCFTypeRef<CFStringRef> product(base::apple::CFCast<CFStringRef>( - IOHIDServiceClientCopyProperty(service, CFSTR(kIOHIDProductKey)))); + base::apple::ScopedCFTypeRef<CFStringRef> product( + base::apple::CFCast<CFStringRef>( + IOHIDServiceClientCopyProperty(service, CFSTR(kIOHIDProductKey)))); if (product == nil) { continue; } @@ -117,7 +118,7 @@ } M1SensorsReader::M1SensorsReader( - base::ScopedCFTypeRef<IOHIDEventSystemClientRef> system) + base::apple::ScopedCFTypeRef<IOHIDEventSystemClientRef> system) : system_(std::move(system)) {} } // namespace power_metrics
diff --git a/components/remote_cocoa/app_shim/certificate_viewer.mm b/components/remote_cocoa/app_shim/certificate_viewer.mm index db12f8b..0c2fa1f 100644 --- a/components/remote_cocoa/app_shim/certificate_viewer.mm +++ b/components/remote_cocoa/app_shim/certificate_viewer.mm
@@ -38,7 +38,7 @@ // the certificate viewer UI from displaying which certificate is revoked. // This is acceptable, as certificate revocation will still be shown in // the page info bubble if a certificate in the chain is actually revoked. - base::ScopedCFTypeRef<CFMutableArrayRef> policies( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> policies( CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)); if (!policies.get()) { NOTREACHED(); @@ -46,7 +46,8 @@ } // Add a basic X.509 policy, in order to match the behaviour of // SFCertificatePanel when no policies are specified. - base::ScopedCFTypeRef<SecPolicyRef> basic_policy(SecPolicyCreateBasicX509()); + base::apple::ScopedCFTypeRef<SecPolicyRef> basic_policy( + SecPolicyCreateBasicX509()); if (!basic_policy) { NOTREACHED(); return;
diff --git a/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm b/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm index b7b0b2e..dfb2bf80a 100644 --- a/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm +++ b/components/remote_cocoa/app_shim/select_file_dialog_bridge.mm
@@ -29,7 +29,8 @@ // TODO(macOS 11): Remove this. CFStringRef CreateUTIFromExtension(const base::FilePath::StringType& ext) { - base::ScopedCFTypeRef<CFStringRef> ext_cf(base::SysUTF8ToCFStringRef(ext)); + base::apple::ScopedCFTypeRef<CFStringRef> ext_cf( + base::SysUTF8ToCFStringRef(ext)); return UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext_cf.get(), nullptr); } @@ -44,7 +45,7 @@ return description; } } else { - base::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); + base::apple::ScopedCFTypeRef<CFStringRef> uti(CreateUTIFromExtension(ext)); NSString* description = base::apple::CFToNSOwnershipCast(UTTypeCopyDescription(uti.get()));
diff --git a/components/search_engines/template_url_prepopulate_data.cc b/components/search_engines/template_url_prepopulate_data.cc index 0d9d6082..be3ad802 100644 --- a/components/search_engines/template_url_prepopulate_data.cc +++ b/components/search_engines/template_url_prepopulate_data.cc
@@ -5,6 +5,7 @@ #include "components/search_engines/template_url_prepopulate_data.h" #include "base/logging.h" +#include "base/rand_util.h" #include "base/ranges/algorithm.h" #include "build/build_config.h" #include "components/country_codes/country_codes.h" @@ -1392,6 +1393,26 @@ return t_urls; } +std::vector<std::unique_ptr<TemplateURLData>> +GetPrepopulatedEnginesForChoiceScreen(PrefService* prefs) { + // TODO (b/282656014): Update the returned list of search engines to comply + // with choice screen requirements. + std::vector<std::unique_ptr<TemplateURLData>> engines = + GetPrepopulatedEngines(prefs, nullptr); + std::vector<TemplateURLData*> tmp_engines; + for (auto& engine : engines) { + tmp_engines.push_back(engine.get()); + } + + base::RandomShuffle(tmp_engines.begin(), tmp_engines.end()); + + std::vector<std::unique_ptr<TemplateURLData>> shuffled_engines; + for (TemplateURLData* engine : tmp_engines) { + shuffled_engines.push_back(std::make_unique<TemplateURLData>(*engine)); + } + return shuffled_engines; +} + std::unique_ptr<TemplateURLData> GetPrepopulatedEngine(PrefService* prefs, int prepopulated_id) { auto engines =
diff --git a/components/search_engines/template_url_prepopulate_data.h b/components/search_engines/template_url_prepopulate_data.h index 1cf84dbb..c649fc6 100644 --- a/components/search_engines/template_url_prepopulate_data.h +++ b/components/search_engines/template_url_prepopulate_data.h
@@ -40,6 +40,11 @@ PrefService* prefs, size_t* default_search_provider_index); +// Returns the prepopulated URLs for the current country, shuffled for display +// in a search engine choice screen. +std::vector<std::unique_ptr<TemplateURLData>> +GetPrepopulatedEnginesForChoiceScreen(PrefService* prefs); + // Returns the prepopulated search engine with the given |prepopulated_id|. std::unique_ptr<TemplateURLData> GetPrepopulatedEngine(PrefService* prefs, int prepopulated_id);
diff --git a/components/search_engines/template_url_prepopulate_data_unittest.cc b/components/search_engines/template_url_prepopulate_data_unittest.cc index 62ca4e40..4e8d68a 100644 --- a/components/search_engines/template_url_prepopulate_data_unittest.cc +++ b/components/search_engines/template_url_prepopulate_data_unittest.cc
@@ -491,3 +491,22 @@ EXPECT_LT(index, urls.size()); EXPECT_EQ(urls[index]->prepopulate_id, kGoogleId); } + +TEST_F(TemplateURLPrepopulateDataTest, GetPrepopulatedEnginesForChoiceScreen) { + std::vector<std::unique_ptr<TemplateURLData>> ordered_urls; + std::vector<std::unique_ptr<TemplateURLData>> shuffled_urls; + prefs_.SetInteger(country_codes::kCountryIDAtInstall, 'U' << 8 | 'S'); + ordered_urls = + TemplateURLPrepopulateData::GetPrepopulatedEngines(&prefs_, nullptr); + + shuffled_urls = + TemplateURLPrepopulateData::GetPrepopulatedEnginesForChoiceScreen( + &prefs_); + + EXPECT_EQ(ordered_urls.size(), shuffled_urls.size()); + for (const auto& url_data : ordered_urls) { + EXPECT_TRUE(base::ranges::find(shuffled_urls, url_data->prepopulate_id, + &TemplateURLData::prepopulate_id) != + shuffled_urls.end()); + } +}
diff --git a/components/search_engines/template_url_service.cc b/components/search_engines/template_url_service.cc index 6335801..792ea03 100644 --- a/components/search_engines/template_url_service.cc +++ b/components/search_engines/template_url_service.cc
@@ -590,6 +590,19 @@ return result; } +TemplateURLService::OwnedTemplateURLVector +TemplateURLService::GetTemplateURLsForChoiceScreen() { + // TODO (b/282656014): Update the returned list of search engines to comply + // with choice screen requirements. + OwnedTemplateURLVector result; + std::vector<std::unique_ptr<TemplateURLData>> engines = + TemplateURLPrepopulateData::GetPrepopulatedEnginesForChoiceScreen(prefs_); + for (const auto& engine : engines) { + result.push_back(std::make_unique<TemplateURL>(*engine)); + } + return result; +} + void TemplateURLService::IncrementUsageCount(TemplateURL* url) { DCHECK(url); // Extension-controlled search engines are not persisted.
diff --git a/components/search_engines/template_url_service.h b/components/search_engines/template_url_service.h index c4936800..c9c9d86 100644 --- a/components/search_engines/template_url_service.h +++ b/components/search_engines/template_url_service.h
@@ -231,6 +231,12 @@ // by TemplateURLService and should not be deleted. TemplateURLVector GetTemplateURLs(); + // Returns the list of prepopulated template URLs for the current country + // shuffled for display in a search engine choice screen. + // TODO (b/282656014): Update the returned list of search engines to comply + // with choice screen requirements. + OwnedTemplateURLVector GetTemplateURLsForChoiceScreen(); + // Increment the usage count of a keyword. // Called when a URL is loaded that was generated from a keyword. void IncrementUsageCount(TemplateURL* url);
diff --git a/components/services/app_service/public/cpp/intent_util.cc b/components/services/app_service/public/cpp/intent_util.cc index 0a1dd4d6..8531bd8 100644 --- a/components/services/app_service/public/cpp/intent_util.cc +++ b/components/services/app_service/public/cpp/intent_util.cc
@@ -622,6 +622,15 @@ } // static +absl::optional<std::string> AuthorityView::PortToString( + const url::Origin& origin) { + if (origin.port() == 0) { + return absl::nullopt; + } + return base::ToString(origin.port()); +} + +// static AuthorityView AuthorityView::Decode(std::string_view encoded_string) { size_t i = encoded_string.find_last_of(kAuthorityHostPortSeparator); if (i == std::string_view::npos) { @@ -637,6 +646,13 @@ return AuthorityView{.host = url.host(), .port = PortToString(url)}.Encode(); } +// static +std::string AuthorityView::Encode(const url::Origin& origin) { + CHECK(!origin.opaque()); + return AuthorityView{.host = origin.host(), .port = PortToString(origin)} + .Encode(); +} + std::string AuthorityView::Encode() { if (!port) { return std::string(host);
diff --git a/components/services/app_service/public/cpp/intent_util.h b/components/services/app_service/public/cpp/intent_util.h index 31a37ba..83a23ce 100644 --- a/components/services/app_service/public/cpp/intent_util.h +++ b/components/services/app_service/public/cpp/intent_util.h
@@ -15,6 +15,7 @@ #include "components/services/app_service/public/cpp/intent_filter.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" +#include "url/origin.h" namespace apps_util { @@ -165,6 +166,7 @@ // Stringifies the effective port of `url` if there is one. Not all URL // schemes have ports. static absl::optional<std::string> PortToString(const GURL& url); + static absl::optional<std::string> PortToString(const url::Origin& url); // Decodes strings of the form: // "www.example.com:1234" into {.host="www.example.com", .port="1234"} @@ -173,6 +175,7 @@ // Delegates to Encode(). static std::string Encode(const GURL& url); + static std::string Encode(const url::Origin& origin); // Encodes into the form: // "www.example.com:1234" if port is set
diff --git a/components/services/app_service/public/cpp/intent_util_unittest.cc b/components/services/app_service/public/cpp/intent_util_unittest.cc index 2a576306..0a062c17b 100644 --- a/components/services/app_service/public/cpp/intent_util_unittest.cc +++ b/components/services/app_service/public/cpp/intent_util_unittest.cc
@@ -285,16 +285,22 @@ GURL(url_spec)); }; - auto explicit_port = MakeAuthorityFilter( - apps_util::AuthorityView::Encode(GURL("https://example.com:1234"))); - EXPECT_TRUE( - MakeViewIntent("https://example.com:1234")->MatchFilter(explicit_port)); - EXPECT_FALSE( - MakeViewIntent("https://example.com")->MatchFilter(explicit_port)); - EXPECT_FALSE( - MakeViewIntent("https://example.com:5678")->MatchFilter(explicit_port)); - EXPECT_FALSE( - MakeViewIntent("https://example.org:1234")->MatchFilter(explicit_port)); + std::vector<std::string> explicit_ports{ + apps_util::AuthorityView::Encode(GURL("https://example.com:1234")), + apps_util::AuthorityView::Encode( + url::Origin::CreateFromNormalizedTuple("https", "example.com", 1234)), + }; + for (const auto& explicit_port : explicit_ports) { + auto authority_filter = MakeAuthorityFilter(explicit_port); + EXPECT_TRUE(MakeViewIntent("https://example.com:1234") + ->MatchFilter(authority_filter)); + EXPECT_FALSE( + MakeViewIntent("https://example.com")->MatchFilter(authority_filter)); + EXPECT_FALSE(MakeViewIntent("https://example.com:5678") + ->MatchFilter(authority_filter)); + EXPECT_FALSE(MakeViewIntent("https://example.org:1234") + ->MatchFilter(authority_filter)); + } auto implicit_port = MakeAuthorityFilter( apps_util::AuthorityView::Encode(GURL("https://example.com"))); @@ -316,12 +322,22 @@ MakeViewIntent("file://test:1234")->MatchFilter(portless_scheme)); EXPECT_FALSE(MakeViewIntent("file://other")->MatchFilter(portless_scheme)); - auto host_only = MakeAuthorityFilter("example.com"); - EXPECT_TRUE(MakeViewIntent("https://example.com")->MatchFilter(host_only)); - EXPECT_TRUE(MakeViewIntent("https://example.com:80")->MatchFilter(host_only)); - EXPECT_TRUE( - MakeViewIntent("https://example.com:1234")->MatchFilter(host_only)); - EXPECT_FALSE(MakeViewIntent("https://example.org")->MatchFilter(host_only)); + std::vector<std::string> host_onlys{ + "example.com", + apps_util::AuthorityView::Encode( + url::Origin::CreateFromNormalizedTuple("https", "example.com", 0)), + }; + for (const auto& host_only : host_onlys) { + auto authority_filter = MakeAuthorityFilter(host_only); + EXPECT_TRUE( + MakeViewIntent("https://example.com")->MatchFilter(authority_filter)); + EXPECT_TRUE(MakeViewIntent("https://example.com:80") + ->MatchFilter(authority_filter)); + EXPECT_TRUE(MakeViewIntent("https://example.com:1234") + ->MatchFilter(authority_filter)); + EXPECT_FALSE( + MakeViewIntent("https://example.org")->MatchFilter(authority_filter)); + } auto host_suffix = MakeAuthorityFilter( apps_util::AuthorityView::Encode(GURL("https://example.com:1234")),
diff --git a/components/services/quarantine/quarantine_mac.mm b/components/services/quarantine/quarantine_mac.mm index 921cc51..21939574 100644 --- a/components/services/quarantine/quarantine_mac.mm +++ b/components/services/quarantine/quarantine_mac.mm
@@ -61,7 +61,7 @@ return false; } - base::ScopedCFTypeRef<MDItemRef> md_item( + base::apple::ScopedCFTypeRef<MDItemRef> md_item( MDItemCreate(kCFAllocatorDefault, base::apple::NSToCFPtrCast(file_path))); if (!md_item) { LOG(WARNING) << "MDItemCreate failed for path " << file.value();
diff --git a/components/services/quarantine/quarantine_mac_unittest.mm b/components/services/quarantine/quarantine_mac_unittest.mm index dd9105f..5592f3cf 100644 --- a/components/services/quarantine/quarantine_mac_unittest.mm +++ b/components/services/quarantine/quarantine_mac_unittest.mm
@@ -164,7 +164,7 @@ NSString* file_path = base::apple::FilePathToNSString(test_file_); ASSERT_NE(nullptr, file_path); - base::ScopedCFTypeRef<MDItemRef> md_item( + base::apple::ScopedCFTypeRef<MDItemRef> md_item( MDItemCreate(kCFAllocatorDefault, base::apple::NSToCFPtrCast(file_path))); if (!md_item) { // The quarantine code ignores it if adding origin metadata fails. If for @@ -173,7 +173,7 @@ return; } - base::ScopedCFTypeRef<CFTypeRef> attr( + base::apple::ScopedCFTypeRef<CFTypeRef> attr( MDItemCopyAttribute(md_item, kMDItemWhereFroms)); EXPECT_FALSE(attr); }
diff --git a/components/storage_monitor/storage_monitor_mac.h b/components/storage_monitor/storage_monitor_mac.h index c9b93bc..44fe27b4 100644 --- a/components/storage_monitor/storage_monitor_mac.h +++ b/components/storage_monitor/storage_monitor_mac.h
@@ -61,7 +61,7 @@ bool FindDiskWithMountPoint(const base::FilePath& mount_point, StorageInfo* info) const; - base::ScopedCFTypeRef<DASessionRef> session_; + base::apple::ScopedCFTypeRef<DASessionRef> session_; // Maps disk bsd names to disk info objects. This map tracks all mountable // devices on the system, though only notifications for removable devices are // posted.
diff --git a/components/storage_monitor/storage_monitor_mac.mm b/components/storage_monitor/storage_monitor_mac.mm index 6632183..d2bcea1c 100644 --- a/components/storage_monitor/storage_monitor_mac.mm +++ b/components/storage_monitor/storage_monitor_mac.mm
@@ -87,7 +87,7 @@ dict, kDADiskDescriptionVolumeUUIDKey); std::string unique_id; if (uuid) { - base::ScopedCFTypeRef<CFStringRef> uuid_string( + base::apple::ScopedCFTypeRef<CFStringRef> uuid_string( CFUUIDCreateString(nullptr, uuid)); if (uuid_string.get()) unique_id = base::SysCFStringRefToUTF8(uuid_string); @@ -119,7 +119,7 @@ struct EjectDiskOptions { std::string bsd_name; base::OnceCallback<void(StorageMonitor::EjectStatus)> callback; - base::ScopedCFTypeRef<DADiskRef> disk; + base::apple::ScopedCFTypeRef<DADiskRef> disk; }; void PostEjectCallback(DADiskRef disk, @@ -291,7 +291,7 @@ receiver()->ProcessDetach(device_id); - base::ScopedCFTypeRef<DADiskRef> disk( + base::apple::ScopedCFTypeRef<DADiskRef> disk( DADiskCreateFromBSDName(nullptr, session_, bsd_name.c_str())); if (!disk.get()) { std::move(callback).Run(StorageMonitor::EJECT_FAILURE); @@ -339,7 +339,8 @@ pending_disk_updates_++; - base::ScopedCFTypeRef<CFDictionaryRef> dict(DADiskCopyDescription(disk)); + base::apple::ScopedCFTypeRef<CFDictionaryRef> dict( + DADiskCopyDescription(disk)); std::string* bsd_name = new std::string; base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
diff --git a/components/subresource_filter/content/renderer/BUILD.gn b/components/subresource_filter/content/renderer/BUILD.gn index d05e70c..9c2af10 100644 --- a/components/subresource_filter/content/renderer/BUILD.gn +++ b/components/subresource_filter/content/renderer/BUILD.gn
@@ -44,4 +44,7 @@ "//third_party/blink/public:blink", "//url", ] + if (is_ios) { + deps += [ "//components/test:subresource_filter_test_bundle_data" ] + } }
diff --git a/components/subresource_filter/core/common/BUILD.gn b/components/subresource_filter/core/common/BUILD.gn index 59b204aa..2fe31505 100644 --- a/components/subresource_filter/core/common/BUILD.gn +++ b/components/subresource_filter/core/common/BUILD.gn
@@ -81,6 +81,9 @@ "//third_party/protobuf:protobuf_lite", "//url", ] + if (is_ios) { + deps += [ "//components/test:subresource_filter_test_bundle_data" ] + } } fuzzer_test("indexed_ruleset_fuzzer") {
diff --git a/components/sync_device_info/local_device_info_util_mac.mm b/components/sync_device_info/local_device_info_util_mac.mm index df56990..a64c80d0 100644 --- a/components/sync_device_info/local_device_info_util_mac.mm +++ b/components/sync_device_info/local_device_info_util_mac.mm
@@ -21,17 +21,17 @@ std::string GetPersonalizableDeviceNameInternal() { // Do not use NSHost currentHost, as it's very slow. http://crbug.com/138570 SCDynamicStoreContext context = {0}; - base::ScopedCFTypeRef<SCDynamicStoreRef> store( + base::apple::ScopedCFTypeRef<SCDynamicStoreRef> store( SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("chrome_sync"), /*callout=*/nullptr, &context)); - base::ScopedCFTypeRef<CFStringRef> machine_name( + base::apple::ScopedCFTypeRef<CFStringRef> machine_name( SCDynamicStoreCopyLocalHostName(store)); if (machine_name) { return base::SysCFStringRefToUTF8(machine_name); } // Fall back to get computer name. - base::ScopedCFTypeRef<CFStringRef> computer_name( + base::apple::ScopedCFTypeRef<CFStringRef> computer_name( SCDynamicStoreCopyComputerName(store, /*nameEncoding=*/nullptr)); if (computer_name) { return base::SysCFStringRefToUTF8(computer_name);
diff --git a/components/test/BUILD.gn b/components/test/BUILD.gn index b4c7d67..68fef3f 100644 --- a/components/test/BUILD.gn +++ b/components/test/BUILD.gn
@@ -95,6 +95,10 @@ testonly = true filelist_name = "data/service_worker/unit_tests_bundle_data.filelist" } + bundle_data_from_filelist("subresource_filter_test_bundle_data") { + testonly = true + filelist_name = "data/subresource_filter/unit_tests_bundle_data.filelist" + } bundle_data_from_filelist("url_rewrite_test_bundle_data") { testonly = true filelist_name = "data/url_rewrite/unit_tests_bundle_data.filelist"
diff --git a/components/test/PRESUBMIT.py b/components/test/PRESUBMIT.py index c132f2b6..2e22964 100644 --- a/components/test/PRESUBMIT.py +++ b/components/test/PRESUBMIT.py
@@ -44,6 +44,9 @@ 'data/service_worker/unit_tests_bundle_data') results += presubmit_support.CheckBundleData( input_api, output_api, + 'data/subresource_filter/unit_tests_bundle_data') + results += presubmit_support.CheckBundleData( + input_api, output_api, 'data/url_rewrite/unit_tests_bundle_data') results += presubmit_support.CheckBundleData( input_api, output_api,
diff --git a/components/test/data/subresource_filter/OWNERS b/components/test/data/subresource_filter/OWNERS new file mode 100644 index 0000000..4e6079c --- /dev/null +++ b/components/test/data/subresource_filter/OWNERS
@@ -0,0 +1,2 @@ +# Anyone can update the test bundle data filelist. +per-file unit_tests_bundle_data.filelist=*
diff --git a/components/test/data/subresource_filter/unit_tests_bundle_data.filelist b/components/test/data/subresource_filter/unit_tests_bundle_data.filelist new file mode 100644 index 0000000..9d3e155 --- /dev/null +++ b/components/test/data/subresource_filter/unit_tests_bundle_data.filelist
@@ -0,0 +1,41 @@ +# 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. +# NOTE: this file is generated by build/ios/update_bundle_filelist.py +# If it requires updating, you should get a presubmit error with +# instructions on how to regenerate. Otherwise, do not edit. +//components/test/data/subresource_filter/delete_loading_frame.html +//components/test/data/subresource_filter/docwrite_creates_subframe.html +//components/test/data/subresource_filter/docwrite_loads_disallowed_resource.html +//components/test/data/subresource_filter/frame_cross_site_set.html +//components/test/data/subresource_filter/frame_d.html +//components/test/data/subresource_filter/frame_set.html +//components/test/data/subresource_filter/frame_set_special_urls.html +//components/test/data/subresource_filter/frame_with_allowed_script.html +//components/test/data/subresource_filter/frame_with_allowed_script.html.mock-http-headers +//components/test/data/subresource_filter/frame_with_delayed_script.html +//components/test/data/subresource_filter/frame_with_included_script.html +//components/test/data/subresource_filter/frame_with_included_script.html.mock-http-headers +//components/test/data/subresource_filter/frame_with_multiple_fetches.html +//components/test/data/subresource_filter/frame_with_no_subresources.html +//components/test/data/subresource_filter/frame_with_no_subresources.html.mock-http-headers +//components/test/data/subresource_filter/iframe_spoof_click_popup.html +//components/test/data/subresource_filter/included_allowed_script.js +//components/test/data/subresource_filter/pixel.png +//components/test/data/subresource_filter/included_script.js +//components/test/data/subresource_filter/empty.js +//components/test/data/subresource_filter/included_script_in_iframe.html +//components/test/data/subresource_filter/included_script_in_iframe.html.mock-http-headers +//components/test/data/subresource_filter/page_with_websocket.html +//components/test/data/subresource_filter/popup.html +//components/test/data/subresource_filter/popup_disallowed_load_helper.html +//components/test/data/subresource_filter/websocket_connection.js +//components/test/data/subresource_filter/websocket_worker.js +//components/test/data/subresource_filter/window_open.html +//components/test/data/subresource_filter/window_open_spoof_click.html +//components/test/data/subresource_filter/window_stop_loads_disallowed_resource.html +//components/test/data/subresource_filter/worker_fetch.html +//components/test/data/subresource_filter/worker_fetch.js +//components/test/data/subresource_filter/worker_fetch_data.txt +//components/test/data/subresource_filter/worklet_script_fetch.html +//components/test/data/subresource_filter/worklet_script_fetch.js
diff --git a/components/test/data/subresource_filter/unit_tests_bundle_data.globlist b/components/test/data/subresource_filter/unit_tests_bundle_data.globlist new file mode 100644 index 0000000..8e54b2f --- /dev/null +++ b/components/test/data/subresource_filter/unit_tests_bundle_data.globlist
@@ -0,0 +1,11 @@ +# Copyright 2023 The Chromium Authors +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +# +# See build/ios/update_bundle_filelist.py for details on how .globlist +# files are used to update their .filelist counterparts. + +//components/test/data/subresource_filter/** +-//components/test/data/subresource_filter/*.filelist +-//components/test/data/subresource_filter/*.globlist +-//components/test/data/subresource_filter/OWNERS
diff --git a/components/viz/service/display_embedder/software_output_device_mac.h b/components/viz/service/display_embedder/software_output_device_mac.h index 3fa9113..67d5ff6 100644 --- a/components/viz/service/display_embedder/software_output_device_mac.h +++ b/components/viz/service/display_embedder/software_output_device_mac.h
@@ -52,7 +52,7 @@ struct Buffer { Buffer(); ~Buffer(); - base::ScopedCFTypeRef<IOSurfaceRef> io_surface; + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface; // The damage of all BeginPaints since this buffer was the back buffer. SkRegion accumulated_damage; };
diff --git a/components/wifi/wifi_service_mac.mm b/components/wifi/wifi_service_mac.mm index 9d281c07..110f5e6 100644 --- a/components/wifi/wifi_service_mac.mm +++ b/components/wifi/wifi_service_mac.mm
@@ -443,7 +443,7 @@ local_wifi_address.sin_len = sizeof(local_wifi_address); local_wifi_address.sin_family = AF_INET; local_wifi_address.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); - base::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability( + base::apple::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability( SCNetworkReachabilityCreateWithAddress( kCFAllocatorDefault, reinterpret_cast<const struct sockaddr*>(&local_wifi_address)));
diff --git a/content/app_shim_remote_cocoa/web_drag_source_mac.mm b/content/app_shim_remote_cocoa/web_drag_source_mac.mm index cc4dcec..57a97e5 100644 --- a/content/app_shim_remote_cocoa/web_drag_source_mac.mm +++ b/content/app_shim_remote_cocoa/web_drag_source_mac.mm
@@ -137,7 +137,7 @@ [UTType typeWithMIMEType:base::SysUTF8ToNSString(mimeType)]; _fileUTType = type.identifier; } else { - base::ScopedCFTypeRef<CFStringRef> mimeTypeCF( + base::apple::ScopedCFTypeRef<CFStringRef> mimeTypeCF( base::SysUTF8ToCFStringRef(mimeType)); _fileUTType = base::apple::CFToNSOwnershipCast( UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType,
diff --git a/content/browser/browser_context_impl.cc b/content/browser/browser_context_impl.cc index 3b215303..4dda379 100644 --- a/content/browser/browser_context_impl.cc +++ b/content/browser/browser_context_impl.cc
@@ -41,7 +41,7 @@ ServiceWorkerContextWrapper* wrapper = static_cast<ServiceWorkerContextWrapper*>( partition->GetServiceWorkerContext()); - wrapper->Shutdown(); + wrapper->process_manager()->Shutdown(); } void ShutdownSharedWorkerContext(StoragePartition* partition) {
diff --git a/content/browser/font_access/font_enumeration_data_source_mac.h b/content/browser/font_access/font_enumeration_data_source_mac.h index e97b6c2..3937c56 100644 --- a/content/browser/font_access/font_enumeration_data_source_mac.h +++ b/content/browser/font_access/font_enumeration_data_source_mac.h
@@ -40,10 +40,10 @@ // Font attributes for a font. Set post-validation. Used only during // enumeration. - base::ScopedCFTypeRef<CFStringRef> cf_postscript_name_; - base::ScopedCFTypeRef<CFStringRef> cf_full_name_; - base::ScopedCFTypeRef<CFStringRef> cf_family_; - base::ScopedCFTypeRef<CFStringRef> cf_style_; + base::apple::ScopedCFTypeRef<CFStringRef> cf_postscript_name_; + base::apple::ScopedCFTypeRef<CFStringRef> cf_full_name_; + base::apple::ScopedCFTypeRef<CFStringRef> cf_family_; + base::apple::ScopedCFTypeRef<CFStringRef> cf_style_; }; } // namespace content
diff --git a/content/browser/font_access/font_enumeration_data_source_mac.mm b/content/browser/font_access/font_enumeration_data_source_mac.mm index a1c766df..12ad58e 100644 --- a/content/browser/font_access/font_enumeration_data_source_mac.mm +++ b/content/browser/font_access/font_enumeration_data_source_mac.mm
@@ -20,17 +20,19 @@ namespace { -base::ScopedCFTypeRef<CFStringRef> GetLocalizedString(CTFontDescriptorRef fd, - CFStringRef attribute) { - return base::ScopedCFTypeRef<CFStringRef>( +base::apple::ScopedCFTypeRef<CFStringRef> GetLocalizedString( + CTFontDescriptorRef fd, + CFStringRef attribute) { + return base::apple::ScopedCFTypeRef<CFStringRef>( base::apple::CFCast<CFStringRef>(CTFontDescriptorCopyLocalizedAttribute( fd, attribute, /*language=*/nullptr))); } -base::ScopedCFTypeRef<CFStringRef> GetString(CTFontDescriptorRef fd, - CFStringRef attribute) { - return base::ScopedCFTypeRef<CFStringRef>(base::apple::CFCast<CFStringRef>( - CTFontDescriptorCopyAttribute(fd, attribute))); +base::apple::ScopedCFTypeRef<CFStringRef> GetString(CTFontDescriptorRef fd, + CFStringRef attribute) { + return base::apple::ScopedCFTypeRef<CFStringRef>( + base::apple::CFCast<CFStringRef>( + CTFontDescriptorCopyAttribute(fd, attribute))); } } // namespace @@ -45,13 +47,13 @@ bool FontEnumerationDataSourceMac::IsValidFontMac( const CTFontDescriptorRef& fd) { - base::ScopedCFTypeRef<CFStringRef> cf_postscript_name = + base::apple::ScopedCFTypeRef<CFStringRef> cf_postscript_name = GetString(fd, kCTFontNameAttribute); - base::ScopedCFTypeRef<CFStringRef> cf_full_name = + base::apple::ScopedCFTypeRef<CFStringRef> cf_full_name = GetLocalizedString(fd, kCTFontDisplayNameAttribute); - base::ScopedCFTypeRef<CFStringRef> cf_family = + base::apple::ScopedCFTypeRef<CFStringRef> cf_family = GetString(fd, kCTFontFamilyNameAttribute); - base::ScopedCFTypeRef<CFStringRef> cf_style = + base::apple::ScopedCFTypeRef<CFStringRef> cf_style = GetString(fd, kCTFontStyleNameAttribute); if (!cf_postscript_name || !cf_full_name || !cf_family || !cf_style) { @@ -77,11 +79,11 @@ base::apple::CFToNSPtrCast(kCTFontCollectionRemoveDuplicatesOption) : @YES }; - base::ScopedCFTypeRef<CTFontCollectionRef> collection( + base::apple::ScopedCFTypeRef<CTFontCollectionRef> collection( CTFontCollectionCreateFromAvailableFonts( base::apple::NSToCFPtrCast(options))); - base::ScopedCFTypeRef<CFArrayRef> font_descs( + base::apple::ScopedCFTypeRef<CFArrayRef> font_descs( CTFontCollectionCreateMatchingFontDescriptors(collection)); // Used to filter duplicates.
diff --git a/content/browser/hid/hid_test_utils.cc b/content/browser/hid/hid_test_utils.cc index 052ad1f..5a43f5d 100644 --- a/content/browser/hid/hid_test_utils.cc +++ b/content/browser/hid/hid_test_utils.cc
@@ -26,17 +26,11 @@ void MockHidDelegate::AddObserver(BrowserContext* browser_context, Observer* observer) { - if (assert_browser_context_) { - ASSERT_TRUE(browser_context); - } observer_list_.AddObserver(observer); } void MockHidDelegate::RemoveObserver(BrowserContext* browser_context, Observer* observer) { - if (assert_browser_context_) { - ASSERT_TRUE(browser_context); - } observer_list_.RemoveObserver(observer); } @@ -69,10 +63,6 @@ } } -void MockHidDelegate::SetAssertBrowserContext(bool assert_browser_context) { - assert_browser_context_ = assert_browser_context; -} - HidTestContentBrowserClient::HidTestContentBrowserClient() = default; HidTestContentBrowserClient::~HidTestContentBrowserClient() = default;
diff --git a/content/browser/hid/hid_test_utils.h b/content/browser/hid/hid_test_utils.h index b361ab0..9aeff38 100644 --- a/content/browser/hid/hid_test_utils.h +++ b/content/browser/hid/hid_test_utils.h
@@ -81,11 +81,8 @@ const base::ObserverList<Observer>& observer_list() { return observer_list_; } - void SetAssertBrowserContext(bool assert_browser_context); - private: base::ObserverList<Observer> observer_list_; - bool assert_browser_context_ = false; }; // Test implementation of ContentBrowserClient for HID tests. The test client
diff --git a/content/browser/media/capture/desktop_capture_device_mac.cc b/content/browser/media/capture/desktop_capture_device_mac.cc index 3a942b7..2fd521c9 100644 --- a/content/browser/media/capture/desktop_capture_device_mac.cc +++ b/content/browser/media/capture/desktop_capture_device_mac.cc
@@ -51,7 +51,7 @@ }; // Retrieve the source display's size. - base::ScopedCFTypeRef<CGDisplayModeRef> mode( + base::apple::ScopedCFTypeRef<CGDisplayModeRef> mode( CGDisplayCopyDisplayMode(display_id_)); const gfx::Size source_size = mode ? gfx::Size(CGDisplayModeGetWidth(mode), CGDisplayModeGetHeight(mode)) @@ -62,14 +62,14 @@ ComputeFrameSizeAndDestRect(source_size, requested_format_.frame_size, dest_rect_in_frame); - base::ScopedCFTypeRef<CFDictionaryRef> properties; + base::apple::ScopedCFTypeRef<CFDictionaryRef> properties; { float max_frame_time = 1.f / requested_format_.frame_rate; - base::ScopedCFTypeRef<CFNumberRef> cf_max_frame_time( + base::apple::ScopedCFTypeRef<CFNumberRef> cf_max_frame_time( CFNumberCreate(nullptr, kCFNumberFloat32Type, &max_frame_time)); - base::ScopedCFTypeRef<CGColorSpaceRef> cg_color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> cg_color_space( CGColorSpaceCreateWithName(kCGColorSpaceSRGB)); - base::ScopedCFTypeRef<CFDictionaryRef> dest_rect_in_frame_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> dest_rect_in_frame_dict( CGRectCreateDictionaryRepresentation(dest_rect_in_frame.ToCGRect())); const size_t kNumKeys = 5; @@ -138,7 +138,7 @@ const CGDirectDisplayID display_id_; const scoped_refptr<base::SingleThreadTaskRunner> device_task_runner_; - base::ScopedCFTypeRef<CGDisplayStreamRef> display_stream_; + base::apple::ScopedCFTypeRef<CGDisplayStreamRef> display_stream_; media::VideoCaptureFormat requested_format_; base::WeakPtrFactory<DesktopCaptureDeviceMac> weak_factory_; };
diff --git a/content/browser/renderer_host/cursor_manager.cc b/content/browser/renderer_host/cursor_manager.cc index e783e00..8a47b36 100644 --- a/content/browser/renderer_host/cursor_manager.cc +++ b/content/browser/renderer_host/cursor_manager.cc
@@ -4,9 +4,16 @@ #include "content/browser/renderer_host/cursor_manager.h" +#include <algorithm> +#include <string> +#include <vector> + +#include "base/check.h" +#include "base/ranges/algorithm.h" #include "content/browser/renderer_host/render_widget_host_view_base.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" +#include "ui/gfx/geometry/skia_conversions.h" namespace content { @@ -50,25 +57,21 @@ return view == view_under_cursor_; } -base::ScopedClosureRunner CursorManager::CreateDisallowCustomCursorScope() { - bool should_update_cursor = false; +base::ScopedClosureRunner CursorManager::CreateDisallowCustomCursorScope( + int max_dimension_dips) { + const ui::Cursor& target_cursor = cursor_map_[view_under_cursor_]; + const bool cursor_allowed_before = IsCursorAllowed(target_cursor); + dimension_restrictions_.push_back(max_dimension_dips); - // If custom cursors are about to be disallowed and the current view uses a - // custom cursor, the cursor needs to be updated to replace the custom cursor. - if (AreCustomCursorsAllowed() && cursor_map_[view_under_cursor_].type() == - ui::mojom::CursorType::kCustom) { - should_update_cursor = true; - } - - ++disallow_custom_cursor_scope_count_; - - if (should_update_cursor) { + // If the new restriction eliminates the cursor under the current view, update + // it. + if (cursor_allowed_before && !IsCursorAllowed(target_cursor)) { UpdateCursor(); } return base::ScopedClosureRunner( base::BindOnce(&CursorManager::DisallowCustomCursorScopeExpired, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr(), max_dimension_dips)); } bool CursorManager::GetCursorForTesting(RenderWidgetHostViewBase* view, @@ -81,17 +84,30 @@ return true; } -bool CursorManager::AreCustomCursorsAllowed() const { - return disallow_custom_cursor_scope_count_ == 0; +bool CursorManager::IsCursorAllowed(const ui::Cursor& cursor) const { + if (cursor.type() != ui::mojom::CursorType::kCustom || + dimension_restrictions_.empty()) { + return true; + } + + const int max_dimension_dips = base::ranges::min(dimension_restrictions_); + const gfx::Size size_in_dip = gfx::ScaleToCeiledSize( + gfx::SkISizeToSize(cursor.custom_bitmap().dimensions()), + 1 / cursor.image_scale_factor()); + + return std::max(size_in_dip.width(), size_in_dip.height()) < + max_dimension_dips; } -void CursorManager::DisallowCustomCursorScopeExpired() { - --disallow_custom_cursor_scope_count_; +void CursorManager::DisallowCustomCursorScopeExpired(int max_dimension_dips) { + const ui::Cursor& target_cursor = cursor_map_[view_under_cursor_]; + const bool cursor_allowed_before = IsCursorAllowed(target_cursor); - // If custom cursors started being allowed and the current view has a custom - // cursor, update the cursor to ensure the custom cursor is now displayed. - if (AreCustomCursorsAllowed() && cursor_map_[view_under_cursor_].type() == - ui::mojom::CursorType::kCustom) { + auto it = base::ranges::find(dimension_restrictions_, max_dimension_dips); + CHECK(it != dimension_restrictions_.end()); + dimension_restrictions_.erase(it); + + if (!cursor_allowed_before && IsCursorAllowed((target_cursor))) { UpdateCursor(); } } @@ -100,9 +116,7 @@ ui::Cursor cursor(ui::mojom::CursorType::kPointer); auto it = cursor_map_.find(view_under_cursor_); - if (it != cursor_map_.end() && - (AreCustomCursorsAllowed() || - it->second.type() != ui::mojom::CursorType::kCustom)) { + if (it != cursor_map_.end() && IsCursorAllowed(it->second)) { cursor = it->second; }
diff --git a/content/browser/renderer_host/cursor_manager.h b/content/browser/renderer_host/cursor_manager.h index 4c23db4..31ea279 100644 --- a/content/browser/renderer_host/cursor_manager.h +++ b/content/browser/renderer_host/cursor_manager.h
@@ -6,6 +6,7 @@ #define CONTENT_BROWSER_RENDERER_HOST_CURSOR_MANAGER_H_ #include <map> +#include <vector> #include "base/functional/callback_helpers.h" #include "base/memory/raw_ptr.h" @@ -45,7 +46,10 @@ // cursor. This is only used for cursor triggered tooltips. bool IsViewUnderCursor(RenderWidgetHostViewBase*) const; - [[nodiscard]] base::ScopedClosureRunner CreateDisallowCustomCursorScope(); + // Disallows custom cursors whose height or width are larger or equal to + // `max_dimension` DIPs. + [[nodiscard]] base::ScopedClosureRunner CreateDisallowCustomCursorScope( + int max_dimension_dips); // Accessor for browser tests, enabling verification of the cursor_map_. // Returns false if the provided View is not in the map, and outputs @@ -57,8 +61,8 @@ } private: - bool AreCustomCursorsAllowed() const; - void DisallowCustomCursorScopeExpired(); + bool IsCursorAllowed(const ui::Cursor&) const; + void DisallowCustomCursorScopeExpired(int max_dimension_dips); void UpdateCursor(); // Stores the last received cursor from each RenderWidgetHostView. @@ -71,9 +75,12 @@ // The root view is the target for DisplayCursor calls whenever the active // cursor needs to change. - raw_ptr<RenderWidgetHostViewBase> root_view_; + const raw_ptr<RenderWidgetHostViewBase> root_view_; - int disallow_custom_cursor_scope_count_ = 0; + // Restrictions on the maximum dimension (either width or height) imposed + // on custom cursors. + // Restrictions can be created by `CreateDisallowCustomCursorScope`. + std::vector<int> dimension_restrictions_; ui::mojom::CursorType last_set_cursor_type_for_testing_;
diff --git a/content/browser/renderer_host/cursor_manager_unittest.cc b/content/browser/renderer_host/cursor_manager_unittest.cc index 29accba..e437825 100644 --- a/content/browser/renderer_host/cursor_manager_unittest.cc +++ b/content/browser/renderer_host/cursor_manager_unittest.cc
@@ -3,7 +3,9 @@ // found in the LICENSE file. #include "content/browser/renderer_host/cursor_manager.h" + #include <memory> +#include <utility> #include "base/memory/raw_ptr.h" #include "build/build_config.h" @@ -16,8 +18,10 @@ #include "content/test/mock_render_widget_host_delegate.h" #include "content/test/test_render_view_host.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" +#include "ui/gfx/geometry/point.h" // CursorManager is only instantiated on Aura and Mac. #if defined(USE_AURA) || BUILDFLAG(IS_MAC) @@ -29,7 +33,17 @@ const ui::Cursor kCursorHand(ui::mojom::CursorType::kHand); const ui::Cursor kCursorCross(ui::mojom::CursorType::kCross); const ui::Cursor kCursorPointer(ui::mojom::CursorType::kPointer); -const ui::Cursor kCursorCustom(ui::mojom::CursorType::kCustom); + +ui::Cursor CreateCustomCursor(int width, int height) { + SkBitmap bitmap; + bitmap.allocN32Pixels(width, height); + bitmap.eraseColor(SK_ColorRED); + + return ui::Cursor::NewCustom(std::move(bitmap), /*hotspot=*/gfx::Point(0, 0), + /*image_scale_factor=*/1.0f); +} + +const ui::Cursor kCursorCustom = CreateCustomCursor(0, 0); class MockRenderWidgetHostViewForCursors : public TestRenderWidgetHostView { public: @@ -190,7 +204,8 @@ { auto disallow_scope = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorPointer); } @@ -198,13 +213,75 @@ } TEST_F(CursorManagerTest, + CustomCursorDisallowedScope_CustomCursorsAreNotAllowedAboveSizeLimit) { + const ui::Cursor kCursorCustomLarge = CreateCustomCursor(20, 50); + + top_view_->GetCursorManager()->UpdateCursor(top_view_, kCursorCustomLarge); + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); + + { + auto disallow_scope = + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/40); + EXPECT_EQ(top_view_->cursor(), kCursorPointer); + } + + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); +} + +TEST_F(CursorManagerTest, + CustomCursorDisallowedScope_CustomCursorsAreAllowedBelowSizeLimit) { + const ui::Cursor kCursorCustomLarge = CreateCustomCursor(20, 35); + + top_view_->GetCursorManager()->UpdateCursor(top_view_, kCursorCustomLarge); + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); + + { + auto disallow_scope = + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/40); + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); + } + + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); +} + +TEST_F(CursorManagerTest, + CustomCursorDisallowedScope_CustomCursorSubjectToMultipleSizeLimits) { + const ui::Cursor kCursorCustomLarge = CreateCustomCursor(20, 35); + + top_view_->GetCursorManager()->UpdateCursor(top_view_, kCursorCustomLarge); + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); + + { + auto disallow_scope1 = + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/40); + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); + + auto disallow_scope2 = + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/30); + EXPECT_EQ(top_view_->cursor(), kCursorPointer); + + // Running the first closure leaves the restriction from the second closure + // in place. + disallow_scope1.RunAndReset(); + EXPECT_EQ(top_view_->cursor(), kCursorPointer); + } + + EXPECT_EQ(top_view_->cursor(), kCursorCustomLarge); +} + +TEST_F(CursorManagerTest, CustomCursorDisallowedScope_OtherCursorsStillAllowed) { top_view_->GetCursorManager()->UpdateCursor(top_view_, kCursorHand); EXPECT_EQ(top_view_->cursor(), kCursorHand); { auto disallow_scope = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorHand); } @@ -218,7 +295,8 @@ { auto disallow_scope = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorHand); top_view_->GetCursorManager()->UpdateCursor(top_view_, kCursorCustom); @@ -235,7 +313,8 @@ { auto disallow_scope = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorPointer); top_view_->GetCursorManager()->UpdateCursor(top_view_, kCursorHand); @@ -250,16 +329,19 @@ EXPECT_EQ(top_view_->cursor(), kCursorCustom); auto disallow_scope1 = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); auto disallow_scope2 = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorPointer); disallow_scope1.RunAndReset(); EXPECT_EQ(top_view_->cursor(), kCursorPointer); auto disallow_scope3 = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); disallow_scope2.RunAndReset(); EXPECT_EQ(top_view_->cursor(), kCursorPointer); @@ -278,7 +360,8 @@ { auto disallow_scope = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorHand); top_view_->GetCursorManager()->UpdateViewUnderCursor(child_view.get()); @@ -301,7 +384,8 @@ { auto disallow_scope = - top_view_->GetCursorManager()->CreateDisallowCustomCursorScope(); + top_view_->GetCursorManager()->CreateDisallowCustomCursorScope( + /*max_dimension_dips=*/0); EXPECT_EQ(top_view_->cursor(), kCursorPointer); top_view_->GetCursorManager()->UpdateViewUnderCursor(top_view_);
diff --git a/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc b/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc index 41561b5..e184d4d 100644 --- a/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc +++ b/content/browser/renderer_host/input/touch_selection_controller_client_aura_browsertest.cc
@@ -51,11 +51,9 @@ namespace content { namespace { -#if BUILDFLAG(IS_CHROMEOS) // Character dimensions in px, from the font size in `touch_selection.html`. constexpr int kCharacterWidth = 15; constexpr int kCharacterHeight = 15; -#endif bool JSONToPoint(const std::string& str, gfx::PointF* point) { absl::optional<base::Value> value = base::JSONReader::Read(str); @@ -75,7 +73,7 @@ gfx::RectF ConvertRectFToChildCoords(RenderWidgetHostViewAura* parent, RenderWidgetHostViewChildFrame* child, - const gfx::RectF rect) { + const gfx::RectF& rect) { return gfx::BoundingRect( child->TransformRootPointToViewCoordSpace(rect.origin()), child->TransformRootPointToViewCoordSpace(rect.bottom_right())); @@ -269,25 +267,29 @@ content->GetHost()->SetBoundsInPixels(gfx::Rect(800, 600)); } - gfx::PointF GetPointInsideText() { + gfx::PointF GetPointInText(int cursor_index) const { gfx::PointF point; - JSONToPoint(EvalJs(shell(), "get_point_inside_text()").ExtractString(), + JSONToPoint(EvalJs(shell(), "get_top_left_of_text()").ExtractString(), &point); + point.Offset(cursor_index * kCharacterWidth, 0.5f * kCharacterHeight); return point; } - gfx::PointF GetPointInsideTextfield() { + gfx::PointF GetPointInTextfield(int cursor_index) const { gfx::PointF point; - JSONToPoint(EvalJs(shell(), "get_point_inside_textfield()").ExtractString(), + JSONToPoint(EvalJs(shell(), "get_top_left_of_textfield()").ExtractString(), &point); + point.Offset(cursor_index * kCharacterWidth, 0.5f * kCharacterHeight); return point; } - gfx::PointF GetPointInsideEmptyTextfield() { + gfx::PointF GetPointInsideEmptyTextfield() const { gfx::PointF point; JSONToPoint( - EvalJs(shell(), "get_point_inside_empty_textfield()").ExtractString(), + EvalJs(shell(), "get_top_left_of_empty_textfield()").ExtractString(), &point); + // Offset the point so that it is within the textfield. + point.Offset(0.5f * kCharacterWidth, 0.5f * kCharacterHeight); return point; } @@ -418,7 +420,7 @@ selection_controller_client()->InitWaitForSelectionEvent( ui::SELECTION_HANDLES_SHOWN); - gfx::PointF point = GetPointInsideText(); + gfx::PointF point = GetPointInText(2); ui::GestureEventDetails long_press_details(ui::ET_GESTURE_LONG_PRESS); long_press_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent long_press(point.x(), point.y(), 0, ui::EventTimeForNow(), @@ -630,9 +632,10 @@ // Find the location of some text to select. gfx::PointF point_f; - JSONToPoint(EvalJs(child->current_frame_host(), "get_point_inside_text()") + JSONToPoint(EvalJs(child->current_frame_host(), "get_top_left_of_text()") .ExtractString(), &point_f); + point_f.Offset(2.0 * kCharacterWidth, 0.5f * kCharacterHeight); point_f = child_view->TransformPointToRootCoordSpaceF(point_f); // Initiate selection with a sequence of events that go through the targeting @@ -758,9 +761,10 @@ // Find the location of some text to select. gfx::PointF point_f; - JSONToPoint(EvalJs(child->current_frame_host(), "get_point_inside_text()") + JSONToPoint(EvalJs(child->current_frame_host(), "get_top_left_of_text()") .ExtractString(), &point_f); + point_f.Offset(2.0 * kCharacterWidth, 0.5f * kCharacterHeight); point_f = child_view->TransformPointToRootCoordSpaceF(point_f); // Initiate selection with a sequence of events that go through the targeting @@ -934,9 +938,10 @@ // Find the location of some text in the child view to select. gfx::PointF point_in_text; - JSONToPoint(EvalJs(child->current_frame_host(), "get_point_inside_text()") + JSONToPoint(EvalJs(child->current_frame_host(), "get_top_left_of_text()") .ExtractString(), &point_in_text); + point_in_text.Offset(2.0 * kCharacterWidth, 0.5f * kCharacterHeight); point_in_text = child_view->TransformPointToRootCoordSpaceF(point_in_text); // Long press to show selection handles. @@ -1004,7 +1009,7 @@ selection_controller_client()->InitWaitForSelectionEvent( ui::INSERTION_HANDLE_SHOWN); - gfx::Point point = gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point); generator.GestureTapAt(point); @@ -1043,7 +1048,7 @@ ui::test::EventGenerator generator(native_view->GetRootWindow()); // Long pressing on readable text should select the closest word. - gfx::Point point_in_readable_text = gfx::ToRoundedPoint(GetPointInsideText()); + gfx::Point point_in_readable_text = gfx::ToRoundedPoint(GetPointInText(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point_in_readable_text); SelectWithLongPress(generator, point_in_readable_text); @@ -1080,8 +1085,7 @@ ui::test::EventGenerator generator(native_view->GetRootWindow()); // Long pressing on editable text should select the closest word. - gfx::Point point_in_textfield = - gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point_in_textfield = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point_in_textfield); SelectWithLongPress(generator, point_in_textfield); @@ -1118,8 +1122,7 @@ ui::test::EventGenerator generator(native_view->GetRootWindow()); // Double pressing on editable text should select the closest word. - gfx::Point point_in_textfield = - gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point_in_textfield = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point_in_textfield); SelectWithDoublePress(generator, point_in_textfield); @@ -1156,8 +1159,7 @@ ui::test::EventGenerator generator(native_view->GetRootWindow()); // Double press in editable text to select the closest word. - gfx::Point point_in_textfield = - gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point_in_textfield = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point_in_textfield); SelectWithDoublePress(generator, point_in_textfield); @@ -1211,8 +1213,7 @@ ui::test::EventGenerator generator(native_view->GetRootWindow()); // Double press in textfield then start touch selection dragging. - gfx::Point point_in_textfield = - gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point_in_textfield = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point_in_textfield); SelectWithDoublePress(generator, point_in_textfield); @@ -1248,7 +1249,7 @@ // Mouse click inside the textfield to make a caret appear. selection_controller_client()->InitWaitForSelectionUpdate(); - gfx::Point point = gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point); generator.MoveMouseTo(point); generator.PressLeftButton(); @@ -1297,7 +1298,7 @@ // Tap inside the textfield to place a caret and show an insertion handle. selection_controller_client()->InitWaitForSelectionEvent( ui::INSERTION_HANDLE_SHOWN); - gfx::Point caret_location = gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point caret_location = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &caret_location); generator.GestureTapAt(caret_location); selection_controller_client()->Wait(); @@ -1350,8 +1351,7 @@ RenderWidgetHostViewAura* rwhva = GetRenderWidgetHostViewAura(); gfx::NativeView native_view = rwhva->GetNativeView(); ui::test::EventGenerator generator(native_view->GetRootWindow()); - gfx::Point point_in_textfield = - gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point_in_textfield = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point_in_textfield); @@ -1400,7 +1400,7 @@ selection_controller_client()->InitWaitForSelectionEvent( ui::SELECTION_HANDLES_SHOWN); - gfx::PointF point = GetPointInsideText(); + gfx::PointF point = GetPointInText(2); ui::GestureEventDetails long_press_details(ui::ET_GESTURE_LONG_PRESS); long_press_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent long_press(point.x(), point.y(), 0, ui::EventTimeForNow(), @@ -1466,7 +1466,7 @@ selection_controller_client()->InitWaitForSelectionEvent( ui::SELECTION_HANDLES_SHOWN); - gfx::PointF point = GetPointInsideText(); + gfx::PointF point = GetPointInText(2); ui::GestureEventDetails long_press_details(ui::ET_GESTURE_LONG_PRESS); long_press_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent long_press(point.x(), point.y(), 0, ui::EventTimeForNow(), @@ -1546,7 +1546,7 @@ // Tap to focus the textfield. selection_controller_client()->InitWaitForSelectionEvent( ui::INSERTION_HANDLE_SHOWN); - gfx::Point start = gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point start = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &start); generator.GestureTapAt(start); selection_controller_client()->Wait(); @@ -1595,7 +1595,7 @@ // Tap inside the textfield and wait for the insertion handle to appear. selection_controller_client()->InitWaitForSelectionEvent( ui::INSERTION_HANDLE_SHOWN); - gfx::Point point = gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point); generator.GestureTapAt(point); selection_controller_client()->Wait(); @@ -1651,7 +1651,7 @@ // Tap inside the textfield and wait for the insertion handle to appear. selection_controller_client()->InitWaitForSelectionEvent( ui::INSERTION_HANDLE_SHOWN); - gfx::Point point = gfx::ToRoundedPoint(GetPointInsideTextfield()); + gfx::Point point = gfx::ToRoundedPoint(GetPointInTextfield(2)); generator.delegate()->ConvertPointFromTarget(native_view, &point); generator.GestureTapAt(point); selection_controller_client()->Wait(); @@ -1758,7 +1758,7 @@ // Long-press on the text and wait for handles to appear. selection_controller_client()->InitWaitForSelectionEvent( ui::SELECTION_HANDLES_SHOWN); - gfx::PointF point = GetPointInsideText(); + gfx::PointF point = GetPointInText(2); ui::GestureEventDetails long_press_details(ui::ET_GESTURE_LONG_PRESS); long_press_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHSCREEN); ui::GestureEvent long_press(point.x(), point.y(), 0, ui::EventTimeForNow(), @@ -1859,7 +1859,7 @@ selection_controller_client()->InitWaitForSelectionEvent( ui::INSERTION_HANDLE_SHOWN); - gfx::PointF point = GetPointInsideTextfield(); + gfx::PointF point = GetPointInTextfield(2); ui::GestureEventDetails gesture_tap_down_details(ui::ET_GESTURE_TAP_DOWN); gesture_tap_down_details.set_device_type(
diff --git a/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm b/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm index 8aefff3..d34ecd97 100644 --- a/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm +++ b/content/browser/renderer_host/input/web_input_event_builders_mac_unittest.mm
@@ -89,7 +89,7 @@ float tilt_y = 0.0, float tangential_pressure = 0.0, NSUInteger button_number = 0) { - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateMouseEvent( + base::apple::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateMouseEvent( /*source=*/nullptr, mouse_type, location, button)); CGEventSetIntegerValueField(cg_event, kCGMouseEventSubtype, subtype); CGEventSetDoubleValueField(cg_event, kCGTabletEventRotation, rotation);
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.h b/content/browser/renderer_host/render_widget_host_view_mac.h index cc5e026..3edad19 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.h +++ b/content/browser/renderer_host/render_widget_host_view_mac.h
@@ -14,6 +14,7 @@ #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" +#include "base/timer/timer.h" #include "components/viz/common/surfaces/surface_id.h" #include "content/app_shim_remote_cocoa/render_widget_host_ns_view_host_helper.h" #include "content/browser/renderer_host/browser_compositor_view_mac.h" @@ -553,6 +554,8 @@ // OnTooltipTextUpdated() function, if not null. void SetTooltipText(const std::u16string& tooltip_text); + void UpdateWindowsNow(); + // Interface through which the NSView is to be manipulated. This points either // to |in_process_ns_view_bridge_| or to |remote_ns_view_|. raw_ptr<remote_cocoa::mojom::RenderWidgetHostNSView> ns_view_ = nullptr; @@ -697,6 +700,10 @@ const uint64_t ns_view_id_; + // See description of `kDelayUpdateWindowsAfterTextInputStateChanged` for + // details. + base::OneShotTimer update_windows_timer_; + // Factory used to safely scope delayed calls to ShutdownHost(). base::WeakPtrFactory<RenderWidgetHostViewMac> weak_factory_; };
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm index 8883b30..f57fb45 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -87,6 +87,18 @@ namespace content { +namespace { + +// If enabled, when the text input state changes `[NSApp updateWindows]` is +// called after a delay. This is done as `updateWindows` can be quite +// costly, and if the text input state is changing rapidly there is no need to +// update it immediately. +BASE_FEATURE(kDelayUpdateWindowsAfterTextInputStateChanged, + "DelayUpdateWindowsAfterTextInputStateChanged", + base::FEATURE_DISABLED_BY_DEFAULT); + +} // namespace + //////////////////////////////////////////////////////////////////////////////// // BrowserCompositorMacClient, public: @@ -681,7 +693,13 @@ // Let AppKit cache the new input context to make IMEs happy. // See http://crbug.com/73039. - [NSApp updateWindows]; + if (base::FeatureList::IsEnabled( + kDelayUpdateWindowsAfterTextInputStateChanged)) { + update_windows_timer_.Start(FROM_HERE, base::Milliseconds(100), this, + &RenderWidgetHostViewMac::UpdateWindowsNow); + } else { + [NSApp updateWindows]; + } } } @@ -1642,6 +1660,7 @@ } else { password_input_enabler_.reset(); } + update_windows_timer_.Stop(); } MouseWheelPhaseHandler* RenderWidgetHostViewMac::GetMouseWheelPhaseHandler() { @@ -2378,6 +2397,10 @@ tooltip_observer_for_testing_->OnTooltipTextUpdated(tooltip_text); } +void RenderWidgetHostViewMac::UpdateWindowsNow() { + [NSApp updateWindows]; +} + Class GetRenderWidgetHostViewCocoaClassForTesting() { return [RenderWidgetHostViewCocoa class]; }
diff --git a/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm b/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm index 2f42c1e6..2ef6869 100644 --- a/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm +++ b/content/browser/renderer_host/render_widget_host_view_mac_unittest.mm
@@ -240,7 +240,8 @@ NSEvent* MockTabletEventWithParams(CGEventType type, bool is_entering_proximity, NSPointingDeviceType device_type) { - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreate(/*source=*/nullptr)); + base::apple::ScopedCFTypeRef<CGEventRef> cg_event( + CGEventCreate(/*source=*/nullptr)); CGEventSetType(cg_event, type); CGEventSetIntegerValueField(cg_event, kCGTabletProximityEventEnterProximity, is_entering_proximity); @@ -260,7 +261,7 @@ // an NSEvent, below, flips the location back to bottom left origin. CGPoint cg_location = CGPointMake(location.x, NSHeight(NSScreen.screens[0].frame) - location.y); - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateMouseEvent( + base::apple::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateMouseEvent( /*source=*/nullptr, mouse_type, cg_location, button)); CGEventSetIntegerValueField(cg_event, kCGMouseEventSubtype, subtype); CGEventSetIntegerValueField(cg_event, kCGTabletProximityEventEnterProximity, @@ -436,8 +437,9 @@ // should correspond to a method in |MockPhaseMethods| that returns the desired // phase. NSEvent* MockScrollWheelEventWithPhase(SEL mockPhaseSelector, int32_t delta) { - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateScrollWheelEvent( - /*source=*/nullptr, kCGScrollEventUnitLine, 1, delta, 0)); + base::apple::ScopedCFTypeRef<CGEventRef> cg_event( + CGEventCreateScrollWheelEvent( + /*source=*/nullptr, kCGScrollEventUnitLine, 1, delta, 0)); CGEventTimestamp timestamp = 0; CGEventSetTimestamp(cg_event, timestamp); NSEvent* event = [NSEvent eventWithCGEvent:cg_event]; @@ -452,8 +454,9 @@ // Create a fake event with phaseNone. This is for resetting the phase info // of CGEventRef. MockScrollWheelEventWithPhase(@selector(phaseNone), 0); - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateScrollWheelEvent( - /*source=*/nullptr, kCGScrollEventUnitLine, 1, delta, 0)); + base::apple::ScopedCFTypeRef<CGEventRef> cg_event( + CGEventCreateScrollWheelEvent( + /*source=*/nullptr, kCGScrollEventUnitLine, 1, delta, 0)); CGEventTimestamp timestamp = 0; CGEventSetTimestamp(cg_event, timestamp); NSEvent* event = [NSEvent eventWithCGEvent:cg_event];
diff --git a/content/browser/service_worker/embedded_worker_instance.cc b/content/browser/service_worker/embedded_worker_instance.cc index 79fef11..2f1dd8fe 100644 --- a/content/browser/service_worker/embedded_worker_instance.cc +++ b/content/browser/service_worker/embedded_worker_instance.cc
@@ -406,7 +406,7 @@ GetContentClient() ->browser() ->UpdateEnabledBlinkRuntimeFeaturesInIsolatedWorker( - context_->wrapper()->browser_context(), params->script_url, + process_manager->browser_context(), params->script_url, params->forced_enabled_runtime_features); } CHECK(params->forced_enabled_runtime_features.empty() || @@ -414,11 +414,10 @@ // TODO(crbug.com/862854): Support changes to blink::RendererPreferences while // the worker is running. - DCHECK(context_->wrapper()->browser_context() || - process_manager->IsShutdown()); + DCHECK(process_manager->browser_context() || process_manager->IsShutdown()); params->renderer_preferences = blink::RendererPreferences(); GetContentClient()->browser()->UpdateRendererPreferencesForWorker( - context_->wrapper()->browser_context(), ¶ms->renderer_preferences); + process_manager->browser_context(), ¶ms->renderer_preferences); { // Create a RendererPreferenceWatcher to observe updates in the preferences. @@ -426,7 +425,7 @@ params->preference_watcher_receiver = watcher_remote.InitWithNewPipeAndPassReceiver(); GetContentClient()->browser()->RegisterRendererPreferenceWatcher( - context_->wrapper()->browser_context(), std::move(watcher_remote)); + process_manager->browser_context(), std::move(watcher_remote)); } // If we allocated a process, WorkerProcessHandle has to be created before
diff --git a/content/browser/service_worker/service_worker_context_wrapper.cc b/content/browser/service_worker/service_worker_context_wrapper.cc index be2681f9a..0d1a5e08 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.cc +++ b/content/browser/service_worker/service_worker_context_wrapper.cc
@@ -244,8 +244,8 @@ BrowserContext* browser_context) : core_observer_list_( base::MakeRefCounted<ServiceWorkerContextObserverList>()), - browser_context_(browser_context), - process_manager_(std::make_unique<ServiceWorkerProcessManager>()) { + process_manager_( + std::make_unique<ServiceWorkerProcessManager>(browser_context)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Add this object as an observer of the wrapped |context_core_|. This lets us @@ -303,7 +303,6 @@ process_manager_->Shutdown(); storage_control_.reset(); context_core_.reset(); - browser_context_ = nullptr; } void ServiceWorkerContextWrapper::DeleteAndStartOver() { @@ -332,7 +331,7 @@ BrowserContext* ServiceWorkerContextWrapper::browser_context() { DCHECK_CURRENTLY_ON(BrowserThread::UI); - return browser_context_; + return process_manager()->browser_context(); } void ServiceWorkerContextWrapper::OnRegistrationCompleted(
diff --git a/content/browser/service_worker/service_worker_context_wrapper.h b/content/browser/service_worker/service_worker_context_wrapper.h index 7e0cda8..07a92c26 100644 --- a/content/browser/service_worker/service_worker_context_wrapper.h +++ b/content/browser/service_worker/service_worker_context_wrapper.h
@@ -522,10 +522,6 @@ base::ObserverList<ServiceWorkerContextObserver, true>::Unchecked observer_list_; - // `browser_context_` is maintained to be valid within the lifetime of the - // browser context. - raw_ptr<BrowserContext, DanglingUntriaged> browser_context_; - const std::unique_ptr<ServiceWorkerProcessManager> process_manager_; std::unique_ptr<ServiceWorkerContextCore> context_core_;
diff --git a/content/browser/service_worker/service_worker_hid_delegate_observer_unittest.cc b/content/browser/service_worker/service_worker_hid_delegate_observer_unittest.cc index 80b0c490..a0c5d969 100644 --- a/content/browser/service_worker/service_worker_hid_delegate_observer_unittest.cc +++ b/content/browser/service_worker/service_worker_hid_delegate_observer_unittest.cc
@@ -164,7 +164,6 @@ void SetUp() override { ServiceWorkerDeviceDelegateObserverTest::SetUp(); - hid_delegate().SetAssertBrowserContext(true); ON_CALL(hid_delegate(), GetHidManager).WillByDefault(Return(&hid_manager_)); ON_CALL(hid_delegate(), IsFidoAllowedForOrigin) .WillByDefault(Return(false)); @@ -917,22 +916,4 @@ context()->hid_delegate_observer()->registration_id_map().empty()); } -// Shutdown the service worker context and make sure that -// ServiceWorkerHidDelegateObserver removes itself from the hid delegate -// properly. -TEST_F(ServiceWorkerHidDelegateObserverTest, ShutdownServiceWorkerContext) { - const GURL origin(kTestUrl); - auto registration = InstallServiceWorker(origin); - auto* version = registration->newest_installed_version(); - ASSERT_NE(version, nullptr); - StartServiceWorker(version); - CreateHidService(version); - EXPECT_TRUE(context()->hid_delegate_observer()->GetHidServiceForTesting( - registration->id())); - - EXPECT_FALSE(hid_delegate().observer_list().empty()); - helper()->ShutdownContext(); - EXPECT_TRUE(hid_delegate().observer_list().empty()); -} - } // namespace content
diff --git a/content/browser/service_worker/service_worker_new_script_fetcher.cc b/content/browser/service_worker/service_worker_new_script_fetcher.cc index 4d4f786..e65644a 100644 --- a/content/browser/service_worker/service_worker_new_script_fetcher.cc +++ b/content/browser/service_worker/service_worker_new_script_fetcher.cc
@@ -89,7 +89,8 @@ void ServiceWorkerNewScriptFetcher::StartScriptLoadingWithNewResourceID( int64_t resource_id) { - BrowserContext* browser_context = context_->wrapper()->browser_context(); + BrowserContext* browser_context = + context_->process_manager()->browser_context(); if (!browser_context) { std::move(callback_).Run(/*main_script_load_params=*/nullptr); return;
diff --git a/content/browser/service_worker/service_worker_process_manager.cc b/content/browser/service_worker/service_worker_process_manager.cc index de47c9fa..a33bb65f 100644 --- a/content/browser/service_worker/service_worker_process_manager.cc +++ b/content/browser/service_worker/service_worker_process_manager.cc
@@ -23,12 +23,15 @@ namespace content { -ServiceWorkerProcessManager::ServiceWorkerProcessManager() - : storage_partition_(nullptr), +ServiceWorkerProcessManager::ServiceWorkerProcessManager( + BrowserContext* browser_context) + : browser_context_(browser_context), + storage_partition_(nullptr), process_id_for_test_(ChildProcessHost::kInvalidUniqueID), new_process_id_for_test_(ChildProcessHost::kInvalidUniqueID), force_new_process_for_test_(false) { DCHECK_CURRENTLY_ON(BrowserThread::UI); + DCHECK(browser_context); weak_this_ = weak_this_factory_.GetWeakPtr(); } @@ -43,11 +46,22 @@ CHECK(worker_process_map_.empty()); } +BrowserContext* ServiceWorkerProcessManager::browser_context() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + // This is safe because reading |browser_context_| on the UI thread doesn't + // need locking (while modifying does). + return browser_context_; +} + void ServiceWorkerProcessManager::Shutdown() { DCHECK_CURRENTLY_ON(BrowserThread::UI); // `StoragePartitionImpl` might be destroyed before `this` is destroyed. Set // `storage_partition_` to nullptr to avoid holding a dangling ptr. storage_partition_ = nullptr; + { + base::AutoLock lock(browser_context_lock_); + browser_context_ = nullptr; + } // In single-process mode, Shutdown() is called when deleting the default // browser context, which is itself destroyed after the RenderProcessHost. @@ -63,11 +77,11 @@ } } worker_process_map_.clear(); - is_shutdown_ = true; } bool ServiceWorkerProcessManager::IsShutdown() { - return is_shutdown_; + base::AutoLock lock(browser_context_lock_); + return !browser_context_; } blink::ServiceWorkerStatusCode @@ -122,9 +136,9 @@ url::Origin::Create(script_url)) : WebExposedIsolationInfo::CreateNonIsolated())); scoped_refptr<SiteInstanceImpl> site_instance = - SiteInstanceImpl::CreateForServiceWorker( - storage_partition_->browser_context(), url_info, - can_use_existing_process, is_guest, is_fenced); + SiteInstanceImpl::CreateForServiceWorker(browser_context_, url_info, + can_use_existing_process, + is_guest, is_fenced); // Get the process from the SiteInstance. RenderProcessHost* rph = site_instance->GetProcess();
diff --git a/content/browser/service_worker/service_worker_process_manager.h b/content/browser/service_worker/service_worker_process_manager.h index 599492ab..7dd31ca 100644 --- a/content/browser/service_worker/service_worker_process_manager.h +++ b/content/browser/service_worker/service_worker_process_manager.h
@@ -13,6 +13,7 @@ #include "base/gtest_prod_util.h" #include "base/memory/raw_ptr.h" #include "base/memory/weak_ptr.h" +#include "base/synchronization/lock.h" #include "content/browser/service_worker/service_worker_metrics.h" #include "content/common/content_export.h" #include "services/network/public/mojom/cross_origin_embedder_policy.mojom-forward.h" @@ -24,6 +25,7 @@ namespace content { +class BrowserContext; class SiteInstance; class StoragePartitionImpl; @@ -44,12 +46,16 @@ ServiceWorkerMetrics::StartSituation start_situation; }; - // |*this| must be owned by a ServiceWorkerContextWrapper. - ServiceWorkerProcessManager(); + // |*this| must be owned by a ServiceWorkerContextWrapper in a + // StoragePartition within |browser_context|. + explicit ServiceWorkerProcessManager(BrowserContext* browser_context); // Shutdown must be called before the ProcessManager is destroyed. ~ServiceWorkerProcessManager(); + // Called on the UI thread. + BrowserContext* browser_context(); + // Synchronously prevents new processes from being allocated // and drops references to RenderProcessHosts. Called on the UI thread. void Shutdown(); @@ -116,6 +122,14 @@ private: friend class ServiceWorkerProcessManagerTest; + // Guarded by |browser_context_lock_|. + // Written only on the UI thread, so the UI thread doesn't need to acquire the + // lock when reading. Can be read from other threads with the lock. + raw_ptr<BrowserContext, DanglingUntriaged> browser_context_; + + // Protects |browser_context_|. + base::Lock browser_context_lock_; + ////////////////////////////////////////////////////////////////////////////// // All fields below are only accessed on the UI thread. @@ -136,9 +150,6 @@ bool force_new_process_for_test_; - // If it has been shut down. - bool is_shutdown_ = false; - // Used to double-check that we don't access *this after it's destroyed. base::WeakPtr<ServiceWorkerProcessManager> weak_this_; base::WeakPtrFactory<ServiceWorkerProcessManager> weak_this_factory_{this};
diff --git a/content/browser/service_worker/service_worker_process_manager_unittest.cc b/content/browser/service_worker/service_worker_process_manager_unittest.cc index 07333b5..e0a781cb 100644 --- a/content/browser/service_worker/service_worker_process_manager_unittest.cc +++ b/content/browser/service_worker/service_worker_process_manager_unittest.cc
@@ -78,7 +78,8 @@ void SetUp() override { browser_context_ = std::make_unique<TestBrowserContext>(); - process_manager_ = std::make_unique<ServiceWorkerProcessManager>(); + process_manager_ = + std::make_unique<ServiceWorkerProcessManager>(browser_context_.get()); process_manager_->set_storage_partition(static_cast<StoragePartitionImpl*>( browser_context_->GetDefaultStoragePartition())); script_url_ = GURL("http://www.example.com/sw.js");
diff --git a/content/browser/service_worker/service_worker_update_checker.cc b/content/browser/service_worker/service_worker_update_checker.cc index 69eac2f..06a1139 100644 --- a/content/browser/service_worker/service_worker_update_checker.cc +++ b/content/browser/service_worker/service_worker_update_checker.cc
@@ -246,7 +246,7 @@ url, is_main_script, main_script_url_, version_to_update_->scope(), force_bypass_cache_, worker_script_type_, update_via_cache_, fetch_client_settings_object_, time_since_last_check_, - context_->wrapper()->browser_context(), loader_factory_, + context_->process_manager()->browser_context(), loader_factory_, std::move(compare_reader), std::move(copy_reader), std::move(writer), new_resource_id, // If the main script checksum is empty, then calculate each script
diff --git a/content/browser/site_per_process_browsertest.cc b/content/browser/site_per_process_browsertest.cc index 3d56415..c7e3734 100644 --- a/content/browser/site_per_process_browsertest.cc +++ b/content/browser/site_per_process_browsertest.cc
@@ -9360,9 +9360,14 @@ gfx::PointF GetPointInChild() { gfx::PointF point_f; std::string str = EvalJs(child_frame_tree_node_->current_frame_host(), - "get_point_inside_text()") + "get_top_left_of_text()") .ExtractString(); ConvertJSONToPoint(str, &point_f); + // Offset the point so that it is within the text. Character dimensions are + // based on the font size in `touch_selection.html`. + constexpr int kCharacterWidth = 15; + constexpr int kCharacterHeight = 15; + point_f.Offset(2 * kCharacterWidth, 0.5f * kCharacterHeight); point_f = child_rwhv()->TransformPointToRootCoordSpaceF(point_f); return point_f; }
diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 0233658e..4d2396f 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc
@@ -9952,7 +9952,8 @@ new_contents); } -base::ScopedClosureRunner WebContentsImpl::CreateDisallowCustomCursorScope() { +base::ScopedClosureRunner WebContentsImpl::CreateDisallowCustomCursorScope( + int max_dimension_dips) { auto* render_widget_host_base = GetPrimaryMainFrame() ->GetRenderWidgetHost() ->GetRenderWidgetHostViewBase(); @@ -9965,7 +9966,7 @@ } auto* cursor_manager = render_widget_host_base->GetCursorManager(); - return cursor_manager->CreateDisallowCustomCursorScope(); + return cursor_manager->CreateDisallowCustomCursorScope(max_dimension_dips); } bool WebContentsImpl::CancelPrerendering(FrameTreeNode* frame_tree_node,
diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h index c7edabf..0af6659 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h
@@ -589,8 +589,8 @@ void AboutToBeDiscarded(WebContents* new_contents) override; - [[nodiscard]] base::ScopedClosureRunner CreateDisallowCustomCursorScope() - override; + [[nodiscard]] base::ScopedClosureRunner CreateDisallowCustomCursorScope( + int max_dimension_dips) override; void SetOverscrollNavigationEnabled(bool enabled) override;
diff --git a/content/common/font_list_mac.mm b/content/common/font_list_mac.mm index 7821a31a..1ef56c7 100644 --- a/content/common/font_list_mac.mm +++ b/content/common/font_list_mac.mm
@@ -43,19 +43,19 @@ FontFamilyResolver& operator=(const FontFamilyResolver&) = delete; // Returns a localized font family name for the given family name. - base::ScopedCFTypeRef<CFStringRef> CopyLocalizedFamilyName( + base::apple::ScopedCFTypeRef<CFStringRef> CopyLocalizedFamilyName( CFStringRef family_name) { DCHECK(family_name != nullptr); CFDictionarySetValue(font_descriptor_attributes_.get(), kCTFontFamilyNameAttribute, family_name); - base::ScopedCFTypeRef<CTFontDescriptorRef> raw_descriptor( + base::apple::ScopedCFTypeRef<CTFontDescriptorRef> raw_descriptor( CTFontDescriptorCreateWithAttributes( font_descriptor_attributes_.get())); DCHECK(raw_descriptor != nullptr) << "CTFontDescriptorCreateWithAttributes returned null"; - base::ScopedCFTypeRef<CFArrayRef> normalized_descriptors( + base::apple::ScopedCFTypeRef<CFArrayRef> normalized_descriptors( CTFontDescriptorCreateMatchingFontDescriptors( raw_descriptor, mandatory_attributes_.get())); return CopyLocalizedFamilyNameFrom(family_name, @@ -73,9 +73,8 @@ // return null, even on macOS 11. Discovery documented in crbug.com/1235042. // // Returns null if none of the descriptors match. - static base::ScopedCFTypeRef<CTFontDescriptorRef> FindFirstWithFamilyName( - CFStringRef family_name, - CFArrayRef descriptors) { + static base::apple::ScopedCFTypeRef<CTFontDescriptorRef> + FindFirstWithFamilyName(CFStringRef family_name, CFArrayRef descriptors) { DCHECK(family_name != nullptr); CFIndex descriptor_count = descriptors ? CFArrayGetCount(descriptors) : 0; @@ -86,16 +85,16 @@ DCHECK(descriptor != nullptr) << "The descriptors array has a null element."; - base::ScopedCFTypeRef<CFStringRef> descriptor_family_name( + base::apple::ScopedCFTypeRef<CFStringRef> descriptor_family_name( base::apple::CFCastStrict<CFStringRef>(CTFontDescriptorCopyAttribute( descriptor, kCTFontFamilyNameAttribute))); if (CFStringCompare(family_name, descriptor_family_name, /*compareOptions=*/0) == kCFCompareEqualTo) { - return base::ScopedCFTypeRef<CTFontDescriptorRef>( + return base::apple::ScopedCFTypeRef<CTFontDescriptorRef>( descriptor, base::scoped_policy::RETAIN); } } - return base::ScopedCFTypeRef<CTFontDescriptorRef>(nullptr); + return base::apple::ScopedCFTypeRef<CTFontDescriptorRef>(nullptr); } // Returns a localized font family name for the given family name. @@ -109,21 +108,21 @@ // // The given family name is returned as a fallback, if none of the descriptors // match the desired font family name. - static base::ScopedCFTypeRef<CFStringRef> CopyLocalizedFamilyNameFrom( + static base::apple::ScopedCFTypeRef<CFStringRef> CopyLocalizedFamilyNameFrom( CFStringRef family_name, CFArrayRef descriptors) { DCHECK(family_name != nullptr); - base::ScopedCFTypeRef<CTFontDescriptorRef> descriptor = + base::apple::ScopedCFTypeRef<CTFontDescriptorRef> descriptor = FindFirstWithFamilyName(family_name, descriptors); if (descriptor == nullptr) { DLOG(WARNING) << "Will use non-localized family name for font family: " << family_name; - return base::ScopedCFTypeRef<CFStringRef>(family_name, - base::scoped_policy::RETAIN); + return base::apple::ScopedCFTypeRef<CFStringRef>( + family_name, base::scoped_policy::RETAIN); } - base::ScopedCFTypeRef<CFStringRef> localized_family_name( + base::apple::ScopedCFTypeRef<CFStringRef> localized_family_name( base::apple::CFCastStrict<CFStringRef>( CTFontDescriptorCopyLocalizedAttribute(descriptor, kCTFontFamilyNameAttribute, @@ -139,24 +138,24 @@ if (localized_family_name == nullptr) { DLOG(WARNING) << "Will use non-localized family name for font family: " << family_name; - return base::ScopedCFTypeRef<CFStringRef>(family_name, - base::scoped_policy::RETAIN); + return base::apple::ScopedCFTypeRef<CFStringRef>( + family_name, base::scoped_policy::RETAIN); } return localized_family_name; } // Creates the set stored in |mandatory_attributes_|. - static base::ScopedCFTypeRef<CFSetRef> CreateMandatoryAttributes() { + static base::apple::ScopedCFTypeRef<CFSetRef> CreateMandatoryAttributes() { CFStringRef set_values[] = {kCTFontFamilyNameAttribute}; - return base::ScopedCFTypeRef<CFSetRef>(CFSetCreate( + return base::apple::ScopedCFTypeRef<CFSetRef>(CFSetCreate( kCFAllocatorDefault, reinterpret_cast<const void**>(set_values), std::size(set_values), &kCFTypeSetCallBacks)); } // Creates the mutable dictionary stored in |font_descriptor_attributes_|. - static base::ScopedCFTypeRef<CFMutableDictionaryRef> + static base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> CreateFontDescriptorAttributes() { - return base::ScopedCFTypeRef<CFMutableDictionaryRef>( + return base::apple::ScopedCFTypeRef<CFMutableDictionaryRef>( CFDictionaryCreateMutable(kCFAllocatorDefault, /*capacity=*/1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -165,7 +164,7 @@ // Used for all CTFontDescriptorCreateMatchingFontDescriptors() calls. // // Caching this dictionary saves one dictionary creation per lookup. - const base::ScopedCFTypeRef<CFSetRef> mandatory_attributes_ = + const base::apple::ScopedCFTypeRef<CFSetRef> mandatory_attributes_ = CreateMandatoryAttributes(); // Used for all CTFontDescriptorCreateMatchingFontDescriptors() calls. @@ -174,7 +173,7 @@ // associated with the key is overwritten as needed. // // Caching this dictionary saves one dictionary creation per lookup. - const base::ScopedCFTypeRef<CFMutableDictionaryRef> + const base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> font_descriptor_attributes_ = CreateFontDescriptorAttributes(); }; @@ -197,7 +196,7 @@ << "CTFontManagerCopyAvailableFontFamilyNames returned an array with " << "a null element"; - base::ScopedCFTypeRef<CFStringRef> cf_normalized_family_name = + base::apple::ScopedCFTypeRef<CFStringRef> cf_normalized_family_name = resolver.CopyLocalizedFamilyName( base::apple::NSToCFPtrCast(family_name)); DCHECK(cf_normalized_family_name != nullptr)
diff --git a/content/common/service_worker/race_network_request_url_loader_client.cc b/content/common/service_worker/race_network_request_url_loader_client.cc index 5368035b..2e3b380b0 100644 --- a/content/common/service_worker/race_network_request_url_loader_client.cc +++ b/content/common/service_worker/race_network_request_url_loader_client.cc
@@ -96,36 +96,18 @@ return; } - // If we already know that the response from ServiceWorker will commit (e.g. - // redirect) here, we don't have to create another data pipe and transfer - // data. Just forwarding the response to |forwarding_client_|. - if (owner_->commit_responsibility() == FetchResponseFrom::kServiceWorker) { - forwarding_client_->OnReceiveResponse(std::move(head), std::move(body), - std::move(cached_metadata)); - return; + switch (data_consume_policy_) { + case DataConsumePolicy::kTeeResponse: + head_ = std::move(head); + cached_metadata_ = std::move(cached_metadata); + body_ = std::move(body); + WatchDataUpdate(); + break; + case DataConsumePolicy::kForwardingOnly: + forwarding_client_->OnReceiveResponse(std::move(head), std::move(body), + std::move(cached_metadata)); + break; } - - head_ = std::move(head); - cached_metadata_ = std::move(cached_metadata); - body_ = std::move(body); - body_consumer_watcher_.Watch( - body_.get(), MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, - base::BindRepeating( - &ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite, - weak_factory_.GetWeakPtr())); - body_consumer_watcher_.ArmOrNotify(); - data_pipe_for_race_network_request_.watcher.Watch( - data_pipe_for_race_network_request_.producer.get(), - MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, - base::BindRepeating( - &ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite, - weak_factory_.GetWeakPtr())); - data_pipe_for_fetch_handler_.watcher.Watch( - data_pipe_for_fetch_handler_.producer.get(), - MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, - base::BindRepeating( - &ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite, - weak_factory_.GetWeakPtr())); } void ServiceWorkerRaceNetworkRequestURLLoaderClient::OnReceiveRedirect( @@ -134,6 +116,9 @@ if (!owner_) { return; } + // If redirect happened, we don't have to create another data pipe. + data_consume_policy_ = DataConsumePolicy::kForwardingOnly; + // TODO(crbug.com/1420517): Return a redirect response to |owner| as a // RaceNetworkRequest result without breaking the cache storage compatibility. // We need a mechanism to wait for the fetch handler completion. @@ -188,12 +173,15 @@ redirected_); } - if (owner_->commit_responsibility() == FetchResponseFrom::kServiceWorker) { - forwarding_client_->OnComplete(status); - return; + switch (data_consume_policy_) { + case DataConsumePolicy::kTeeResponse: + completion_status_ = status; + MaybeCompleteResponse(); + break; + case DataConsumePolicy::kForwardingOnly: + forwarding_client_->OnComplete(status); + break; } - completion_status_ = status; - MaybeCompleteResponse(); } void ServiceWorkerRaceNetworkRequestURLLoaderClient::Bind( @@ -307,6 +295,27 @@ MaybeCompleteResponse(); } +void ServiceWorkerRaceNetworkRequestURLLoaderClient::WatchDataUpdate() { + body_consumer_watcher_.Watch( + body_.get(), MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, + base::BindRepeating( + &ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite, + weak_factory_.GetWeakPtr())); + body_consumer_watcher_.ArmOrNotify(); + data_pipe_for_race_network_request_.watcher.Watch( + data_pipe_for_race_network_request_.producer.get(), + MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, + base::BindRepeating( + &ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite, + weak_factory_.GetWeakPtr())); + data_pipe_for_fetch_handler_.watcher.Watch( + data_pipe_for_fetch_handler_.producer.get(), + MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED, + base::BindRepeating( + &ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite, + weak_factory_.GetWeakPtr())); +} + void ServiceWorkerRaceNetworkRequestURLLoaderClient::ReadAndWrite( MojoResult aresult) { TRACE_EVENT0("ServiceWorker",
diff --git a/content/common/service_worker/race_network_request_url_loader_client.h b/content/common/service_worker/race_network_request_url_loader_client.h index fc85a5d..43ed024 100644 --- a/content/common/service_worker/race_network_request_url_loader_client.h +++ b/content/common/service_worker/race_network_request_url_loader_client.h
@@ -45,6 +45,16 @@ kAborted, }; + // The enum class that indicates how response data is consumed. + enum class DataConsumePolicy { + // Tee response data into 1) the data pipe for RaceNetworkRequest and 2) the + // data pipe for the fetch handler. + kTeeResponse, + // Just forward data to the data pipe for the fetch handler. This value + // doesn't invoke |ReadAndWrite()|. + kForwardingOnly, + }; + // These values are persisted to logs. Entries should not be renumbered and // numeric values should never be reused. // @@ -160,6 +170,8 @@ // the long fetch handler execution. and test case the mechanism to wait for // the fetch handler void ReadAndWrite(MojoResult); + void WatchDataUpdate(); + void Abort(); State state_ = State::kWaitForBody; @@ -178,6 +190,7 @@ absl::optional<network::URLLoaderCompletionStatus> completion_status_; bool redirected_ = false; std::unique_ptr<mojo::DataPipeDrainer> data_drainer_; + DataConsumePolicy data_consume_policy_ = DataConsumePolicy::kTeeResponse; base::WeakPtrFactory<ServiceWorkerRaceNetworkRequestURLLoaderClient> weak_factory_{this};
diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h index 9fa9cb0a..f02cd75 100644 --- a/content/public/browser/web_contents.h +++ b/content/public/browser/web_contents.h
@@ -1421,10 +1421,11 @@ WindowOpenDisposition disposition) = 0; // Returns a scope object that needs to be owned by caller in order to - // disallow custom cursors. Custom cursors are diallowed in this web contents - // for as long as any of the returned |ScopedClosureRunner| objects is alive. + // disallow custom cursors. Custom cursors whose width or height are larger + // than `max_dimension_dips` are diallowed in this web contents for as long as + // any of the returned `ScopedClosureRunner` objects is alive. [[nodiscard]] virtual base::ScopedClosureRunner - CreateDisallowCustomCursorScope() = 0; + CreateDisallowCustomCursorScope(int max_dimension_dips = 0) = 0; // Enables overscroll history navigation. virtual void SetOverscrollNavigationEnabled(bool enabled) = 0;
diff --git a/content/test/data/touch_selection.html b/content/test/data/touch_selection.html index 69d5523..0f148829 100644 --- a/content/test/data/touch_selection.html +++ b/content/test/data/touch_selection.html
@@ -34,25 +34,27 @@ window.getSelection().collapseToStart(); } -function get_point_inside(element) { +// Returns the top left point of an element, excluding border and padding. +function get_top_left(element) { var rect = element.getBoundingClientRect(); + var cs = getComputedStyle(element); var point = { - x: rect.left + 8, - y: rect.top + 8 + x: rect.left + parseFloat(cs.borderLeft) + parseFloat(cs.paddingLeft), + y: rect.top + parseFloat(cs.borderTop) + parseFloat(cs.paddingTop) }; return JSON.stringify(point); } -function get_point_inside_text() { - return get_point_inside(document.getElementById('textDiv')); +function get_top_left_of_text() { + return get_top_left(document.getElementById('textDiv')); } -function get_point_inside_textfield() { - return get_point_inside(document.getElementById('textfield')); +function get_top_left_of_textfield() { + return get_top_left(document.getElementById('textfield')); } -function get_point_inside_empty_textfield() { - return get_point_inside(document.getElementById('emptyTextfield')); +function get_top_left_of_empty_textfield() { + return get_top_left(document.getElementById('emptyTextfield')); } </script>
diff --git a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt index 234b5b37..e30023d 100644 --- a/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt +++ b/content/test/gpu/gpu_tests/test_expectations/pixel_expectations.txt
@@ -376,11 +376,14 @@ crbug.com/1469875 [ mac graphite-enabled ] Pixel_BackgroundImage [ Failure ] crbug.com/1469875 [ mac graphite-enabled ] Pixel_CSSFilterEffects [ Failure ] crbug.com/1469875 [ mac graphite-enabled ] Pixel_CSSFilterEffects_NoOverlays [ Failure ] -crbug.com/1469875 [ mac graphite-enabled ] Pixel_OffscreenCanvasAccelerated2D [ Failure ] -crbug.com/1469875 [ mac graphite-enabled ] Pixel_OffscreenCanvasAccelerated2DWorker [ Failure ] +crbug.com/1469875 [ amd-0x679e angle-metal graphite-enabled mac-x86_64 monterey no-asan ] Pixel_OffscreenCanvasAccelerated2D [ Failure ] +crbug.com/1469875 [ angle-opengl graphite-enabled no-asan ventura ] Pixel_OffscreenCanvasAccelerated2D [ Failure ] +crbug.com/1469875 [ amd-0x679e angle-metal graphite-enabled mac-x86_64 monterey no-asan ] Pixel_OffscreenCanvasAccelerated2DWorker [ Failure ] +crbug.com/1469875 [ angle-opengl graphite-enabled no-asan ventura ] Pixel_OffscreenCanvasAccelerated2DWorker [ Failure ] crbug.com/1469875 [ mac graphite-enabled ] Pixel_OffscreenCanvasTransferAfterStyleResize [ Failure ] crbug.com/1469875 [ mac graphite-enabled ] Pixel_OffscreenCanvasTransferToImageBitmap [ Failure ] -crbug.com/1469875 [ mac graphite-enabled ] Pixel_PaintWorkletTransform [ Failure ] +crbug.com/1469875 [ amd-0x679e angle-metal graphite-enabled mac-x86_64 monterey no-asan ] Pixel_PaintWorkletTransform [ Failure ] +crbug.com/1469875 [ angle-opengl graphite-enabled no-asan ventura ] Pixel_PaintWorkletTransform [ Failure ] crbug.com/1469875 [ mac graphite-enabled amd release no-asan ] Pixel_SVGHuge [ Failure ] crbug.com/1469875 [ mac graphite-enabled apple ] Pixel_SVGHuge [ Failure ] crbug.com/1469875 [ mac graphite-enabled intel release no-asan ] Pixel_SVGHuge [ Failure ]
diff --git a/crypto/apple_keychain_ios.mm b/crypto/apple_keychain_ios.mm index 8925cca..1d61f4c 100644 --- a/crypto/apple_keychain_ios.mm +++ b/crypto/apple_keychain_ios.mm
@@ -17,16 +17,17 @@ kKeychainActionUpdate }; -base::ScopedCFTypeRef<CFStringRef> StringWithBytesAndLength(const char* bytes, - UInt32 length) { - return base::ScopedCFTypeRef<CFStringRef>( +base::apple::ScopedCFTypeRef<CFStringRef> StringWithBytesAndLength( + const char* bytes, + UInt32 length) { + return base::apple::ScopedCFTypeRef<CFStringRef>( CFStringCreateWithBytes(nullptr, reinterpret_cast<const UInt8*>(bytes), length, kCFStringEncodingUTF8, /*isExternalRepresentation=*/false)); } // Creates a dictionary that can be used to query the keystore. -base::ScopedCFTypeRef<CFDictionaryRef> MakeGenericPasswordQuery( +base::apple::ScopedCFTypeRef<CFDictionaryRef> MakeGenericPasswordQuery( UInt32 serviceNameLength, const char* serviceName, UInt32 accountNameLength, @@ -51,11 +52,11 @@ CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitOne); CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue); - return base::ScopedCFTypeRef<CFDictionaryRef>(query); + return base::apple::ScopedCFTypeRef<CFDictionaryRef>(query); } // Creates a dictionary containing the data to save into the keychain. -base::ScopedCFTypeRef<CFDictionaryRef> MakeKeychainData( +base::apple::ScopedCFTypeRef<CFDictionaryRef> MakeKeychainData( UInt32 serviceNameLength, const char* serviceName, UInt32 accountNameLength, @@ -74,7 +75,7 @@ // If this is not a creation, no structural information is needed. if (action != kKeychainActionCreate) { - return base::ScopedCFTypeRef<CFDictionaryRef>(keychain_data); + return base::apple::ScopedCFTypeRef<CFDictionaryRef>(keychain_data); } // Set the type of the data. @@ -95,7 +96,7 @@ keychain_data, kSecAttrAccount, StringWithBytesAndLength(accountName, accountNameLength)); - return base::ScopedCFTypeRef<CFDictionaryRef>(keychain_data); + return base::apple::ScopedCFTypeRef<CFDictionaryRef>(keychain_data); } } // namespace @@ -119,21 +120,24 @@ UInt32 passwordLength, const void* passwordData, AppleSecKeychainItemRef* itemRef) const { - base::ScopedCFTypeRef<CFDictionaryRef> query = MakeGenericPasswordQuery( - serviceNameLength, serviceName, accountNameLength, accountName); + base::apple::ScopedCFTypeRef<CFDictionaryRef> query = + MakeGenericPasswordQuery(serviceNameLength, serviceName, + accountNameLength, accountName); // Check that there is not already a password. OSStatus status = SecItemCopyMatching(query, /*result=*/nullptr); if (status == errSecItemNotFound) { // A new entry must be created. - base::ScopedCFTypeRef<CFDictionaryRef> keychain_data = MakeKeychainData( - serviceNameLength, serviceName, accountNameLength, accountName, - passwordLength, passwordData, kKeychainActionCreate); + base::apple::ScopedCFTypeRef<CFDictionaryRef> keychain_data = + MakeKeychainData(serviceNameLength, serviceName, accountNameLength, + accountName, passwordLength, passwordData, + kKeychainActionCreate); status = SecItemAdd(keychain_data, /*result=*/nullptr); } else if (status == noErr) { // The entry must be updated. - base::ScopedCFTypeRef<CFDictionaryRef> keychain_data = MakeKeychainData( - serviceNameLength, serviceName, accountNameLength, accountName, - passwordLength, passwordData, kKeychainActionUpdate); + base::apple::ScopedCFTypeRef<CFDictionaryRef> keychain_data = + MakeKeychainData(serviceNameLength, serviceName, accountNameLength, + accountName, passwordLength, passwordData, + kKeychainActionUpdate); status = SecItemUpdate(query, keychain_data); } @@ -150,11 +154,12 @@ AppleSecKeychainItemRef* itemRef) const { DCHECK((passwordData && passwordLength) || (!passwordData && !passwordLength)); - base::ScopedCFTypeRef<CFDictionaryRef> query = MakeGenericPasswordQuery( - serviceNameLength, serviceName, accountNameLength, accountName); + base::apple::ScopedCFTypeRef<CFDictionaryRef> query = + MakeGenericPasswordQuery(serviceNameLength, serviceName, + accountNameLength, accountName); // Get the keychain item containing the password. - base::ScopedCFTypeRef<CFTypeRef> result; + base::apple::ScopedCFTypeRef<CFTypeRef> result; OSStatus status = SecItemCopyMatching(query, result.InitializeInto()); if (status != noErr) {
diff --git a/device/bluetooth/bluetooth_adapter_mac.mm b/device/bluetooth/bluetooth_adapter_mac.mm index 75343e1f..82836fc5 100644 --- a/device/bluetooth/bluetooth_adapter_mac.mm +++ b/device/bluetooth/bluetooth_adapter_mac.mm
@@ -151,7 +151,7 @@ return false; } - base::ScopedCFTypeRef<CFBooleanRef> connected( + base::apple::ScopedCFTypeRef<CFBooleanRef> connected( base::apple::CFCast<CFBooleanRef>(IORegistryEntryCreateCFProperty( service, CFSTR("BluetoothTransportConnected"), kCFAllocatorDefault, 0)));
diff --git a/device/fido/mac/browsing_data_deletion_unittest.mm b/device/fido/mac/browsing_data_deletion_unittest.mm index b51bf42..13cf3c3c 100644 --- a/device/fido/mac/browsing_data_deletion_unittest.mm +++ b/device/fido/mac/browsing_data_deletion_unittest.mm
@@ -52,12 +52,13 @@ // Returns a query to use with Keychain instance methods that returns all // credentials in the non-legacy keychain that are tagged with the keychain // access group used in this test. -base::ScopedCFTypeRef<CFMutableDictionaryRef> BaseQuery() { - base::ScopedCFTypeRef<CFMutableDictionaryRef> query(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); +base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> BaseQuery() { + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue(query, kSecClass, kSecClassKey); - base::ScopedCFTypeRef<CFStringRef> access_group_ref( + base::apple::ScopedCFTypeRef<CFStringRef> access_group_ref( base::SysUTF8ToCFStringRef(kKeychainAccessGroup)); CFDictionarySetValue(query, kSecAttrAccessGroup, access_group_ref); CFDictionarySetValue(query, kSecAttrNoLegacy, kCFBooleanTrue); @@ -69,14 +70,14 @@ // Returns all WebAuthn credentials stored in the keychain, regardless of which // profile they are associated with. May return a null reference if an error // occurred. -base::ScopedCFTypeRef<CFArrayRef> QueryAllCredentials() { - base::ScopedCFTypeRef<CFArrayRef> items; +base::apple::ScopedCFTypeRef<CFArrayRef> QueryAllCredentials() { + base::apple::ScopedCFTypeRef<CFArrayRef> items; OSStatus status = Keychain::GetInstance().ItemCopyMatching( BaseQuery(), reinterpret_cast<CFTypeRef*>(items.InitializeInto())); if (status == errSecItemNotFound) { // The API returns null, but we should return an empty array instead to // distinguish from real errors. - items = base::ScopedCFTypeRef<CFArrayRef>( + items = base::apple::ScopedCFTypeRef<CFArrayRef>( CFArrayCreate(nullptr, nullptr, 0, nullptr)); } else if (status != errSecSuccess) { OSSTATUS_DLOG(ERROR, status); @@ -87,7 +88,7 @@ // Returns the number of WebAuthn credentials in the keychain (for all // profiles), or -1 if an error occurs. ssize_t KeychainItemCount() { - base::ScopedCFTypeRef<CFArrayRef> items = QueryAllCredentials(); + base::apple::ScopedCFTypeRef<CFArrayRef> items = QueryAllCredentials(); return items ? CFArrayGetCount(items) : -1; }
diff --git a/device/fido/mac/credential_store.h b/device/fido/mac/credential_store.h index 808c052..4fd1c7c 100644 --- a/device/fido/mac/credential_store.h +++ b/device/fido/mac/credential_store.h
@@ -31,7 +31,7 @@ // Credential represents a WebAuthn credential from the keychain. struct COMPONENT_EXPORT(DEVICE_FIDO) Credential { - Credential(base::ScopedCFTypeRef<SecKeyRef> private_key, + Credential(base::apple::ScopedCFTypeRef<SecKeyRef> private_key, std::vector<uint8_t> credential_id, CredentialMetadata metadata, std::string rp_id); @@ -48,7 +48,7 @@ bool RequiresUvForSignature() const; // An opaque reference to the private key that can be used for signing. - base::ScopedCFTypeRef<SecKeyRef> private_key; + base::apple::ScopedCFTypeRef<SecKeyRef> private_key; // The credential ID is a handle to the key that gets passed to the RP. This // ID is opaque to the RP, but is obtained by encrypting the credential @@ -86,7 +86,7 @@ // CreateCredential inserts a new credential into the keychain. It returns // the new credential and its public key, or absl::nullopt if an error // occurred. - absl::optional<std::pair<Credential, base::ScopedCFTypeRef<SecKeyRef>>> + absl::optional<std::pair<Credential, base::apple::ScopedCFTypeRef<SecKeyRef>>> CreateCredential(const std::string& rp_id, const PublicKeyCredentialUserEntity& user, Discoverable discoverable) const; @@ -94,7 +94,7 @@ // CreateCredentialLegacyCredentialForTesting inserts a credential for an old // `CredentialMetadata::Version`. Such credentials can't be created anymore, // but they still exist and we need to be able to exercise them. - absl::optional<std::pair<Credential, base::ScopedCFTypeRef<SecKeyRef>>> + absl::optional<std::pair<Credential, base::apple::ScopedCFTypeRef<SecKeyRef>>> CreateCredentialLegacyCredentialForTesting( CredentialMetadata::Version version, const std::string& rp_id,
diff --git a/device/fido/mac/credential_store.mm b/device/fido/mac/credential_store.mm index ff635a6..e339d7a 100644 --- a/device/fido/mac/credential_store.mm +++ b/device/fido/mac/credential_store.mm
@@ -36,12 +36,13 @@ // the keychain item class, keychain access group and RP ID (unless `rp_id` is // `nullopt`) filled out. More fields can be set on the return value to refine // the query. -base::ScopedCFTypeRef<CFMutableDictionaryRef> DefaultKeychainQuery( +base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> DefaultKeychainQuery( const AuthenticatorConfig& config, absl::optional<std::string> rp_id) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> query(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue(query, kSecClass, kSecClassKey); CFDictionarySetValue( query, kSecAttrAccessGroup, @@ -57,7 +58,7 @@ // Erase all keychain items with a creation date that is not within [not_before, // not_after). void FilterKeychainItemsByCreationDate( - std::vector<base::ScopedCFTypeRef<CFDictionaryRef>>* keychain_items, + std::vector<base::apple::ScopedCFTypeRef<CFDictionaryRef>>* keychain_items, base::Time not_before, base::Time not_after) { base::EraseIf( @@ -77,7 +78,7 @@ }); } -absl::optional<std::vector<base::ScopedCFTypeRef<CFDictionaryRef>>> +absl::optional<std::vector<base::apple::ScopedCFTypeRef<CFDictionaryRef>>> QueryKeychainItemsForProfile(const std::string& keychain_access_group, const std::string& metadata_secret, base::Time created_not_before, @@ -87,11 +88,12 @@ // profiles). Sadly, the kSecAttrAccessGroup filter doesn't quite work, and // so we also get results from the legacy keychain that are tagged with no // keychain access group. - std::vector<base::ScopedCFTypeRef<CFDictionaryRef>> result; + std::vector<base::apple::ScopedCFTypeRef<CFDictionaryRef>> result; - base::ScopedCFTypeRef<CFMutableDictionaryRef> query(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue(query, kSecClass, kSecClassKey); CFDictionarySetValue(query, kSecAttrAccessGroup, base::SysUTF8ToCFStringRef(keychain_access_group)); @@ -100,7 +102,7 @@ CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecReturnAttributes, kCFBooleanTrue); - base::ScopedCFTypeRef<CFArrayRef> keychain_items; + base::apple::ScopedCFTypeRef<CFArrayRef> keychain_items; { OSStatus status = Keychain::GetInstance().ItemCopyMatching( query, reinterpret_cast<CFTypeRef*>(keychain_items.InitializeInto())); @@ -169,7 +171,7 @@ } // namespace -Credential::Credential(base::ScopedCFTypeRef<SecKeyRef> private_key, +Credential::Credential(base::apple::ScopedCFTypeRef<SecKeyRef> private_key, std::vector<uint8_t> credential_id, CredentialMetadata metadata, std::string rp_id) @@ -211,12 +213,12 @@ objc_storage_->authentication_context = authentication_context; } -absl::optional<std::pair<Credential, base::ScopedCFTypeRef<SecKeyRef>>> +absl::optional<std::pair<Credential, base::apple::ScopedCFTypeRef<SecKeyRef>>> TouchIdCredentialStore::CreateCredential( const std::string& rp_id, const PublicKeyCredentialUserEntity& user, Discoverable discoverable) const { - base::ScopedCFTypeRef<CFMutableDictionaryRef> params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -247,7 +249,7 @@ params, kSecAttrApplicationLabel, base::apple::NSToCFPtrCast([NSData dataWithBytes:credential_id.data() length:credential_id.size()])); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -256,7 +258,7 @@ // The credential can only be used for signing, and the device needs to be in // an unlocked state. auto flags = kSecAccessControlPrivateKeyUsage; - base::ScopedCFTypeRef<SecAccessControlRef> access_control( + base::apple::ScopedCFTypeRef<SecAccessControlRef> access_control( SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, flags, /*error=*/nullptr)); @@ -267,15 +269,15 @@ private_key_params, kSecUseAuthenticationContext, (__bridge CFTypeRef)objc_storage_->authentication_context); } - base::ScopedCFTypeRef<CFErrorRef> cferr; - base::ScopedCFTypeRef<SecKeyRef> private_key = + base::apple::ScopedCFTypeRef<CFErrorRef> cferr; + base::apple::ScopedCFTypeRef<SecKeyRef> private_key = Keychain::GetInstance().KeyCreateRandomKey(params, cferr.InitializeInto()); if (!private_key) { FIDO_LOG(ERROR) << "SecKeyCreateRandomKey failed: " << cferr; return absl::nullopt; } - base::ScopedCFTypeRef<SecKeyRef> public_key( + base::apple::ScopedCFTypeRef<SecKeyRef> public_key( Keychain::GetInstance().KeyCopyPublicKey(private_key)); if (!public_key) { FIDO_LOG(ERROR) << "SecKeyCopyPublicKey failed"; @@ -288,7 +290,7 @@ std::move(public_key)); } -absl::optional<std::pair<Credential, base::ScopedCFTypeRef<SecKeyRef>>> +absl::optional<std::pair<Credential, base::apple::ScopedCFTypeRef<SecKeyRef>>> TouchIdCredentialStore::CreateCredentialLegacyCredentialForTesting( CredentialMetadata::Version version, const std::string& rp_id, @@ -306,7 +308,7 @@ credential_id); DCHECK(metadata); - base::ScopedCFTypeRef<CFMutableDictionaryRef> params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -330,7 +332,7 @@ params, kSecAttrApplicationLabel, base::apple::NSToCFPtrCast([NSData dataWithBytes:credential_id.data() length:credential_id.size()])); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -339,7 +341,7 @@ // Credential can only be used when the device is unlocked. Private key is // available for signing after user authorization with biometrics or // password. - base::ScopedCFTypeRef<SecAccessControlRef> access_control( + base::apple::ScopedCFTypeRef<SecAccessControlRef> access_control( SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage | kSecAccessControlUserPresence, @@ -351,15 +353,15 @@ private_key_params, kSecUseAuthenticationContext, (__bridge CFTypeRef)objc_storage_->authentication_context); } - base::ScopedCFTypeRef<CFErrorRef> cferr; - base::ScopedCFTypeRef<SecKeyRef> private_key = + base::apple::ScopedCFTypeRef<CFErrorRef> cferr; + base::apple::ScopedCFTypeRef<SecKeyRef> private_key = Keychain::GetInstance().KeyCreateRandomKey(params, cferr.InitializeInto()); if (!private_key) { FIDO_LOG(ERROR) << "SecKeyCreateRandomKey failed: " << cferr; return absl::nullopt; } - base::ScopedCFTypeRef<SecKeyRef> public_key( + base::apple::ScopedCFTypeRef<SecKeyRef> public_key( Keychain::GetInstance().KeyCopyPublicKey(private_key)); if (!public_key) { FIDO_LOG(ERROR) << "SecKeyCopyPublicKey failed"; @@ -444,7 +446,7 @@ bool TouchIdCredentialStore::DeleteCredentialsSync( base::Time created_not_before, base::Time created_not_after) { - absl::optional<std::vector<base::ScopedCFTypeRef<CFDictionaryRef>>> + absl::optional<std::vector<base::apple::ScopedCFTypeRef<CFDictionaryRef>>> keychain_items = QueryKeychainItemsForProfile( config_.keychain_access_group, config_.metadata_secret, created_not_before, created_not_after); @@ -453,7 +455,7 @@ } bool result = true; - for (const base::ScopedCFTypeRef<CFDictionaryRef>& attributes : + for (const base::apple::ScopedCFTypeRef<CFDictionaryRef>& attributes : *keychain_items) { // kSecAttrApplicationLabel stores the credential ID. CFDataRef credential_id_data = @@ -476,7 +478,7 @@ size_t TouchIdCredentialStore::CountCredentialsSync( base::Time created_not_before, base::Time created_not_after) { - absl::optional<std::vector<base::ScopedCFTypeRef<CFDictionaryRef>>> + absl::optional<std::vector<base::apple::ScopedCFTypeRef<CFDictionaryRef>>> keychain_items = QueryKeychainItemsForProfile( config_.keychain_access_group, config_.metadata_secret, created_not_before, created_not_after); @@ -509,7 +511,7 @@ // Query all credentials for the RP. Filtering for `rp_id` here ensures we // don't retrieve credentials for other profiles, because their // `kSecAttrLabel` attribute wouldn't match the encoded RP ID. - base::ScopedCFTypeRef<CFMutableDictionaryRef> query = + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query = DefaultKeychainQuery(config_, rp_id); if (objc_storage_->authentication_context) { CFDictionarySetValue( @@ -520,7 +522,7 @@ CFDictionarySetValue(query, kSecReturnAttributes, kCFBooleanTrue); CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll); - base::ScopedCFTypeRef<CFArrayRef> keychain_items; + base::apple::ScopedCFTypeRef<CFArrayRef> keychain_items; OSStatus status = Keychain::GetInstance().ItemCopyMatching( query, reinterpret_cast<CFTypeRef*>(keychain_items.InitializeInto())); if (status == errSecItemNotFound) { @@ -614,8 +616,8 @@ FIDO_LOG(ERROR) << "credential with missing value ref"; return absl::nullopt; } - base::ScopedCFTypeRef<SecKeyRef> private_key(key, - base::scoped_policy::RETAIN); + base::apple::ScopedCFTypeRef<SecKeyRef> private_key( + key, base::scoped_policy::RETAIN); credentials.emplace_back(std::move(private_key), std::move(credential_id), std::move(*metadata), std::move(rp_id_value)); @@ -627,7 +629,7 @@ base::span<const uint8_t> credential_id) const { // The sane way to delete a credential would be by SecKeyRef, like so: // - // base::ScopedCFTypeRef<CFMutableDictionaryRef> query( + // base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( // CFDictionaryCreateMutable(kCFAllocatorDefault, 0, // &kCFTypeDictionaryKeyCallBacks, // &kCFTypeDictionaryValueCallBacks)); @@ -642,9 +644,10 @@ // keychain items by credential ID (stored in `kSecAttrApplicationLabel`). // TODO(https://crbug.com/1463798): Update to this better approach that // requires 10.15 now that Chromium requires 10.15. - base::ScopedCFTypeRef<CFMutableDictionaryRef> query(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue( query, kSecAttrAccessGroup, base::SysUTF8ToCFStringRef(config_.keychain_access_group)); @@ -673,7 +676,7 @@ FIDO_LOG(ERROR) << "no credentials found"; return false; } - base::ScopedCFTypeRef<CFMutableDictionaryRef> params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -695,9 +698,10 @@ FIDO_LOG(ERROR) << "no credential with matching credential_id"; return false; } - base::ScopedCFTypeRef<CFMutableDictionaryRef> query(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue( query, kSecAttrAccessGroup, base::SysUTF8ToCFStringRef(config_.keychain_access_group));
diff --git a/device/fido/mac/credential_store_unittest.mm b/device/fido/mac/credential_store_unittest.mm index 101c192..1dd0063 100644 --- a/device/fido/mac/credential_store_unittest.mm +++ b/device/fido/mac/credential_store_unittest.mm
@@ -79,7 +79,8 @@ Credential credential = std::move(result->first); EXPECT_EQ(credential.credential_id.size(), 32u); EXPECT_NE(credential.private_key, nullptr); - base::ScopedCFTypeRef<SecKeyRef> public_key = std::move(result->second); + base::apple::ScopedCFTypeRef<SecKeyRef> public_key = + std::move(result->second); EXPECT_NE(public_key, nullptr); EXPECT_EQ( credential.metadata,
diff --git a/device/fido/mac/fake_keychain.h b/device/fido/mac/fake_keychain.h index a1269cc..091da90 100644 --- a/device/fido/mac/fake_keychain.h +++ b/device/fido/mac/fake_keychain.h
@@ -28,21 +28,21 @@ ~FakeKeychain() override; // Keychain: - base::ScopedCFTypeRef<SecKeyRef> KeyCreateRandomKey( + base::apple::ScopedCFTypeRef<SecKeyRef> KeyCreateRandomKey( CFDictionaryRef params, CFErrorRef* error) override; OSStatus ItemCopyMatching(CFDictionaryRef query, CFTypeRef* result) override; OSStatus ItemDelete(CFDictionaryRef query) override; - OSStatus ItemUpdate( - CFDictionaryRef query, - base::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_data) override; + OSStatus ItemUpdate(CFDictionaryRef query, + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> + keychain_data) override; private: // items_ contains the keychain items created by `KeyCreateRandomKey`. - std::vector<base::ScopedCFTypeRef<CFDictionaryRef>> items_; + std::vector<base::apple::ScopedCFTypeRef<CFDictionaryRef>> items_; // keychain_access_group_ is the value of `kSecAttrAccessGroup` that this // keychain expects to operate on. - base::ScopedCFTypeRef<CFStringRef> keychain_access_group_; + base::apple::ScopedCFTypeRef<CFStringRef> keychain_access_group_; }; // ScopedFakeKeychain installs itself as testing override for
diff --git a/device/fido/mac/fake_keychain.mm b/device/fido/mac/fake_keychain.mm index 44ce82b95..dd20525 100644 --- a/device/fido/mac/fake_keychain.mm +++ b/device/fido/mac/fake_keychain.mm
@@ -32,7 +32,7 @@ #endif } -base::ScopedCFTypeRef<SecKeyRef> FakeKeychain::KeyCreateRandomKey( +base::apple::ScopedCFTypeRef<SecKeyRef> FakeKeychain::KeyCreateRandomKey( CFDictionaryRef params, CFErrorRef* error) { // Validate certain fields that we always expect to be set. @@ -56,7 +56,7 @@ // Call Keychain services to create a key pair, but first drop all parameters // that aren't appropriate in tests. - base::ScopedCFTypeRef<CFMutableDictionaryRef> params_copy( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> params_copy( CFDictionaryCreateMutableCopy(kCFAllocatorDefault, /*capacity=*/0, params)); // Don't create a Secure Enclave key. @@ -64,7 +64,7 @@ // Don't bind to a keychain-access-group, which would require an entitlement. CFDictionaryRemoveValue(params_copy, kSecAttrAccessGroup); - base::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> private_key_params( CFDictionaryCreateMutableCopy( kCFAllocatorDefault, /*capacity=*/0, base::apple::GetValueFromDictionary<CFDictionaryRef>( @@ -77,17 +77,17 @@ CFDictionaryRemoveValue(private_key_params, kSecAttrAccessControl); CFDictionaryRemoveValue(private_key_params, kSecUseAuthenticationContext); CFDictionarySetValue(params_copy, kSecPrivateKeyAttrs, private_key_params); - base::ScopedCFTypeRef<SecKeyRef> private_key( + base::apple::ScopedCFTypeRef<SecKeyRef> private_key( SecKeyCreateRandomKey(params_copy, error)); if (!private_key) { - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); } // Stash everything in `items_` so it can be retrieved in with // `ItemCopyMatching. This uses the original `params` rather than the modified // copy so that `ItemCopyMatching()` will correctly filter on // kSecAttrAccessGroup. - base::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_item( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_item( CFDictionaryCreateMutableCopy(kCFAllocatorDefault, /*capacity=*/0, params)); CFDictionarySetValue(keychain_item, kSecValueRef, private_key.get()); @@ -111,7 +111,7 @@ kSecMatchLimitAll); // Filter the items based on `query`. - base::ScopedCFTypeRef<CFMutableArrayRef> items( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> items( CFArrayCreateMutable(nullptr, items_.size(), &kCFTypeArrayCallBacks)); for (auto& item : items_) { // Each `Keychain` instance is expected to operate only on items of a single @@ -142,7 +142,7 @@ item, kSecAttrApplicationLabel)))) { continue; } - base::ScopedCFTypeRef<CFDictionaryRef> item_copy( + base::apple::ScopedCFTypeRef<CFDictionaryRef> item_copy( CFDictionaryCreateCopy(kCFAllocatorDefault, item)); CFArrayAppendValue(items, item_copy); } @@ -167,7 +167,7 @@ kSecAttrApplicationLabel); DCHECK(query_credential_id); for (auto it = items_.begin(); it != items_.end(); ++it) { - const base::ScopedCFTypeRef<CFDictionaryRef>& item = *it; + const base::apple::ScopedCFTypeRef<CFDictionaryRef>& item = *it; CFDataRef item_credential_id = base::apple::GetValueFromDictionary<CFDataRef>( item, kSecAttrApplicationLabel); @@ -182,7 +182,7 @@ OSStatus FakeKeychain::ItemUpdate( CFDictionaryRef query, - base::ScopedCFTypeRef<CFMutableDictionaryRef> attributes_to_update) { + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> attributes_to_update) { DCHECK_EQ(base::apple::GetValueFromDictionary<CFStringRef>(query, kSecClass), kSecClassKey); DCHECK(CFEqual(base::apple::GetValueFromDictionary<CFStringRef>( @@ -193,7 +193,7 @@ kSecAttrApplicationLabel); DCHECK(query_credential_id); for (auto it = items_.begin(); it != items_.end(); ++it) { - const base::ScopedCFTypeRef<CFDictionaryRef>& item = *it; + const base::apple::ScopedCFTypeRef<CFDictionaryRef>& item = *it; CFDataRef item_credential_id = base::apple::GetValueFromDictionary<CFDataRef>( item, kSecAttrApplicationLabel); @@ -201,7 +201,7 @@ if (!CFEqual(query_credential_id, item_credential_id)) { continue; } - base::ScopedCFTypeRef<CFMutableDictionaryRef> item_copy( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> item_copy( CFDictionaryCreateMutableCopy(kCFAllocatorDefault, /*capacity=*/0, item)); size_t size = CFDictionaryGetCount(attributes_to_update.get()); @@ -213,7 +213,7 @@ for (size_t i = 0; i < size; ++i) { CFDictionarySetValue(item_copy, keys[i], values[i]); } - *it = base::ScopedCFTypeRef<CFDictionaryRef>(item_copy.release()); + *it = base::apple::ScopedCFTypeRef<CFDictionaryRef>(item_copy.release()); return errSecSuccess; } return errSecItemNotFound;
diff --git a/device/fido/mac/get_assertion_operation.mm b/device/fido/mac/get_assertion_operation.mm index 86eecb5..bc3f24b 100644 --- a/device/fido/mac/get_assertion_operation.mm +++ b/device/fido/mac/get_assertion_operation.mm
@@ -28,7 +28,7 @@ namespace device::fido::mac { -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; GetAssertionOperation::GetAssertionOperation( CtapGetAssertionRequest request,
diff --git a/device/fido/mac/icloud_keychain_sys.mm b/device/fido/mac/icloud_keychain_sys.mm index 825fca0..3b1878bd 100644 --- a/device/fido/mac/icloud_keychain_sys.mm +++ b/device/fido/mac/icloud_keychain_sys.mm
@@ -182,12 +182,12 @@ } bool ProcessHasEntitlement() { - base::ScopedCFTypeRef<SecTaskRef> task(SecTaskCreateFromSelf(nullptr)); + base::apple::ScopedCFTypeRef<SecTaskRef> task(SecTaskCreateFromSelf(nullptr)); if (!task) { return false; } - base::ScopedCFTypeRef<CFTypeRef> entitlement_value_cftype( + base::apple::ScopedCFTypeRef<CFTypeRef> entitlement_value_cftype( SecTaskCopyValueForEntitlement( task, CFSTR("com.apple.developer.web-browser.public-key-credential"), nullptr));
diff --git a/device/fido/mac/keychain.h b/device/fido/mac/keychain.h index 577d8ee0..46e7065 100644 --- a/device/fido/mac/keychain.h +++ b/device/fido/mac/keychain.h
@@ -31,17 +31,18 @@ Keychain& operator=(const Keychain&) = delete; // KeyCreateRandomKey wraps the |SecKeyCreateRandomKey| function. - virtual base::ScopedCFTypeRef<SecKeyRef> KeyCreateRandomKey( + virtual base::apple::ScopedCFTypeRef<SecKeyRef> KeyCreateRandomKey( CFDictionaryRef params, CFErrorRef* error); // KeyCreateSignature wraps the |SecKeyCreateSignature| function. - virtual base::ScopedCFTypeRef<CFDataRef> KeyCreateSignature( + virtual base::apple::ScopedCFTypeRef<CFDataRef> KeyCreateSignature( SecKeyRef key, SecKeyAlgorithm algorithm, CFDataRef data, CFErrorRef* error); // KeyCopyPublicKey wraps the |SecKeyCopyPublicKey| function. - virtual base::ScopedCFTypeRef<SecKeyRef> KeyCopyPublicKey(SecKeyRef key); + virtual base::apple::ScopedCFTypeRef<SecKeyRef> KeyCopyPublicKey( + SecKeyRef key); // ItemCopyMatching wraps the |SecItemCopyMatching| function. virtual OSStatus ItemCopyMatching(CFDictionaryRef query, CFTypeRef* result); @@ -50,7 +51,7 @@ // ItemDelete wraps the |SecItemUpdate| function. virtual OSStatus ItemUpdate( CFDictionaryRef query, - base::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_data); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_data); protected: Keychain();
diff --git a/device/fido/mac/keychain.mm b/device/fido/mac/keychain.mm index c522b5b..484befd 100644 --- a/device/fido/mac/keychain.mm +++ b/device/fido/mac/keychain.mm
@@ -38,23 +38,25 @@ Keychain::Keychain() = default; Keychain::~Keychain() = default; -base::ScopedCFTypeRef<SecKeyRef> Keychain::KeyCreateRandomKey( +base::apple::ScopedCFTypeRef<SecKeyRef> Keychain::KeyCreateRandomKey( CFDictionaryRef params, CFErrorRef* error) { - return base::ScopedCFTypeRef<SecKeyRef>(SecKeyCreateRandomKey(params, error)); + return base::apple::ScopedCFTypeRef<SecKeyRef>( + SecKeyCreateRandomKey(params, error)); } -base::ScopedCFTypeRef<CFDataRef> Keychain::KeyCreateSignature( +base::apple::ScopedCFTypeRef<CFDataRef> Keychain::KeyCreateSignature( SecKeyRef key, SecKeyAlgorithm algorithm, CFDataRef data, CFErrorRef* error) { - return base::ScopedCFTypeRef<CFDataRef>( + return base::apple::ScopedCFTypeRef<CFDataRef>( SecKeyCreateSignature(key, algorithm, data, error)); } -base::ScopedCFTypeRef<SecKeyRef> Keychain::KeyCopyPublicKey(SecKeyRef key) { - return base::ScopedCFTypeRef<SecKeyRef>(SecKeyCopyPublicKey(key)); +base::apple::ScopedCFTypeRef<SecKeyRef> Keychain::KeyCopyPublicKey( + SecKeyRef key) { + return base::apple::ScopedCFTypeRef<SecKeyRef>(SecKeyCopyPublicKey(key)); } OSStatus Keychain::ItemCopyMatching(CFDictionaryRef query, CFTypeRef* result) { @@ -67,7 +69,7 @@ OSStatus Keychain::ItemUpdate( CFDictionaryRef query, - base::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_data) { + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> keychain_data) { return SecItemUpdate(query, keychain_data); }
diff --git a/device/fido/mac/make_credential_operation.mm b/device/fido/mac/make_credential_operation.mm index a939e69..e698949b 100644 --- a/device/fido/mac/make_credential_operation.mm +++ b/device/fido/mac/make_credential_operation.mm
@@ -115,7 +115,7 @@ // // New credentials are always discoverable. But older non-discoverable // credentials may exist. - absl::optional<std::pair<Credential, base::ScopedCFTypeRef<SecKeyRef>>> + absl::optional<std::pair<Credential, base::apple::ScopedCFTypeRef<SecKeyRef>>> credential_result = credential_store_->CreateCredential( request_.rp.id, request_.user, TouchIdCredentialStore::kDiscoverable); if (!credential_result) {
diff --git a/device/fido/mac/touch_id_context.mm b/device/fido/mac/touch_id_context.mm index 7b7ad8a5..52aa4b9 100644 --- a/device/fido/mac/touch_id_context.mm +++ b/device/fido/mac/touch_id_context.mm
@@ -34,12 +34,12 @@ // enclave. bool ExecutableHasKeychainAccessGroupEntitlement( const std::string& keychain_access_group) { - base::ScopedCFTypeRef<SecTaskRef> task(SecTaskCreateFromSelf(nullptr)); + base::apple::ScopedCFTypeRef<SecTaskRef> task(SecTaskCreateFromSelf(nullptr)); if (!task) { return false; } - base::ScopedCFTypeRef<CFTypeRef> entitlement_value_cftype( + base::apple::ScopedCFTypeRef<CFTypeRef> entitlement_value_cftype( SecTaskCopyValueForEntitlement(task, CFSTR("keychain-access-groups"), nullptr)); if (!entitlement_value_cftype) { @@ -62,7 +62,7 @@ base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::MAY_BLOCK); - base::ScopedCFTypeRef<CFMutableDictionaryRef> params( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> params( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -73,15 +73,15 @@ CFDictionarySetValue(params, kSecAttrTokenID, kSecAttrTokenIDSecureEnclave); CFDictionarySetValue(params, kSecAttrIsPermanent, kCFBooleanFalse); - base::ScopedCFTypeRef<CFErrorRef> cferr; - base::ScopedCFTypeRef<SecKeyRef> private_key( + base::apple::ScopedCFTypeRef<CFErrorRef> cferr; + base::apple::ScopedCFTypeRef<SecKeyRef> private_key( Keychain::GetInstance().KeyCreateRandomKey(params, cferr.InitializeInto())); return !!private_key; } -base::ScopedCFTypeRef<SecAccessControlRef> CreateDefaultAccessControl() { - return base::ScopedCFTypeRef<SecAccessControlRef>( +base::apple::ScopedCFTypeRef<SecAccessControlRef> CreateDefaultAccessControl() { + return base::apple::ScopedCFTypeRef<SecAccessControlRef>( SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, kSecAccessControlPrivateKeyUsage | kSecAccessControlUserPresence, @@ -171,7 +171,7 @@ // SecAccessControl, but for older credentials we used kSecAttrAccessControl // attribute to ensure the keychain would only produce signatures in exchange // for biometrics or device password. - base::ScopedCFTypeRef<SecAccessControlRef> access_control = + base::apple::ScopedCFTypeRef<SecAccessControlRef> access_control = CreateDefaultAccessControl(); [context_ evaluateAccessControl:access_control operation:LAAccessControlOperationUseKeySign
diff --git a/device/fido/mac/util.mm b/device/fido/mac/util.mm index 72696a6..c8c58dded 100644 --- a/device/fido/mac/util.mm +++ b/device/fido/mac/util.mm
@@ -26,7 +26,7 @@ namespace device::fido::mac { -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; using cbor::Value; using cbor::Writer; @@ -163,12 +163,12 @@ } CodeSigningState ProcessIsSigned() { - base::ScopedCFTypeRef<SecTaskRef> task(SecTaskCreateFromSelf(nullptr)); + base::apple::ScopedCFTypeRef<SecTaskRef> task(SecTaskCreateFromSelf(nullptr)); if (!task) { return CodeSigningState::kNotSigned; } - base::ScopedCFTypeRef<CFStringRef> sign_id( + base::apple::ScopedCFTypeRef<CFStringRef> sign_id( SecTaskCopySigningIdentifier(task.get(), /*error=*/nullptr)); return static_cast<bool>(sign_id) ? CodeSigningState::kSigned : CodeSigningState::kNotSigned;
diff --git a/device/gamepad/gamepad_device_mac.mm b/device/gamepad/gamepad_device_mac.mm index 47599af..d10175e 100644 --- a/device/gamepad/gamepad_device_mac.mm +++ b/device/gamepad/gamepad_device_mac.mm
@@ -179,8 +179,9 @@ } bool GamepadDeviceMac::AddButtons(Gamepad* gamepad) { - base::ScopedCFTypeRef<CFArrayRef> elements(IOHIDDeviceCopyMatchingElements( - device_ref_, /*matching=*/nullptr, kIOHIDOptionsTypeNone)); + base::apple::ScopedCFTypeRef<CFArrayRef> elements( + IOHIDDeviceCopyMatchingElements(device_ref_, /*matching=*/nullptr, + kIOHIDOptionsTypeNone)); DCHECK(elements); DCHECK(gamepad); memset(gamepad->buttons, 0, sizeof(gamepad->buttons)); @@ -259,8 +260,9 @@ } bool GamepadDeviceMac::AddAxes(Gamepad* gamepad) { - base::ScopedCFTypeRef<CFArrayRef> elements(IOHIDDeviceCopyMatchingElements( - device_ref_, nullptr, kIOHIDOptionsTypeNone)); + base::apple::ScopedCFTypeRef<CFArrayRef> elements( + IOHIDDeviceCopyMatchingElements(device_ref_, nullptr, + kIOHIDOptionsTypeNone)); DCHECK(elements); DCHECK(gamepad); memset(gamepad->axes, 0, sizeof(gamepad->axes));
diff --git a/device/gamepad/gamepad_platform_data_fetcher_mac.h b/device/gamepad/gamepad_platform_data_fetcher_mac.h index 36eab98..21244c5 100644 --- a/device/gamepad/gamepad_platform_data_fetcher_mac.h +++ b/device/gamepad/gamepad_platform_data_fetcher_mac.h
@@ -95,7 +95,7 @@ bool enabled_ = false; bool paused_ = false; - base::ScopedCFTypeRef<IOHIDManagerRef> hid_manager_ref_; + base::apple::ScopedCFTypeRef<IOHIDManagerRef> hid_manager_ref_; // A map of all devices using this data fetcher with the source_id as the key. std::unordered_map<int, std::unique_ptr<GamepadDeviceMac>> devices_;
diff --git a/device/gamepad/xbox_controller_mac.h b/device/gamepad/xbox_controller_mac.h index 8c56b9b..57511eb2 100644 --- a/device/gamepad/xbox_controller_mac.h +++ b/device/gamepad/xbox_controller_mac.h
@@ -175,7 +175,7 @@ bool device_is_open_ = false; bool interface_is_open_ = false; - base::ScopedCFTypeRef<CFRunLoopSourceRef> source_; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> source_; // This will be set to the max packet size reported by the interface, which // is 32 bytes. I would have expected USB to do message framing itself, but
diff --git a/device/gamepad/xbox_data_fetcher_mac.cc b/device/gamepad/xbox_data_fetcher_mac.cc index c2862ce..01e7845b 100644 --- a/device/gamepad/xbox_data_fetcher_mac.cc +++ b/device/gamepad/xbox_data_fetcher_mac.cc
@@ -131,7 +131,7 @@ io_service_t ref; while ((ref = IOIteratorNext(iterator))) { base::mac::ScopedIOObject<io_service_t> scoped_ref(ref); - base::ScopedCFTypeRef<CFNumberRef> number( + base::apple::ScopedCFTypeRef<CFNumberRef> number( base::apple::CFCastStrict<CFNumberRef>(IORegistryEntryCreateCFProperty( ref, CFSTR(kUSBDevicePropertyLocationID), kCFAllocatorDefault, kNilOptions))); @@ -210,11 +210,11 @@ bool XboxDataFetcher::RegisterForDeviceNotifications(int vendor_id, int product_id) { - base::ScopedCFTypeRef<CFNumberRef> vendor_cf( + base::apple::ScopedCFTypeRef<CFNumberRef> vendor_cf( CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vendor_id)); - base::ScopedCFTypeRef<CFNumberRef> product_cf( + base::apple::ScopedCFTypeRef<CFNumberRef> product_cf( CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &product_id)); - base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( IOServiceMatching(kIOUSBDeviceClassName)); if (!matching_dict) return false;
diff --git a/docs/android_build_instructions.md b/docs/android_build_instructions.md index d219ea3..4af92b2 100644 --- a/docs/android_build_instructions.md +++ b/docs/android_build_instructions.md
@@ -333,7 +333,7 @@ ```shell export CHROMIUM_LOGCAT_HIGHLIGHT='(WARNING|cr_Child)' -out/Default.bin/chrome_public_apk logcat +out/Default/bin/chrome_public_apk logcat # Highlights messages/tags containing WARNING and cr_Child strings. ```
diff --git a/docs/experiments/compression-dictionary-transport.md b/docs/experiments/compression-dictionary-transport.md index 4ad1f764..81ea2376 100644 --- a/docs/experiments/compression-dictionary-transport.md +++ b/docs/experiments/compression-dictionary-transport.md
@@ -12,7 +12,8 @@ Starting from version 117, Chrome experimentally supports Compression Dictionary Transport feature. This feature adds support for using designated previous -responses, as an external dictionary for Brotli-compressing HTTP responses. +responses, as an external dictionary for Brotli- or Zstandard-compressed HTTP +responses. ## Activation @@ -145,8 +146,11 @@ ## Supported compression scheme -Currently Chrome only supports Shared Brotli. Supporting Zstandard's shared -dictionary is tracked at [crbug.com/1462543][zstd-issue]. +Chrome 117.0.5857.0 introduced support for Shared Brotli, and Chrome +118.0.5952.0 adds support for Shared Zstandard. + +Shared Zstandard can be enabled/disabled from +[chrome://flags/#enable-shared-zstd][shared-zstd-flag]. ## Debugging @@ -180,10 +184,10 @@ [explainer]: https://github.com/WICG/compression-dictionary-transport [flag]: chrome://flags/#enable-compression-dictionary-transport [backend-flag]: chrome://flags/#enable-compression-dictionary-transport-backend +[shared-zstd-flag]: chrome://flags/#enable-shared-zstd [shared_dictionary_readme]: ../../services/network/shared_dictionary/README.md#flags [ot-blog]: https://developer.chrome.com/blog/origin-trials/ [ot-console]: https://developer.chrome.com/origintrials/#/trials/active -[zstd-issue]: https://crbug.com/1462543 [third-party-ot-dd]: https://docs.google.com/document/d/1xALH9W7rWmX0FpjudhDeS2TNTEOXuPn4Tlc9VmuPdHA/edit#heading=h.bvw2lcb2dczg [httpbis-draft]: https://datatracker.ietf.org/doc/draft-meenan-httpbis-compression-dictionary/ [net-internals-sd]: chrome://net-internals/#sharedDictionary
diff --git a/extensions/browser/path_util.cc b/extensions/browser/path_util.cc index c1efc3bf..870d0f3 100644 --- a/extensions/browser/path_util.cc +++ b/extensions/browser/path_util.cc
@@ -28,14 +28,15 @@ // Retrieves the localized display name for the base name of the given path. // If the path is not localized, this will just return the base name. std::string GetDisplayBaseName(const base::FilePath& path) { - base::ScopedCFTypeRef<CFURLRef> url(CFURLCreateFromFileSystemRepresentation( - nullptr, (const UInt8*)path.value().c_str(), path.value().length(), - /*isDirectory=*/true)); + base::apple::ScopedCFTypeRef<CFURLRef> url( + CFURLCreateFromFileSystemRepresentation( + nullptr, (const UInt8*)path.value().c_str(), path.value().length(), + /*isDirectory=*/true)); if (!url) { return path.BaseName().value(); } - base::ScopedCFTypeRef<CFStringRef> str; + base::apple::ScopedCFTypeRef<CFStringRef> str; if (!CFURLCopyResourcePropertyForKey(url, kCFURLLocalizedNameKey, str.InitializeInto(), /*error=*/nullptr)) {
diff --git a/gpu/command_buffer/service/shared_image/iosurface_image_backing.mm b/gpu/command_buffer/service/shared_image/iosurface_image_backing.mm index d083e94..ee5ff253 100644 --- a/gpu/command_buffer/service/shared_image/iosurface_image_backing.mm +++ b/gpu/command_buffer/service/shared_image/iosurface_image_backing.mm
@@ -556,7 +556,7 @@ SharedImageBacking* backing, MemoryTypeTracker* tracker, wgpu::Device device, - base::ScopedCFTypeRef<IOSurfaceRef> io_surface, + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface, const gfx::Size& io_surface_size, wgpu::TextureFormat wgpu_format, std::vector<wgpu::TextureFormat> view_formats)
diff --git a/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm b/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm index f384c54..5a698b0 100644 --- a/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm +++ b/gpu/command_buffer/service/shared_image/iosurface_image_backing_factory.mm
@@ -54,7 +54,7 @@ } #if BUILDFLAG(IS_MAC) - base::ScopedCFTypeRef<CFDataRef> cf_data = + base::apple::ScopedCFTypeRef<CFDataRef> cf_data = gfx::DisplayICCProfiles::GetInstance()->GetDataForColorSpace(color_space); if (cf_data) { IOSurfaceSetValue(io_surface, CFSTR("IOSurfaceColorSpace"), cf_data);
diff --git a/gpu/command_buffer/tests/gl_manager.cc b/gpu/command_buffer/tests/gl_manager.cc index a01573c..06a224ca 100644 --- a/gpu/command_buffer/tests/gl_manager.cc +++ b/gpu/command_buffer/tests/gl_manager.cc
@@ -171,7 +171,7 @@ private: bool mapped_; - base::ScopedCFTypeRef<IOSurfaceRef> iosurface_; + base::apple::ScopedCFTypeRef<IOSurfaceRef> iosurface_; const gfx::Size size_; gfx::BufferFormat format_; };
diff --git a/gpu/ipc/common/gpu_memory_buffer_impl_io_surface.h b/gpu/ipc/common/gpu_memory_buffer_impl_io_surface.h index 74ac49d8..a70a992 100644 --- a/gpu/ipc/common/gpu_memory_buffer_impl_io_surface.h +++ b/gpu/ipc/common/gpu_memory_buffer_impl_io_surface.h
@@ -60,7 +60,7 @@ IOSurfaceRef io_surface, uint32_t lock_flags); - base::ScopedCFTypeRef<IOSurfaceRef> io_surface_; + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface_; uint32_t lock_flags_; // Cache the color space, because re-assigning the same value can be // expensive.
diff --git a/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc b/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc index 268ca5d..e9bfc8b 100644 --- a/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc +++ b/gpu/ipc/service/gpu_memory_buffer_factory_io_surface.cc
@@ -40,7 +40,7 @@ DCHECK_EQ(framebuffer_size, size); bool should_clear = true; - base::ScopedCFTypeRef<IOSurfaceRef> io_surface = + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface = gfx::CreateIOSurface(size, format, should_clear); if (!io_surface) { LOG(ERROR) << "Failed to allocate IOSurface.";
diff --git a/headless/lib/browser/policy/headless_browser_policy_connector.cc b/headless/lib/browser/policy/headless_browser_policy_connector.cc index b795792c..d69175ce 100644 --- a/headless/lib/browser/policy/headless_browser_policy_connector.cc +++ b/headless/lib/browser/policy/headless_browser_policy_connector.cc
@@ -141,7 +141,7 @@ // policies. CFStringRef bundle_id = CFSTR("com.google.Chrome"); #else - base::ScopedCFTypeRef<CFStringRef> bundle_id( + base::apple::ScopedCFTypeRef<CFStringRef> bundle_id( base::SysUTF8ToCFStringRef(base::apple::BaseBundleID())); #endif auto loader = std::make_unique<PolicyLoaderMac>(
diff --git a/infra/config/generated/builders/ci/Linux TSan Builder/properties.json b/infra/config/generated/builders/ci/Linux TSan Builder/properties.json index 2ea3288..28e840d 100644 --- a/infra/config/generated/builders/ci/Linux TSan Builder/properties.json +++ b/infra/config/generated/builders/ci/Linux TSan Builder/properties.json
@@ -74,6 +74,10 @@ { "builder": "linux_chromium_tsan_rel_ng", "group": "tryserver.chromium.linux" + }, + { + "builder": "linux_chromium_tsan_siso_rel_ng", + "group": "tryserver.chromium.linux" } ] }
diff --git a/infra/config/generated/builders/ci/Linux TSan Tests/properties.json b/infra/config/generated/builders/ci/Linux TSan Tests/properties.json index 30992758..0dbc904 100644 --- a/infra/config/generated/builders/ci/Linux TSan Tests/properties.json +++ b/infra/config/generated/builders/ci/Linux TSan Tests/properties.json
@@ -67,6 +67,10 @@ { "builder": "linux_chromium_tsan_rel_ng", "group": "tryserver.chromium.linux" + }, + { + "builder": "linux_chromium_tsan_siso_rel_ng", + "group": "tryserver.chromium.linux" } ] }
diff --git a/infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng-compilator/properties.json b/infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng-compilator/properties.json new file mode 100644 index 0000000..ba594c5 --- /dev/null +++ b/infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng-compilator/properties.json
@@ -0,0 +1,105 @@ +{ + "$build/chromium_tests_builder_config": { + "builder_config": { + "builder_db": { + "entries": [ + { + "builder_id": { + "bucket": "ci", + "builder": "Linux TSan Builder", + "project": "chromium" + }, + "builder_spec": { + "build_gs_bucket": "chromium-memory-archive", + "builder_group": "chromium.memory", + "execution_mode": "COMPILE_AND_TEST", + "legacy_chromium_config": { + "apply_configs": [ + "mb" + ], + "build_config": "Release", + "config": "chromium_tsan2", + "target_bits": 64 + }, + "legacy_gclient_config": { + "config": "chromium" + } + } + }, + { + "builder_id": { + "bucket": "ci", + "builder": "Linux TSan Tests", + "project": "chromium" + }, + "builder_spec": { + "build_gs_bucket": "chromium-memory-archive", + "builder_group": "chromium.memory", + "execution_mode": "TEST", + "legacy_chromium_config": { + "apply_configs": [ + "mb" + ], + "build_config": "Release", + "config": "chromium_tsan2", + "target_bits": 64 + }, + "legacy_gclient_config": { + "config": "chromium" + }, + "parent": { + "bucket": "ci", + "builder": "Linux TSan Builder", + "project": "chromium" + } + } + } + ] + }, + "builder_ids": [ + { + "bucket": "ci", + "builder": "Linux TSan Builder", + "project": "chromium" + } + ], + "builder_ids_in_scope_for_testing": [ + { + "bucket": "ci", + "builder": "Linux TSan Tests", + "project": "chromium" + } + ], + "is_compile_only": true, + "rts_config": { + "condition": "QUICK_RUN_ONLY" + } + } + }, + "$build/flakiness": { + "check_for_flakiness": true, + "check_for_flakiness_with_resultdb": true + }, + "$build/reclient": { + "instance": "rbe-chromium-untrusted", + "jobs": 500, + "metrics_project": "chromium-reclient-metrics", + "scandeps_server": true + }, + "$build/siso": { + "configs": null, + "enable_cloud_profiler": true, + "enable_cloud_trace": true, + "experiments": [], + "project": "rbe-chromium-untrusted" + }, + "$recipe_engine/resultdb/test_presentation": { + "column_keys": [], + "grouping_keys": [ + "status", + "v.test_suite" + ] + }, + "builder_group": "tryserver.chromium.linux", + "recipe": "chromium/compilator" +} \ No newline at end of file
diff --git a/infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng/properties.json b/infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng/properties.json new file mode 100644 index 0000000..eaca6e9 --- /dev/null +++ b/infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng/properties.json
@@ -0,0 +1,97 @@ +{ + "$build/chromium_orchestrator": { + "compilator": "linux_chromium_tsan_siso_rel_ng-compilator", + "compilator_watcher_git_revision": "e6d08be3fd589d4f222dae5d18dbc972e6117b23" + }, + "$build/chromium_tests_builder_config": { + "builder_config": { + "builder_db": { + "entries": [ + { + "builder_id": { + "bucket": "ci", + "builder": "Linux TSan Builder", + "project": "chromium" + }, + "builder_spec": { + "build_gs_bucket": "chromium-memory-archive", + "builder_group": "chromium.memory", + "execution_mode": "COMPILE_AND_TEST", + "legacy_chromium_config": { + "apply_configs": [ + "mb" + ], + "build_config": "Release", + "config": "chromium_tsan2", + "target_bits": 64 + }, + "legacy_gclient_config": { + "config": "chromium" + } + } + }, + { + "builder_id": { + "bucket": "ci", + "builder": "Linux TSan Tests", + "project": "chromium" + }, + "builder_spec": { + "build_gs_bucket": "chromium-memory-archive", + "builder_group": "chromium.memory", + "execution_mode": "TEST", + "legacy_chromium_config": { + "apply_configs": [ + "mb" + ], + "build_config": "Release", + "config": "chromium_tsan2", + "target_bits": 64 + }, + "legacy_gclient_config": { + "config": "chromium" + }, + "parent": { + "bucket": "ci", + "builder": "Linux TSan Builder", + "project": "chromium" + } + } + } + ] + }, + "builder_ids": [ + { + "bucket": "ci", + "builder": "Linux TSan Builder", + "project": "chromium" + } + ], + "builder_ids_in_scope_for_testing": [ + { + "bucket": "ci", + "builder": "Linux TSan Tests", + "project": "chromium" + } + ], + "is_compile_only": true, + "rts_config": { + "condition": "QUICK_RUN_ONLY" + } + } + }, + "$build/flakiness": { + "check_for_flakiness": true, + "check_for_flakiness_with_resultdb": true + }, + "$recipe_engine/resultdb/test_presentation": { + "column_keys": [], + "grouping_keys": [ + "status", + "v.test_suite" + ] + }, + "builder_group": "tryserver.chromium.linux", + "cq": "required", + "recipe": "chromium/orchestrator" +} \ No newline at end of file
diff --git a/infra/config/generated/cq-builders.md b/infra/config/generated/cq-builders.md index 7fbf55f..bd3dcb5 100644 --- a/infra/config/generated/cq-builders.md +++ b/infra/config/generated/cq-builders.md
@@ -600,6 +600,9 @@ * [linux_chromium_asan_siso_rel_ng](https://ci.chromium.org/p/chromium/builders/try/linux_chromium_asan_siso_rel_ng) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""linux_chromium_asan_siso_rel_ng"")) * Experiment percentage: 20.0 +* [linux_chromium_tsan_siso_rel_ng](https://ci.chromium.org/p/chromium/builders/try/linux_chromium_tsan_siso_rel_ng) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""linux_chromium_tsan_siso_rel_ng"")) + * Experiment percentage: 20.0 + * [mac13-arm64-rel](https://ci.chromium.org/p/chromium/builders/try/mac13-arm64-rel) ([definition](https://cs.chromium.org/search?q=+file:/try/.*\.star$+""mac13-arm64-rel"")) * Experiment percentage: 100.0
diff --git a/infra/config/generated/luci/commit-queue.cfg b/infra/config/generated/luci/commit-queue.cfg index 2801537..8c2121c 100644 --- a/infra/config/generated/luci/commit-queue.cfg +++ b/infra/config/generated/luci/commit-queue.cfg
@@ -3724,6 +3724,31 @@ includable_only: true } builders { + name: "chromium/try/linux_chromium_tsan_siso_rel_ng" + experiment_percentage: 20 + location_filters { + gerrit_host_regexp: ".*" + gerrit_project_regexp: ".*" + path_regexp: "docs/.+" + exclude: true + } + location_filters { + gerrit_host_regexp: ".*" + gerrit_project_regexp: ".*" + path_regexp: "infra/config/.+" + exclude: true + } + location_filters { + gerrit_host_regexp: ".*" + gerrit_project_regexp: ".*" + path_regexp: "infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng/.+" + } + } + builders { + name: "chromium/try/linux_chromium_tsan_siso_rel_ng-compilator" + includable_only: true + } + builders { name: "chromium/try/linux_chromium_ubsan_rel_ng" includable_only: true }
diff --git a/infra/config/generated/luci/cr-buildbucket.cfg b/infra/config/generated/luci/cr-buildbucket.cfg index 6d7e2b66..a97620c 100644 --- a/infra/config/generated/luci/cr-buildbucket.cfg +++ b/infra/config/generated/luci/cr-buildbucket.cfg
@@ -62684,7 +62684,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/android-12-x64-siso-rel-compilator\">android-12-x64-siso-rel-compilator</a>." + description_html: "This builder shadows android-12-x64-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating android-12-x64-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/android-12-x64-siso-rel-compilator\">android-12-x64-siso-rel-compilator</a>." } builders { name: "android-12-x64-siso-rel-compilator" @@ -63491,7 +63491,7 @@ use_invocation_timestamp: true } } - description_html: "This builder may trigger tests on multiple Android versions.<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/android-arm64-siso-rel-compilator\">android-arm64-siso-rel-compilator</a>." + description_html: "This builder shadows android-arm64-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating android-arm64-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/android-arm64-siso-rel-compilator\">android-arm64-siso-rel-compilator</a>." } builders { name: "android-arm64-siso-rel-compilator" @@ -66650,7 +66650,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/android-nougat-x86-siso-rel-compilator\">android-nougat-x86-siso-rel-compilator</a>." + description_html: "This builder shadows android-nougat-x86-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating android-nougat-x86-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/android-nougat-x86-siso-rel-compilator\">android-nougat-x86-siso-rel-compilator</a>." } builders { name: "android-nougat-x86-siso-rel-compilator" @@ -69905,7 +69905,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/chromeos-amd64-generic-siso-rel-compilator\">chromeos-amd64-generic-siso-rel-compilator</a>." + description_html: "This builder shadows chromeos-amd64-generic-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating chromeos-amd64-generic-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/chromeos-amd64-generic-siso-rel-compilator\">chromeos-amd64-generic-siso-rel-compilator</a>." } builders { name: "chromeos-amd64-generic-siso-rel-compilator" @@ -73465,7 +73465,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/fuchsia-x64-cast-receiver-siso-rel-compilator\">fuchsia-x64-cast-receiver-siso-rel-compilator</a>." + description_html: "This builder shadows fuchsia-x64-cast-receiver-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating fuchsia-x64-cast-receiver-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/fuchsia-x64-cast-receiver-siso-rel-compilator\">fuchsia-x64-cast-receiver-siso-rel-compilator</a>." } builders { name: "fuchsia-x64-cast-receiver-siso-rel-compilator" @@ -82156,7 +82156,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-chromeos-siso-rel-compilator\">linux-chromeos-siso-rel-compilator</a>." + description_html: "This builder shadows linux-chromeos-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating linux-chromeos-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-chromeos-siso-rel-compilator\">linux-chromeos-siso-rel-compilator</a>." } builders { name: "linux-chromeos-siso-rel-compilator" @@ -84399,7 +84399,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-lacros-siso-rel-compilator\">linux-lacros-siso-rel-compilator</a>." + description_html: "This builder shadows linux-lacros-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating linux-lacros-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-lacros-siso-rel-compilator\">linux-lacros-siso-rel-compilator</a>." } builders { name: "linux-lacros-siso-rel-compilator" @@ -85676,7 +85676,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-siso-rel-compilator\">linux-siso-rel-compilator</a>." + description_html: "This builder shadows linux-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating linux-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-siso-rel-compilator\">linux-siso-rel-compilator</a>." } builders { name: "linux-siso-rel-compilator" @@ -86969,7 +86969,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-wayland-siso-rel-compilator\">linux-wayland-siso-rel-compilator</a>." + description_html: "This builder shadows linux-wayland-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating linux-wayland-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux-wayland-siso-rel-compilator\">linux-wayland-siso-rel-compilator</a>." } builders { name: "linux-wayland-siso-rel-compilator" @@ -88250,7 +88250,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux_chromium_asan_siso_rel_ng-compilator\">linux_chromium_asan_siso_rel_ng-compilator</a>." + description_html: "This builder shadows linux_chromium_asan_rel_ng builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating linux_chromium_asan_rel_ng from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux_chromium_asan_siso_rel_ng-compilator\">linux_chromium_asan_siso_rel_ng-compilator</a>." } builders { name: "linux_chromium_asan_siso_rel_ng-compilator" @@ -89346,6 +89346,196 @@ description_html: "This is the compilator half of an orchestrator + compilator pair of builders. The orchestrator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux_chromium_tsan_rel_ng\">linux_chromium_tsan_rel_ng</a>." } builders { + name: "linux_chromium_tsan_siso_rel_ng" + swarming_host: "chromium-swarm.appspot.com" + dimensions: "builder:linux_chromium_tsan_siso_rel_ng" + dimensions: "cores:2" + dimensions: "cpu:x86-64" + dimensions: "os:Ubuntu-22.04" + dimensions: "pool:luci.chromium.try" + exe { + cipd_package: "infra/chromium/bootstrapper/${platform}" + cipd_version: "latest" + cmd: "bootstrapper" + } + properties: + '{' + ' "$bootstrap/exe": {' + ' "exe": {' + ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' + ' "cipd_version": "refs/heads/main",' + ' "cmd": [' + ' "luciexe"' + ' ]' + ' }' + ' },' + ' "$bootstrap/properties": {' + ' "properties_file": "infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng/properties.json",' + ' "top_level_project": {' + ' "ref": "refs/heads/main",' + ' "repo": {' + ' "host": "chromium.googlesource.com",' + ' "project": "chromium/src"' + ' }' + ' }' + ' },' + ' "builder_group": "tryserver.chromium.linux",' + ' "cq": "required",' + ' "led_builder_is_bootstrapped": true,' + ' "recipe": "chromium/orchestrator"' + '}' + execution_timeout_secs: 14400 + expiration_secs: 7200 + grace_period { + seconds: 120 + } + build_numbers: YES + service_account: "chromium-orchestrator@chops-service-accounts.iam.gserviceaccount.com" + task_template_canary_percentage { + value: 5 + } + experiments { + key: "chromium.add_one_test_shard" + value: 10 + } + experiments { + key: "chromium_rts.inverted_rts" + value: 100 + } + experiments { + key: "chromium_swarming.expose_merge_script_failures" + value: 100 + } + experiments { + key: "luci.recipes.use_python3" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "try_test_results" + test_results {} + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "gpu_try_test_results" + test_results { + predicate { + test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" + } + } + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "blink_web_tests_try_test_results" + test_results { + predicate { + test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + description_html: "This builder shadows linux_chromium_tsan_rel_ng builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating linux_chromium_tsan_rel_ng from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux_chromium_tsan_siso_rel_ng-compilator\">linux_chromium_tsan_siso_rel_ng-compilator</a>." + } + builders { + name: "linux_chromium_tsan_siso_rel_ng-compilator" + swarming_host: "chromium-swarm.appspot.com" + dimensions: "builder:linux_chromium_tsan_siso_rel_ng-compilator" + dimensions: "cores:8" + dimensions: "cpu:x86-64" + dimensions: "os:Ubuntu-22.04" + dimensions: "pool:luci.chromium.try" + dimensions: "ssd:1" + exe { + cipd_package: "infra/chromium/bootstrapper/${platform}" + cipd_version: "latest" + cmd: "bootstrapper" + } + properties: + '{' + ' "$bootstrap/exe": {' + ' "exe": {' + ' "cipd_package": "infra/recipe_bundles/chromium.googlesource.com/chromium/tools/build",' + ' "cipd_version": "refs/heads/main",' + ' "cmd": [' + ' "luciexe"' + ' ]' + ' }' + ' },' + ' "$bootstrap/properties": {' + ' "properties_file": "infra/config/generated/builders/try/linux_chromium_tsan_siso_rel_ng-compilator/properties.json",' + ' "top_level_project": {' + ' "ref": "refs/heads/main",' + ' "repo": {' + ' "host": "chromium.googlesource.com",' + ' "project": "chromium/src"' + ' }' + ' }' + ' },' + ' "builder_group": "tryserver.chromium.linux",' + ' "led_builder_is_bootstrapped": true,' + ' "recipe": "chromium/compilator"' + '}' + execution_timeout_secs: 14400 + expiration_secs: 7200 + grace_period { + seconds: 120 + } + build_numbers: YES + service_account: "chromium-try-builder@chops-service-accounts.iam.gserviceaccount.com" + task_template_canary_percentage { + value: 5 + } + experiments { + key: "chromium_swarming.expose_merge_script_failures" + value: 100 + } + experiments { + key: "luci.recipes.use_python3" + value: 100 + } + resultdb { + enable: true + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "try_test_results" + test_results {} + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "gpu_try_test_results" + test_results { + predicate { + test_id_regexp: "ninja://chrome/test:telemetry_gpu_integration_test[^/]*/.+" + } + } + } + bq_exports { + project: "chrome-luci-data" + dataset: "chromium" + table: "blink_web_tests_try_test_results" + test_results { + predicate { + test_id_regexp: "(ninja://[^/]*blink_web_tests/.+)|(ninja://[^/]*blink_wpt_tests/.+)" + } + } + } + history_options { + use_invocation_timestamp: true + } + } + description_html: "This is the compilator half of an orchestrator + compilator pair of builders. The orchestrator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/linux_chromium_tsan_siso_rel_ng\">linux_chromium_tsan_siso_rel_ng</a>." + } + builders { name: "linux_chromium_ubsan_rel_ng" swarming_host: "chromium-swarm.appspot.com" dimensions: "builderless:1" @@ -96856,7 +97046,7 @@ use_invocation_timestamp: true } } - description_html: "This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/win-siso-rel-compilator\">win-siso-rel-compilator</a>." + description_html: "This builder shadows win-rel builder to compare between Siso builds and Ninja builds.<br/>\nThis builder should be removed after migrating win-rel from Ninja to Siso. b/277863839\n<br/>This is the orchestrator half of an orchestrator + compilator pair of builders. The compilator is <a href=\"https://ci.chromium.org/p/chromium/builders/try/win-siso-rel-compilator\">win-siso-rel-compilator</a>." } builders { name: "win-siso-rel-compilator"
diff --git a/infra/config/generated/luci/luci-milo.cfg b/infra/config/generated/luci/luci-milo.cfg index e3f8cff..d2486fa 100644 --- a/infra/config/generated/luci/luci-milo.cfg +++ b/infra/config/generated/luci/luci-milo.cfg
@@ -3241,6 +3241,12 @@ name: "buildbucket/luci.chromium.try/linux_chromium_tsan_rel_ng-compilator" } builders { + name: "buildbucket/luci.chromium.try/linux_chromium_tsan_siso_rel_ng" + } + builders { + name: "buildbucket/luci.chromium.try/linux_chromium_tsan_siso_rel_ng-compilator" + } + builders { name: "buildbucket/luci.chromium.try/linux_optional_gpu_tests_rel" } builders { @@ -18201,6 +18207,12 @@ name: "buildbucket/luci.chromium.try/linux_chromium_tsan_rel_ng-compilator" } builders { + name: "buildbucket/luci.chromium.try/linux_chromium_tsan_siso_rel_ng" + } + builders { + name: "buildbucket/luci.chromium.try/linux_chromium_tsan_siso_rel_ng-compilator" + } + builders { name: "buildbucket/luci.chromium.try/linux_chromium_ubsan_rel_ng" } builders { @@ -19434,6 +19446,12 @@ name: "buildbucket/luci.chromium.try/linux_chromium_tsan_rel_ng-compilator" } builders { + name: "buildbucket/luci.chromium.try/linux_chromium_tsan_siso_rel_ng" + } + builders { + name: "buildbucket/luci.chromium.try/linux_chromium_tsan_siso_rel_ng-compilator" + } + builders { name: "buildbucket/luci.chromium.try/linux_chromium_ubsan_rel_ng" } builders {
diff --git a/infra/config/generated/testing/variants.pyl b/infra/config/generated/testing/variants.pyl index ab75cd9..7ceb1d1 100644 --- a/infra/config/generated/testing/variants.pyl +++ b/infra/config/generated/testing/variants.pyl
@@ -16,16 +16,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'identifier': 'Lacros version skew testing ash canary', - 'description': 'Run with ash-chrome version 118.0.5962.0', + 'description': 'Run with ash-chrome version 118.0.5963.0', 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome', ], 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v118.0.5962.0', - 'revision': 'version:118.0.5962.0', + 'location': 'lacros_version_skew_tests_v118.0.5963.0', + 'revision': 'version:118.0.5963.0', }, ], },
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star index 91ca742..c04e507 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.android.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.android.star
@@ -87,10 +87,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# android-12-x64-rel to Siso. try_.orchestrator_builder( name = "android-12-x64-siso-rel", + description_html = """\ +This builder shadows android-12-x64-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating android-12-x64-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/android-12-x64-rel"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -165,11 +167,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# android-arm64-rel to Siso. try_.orchestrator_builder( name = "android-arm64-siso-rel", - description_html = "This builder may trigger tests on multiple Android versions.", + description_html = """\ +This builder shadows android-arm64-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating android-arm64-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/android-arm64-rel"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -421,10 +424,12 @@ mirrors = builder_config.copy_from("try/android-pie-x86-rel"), ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# android-nougat-x86-rel to Siso. try_.orchestrator_builder( name = "android-nougat-x86-siso-rel", + description_html = """\ +This builder shadows android-nougat-x86-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating android-nougat-x86-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/android-nougat-x86-rel"), try_settings = builder_config.try_settings( is_compile_only = True,
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.chromiumos.star b/infra/config/subprojects/chromium/try/tryserver.chromium.chromiumos.star index 6f15fb8..697de81 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.chromiumos.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.chromiumos.star
@@ -78,10 +78,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# chromeos-amd64-generic-rel to Siso. try_.orchestrator_builder( name = "chromeos-amd64-generic-siso-rel", + description_html = """\ +This builder shadows chromeos-amd64-generic-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating chromeos-amd64-generic-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/chromeos-amd64-generic-rel"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -292,10 +294,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# linux-chromeos-rel to Siso. try_.orchestrator_builder( name = "linux-chromeos-siso-rel", + description_html = """\ +This builder shadows linux-chromeos-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating linux-chromeos-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/linux-chromeos-rel"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -352,10 +356,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# linux-lacros-rel to Siso. try_.orchestrator_builder( name = "linux-lacros-siso-rel", + description_html = """\ +This builder shadows linux-lacros-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating linux-lacros-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/linux-lacros-rel"), try_settings = builder_config.try_settings( is_compile_only = True,
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.fuchsia.star b/infra/config/subprojects/chromium/try/tryserver.chromium.fuchsia.star index bc247cd3..3f78652 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.fuchsia.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.fuchsia.star
@@ -155,10 +155,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# fuchsia-x64-cast-receiver-rel to Siso. try_.orchestrator_builder( name = "fuchsia-x64-cast-receiver-siso-rel", + description_html = """\ +This builder shadows fuchsia-x64-cast-receiver-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating fuchsia-x64-cast-receiver-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/fuchsia-x64-cast-receiver-rel"), try_settings = builder_config.try_settings( is_compile_only = True,
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star index a810938..90d3a7d9 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.linux.star
@@ -266,10 +266,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate linux-rel -# to Siso. try_.orchestrator_builder( name = "linux-siso-rel", + description_html = """\ +This builder shadows linux-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating linux-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/linux-rel"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -337,10 +339,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# linux-wayland-rel to Siso. try_.orchestrator_builder( name = "linux-wayland-siso-rel", + description_html = """\ +This builder shadows linux-wayland-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating linux-wayland-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/linux-wayland-rel"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -493,10 +497,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# linux_chromium_asan_rel_ng to Siso. try_.orchestrator_builder( name = "linux_chromium_asan_siso_rel_ng", + description_html = """\ +This builder shadows linux_chromium_asan_rel_ng builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating linux_chromium_asan_rel_ng from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/linux_chromium_asan_rel_ng"), try_settings = builder_config.try_settings( is_compile_only = True, @@ -678,6 +684,37 @@ main_list_view = "try", ) +try_.orchestrator_builder( + name = "linux_chromium_tsan_siso_rel_ng", + description_html = """\ +This builder shadows linux_chromium_tsan_rel_ng builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating linux_chromium_tsan_rel_ng from Ninja to Siso. b/277863839 +""", + mirrors = builder_config.copy_from("try/linux_chromium_tsan_rel_ng"), + try_settings = builder_config.try_settings( + is_compile_only = True, + rts_config = builder_config.rts_config( + condition = builder_config.rts_condition.QUICK_RUN_ONLY, + ), + ), + compilator = "linux_chromium_tsan_siso_rel_ng-compilator", + experiments = { + "chromium_rts.inverted_rts": 100, + # go/nplus1shardsproposal + "chromium.add_one_test_shard": 10, + }, + main_list_view = "try", + tryjob = try_.job( + experiment_percentage = 20, + ), +) + +try_.compilator_builder( + name = "linux_chromium_tsan_siso_rel_ng-compilator", + main_list_view = "try", + siso_enabled = True, +) + try_.builder( name = "linux_chromium_ubsan_rel_ng", mirrors = [
diff --git a/infra/config/subprojects/chromium/try/tryserver.chromium.win.star b/infra/config/subprojects/chromium/try/tryserver.chromium.win.star index cdd8d4c..a7171648 100644 --- a/infra/config/subprojects/chromium/try/tryserver.chromium.win.star +++ b/infra/config/subprojects/chromium/try/tryserver.chromium.win.star
@@ -106,10 +106,12 @@ main_list_view = "try", ) -# TODO(b/277863839): remove Siso experimental builders after migrate -# win-rel to Siso. try_.orchestrator_builder( name = "win-siso-rel", + description_html = """\ +This builder shadows win-rel builder to compare between Siso builds and Ninja builds.<br/> +This builder should be removed after migrating win-rel from Ninja to Siso. b/277863839 +""", mirrors = builder_config.copy_from("try/win-rel"), try_settings = builder_config.try_settings( is_compile_only = True,
diff --git a/infra/config/targets/lacros-version-skew-variants.json b/infra/config/targets/lacros-version-skew-variants.json index 461729f..7ce5437a 100644 --- a/infra/config/targets/lacros-version-skew-variants.json +++ b/infra/config/targets/lacros-version-skew-variants.json
@@ -1,16 +1,16 @@ { "LACROS_VERSION_SKEW_CANARY": { "args": [ - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "identifier": "Lacros version skew testing ash canary", "swarming": { "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ] }
diff --git a/ios/chrome/browser/snapshots/snapshot_cache_unittest.mm b/ios/chrome/browser/snapshots/snapshot_cache_unittest.mm index 2e08b9e0..d36e99a 100644 --- a/ios/chrome/browser/snapshots/snapshot_cache_unittest.mm +++ b/ios/chrome/browser/snapshots/snapshot_cache_unittest.mm
@@ -331,7 +331,7 @@ CGImageRef cgImage = [image CGImage]; ASSERT_TRUE(cgImage != nullptr); - base::ScopedCFTypeRef<CFDataRef> pixelData( + base::apple::ScopedCFTypeRef<CFDataRef> pixelData( CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); const char* pixels = reinterpret_cast<const char*>(CFDataGetBytePtr(pixelData)); @@ -339,7 +339,7 @@ UIImage* referenceImage = [testImages_ objectAtIndex:i]; CGImageRef referenceCgImage = [referenceImage CGImage]; - base::ScopedCFTypeRef<CFDataRef> referenceData( + base::apple::ScopedCFTypeRef<CFDataRef> referenceData( CGDataProviderCopyData(CGImageGetDataProvider(referenceCgImage))); const char* referencePixels = reinterpret_cast<const char*>(CFDataGetBytePtr(referenceData));
diff --git a/ios/components/credential_provider_extension/password_util_unittest.mm b/ios/components/credential_provider_extension/password_util_unittest.mm index c9799a49..e639317 100644 --- a/ios/components/credential_provider_extension/password_util_unittest.mm +++ b/ios/components/credential_provider_extension/password_util_unittest.mm
@@ -38,7 +38,7 @@ void AddPasswordForKey(NSString* key, NSString* password) { std::string utf8_password = base::SysNSStringToUTF8(password); - base::ScopedCFTypeRef<CFDataRef> data(CFDataCreate( + base::apple::ScopedCFTypeRef<CFDataRef> data(CFDataCreate( nullptr, reinterpret_cast<const UInt8*>(utf8_password.data()), utf8_password.size())); @@ -60,7 +60,7 @@ (__bridge NSString*)kSecAttrAccount : KeyWithPrefix(key), (__bridge NSString*)kSecReturnData : @YES, }; - base::ScopedCFTypeRef<CFTypeRef> cf_result; + base::apple::ScopedCFTypeRef<CFTypeRef> cf_result; OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, cf_result.InitializeInto()); ASSERT_EQ(errSecItemNotFound, status);
diff --git a/ios/web/navigation/crw_wk_navigation_handler.mm b/ios/web/navigation/crw_wk_navigation_handler.mm index 24b6778a..d91c9fe 100644 --- a/ios/web/navigation/crw_wk_navigation_handler.mm +++ b/ios/web/navigation/crw_wk_navigation_handler.mm
@@ -1023,8 +1023,8 @@ } SecTrustRef trust = challenge.protectionSpace.serverTrust; - base::ScopedCFTypeRef<SecTrustRef> scopedTrust(trust, - base::scoped_policy::RETAIN); + base::apple::ScopedCFTypeRef<SecTrustRef> scopedTrust( + trust, base::scoped_policy::RETAIN); __weak CRWWKNavigationHandler* weakSelf = self; [self.certVerificationController decideLoadPolicyForTrust:scopedTrust @@ -1656,20 +1656,20 @@ // iOS 15. scoped_refptr<net::X509Certificate> leafCert = nil; if (@available(iOS 15.0, *)) { - base::ScopedCFTypeRef<CFArrayRef> certificateChain( + base::apple::ScopedCFTypeRef<CFArrayRef> certificateChain( SecTrustCopyCertificateChain(trust)); SecCertificateRef secCertificate = base::apple::CFCastStrict<SecCertificateRef>( CFArrayGetValueAtIndex(certificateChain, 0)); leafCert = net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>(secCertificate, - base::scoped_policy::RETAIN), + base::apple::ScopedCFTypeRef<SecCertificateRef>( + secCertificate, base::scoped_policy::RETAIN), {}); } #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0 else { leafCert = net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>( + base::apple::ScopedCFTypeRef<SecCertificateRef>( SecTrustGetCertificateAtIndex(trust, 0), base::scoped_policy::RETAIN), {});
diff --git a/ios/web/security/crw_cert_verification_controller.h b/ios/web/security/crw_cert_verification_controller.h index 644c5c0..7c481050 100644 --- a/ios/web/security/crw_cert_verification_controller.h +++ b/ios/web/security/crw_cert_verification_controller.h
@@ -60,7 +60,8 @@ // compatible form (e.g. for "http://名がドメイン.com", it should be // "xn--v8jxj3d1dzdz08w.com"). `completionHandler` cannot be null and will be // called asynchronously on the UI thread. -- (void)decideLoadPolicyForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust +- (void)decideLoadPolicyForTrust: + (base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(web::PolicyDecisionHandler)completionHandler; @@ -72,7 +73,7 @@ // It is possible for an untrusted certificate to return a net::CertStatus with // no errors if the cause could not be determined. Callers must handle this case // gracefully. -- (void)querySSLStatusForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust +- (void)querySSLStatusForTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(web::StatusQueryHandler)completionHandler; @end
diff --git a/ios/web/security/crw_cert_verification_controller.mm b/ios/web/security/crw_cert_verification_controller.mm index 8a8cb40..a77729f 100644 --- a/ios/web/security/crw_cert_verification_controller.mm +++ b/ios/web/security/crw_cert_verification_controller.mm
@@ -33,28 +33,31 @@ // Returns cert status for the given `trust`. - (net::CertStatus)certStatusFromTrustResult:(SecTrustResultType)trustResult - trustError:(base::ScopedCFTypeRef<CFErrorRef>) - trustError; + trustError: + (base::apple::ScopedCFTypeRef<CFErrorRef>) + trustError; // Decides the policy for the given `trust` which was rejected by iOS and the // given `host` and calls `handler` on completion. Must be called on UI thread. // `handler` can not be null and will be called on UI thread. - (void) decideLoadPolicyForRejectedTrustResult:(SecTrustResultType)trustResult - trustError:(base::ScopedCFTypeRef<CFErrorRef>) - trustError + trustError: + (base::apple::ScopedCFTypeRef<CFErrorRef>) + trustError serverTrust: - (base::ScopedCFTypeRef<SecTrustRef>)trust + (base::apple::ScopedCFTypeRef<SecTrustRef>) + trust host:(NSString*)host completionHandler:(web::PolicyDecisionHandler)handler; // Verifies the given `trust` using SecTrustRef API. `completionHandler` cannot // be null and will be called on UI thread or never be called if the worker task // can't start or complete. Must be called on UI thread. -- (void)verifyTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust +- (void)verifyTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust completionHandler: (void (^)(SecTrustResultType, - base::ScopedCFTypeRef<CFErrorRef>))completionHandler; + base::apple::ScopedCFTypeRef<CFErrorRef>))completionHandler; // Returns cert accept policy for the given SecTrust result. `trustResult` must // not be for a valid cert. Must be called on IO thread. @@ -81,7 +84,8 @@ return self; } -- (void)decideLoadPolicyForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust +- (void)decideLoadPolicyForTrust: + (base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(web::PolicyDecisionHandler)completionHandler { DCHECK_CURRENTLY_ON(WebThread::UI); @@ -89,7 +93,7 @@ [self verifyTrust:trust completionHandler:^(SecTrustResultType trustResult, - base::ScopedCFTypeRef<CFErrorRef> trustError) { + base::apple::ScopedCFTypeRef<CFErrorRef> trustError) { DCHECK_CURRENTLY_ON(WebThread::UI); if (trustResult == kSecTrustResultProceed || trustResult == kSecTrustResultUnspecified) { @@ -104,7 +108,7 @@ }]; } -- (void)querySSLStatusForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust +- (void)querySSLStatusForTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(web::StatusQueryHandler)completionHandler { DCHECK_CURRENTLY_ON(WebThread::UI); @@ -112,7 +116,7 @@ [self verifyTrust:trust completionHandler:^(SecTrustResultType trustResult, - base::ScopedCFTypeRef<CFErrorRef> trustError) { + base::apple::ScopedCFTypeRef<CFErrorRef> trustError) { web::SecurityStyle securityStyle = web::GetSecurityStyleFromTrustResult(trustResult); @@ -125,8 +129,9 @@ #pragma mark - Private - (net::CertStatus)certStatusFromTrustResult:(SecTrustResultType)trustResult - trustError:(base::ScopedCFTypeRef<CFErrorRef>) - trustError { + trustError: + (base::apple::ScopedCFTypeRef<CFErrorRef>) + trustError { net::CertStatus certStatus = net::CertStatus(); switch (trustResult) { case kSecTrustResultProceed: @@ -147,10 +152,12 @@ - (void) decideLoadPolicyForRejectedTrustResult:(SecTrustResultType)trustResult - trustError:(base::ScopedCFTypeRef<CFErrorRef>) - trustError + trustError: + (base::apple::ScopedCFTypeRef<CFErrorRef>) + trustError serverTrust: - (base::ScopedCFTypeRef<SecTrustRef>)trust + (base::apple::ScopedCFTypeRef<SecTrustRef>) + trust host:(NSString*)host completionHandler:(web::PolicyDecisionHandler)handler { DCHECK_CURRENTLY_ON(WebThread::UI); @@ -181,10 +188,10 @@ })); } -- (void)verifyTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust +- (void)verifyTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust completionHandler: (void (^)(SecTrustResultType, - base::ScopedCFTypeRef<CFErrorRef>))completionHandler { + base::apple::ScopedCFTypeRef<CFErrorRef>))completionHandler { DCHECK_CURRENTLY_ON(WebThread::UI); DCHECK(completionHandler); // SecTrustEvaluate performs trust evaluation synchronously, possibly making @@ -192,7 +199,7 @@ base::ThreadPool::PostTask( FROM_HERE, {TaskShutdownBehavior::BLOCK_SHUTDOWN}, base::BindOnce(^{ SecTrustResultType trustResult = kSecTrustResultInvalid; - base::ScopedCFTypeRef<CFErrorRef> trustError; + base::apple::ScopedCFTypeRef<CFErrorRef> trustError; bool isTrusted = SecTrustEvaluateWithError(trust.get(), trustError.InitializeInto()); if (SecTrustGetTrustResult(trust.get(), &trustResult) != errSecSuccess) @@ -229,20 +236,20 @@ // iOS 15. scoped_refptr<net::X509Certificate> leafCert = nil; if (@available(iOS 15.0, *)) { - base::ScopedCFTypeRef<CFArrayRef> certificateChain( + base::apple::ScopedCFTypeRef<CFArrayRef> certificateChain( SecTrustCopyCertificateChain(trust)); SecCertificateRef secCertificate = base::apple::CFCastStrict<SecCertificateRef>( CFArrayGetValueAtIndex(certificateChain, 0)); leafCert = net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>(secCertificate, - base::scoped_policy::RETAIN), + base::apple::ScopedCFTypeRef<SecCertificateRef>( + secCertificate, base::scoped_policy::RETAIN), {}); } #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0 else { leafCert = net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>( + base::apple::ScopedCFTypeRef<SecCertificateRef>( SecTrustGetCertificateAtIndex(trust, 0), base::scoped_policy::RETAIN), {});
diff --git a/ios/web/security/crw_cert_verification_controller_unittest.mm b/ios/web/security/crw_cert_verification_controller_unittest.mm index 569e5a97..7010afb 100644 --- a/ios/web/security/crw_cert_verification_controller_unittest.mm +++ b/ios/web/security/crw_cert_verification_controller_unittest.mm
@@ -40,7 +40,7 @@ net::ImportCertFromFile(net::GetTestCertsDirectory(), kCertFileName); ASSERT_TRUE(cert_); - base::ScopedCFTypeRef<CFMutableArrayRef> chain( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> chain( net::x509_util::CreateSecCertificateArrayForX509Certificate( cert_.get())); ASSERT_TRUE(chain); @@ -53,7 +53,7 @@ // Synchronously returns result of // decideLoadPolicyForTrust:host:completionHandler: call. - void DecidePolicy(const base::ScopedCFTypeRef<SecTrustRef>& trust, + void DecidePolicy(const base::apple::ScopedCFTypeRef<SecTrustRef>& trust, NSString* host, web::CertAcceptPolicy* policy, net::CertStatus* status) { @@ -75,7 +75,7 @@ // Synchronously returns result of // querySSLStatusForTrust:host:completionHandler: call. - void QueryStatus(const base::ScopedCFTypeRef<SecTrustRef>& trust, + void QueryStatus(const base::apple::ScopedCFTypeRef<SecTrustRef>& trust, NSString* host, SecurityStyle* style, net::CertStatus* status) { @@ -95,8 +95,8 @@ } scoped_refptr<net::X509Certificate> cert_; - base::ScopedCFTypeRef<SecTrustRef> valid_trust_; - base::ScopedCFTypeRef<SecTrustRef> invalid_trust_; + base::apple::ScopedCFTypeRef<SecTrustRef> valid_trust_; + base::apple::ScopedCFTypeRef<SecTrustRef> invalid_trust_; CRWCertVerificationController* controller_; }; @@ -137,7 +137,7 @@ TEST_F(CRWCertVerificationControllerTest, PolicyForNullTrust) { web::CertAcceptPolicy policy = CERT_ACCEPT_POLICY_ALLOW; net::CertStatus status; - base::ScopedCFTypeRef<SecTrustRef> null_trust; + base::apple::ScopedCFTypeRef<SecTrustRef> null_trust; DecidePolicy(null_trust, kHostName, &policy, &status); EXPECT_EQ(CERT_ACCEPT_POLICY_NON_RECOVERABLE_ERROR, policy); EXPECT_EQ(net::CERT_STATUS_INVALID, status);
diff --git a/ios/web/security/crw_ssl_status_updater.h b/ios/web/security/crw_ssl_status_updater.h index 0c2bf27..e3e62a81 100644 --- a/ios/web/security/crw_ssl_status_updater.h +++ b/ios/web/security/crw_ssl_status_updater.h
@@ -38,11 +38,12 @@ // Updates SSL status for the current navigation item. The SSL Status is // obtained from `host`, `chain` and `hasOnlySecureContent` flag. -- (void)updateSSLStatusForNavigationItem:(web::NavigationItem*)navigationItem - withCertHost:(NSString*)host - trust: - (base::ScopedCFTypeRef<SecTrustRef>)trust - hasOnlySecureContent:(BOOL)hasOnlySecureContent; +- (void) + updateSSLStatusForNavigationItem:(web::NavigationItem*)navigationItem + withCertHost:(NSString*)host + trust:(base::apple::ScopedCFTypeRef<SecTrustRef>) + trust + hasOnlySecureContent:(BOOL)hasOnlySecureContent; @end @@ -59,7 +60,7 @@ // `completionHandler` is called asynchronously when web::SecurityStyle and // net::CertStatus are computed. - (void)SSLStatusUpdater:(CRWSSLStatusUpdater*)SSLStatusUpdater - querySSLStatusForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust + querySSLStatusForTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(StatusQueryHandler)completionHandler;
diff --git a/ios/web/security/crw_ssl_status_updater.mm b/ios/web/security/crw_ssl_status_updater.mm index a1e2ebc..56ecdea 100644 --- a/ios/web/security/crw_ssl_status_updater.mm +++ b/ios/web/security/crw_ssl_status_updater.mm
@@ -13,7 +13,7 @@ #import "net/cert/x509_certificate.h" #import "url/gurl.h" -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; using net::CertStatus; using web::SecurityStyle;
diff --git a/ios/web/security/crw_ssl_status_updater_unittest.mm b/ios/web/security/crw_ssl_status_updater_unittest.mm index 37145d82..453d9af4 100644 --- a/ios/web/security/crw_ssl_status_updater_unittest.mm +++ b/ios/web/security/crw_ssl_status_updater_unittest.mm
@@ -52,7 +52,7 @@ #pragma mark CRWSSLStatusUpdaterDataSource - (void)SSLStatusUpdater:(CRWSSLStatusUpdater*)SSLStatusUpdater - querySSLStatusForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust + querySSLStatusForTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(StatusQueryHandler)completionHandler { _verificationCompletionHandler = [completionHandler copy]; @@ -100,7 +100,7 @@ scoped_refptr<net::X509Certificate> cert = net::ImportCertFromFile(net::GetTestCertsDirectory(), kCertFileName); ASSERT_TRUE(cert); - base::ScopedCFTypeRef<CFMutableArrayRef> chain( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> chain( net::x509_util::CreateSecCertificateArrayForX509Certificate( cert.get())); ASSERT_TRUE(chain); @@ -131,7 +131,7 @@ std::unique_ptr<NavigationManagerImpl> nav_manager_; FakeNavigationManagerDelegate fake_nav_delegate_; CRWSSLStatusUpdater* ssl_status_updater_; - base::ScopedCFTypeRef<SecTrustRef> trust_; + base::apple::ScopedCFTypeRef<SecTrustRef> trust_; }; // Tests that CRWSSLStatusUpdater init returns non nil object. @@ -193,7 +193,8 @@ [ssl_status_updater_ updateSSLStatusForNavigationItem:item withCertHost:kHostName - trust:base::ScopedCFTypeRef<SecTrustRef>() + trust:base::apple::ScopedCFTypeRef< + SecTrustRef>() hasOnlySecureContent:YES]; // No certificate. EXPECT_FALSE(!!item->GetSSL().certificate);
diff --git a/ios/web/security/wk_web_view_security_util.h b/ios/web/security/wk_web_view_security_util.h index 733bff5..bc9cc3e0 100644 --- a/ios/web/security/wk_web_view_security_util.h +++ b/ios/web/security/wk_web_view_security_util.h
@@ -36,8 +36,9 @@ // Returns null if `certs` is null or empty. // TODO(crbug.com/827554): This method is only used from tests and should be // removed from here. -base::ScopedCFTypeRef<SecTrustRef> CreateServerTrustFromChain(NSArray* certs, - NSString* host); +base::apple::ScopedCFTypeRef<SecTrustRef> CreateServerTrustFromChain( + NSArray* certs, + NSString* host); // Makes SecTrustEvaluate call to return kSecTrustResultProceed. // Should be called only if the user expilitely agreed to proceed with `trust`
diff --git a/ios/web/security/wk_web_view_security_util.mm b/ios/web/security/wk_web_view_security_util.mm index 99db7fe..c9331208 100644 --- a/ios/web/security/wk_web_view_security_util.mm +++ b/ios/web/security/wk_web_view_security_util.mm
@@ -49,13 +49,13 @@ scoped_refptr<net::X509Certificate> CreateCertFromChain(NSArray* certs) { if (certs.count == 0) return nullptr; - std::vector<base::ScopedCFTypeRef<SecCertificateRef>> intermediates; + std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>> intermediates; for (NSUInteger i = 1; i < certs.count; i++) { - base::ScopedCFTypeRef<SecCertificateRef> cert( + base::apple::ScopedCFTypeRef<SecCertificateRef> cert( (__bridge SecCertificateRef)certs[i], base::scoped_policy::RETAIN); intermediates.push_back(cert); } - base::ScopedCFTypeRef<SecCertificateRef> root_cert( + base::apple::ScopedCFTypeRef<SecCertificateRef> root_cert( (__bridge SecCertificateRef)certs[0], base::scoped_policy::RETAIN); return net::x509_util::CreateX509CertificateFromSecCertificate( std::move(root_cert), intermediates); @@ -71,12 +71,12 @@ return nullptr; } - std::vector<base::ScopedCFTypeRef<SecCertificateRef>> intermediates; + std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>> intermediates; // TODO(crbug.com/1418068): Remove available and compile guard after minimum // version required is >= iOS 15. if (@available(iOS 15.0, *)) { - base::ScopedCFTypeRef<CFArrayRef> certificateChain( + base::apple::ScopedCFTypeRef<CFArrayRef> certificateChain( SecTrustCopyCertificateChain(trust)); for (CFIndex i = 1; i < cert_count; i++) { SecCertificateRef secCertificate = @@ -88,8 +88,8 @@ base::apple::CFCastStrict<SecCertificateRef>( CFArrayGetValueAtIndex(certificateChain, 0)); return net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>(secCertificate, - base::scoped_policy::RETAIN), + base::apple::ScopedCFTypeRef<SecCertificateRef>( + secCertificate, base::scoped_policy::RETAIN), intermediates); } #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0 @@ -99,7 +99,7 @@ base::scoped_policy::RETAIN); } return net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>( + base::apple::ScopedCFTypeRef<SecCertificateRef>( SecTrustGetCertificateAtIndex(trust, 0), base::scoped_policy::RETAIN), intermediates); @@ -109,17 +109,18 @@ // removed when compile and available guards are cleaned up. NOTREACHED(); return net::x509_util::CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef>(nullptr), intermediates); + base::apple::ScopedCFTypeRef<SecCertificateRef>(nullptr), intermediates); #endif // __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0 } -base::ScopedCFTypeRef<SecTrustRef> CreateServerTrustFromChain(NSArray* certs, - NSString* host) { - base::ScopedCFTypeRef<SecTrustRef> scoped_result; +base::apple::ScopedCFTypeRef<SecTrustRef> CreateServerTrustFromChain( + NSArray* certs, + NSString* host) { + base::apple::ScopedCFTypeRef<SecTrustRef> scoped_result; if (certs.count == 0) return scoped_result; - base::ScopedCFTypeRef<SecPolicyRef> policy( + base::apple::ScopedCFTypeRef<SecPolicyRef> policy( SecPolicyCreateSSL(TRUE, static_cast<CFStringRef>(host))); SecTrustRef ref_result = nullptr; if (SecTrustCreateWithCertificates((__bridge CFArrayRef)certs, policy, @@ -130,7 +131,8 @@ } void EnsureFutureTrustEvaluationSucceeds(SecTrustRef trust) { - base::ScopedCFTypeRef<CFDataRef> exceptions(SecTrustCopyExceptions(trust)); + base::apple::ScopedCFTypeRef<CFDataRef> exceptions( + SecTrustCopyExceptions(trust)); SecTrustSetExceptions(trust, exceptions); }
diff --git a/ios/web/security/wk_web_view_security_util_unittest.mm b/ios/web/security/wk_web_view_security_util_unittest.mm index 13e129f..efac82c8 100644 --- a/ios/web/security/wk_web_view_security_util_unittest.mm +++ b/ios/web/security/wk_web_view_security_util_unittest.mm
@@ -37,7 +37,7 @@ "CN=" + subject, 1, base::Time::Now(), base::Time::Now() + base::Days(1), &private_key, &der_cert); - base::ScopedCFTypeRef<SecCertificateRef> cert( + base::apple::ScopedCFTypeRef<SecCertificateRef> cert( net::x509_util::CreateSecCertificateFromBytes( reinterpret_cast<const uint8_t*>(der_cert.data()), der_cert.size())); if (!cert) @@ -54,12 +54,12 @@ } // Returns SecTrustRef object for testing. -base::ScopedCFTypeRef<SecTrustRef> CreateTestTrust(NSArray* cert_chain) { - base::ScopedCFTypeRef<SecPolicyRef> policy(SecPolicyCreateBasicX509()); +base::apple::ScopedCFTypeRef<SecTrustRef> CreateTestTrust(NSArray* cert_chain) { + base::apple::ScopedCFTypeRef<SecPolicyRef> policy(SecPolicyCreateBasicX509()); SecTrustRef trust = nullptr; SecTrustCreateWithCertificates(base::apple::NSToCFPtrCast(cert_chain), policy, &trust); - return base::ScopedCFTypeRef<SecTrustRef>(trust); + return base::apple::ScopedCFTypeRef<SecTrustRef>(trust); } } // namespace @@ -88,7 +88,7 @@ // Tests MakeTrustValid with self-signed cert. TEST_F(WKWebViewSecurityUtilTest, MakingTrustValid) { // Create invalid trust object. - base::ScopedCFTypeRef<SecTrustRef> trust = + base::apple::ScopedCFTypeRef<SecTrustRef> trust = CreateTestTrust(MakeTestCertChain(kTestSubject)); CFErrorRef error; @@ -104,7 +104,7 @@ // Tests CreateCertFromTrust. TEST_F(WKWebViewSecurityUtilTest, CreationCertFromTrust) { - base::ScopedCFTypeRef<SecTrustRef> trust = + base::apple::ScopedCFTypeRef<SecTrustRef> trust = CreateTestTrust(MakeTestCertChain(kTestSubject)); scoped_refptr<net::X509Certificate> cert = CreateCertFromTrust(trust); ASSERT_TRUE(cert); @@ -120,7 +120,7 @@ TEST_F(WKWebViewSecurityUtilTest, CreationServerTrust) { // Create server trust. NSArray* chain = MakeTestCertChain(kTestSubject); - base::ScopedCFTypeRef<SecTrustRef> server_trust( + base::apple::ScopedCFTypeRef<SecTrustRef> server_trust( CreateServerTrustFromChain(chain, kTestHost)); EXPECT_TRUE(server_trust); @@ -132,7 +132,7 @@ // iOS 15. SecCertificateRef secCertificate = nil; if (@available(iOS 15.0, *)) { - base::ScopedCFTypeRef<CFArrayRef> certificateChain( + base::apple::ScopedCFTypeRef<CFArrayRef> certificateChain( SecTrustCopyCertificateChain(server_trust.get())); secCertificate = base::apple::CFCastStrict<SecCertificateRef>( CFArrayGetValueAtIndex(certificateChain, static_cast<CFIndex>(i))); @@ -149,12 +149,12 @@ }]; // Verify policies. - base::ScopedCFTypeRef<CFArrayRef> policies; + base::apple::ScopedCFTypeRef<CFArrayRef> policies; EXPECT_EQ(errSecSuccess, SecTrustCopyPolicies(server_trust.get(), policies.InitializeInto())); EXPECT_EQ(1, CFArrayGetCount(policies)); SecPolicyRef policy = (SecPolicyRef)CFArrayGetValueAtIndex(policies, 0); - base::ScopedCFTypeRef<CFDictionaryRef> properties( + base::apple::ScopedCFTypeRef<CFDictionaryRef> properties( SecPolicyCopyProperties(policy)); NSString* name = static_cast<NSString*>( CFDictionaryGetValue(properties.get(), kSecPolicyName));
diff --git a/ios/web/web_state/ui/crw_web_controller.mm b/ios/web/web_state/ui/crw_web_controller.mm index dc812d425..b36177c 100644 --- a/ios/web/web_state/ui/crw_web_controller.mm +++ b/ios/web/web_state/ui/crw_web_controller.mm
@@ -1433,7 +1433,7 @@ } NSString* host = base::SysUTF8ToNSString(_documentURL.host()); BOOL hasOnlySecureContent = [self.webView hasOnlySecureContent]; - base::ScopedCFTypeRef<SecTrustRef> trust; + base::apple::ScopedCFTypeRef<SecTrustRef> trust; trust.reset([self.webView serverTrust], base::scoped_policy::RETAIN); [_SSLStatusUpdater updateSSLStatusForNavigationItem:currentNavItem @@ -1622,7 +1622,7 @@ #pragma mark - CRWSSLStatusUpdaterDataSource - (void)SSLStatusUpdater:(CRWSSLStatusUpdater*)SSLStatusUpdater - querySSLStatusForTrust:(base::ScopedCFTypeRef<SecTrustRef>)trust + querySSLStatusForTrust:(base::apple::ScopedCFTypeRef<SecTrustRef>)trust host:(NSString*)host completionHandler:(StatusQueryHandler)completionHandler { [_certVerificationController querySSLStatusForTrust:std::move(trust)
diff --git a/media/audio/cras/cras_unified.cc b/media/audio/cras/cras_unified.cc index 5c06d03..8146022 100644 --- a/media/audio/cras/cras_unified.cc +++ b/media/audio/cras/cras_unified.cc
@@ -303,17 +303,22 @@ // Static callback asking for samples. int CrasUnifiedStream::UnifiedCallback(struct libcras_stream_cb_data* data) { - TRACE_EVENT_BEGIN("audio", "CrasUnifiedStream::UnifiedCallback"); unsigned int frames; uint8_t* buf; struct timespec latency; void* usr_arg; struct timespec underrun_duration_ts; + cras_stream_id_t stream_id; libcras_stream_cb_data_get_frames(data, &frames); libcras_stream_cb_data_get_buf(data, &buf); libcras_stream_cb_data_get_latency(data, &latency); libcras_stream_cb_data_get_usr_arg(data, &usr_arg); libcras_stream_cb_data_get_underrun_duration(data, &underrun_duration_ts); + libcras_stream_cb_data_get_stream_id(data, &stream_id); + TRACE_EVENT_BEGIN( + "audio", "CrasUnifiedStream::UnifiedCallback", + perfetto::Flow::ProcessScoped(static_cast<uint64_t>(stream_id))); + CrasUnifiedStream* me = static_cast<CrasUnifiedStream*>(usr_arg); base::TimeDelta underrun_duration = base::TimeDelta::FromTimeSpec(underrun_duration_ts); @@ -344,7 +349,6 @@ DCHECK_EQ(frames, static_cast<size_t>(output_bus_->frames())); const base::TimeDelta latency = base::TimeDelta::FromTimeSpec(*latency_ts); TRACE_EVENT("audio", "CrasUnifiedStream::WriteAudio", - perfetto::Flow::ProcessScoped(stream_id_), [&](perfetto::EventContext ctx) { auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
diff --git a/media/audio/mac/audio_low_latency_input_mac.cc b/media/audio/mac/audio_low_latency_input_mac.cc index 2e7d75d..9642854 100644 --- a/media/audio/mac/audio_low_latency_input_mac.cc +++ b/media/audio/mac/audio_low_latency_input_mac.cc
@@ -127,7 +127,7 @@ const AudioObjectPropertyAddress property_address = { kAudioAggregateDevicePropertyFullSubDeviceList, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; - base::ScopedCFTypeRef<CFArrayRef> subdevices; + base::apple::ScopedCFTypeRef<CFArrayRef> subdevices; UInt32 size = sizeof(subdevices); OSStatus result = AudioObjectGetPropertyData( aggregate_device_id, &property_address, 0 /* inQualifierDataSize */,
diff --git a/media/audio/mac/audio_manager_mac.cc b/media/audio/mac/audio_manager_mac.cc index ddddcfc4..f834373 100644 --- a/media/audio/mac/audio_manager_mac.cc +++ b/media/audio/mac/audio_manager_mac.cc
@@ -196,7 +196,7 @@ &audio_device_id); } else { // Non-default device. - base::ScopedCFTypeRef<CFStringRef> uid( + base::apple::ScopedCFTypeRef<CFStringRef> uid( base::SysUTF8ToCFStringRef(device_id)); AudioValueTranslation value; value.mInputData = &uid;
diff --git a/media/base/mac/color_space_util_mac.mm b/media/base/mac/color_space_util_mac.mm index d309f83..8bc8179 100644 --- a/media/base/mac/color_space_util_mac.mm +++ b/media/base/mac/color_space_util_mac.mm
@@ -267,10 +267,10 @@ } // anonymous namespace gfx::ColorSpace GetImageBufferColorSpace(CVImageBufferRef image_buffer) { - base::ScopedCFTypeRef<CFTypeRef> color_primaries; - base::ScopedCFTypeRef<CFTypeRef> transfer_function; - base::ScopedCFTypeRef<CFTypeRef> gamma_level; - base::ScopedCFTypeRef<CFTypeRef> ycbcr_matrix; + base::apple::ScopedCFTypeRef<CFTypeRef> color_primaries; + base::apple::ScopedCFTypeRef<CFTypeRef> transfer_function; + base::apple::ScopedCFTypeRef<CFTypeRef> gamma_level; + base::apple::ScopedCFTypeRef<CFTypeRef> ycbcr_matrix; if (@available(macOS 12, iOS 15, *)) { color_primaries.reset(CVBufferCopyAttachment(
diff --git a/media/base/mac/video_frame_mac.h b/media/base/mac/video_frame_mac.h index 6248638..354669b1 100644 --- a/media/base/mac/video_frame_mac.h +++ b/media/base/mac/video_frame_mac.h
@@ -23,7 +23,7 @@ // The only supported formats are I420 and NV12. Frames with extended pixels // (the visible rect's size does not match the coded size) are not supported. // If an unsupported frame is specified, null is returned. -MEDIA_EXPORT base::ScopedCFTypeRef<CVPixelBufferRef> +MEDIA_EXPORT base::apple::ScopedCFTypeRef<CVPixelBufferRef> WrapVideoFrameInCVPixelBuffer(scoped_refptr<VideoFrame> frame); } // namespace media
diff --git a/media/base/mac/video_frame_mac.mm b/media/base/mac/video_frame_mac.mm index ea92b7b..90b9251 100644 --- a/media/base/mac/video_frame_mac.mm +++ b/media/base/mac/video_frame_mac.mm
@@ -99,9 +99,9 @@ } // namespace -MEDIA_EXPORT base::ScopedCFTypeRef<CVPixelBufferRef> +MEDIA_EXPORT base::apple::ScopedCFTypeRef<CVPixelBufferRef> WrapVideoFrameInCVPixelBuffer(scoped_refptr<VideoFrame> frame) { - base::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer; if (!frame) { return pixel_buffer; } @@ -219,7 +219,7 @@ frame.get(), nullptr, pixel_buffer.InitializeInto()); if (result != kCVReturnSuccess) { DLOG(ERROR) << " CVPixelBufferCreateWithPlanarBytes failed: " << result; - return base::ScopedCFTypeRef<CVPixelBufferRef>(nullptr); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(nullptr); } // The CVPixelBuffer now references the data of the frame, so increment its
diff --git a/media/base/mac/video_frame_mac_unittests.cc b/media/base/mac/video_frame_mac_unittests.cc index 622bd51e..140068b 100644 --- a/media/base/mac/video_frame_mac_unittests.cc +++ b/media/base/mac/video_frame_mac_unittests.cc
@@ -115,7 +115,7 @@ }; for (const auto& format_pair : format_pairs) { - base::ScopedCFTypeRef<CVPixelBufferRef> pb; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pb; CVPixelBufferCreate(nullptr, kWidth, kHeight, format_pair.corevideo, nullptr, pb.InitializeInto()); ASSERT_TRUE(pb.get());
diff --git a/media/base/mac/videotoolbox_helpers.cc b/media/base/mac/videotoolbox_helpers.cc index 7427c64..1f33dd7 100644 --- a/media/base/mac/videotoolbox_helpers.cc +++ b/media/base/mac/videotoolbox_helpers.cc
@@ -21,26 +21,28 @@ static const char kAnnexBHeaderBytes[4] = {0, 0, 0, 1}; } // anonymous namespace -base::ScopedCFTypeRef<CFDictionaryRef> +base::apple::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeysAndValues(CFTypeRef* keys, CFTypeRef* values, size_t size) { - return base::ScopedCFTypeRef<CFDictionaryRef>(CFDictionaryCreate( + return base::apple::ScopedCFTypeRef<CFDictionaryRef>(CFDictionaryCreate( kCFAllocatorDefault, keys, values, size, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); } -base::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeyValue(CFTypeRef key, - CFTypeRef value) { +base::apple::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeyValue( + CFTypeRef key, + CFTypeRef value) { CFTypeRef keys[1] = {key}; CFTypeRef values[1] = {value}; return DictionaryWithKeysAndValues(keys, values, 1); } -base::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegers(const int* v, size_t size) { +base::apple::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegers(const int* v, + size_t size) { std::vector<CFNumberRef> numbers; numbers.reserve(size); for (const int* end = v + size; v < end; ++v) numbers.push_back(CFNumberCreate(nullptr, kCFNumberSInt32Type, v)); - base::ScopedCFTypeRef<CFArrayRef> array(CFArrayCreate( + base::apple::ScopedCFTypeRef<CFArrayRef> array(CFArrayCreate( kCFAllocatorDefault, reinterpret_cast<const void**>(&numbers[0]), numbers.size(), &kCFTypeArrayCallBacks)); for (auto* number : numbers) { @@ -49,12 +51,13 @@ return array; } -base::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegerAndFloat(int int_val, - float float_val) { +base::apple::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegerAndFloat( + int int_val, + float float_val) { std::array<CFNumberRef, 2> numbers = { {CFNumberCreate(nullptr, kCFNumberSInt32Type, &int_val), CFNumberCreate(nullptr, kCFNumberFloat32Type, &float_val)}}; - base::ScopedCFTypeRef<CFArrayRef> array(CFArrayCreate( + base::apple::ScopedCFTypeRef<CFArrayRef> array(CFArrayCreate( kCFAllocatorDefault, reinterpret_cast<const void**>(numbers.data()), numbers.size(), &kCFTypeArrayCallBacks)); for (auto* number : numbers) @@ -238,7 +241,7 @@ // Block buffers can be composed of non-contiguous chunks. For the sake of // keeping this code simple, flatten non-contiguous block buffers. - base::ScopedCFTypeRef<CMBlockBufferRef> contiguous_bb( + base::apple::ScopedCFTypeRef<CMBlockBufferRef> contiguous_bb( bb, base::scoped_policy::RETAIN); if (!CMBlockBufferIsRangeContiguous(bb, 0, 0)) { contiguous_bb.reset(); @@ -295,7 +298,7 @@ } SessionPropertySetter::SessionPropertySetter( - base::ScopedCFTypeRef<VTCompressionSessionRef> session) + base::apple::ScopedCFTypeRef<VTCompressionSessionRef> session) : session_(session) {} SessionPropertySetter::~SessionPropertySetter() {} @@ -312,7 +315,7 @@ bool SessionPropertySetter::Set(CFStringRef key, int32_t value) { DCHECK(session_); - base::ScopedCFTypeRef<CFNumberRef> cfvalue( + base::apple::ScopedCFTypeRef<CFNumberRef> cfvalue( CFNumberCreate(nullptr, kCFNumberSInt32Type, &value)); return VTSessionSetProperty(session_, key, cfvalue) == noErr; } @@ -325,7 +328,7 @@ bool SessionPropertySetter::Set(CFStringRef key, double value) { DCHECK(session_); - base::ScopedCFTypeRef<CFNumberRef> cfvalue( + base::apple::ScopedCFTypeRef<CFNumberRef> cfvalue( CFNumberCreate(nullptr, kCFNumberDoubleType, &value)); return VTSessionSetProperty(session_, key, cfvalue) == noErr; }
diff --git a/media/base/mac/videotoolbox_helpers.h b/media/base/mac/videotoolbox_helpers.h index bdce41b..5375beb 100644 --- a/media/base/mac/videotoolbox_helpers.h +++ b/media/base/mac/videotoolbox_helpers.h
@@ -17,20 +17,20 @@ namespace video_toolbox { // Create a CFDictionaryRef with the given keys and values. -MEDIA_EXPORT base::ScopedCFTypeRef<CFDictionaryRef> +MEDIA_EXPORT base::apple::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeysAndValues(CFTypeRef* keys, CFTypeRef* values, size_t size); // Create a CFDictionaryRef with the given key and value. -MEDIA_EXPORT base::ScopedCFTypeRef<CFDictionaryRef> DictionaryWithKeyValue( - CFTypeRef key, - CFTypeRef value); +MEDIA_EXPORT base::apple::ScopedCFTypeRef<CFDictionaryRef> +DictionaryWithKeyValue(CFTypeRef key, CFTypeRef value); // Create a CFArrayRef with the given array of integers. -MEDIA_EXPORT base::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegers(const int* v, - size_t size); +MEDIA_EXPORT base::apple::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegers( + const int* v, + size_t size); // Create a CFArrayRef with the given int and float values. -MEDIA_EXPORT base::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegerAndFloat( +MEDIA_EXPORT base::apple::ScopedCFTypeRef<CFArrayRef> ArrayWithIntegerAndFloat( int int_val, float float_val); @@ -50,7 +50,8 @@ // Helper class to add session properties to a VTCompressionSessionRef. class MEDIA_EXPORT SessionPropertySetter { public: - SessionPropertySetter(base::ScopedCFTypeRef<VTCompressionSessionRef> session); + SessionPropertySetter( + base::apple::ScopedCFTypeRef<VTCompressionSessionRef> session); ~SessionPropertySetter(); bool IsSupported(CFStringRef key); @@ -61,8 +62,8 @@ bool Set(CFStringRef key, CFArrayRef value); private: - base::ScopedCFTypeRef<VTCompressionSessionRef> session_; - base::ScopedCFTypeRef<CFDictionaryRef> supported_keys_; + base::apple::ScopedCFTypeRef<VTCompressionSessionRef> session_; + base::apple::ScopedCFTypeRef<CFDictionaryRef> supported_keys_; }; } // namespace video_toolbox
diff --git a/media/base/video_frame.cc b/media/base/video_frame.cc index ca501dc..664e57b0 100644 --- a/media/base/video_frame.cc +++ b/media/base/video_frame.cc
@@ -775,9 +775,10 @@ DLOG(ERROR) << "Failed to lock IOSurface."; return nullptr; } - auto unlock_lambda = [](base::ScopedCFTypeRef<IOSurfaceRef> io_surface) { - IOSurfaceUnlock(io_surface, kIOSurfaceLockReadOnly, nullptr); - }; + auto unlock_lambda = + [](base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface) { + IOSurfaceUnlock(io_surface, kIOSurfaceLockReadOnly, nullptr); + }; scoped_refptr<VideoFrame> frame = new VideoFrame(*layout, storage_type, visible_rect, size, timestamp);
diff --git a/media/base/video_frame.h b/media/base/video_frame.h index d399234..f3ac5cbd 100644 --- a/media/base/video_frame.h +++ b/media/base/video_frame.h
@@ -834,7 +834,7 @@ #if BUILDFLAG(IS_APPLE) // CVPixelBuffer, if this frame is wrapping one. - base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer_; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer_; #endif base::Lock done_callbacks_lock_;
diff --git a/media/capture/video/apple/gpu_memory_buffer_tracker_apple.cc b/media/capture/video/apple/gpu_memory_buffer_tracker_apple.cc index 770332c3..d176f20 100644 --- a/media/capture/video/apple/gpu_memory_buffer_tracker_apple.cc +++ b/media/capture/video/apple/gpu_memory_buffer_tracker_apple.cc
@@ -11,7 +11,7 @@ GpuMemoryBufferTrackerApple::GpuMemoryBufferTrackerApple() {} GpuMemoryBufferTrackerApple::GpuMemoryBufferTrackerApple( - base::ScopedCFTypeRef<IOSurfaceRef> io_surface) + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface) : is_external_io_surface_(true), io_surface_(std::move(io_surface)) {} GpuMemoryBufferTrackerApple::~GpuMemoryBufferTrackerApple() {}
diff --git a/media/capture/video/apple/gpu_memory_buffer_tracker_apple.h b/media/capture/video/apple/gpu_memory_buffer_tracker_apple.h index eeef7fb..a4b4f25 100644 --- a/media/capture/video/apple/gpu_memory_buffer_tracker_apple.h +++ b/media/capture/video/apple/gpu_memory_buffer_tracker_apple.h
@@ -16,7 +16,7 @@ public: GpuMemoryBufferTrackerApple(); explicit GpuMemoryBufferTrackerApple( - base::ScopedCFTypeRef<IOSurfaceRef> io_surface); + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface); GpuMemoryBufferTrackerApple(const GpuMemoryBufferTrackerApple&) = delete; GpuMemoryBufferTrackerApple& operator=(const GpuMemoryBufferTrackerApple&) =
diff --git a/media/capture/video/apple/pixel_buffer_pool.cc b/media/capture/video/apple/pixel_buffer_pool.cc index 1ab467f8..156ec55c 100644 --- a/media/capture/video/apple/pixel_buffer_pool.cc +++ b/media/capture/video/apple/pixel_buffer_pool.cc
@@ -26,11 +26,11 @@ private: T value_; - base::ScopedCFTypeRef<CFNumberRef> number_; + base::apple::ScopedCFTypeRef<CFNumberRef> number_; }; -base::ScopedCFTypeRef<CFDictionaryRef> CreateEmptyCFDictionary() { - return base::ScopedCFTypeRef<CFDictionaryRef>( +base::apple::ScopedCFTypeRef<CFDictionaryRef> CreateEmptyCFDictionary() { + return base::apple::ScopedCFTypeRef<CFDictionaryRef>( CFDictionaryCreate(nil, nil, nil, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); } @@ -52,7 +52,7 @@ sizeof(pixel_buffer_attribute_keys) / sizeof(pixel_buffer_attribute_keys[0]); // Rely on default IOSurface properties. - base::ScopedCFTypeRef<CFDictionaryRef> io_surface_options = + base::apple::ScopedCFTypeRef<CFDictionaryRef> io_surface_options = CreateEmptyCFDictionary(); CFNumber<int> pixel_buffer_format(kCFNumberSInt32Type, format); CFNumber<int> pixel_buffer_width(kCFNumberSInt32Type, width); @@ -64,7 +64,7 @@ sizeof(pixel_buffer_attribute_values) / sizeof(pixel_buffer_attribute_values[0]), "Key count and value count must match"); - base::ScopedCFTypeRef<CFDictionaryRef> pixel_buffer_attributes( + base::apple::ScopedCFTypeRef<CFDictionaryRef> pixel_buffer_attributes( CFDictionaryCreate(nil, (const void**)pixel_buffer_attribute_keys, (const void**)pixel_buffer_attribute_values, pixel_buffer_attribute_count, @@ -77,7 +77,7 @@ // kCVPixelBufferPoolMinimumBufferCountKey and // kCVPixelBufferPoolMaximumBufferAgeKey unless these are more auxiliary // attributes for CVPixelBufferPoolCreatePixelBufferWithAuxAttributes(). - base::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool; + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool; CVReturn pool_creation_error = CVPixelBufferPoolCreate( nil, nil, pixel_buffer_attributes.get(), buffer_pool.InitializeInto()); if (pool_creation_error != noErr) { @@ -90,7 +90,7 @@ } PixelBufferPool::PixelBufferPool( - base::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool, + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool, absl::optional<size_t> max_buffers) : buffer_pool_(std::move(buffer_pool)), max_buffers_(std::move(max_buffers)), @@ -103,9 +103,9 @@ Flush(); } -base::ScopedCFTypeRef<CVPixelBufferRef> PixelBufferPool::CreateBuffer() { +base::apple::ScopedCFTypeRef<CVPixelBufferRef> PixelBufferPool::CreateBuffer() { DCHECK(buffer_pool_); - base::ScopedCFTypeRef<CVPixelBufferRef> buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> buffer; CVReturn buffer_creation_error; if (!max_buffers_.has_value()) { buffer_creation_error = CVPixelBufferPoolCreatePixelBuffer( @@ -121,7 +121,7 @@ static_assert(attribute_count == sizeof(attribute_values) / sizeof(attribute_values[0]), "Key count and value count must match"); - base::ScopedCFTypeRef<CFDictionaryRef> attributes(CFDictionaryCreate( + base::apple::ScopedCFTypeRef<CFDictionaryRef> attributes(CFDictionaryCreate( nil, (const void**)attribute_keys, (const void**)attribute_values, attribute_count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -132,7 +132,7 @@ LOG(ERROR) << "Cannot exceed the pool's maximum buffer count"; // kCVReturnWouldExceedAllocationThreshold does not count as an error. num_consecutive_errors_ = 0; - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } // If a different error occurred, crash on debug builds or log and return null // on release builds. @@ -146,7 +146,7 @@ CHECK_LE(num_consecutive_errors_, kMaxNumConsecutiveErrors) << "Exceeded maximum allowed consecutive error count with error code: " << buffer_creation_error; - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } num_consecutive_errors_ = 0; return buffer;
diff --git a/media/capture/video/apple/pixel_buffer_pool.h b/media/capture/video/apple/pixel_buffer_pool.h index 6b329b2c..dd470b5b 100644 --- a/media/capture/video/apple/pixel_buffer_pool.h +++ b/media/capture/video/apple/pixel_buffer_pool.h
@@ -41,26 +41,27 @@ // // Retaining a pixel buffer and preventing it from returning to the pool can // be done either by keeping a reference directly to the CVPixelBuffer, e.g. - // with a base::ScopedCFTypeRef<CVPixelBufferRef>, or by incrementing the use - // count of the IOSurface, i.e. with IOSurfaceIncrementUseCount(). + // with a base::apple::ScopedCFTypeRef<CVPixelBufferRef>, or by incrementing + // the use count of the IOSurface, i.e. with IOSurfaceIncrementUseCount(). // // WARNING: Retaining references to the pixel buffer's IOSurface (e.g. with - // base::ScopedCFTypeRef<IOSurfaceRef>) without incrementing its use count - // does NOT prevent it from being recycled! - base::ScopedCFTypeRef<CVPixelBufferRef> CreateBuffer(); + // base::apple::ScopedCFTypeRef<IOSurfaceRef>) without incrementing its use + // count does NOT prevent it from being recycled! + base::apple::ScopedCFTypeRef<CVPixelBufferRef> CreateBuffer(); // Frees the memory of any released buffers returned to the pool. void Flush(); private: friend std::unique_ptr<PixelBufferPool> std::make_unique<PixelBufferPool>( - base::ScopedCFTypeRef<CVPixelBufferPoolRef>&& buffer_pool, + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef>&& buffer_pool, absl::optional<size_t>&& max_buffers); - PixelBufferPool(base::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool, - absl::optional<size_t> max_buffers); + PixelBufferPool( + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool, + absl::optional<size_t> max_buffers); - base::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool_; + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef> buffer_pool_; const absl::optional<size_t> max_buffers_; size_t num_consecutive_errors_; };
diff --git a/media/capture/video/apple/pixel_buffer_pool_unittest.mm b/media/capture/video/apple/pixel_buffer_pool_unittest.mm index cbdd222f..078e632 100644 --- a/media/capture/video/apple/pixel_buffer_pool_unittest.mm +++ b/media/capture/video/apple/pixel_buffer_pool_unittest.mm
@@ -29,7 +29,7 @@ TEST(PixelBufferPoolTest, CreatedBufferHasSpecifiedAttributes) { std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create(kPixelFormatNv12, kVgaWidth, kVgaHeight, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); EXPECT_TRUE(CVPixelBufferGetPixelFormatType(buffer) == kPixelFormatNv12); EXPECT_EQ(CVPixelBufferGetWidth(buffer), static_cast<size_t>(kVgaWidth)); EXPECT_EQ(CVPixelBufferGetHeight(buffer), static_cast<size_t>(kVgaHeight)); @@ -38,7 +38,7 @@ TEST(PixelBufferPoolTest, CreatedBufferHasIOSurface) { std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create(kPixelFormatNv12, kVgaWidth, kVgaHeight, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); EXPECT_TRUE(CVPixelBufferGetIOSurface(buffer)); } @@ -46,11 +46,14 @@ constexpr size_t kPoolMaxBuffers = 2; std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = + pool->CreateBuffer(); EXPECT_TRUE(first_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = + pool->CreateBuffer(); EXPECT_TRUE(second_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> third_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> third_buffer = + pool->CreateBuffer(); EXPECT_FALSE(third_buffer); } @@ -58,7 +61,8 @@ constexpr size_t kPoolMaxBuffers = 1; std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = + pool->CreateBuffer(); EXPECT_TRUE(first_buffer); IOSurfaceRef io_surface = CVPixelBufferGetIOSurface(first_buffer); EXPECT_TRUE(io_surface); @@ -67,7 +71,8 @@ IOSurfaceIncrementUseCount(io_surface); first_buffer.reset(); // The pixel buffer has not been returned to the pool. - base::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = + pool->CreateBuffer(); EXPECT_FALSE(second_buffer); // Cleanup. IOSurfaceDecrementUseCount(io_surface); @@ -76,11 +81,14 @@ TEST(PixelBufferPoolTest, CanCreateBuffersIfMaxIsNull) { std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, absl::nullopt); - base::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = + pool->CreateBuffer(); EXPECT_TRUE(first_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = + pool->CreateBuffer(); EXPECT_TRUE(second_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> third_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> third_buffer = + pool->CreateBuffer(); EXPECT_TRUE(third_buffer); } @@ -88,7 +96,7 @@ constexpr size_t kPoolMaxBuffers = 1; std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); buffer.reset(); buffer = pool->CreateBuffer(); EXPECT_TRUE(buffer); @@ -98,7 +106,8 @@ constexpr size_t kPoolMaxBuffers = 1; std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = + pool->CreateBuffer(); EXPECT_TRUE(first_buffer); IOSurfaceRef io_surface = CVPixelBufferGetIOSurface(first_buffer); EXPECT_TRUE(io_surface); @@ -107,7 +116,8 @@ // Decrementing the use count when there are no pixel buffer references // returns it to the pool. IOSurfaceDecrementUseCount(io_surface); - base::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = + pool->CreateBuffer(); EXPECT_TRUE(second_buffer); } @@ -116,18 +126,20 @@ constexpr size_t kPoolMaxBuffers = 1; std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = + pool->CreateBuffer(); EXPECT_TRUE(first_buffer); - base::ScopedCFTypeRef<IOSurfaceRef> first_buffer_io_surface( + base::apple::ScopedCFTypeRef<IOSurfaceRef> first_buffer_io_surface( CVPixelBufferGetIOSurface(first_buffer), base::scoped_policy::RETAIN); EXPECT_TRUE(first_buffer_io_surface); // Releasing the first buffer returns it to the pool, despite the IOSurface // still being referenced by |first_buffer_io_surface|. first_buffer.reset(); - base::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = + pool->CreateBuffer(); EXPECT_TRUE(second_buffer); - base::ScopedCFTypeRef<IOSurfaceRef> second_buffer_io_surface( + base::apple::ScopedCFTypeRef<IOSurfaceRef> second_buffer_io_surface( CVPixelBufferGetIOSurface(second_buffer), base::scoped_policy::RETAIN); EXPECT_TRUE(second_buffer_io_surface); @@ -140,7 +152,8 @@ constexpr size_t kPoolMaxBuffers = 1; std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> first_buffer = + pool->CreateBuffer(); EXPECT_TRUE(first_buffer); IOSurfaceID first_buffer_id = IOSurfaceGetID(CVPixelBufferGetIOSurface(first_buffer)); @@ -152,7 +165,8 @@ pool = PixelBufferPool::Create(kPixelFormatNv12, kVgaWidth / 2, kVgaHeight / 2, kPoolMaxBuffers); - base::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> second_buffer = + pool->CreateBuffer(); EXPECT_TRUE(second_buffer); IOSurfaceID second_buffer_id = IOSurfaceGetID(CVPixelBufferGetIOSurface(second_buffer)); @@ -169,7 +183,7 @@ TEST(PixelBufferPoolTest, BuffersCanOutliveThePool) { std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create(kPixelFormatNv12, kVgaWidth, kVgaHeight, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); + base::apple::ScopedCFTypeRef<CVPixelBufferRef> buffer = pool->CreateBuffer(); pool.reset(); EXPECT_TRUE(CVPixelBufferGetPixelFormatType(buffer) == kPixelFormatNv12); EXPECT_EQ(CVPixelBufferGetWidth(buffer), static_cast<size_t>(kVgaWidth)); @@ -180,9 +194,9 @@ TEST(PixelBufferPoolTest, CanFlushWhileBufferIsInUse) { std::unique_ptr<PixelBufferPool> pool = PixelBufferPool::Create( kPixelFormatNv12, kVgaWidth, kVgaHeight, absl::nullopt); - base::ScopedCFTypeRef<CVPixelBufferRef> retained_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> retained_buffer = pool->CreateBuffer(); - base::ScopedCFTypeRef<CVPixelBufferRef> released_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> released_buffer = pool->CreateBuffer(); released_buffer.reset(); // We expect the memory of |released_buffer| to be freed now, but there is no
diff --git a/media/capture/video/apple/pixel_buffer_transferer.h b/media/capture/video/apple/pixel_buffer_transferer.h index e0c11d6..3edf552 100644 --- a/media/capture/video/apple/pixel_buffer_transferer.h +++ b/media/capture/video/apple/pixel_buffer_transferer.h
@@ -31,7 +31,7 @@ bool TransferImage(CVPixelBufferRef source, CVPixelBufferRef destination); private: - base::ScopedCFTypeRef<VTPixelTransferSessionRef> transfer_session_; + base::apple::ScopedCFTypeRef<VTPixelTransferSessionRef> transfer_session_; }; } // namespace media
diff --git a/media/capture/video/apple/pixel_buffer_transferer_unittest.mm b/media/capture/video/apple/pixel_buffer_transferer_unittest.mm index 4db2c6f..04147276 100644 --- a/media/capture/video/apple/pixel_buffer_transferer_unittest.mm +++ b/media/capture/video/apple/pixel_buffer_transferer_unittest.mm
@@ -52,7 +52,7 @@ CreateYuvsPixelBufferFromSingleRgbColor(kWidth, kHeight, kColorR, kColorG, kColorB); // Destination buffer: A same-sized YUVS buffer. - base::ScopedCFTypeRef<CVPixelBufferRef> destination = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination = PixelBufferPool::Create(kPixelFormat, kWidth, kHeight, 1)->CreateBuffer(); EXPECT_TRUE(transferer.TransferImage(source->pixel_buffer, destination)); // Verify the result is the same color. @@ -79,7 +79,7 @@ CreateYuvsPixelBufferFromSingleRgbColor(kSourceWidth, kSourceHeight, kColorR, kColorG, kColorB); // Destination buffer: A downscaled YUVS buffer. - base::ScopedCFTypeRef<CVPixelBufferRef> destination = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination = PixelBufferPool::Create(kPixelFormat, kDestinationWidth, kDestinationHeight, 1) ->CreateBuffer(); @@ -106,7 +106,7 @@ CreateArgbCheckerPatternBuffer(kSourceWidth, kSourceHeight, kSourceNumTilesAcross)); // Destination buffer: A downscaled YUVS buffer. - base::ScopedCFTypeRef<CVPixelBufferRef> destination = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination = PixelBufferPool::Create(kPixelFormatYuvs, kDestinationWidth, kDestinationHeight, 1) ->CreateBuffer(); @@ -147,7 +147,7 @@ CreateArgbCheckerPatternBuffer(kSourceWidth, kSourceHeight, kSourceNumTilesAcross)); // Destination buffer: A downscaled YUVS buffer. - base::ScopedCFTypeRef<CVPixelBufferRef> destination = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination = PixelBufferPool::Create(kPixelFormatYuvs, kDestinationWidth, kDestinationHeight, 1) ->CreateBuffer(); @@ -181,7 +181,7 @@ CreateYuvsPixelBufferFromSingleRgbColor(kSourceWidth, kSourceHeight, kColorR, kColorG, kColorB); // Destination buffer: A streched YUVS buffer. - base::ScopedCFTypeRef<CVPixelBufferRef> destination = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination = PixelBufferPool::Create(kPixelFormat, kDestinationWidth, kDestinationHeight, 1) ->CreateBuffer(); @@ -204,7 +204,7 @@ CreateYuvsPixelBufferFromSingleRgbColor(kSourceWidth, kSourceHeight, kColorR, kColorG, kColorB); // Destination buffer: A streched NV12 buffer. - base::ScopedCFTypeRef<CVPixelBufferRef> destination = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination = PixelBufferPool::Create(kDestinationPixelFormat, kDestinationWidth, kDestinationHeight, 1) ->CreateBuffer(); @@ -234,7 +234,7 @@ CreateYuvsPixelBufferFromSingleRgbColor(kWidth, kHeight, kColorR, kColorG, kColorB); // YUVS -> pixel_format_from - base::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer_from; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer_from; if (pixel_format_from == kPixelFormatYuvs) { pixel_buffer_from = original_yuvs_buffer->pixel_buffer; } else { @@ -247,14 +247,14 @@ ASSERT_TRUE(pixel_buffer_from); // pixel_format_from -> pixel_format_to - base::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer_to = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer_to = PixelBufferPool::Create(pixel_format_to, kWidth, kHeight, 1) ->CreateBuffer(); EXPECT_TRUE(transferer.TransferImage(pixel_buffer_from, pixel_buffer_to)); // We always convert back to YUVS because this is the only format that the // testing utilities can convert to/from RGB. - base::ScopedCFTypeRef<CVPixelBufferRef> final_yuvs_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> final_yuvs_buffer; // pixel_format_to -> YUVS if (pixel_format_to == kPixelFormatYuvs) { final_yuvs_buffer = pixel_buffer_to;
diff --git a/media/capture/video/apple/sample_buffer_transformer.cc b/media/capture/video/apple/sample_buffer_transformer.cc index 79dc1d61..90afa33 100644 --- a/media/capture/video/apple/sample_buffer_transformer.cc +++ b/media/capture/video/apple/sample_buffer_transformer.cc
@@ -529,8 +529,8 @@ intermediate_nv12_buffer_.resize(0); } -base::ScopedCFTypeRef<CVPixelBufferRef> SampleBufferTransformer::Transform( - CVPixelBufferRef pixel_buffer) { +base::apple::ScopedCFTypeRef<CVPixelBufferRef> +SampleBufferTransformer::Transform(CVPixelBufferRef pixel_buffer) { DCHECK(transformer_ != Transformer::kNotConfigured); DCHECK(pixel_buffer); // Fast path: If source and destination formats are identical, return the @@ -543,24 +543,24 @@ destination_pixel_format_ == CVPixelBufferGetPixelFormatType(pixel_buffer) && CVPixelBufferGetIOSurface(pixel_buffer)) { - return base::ScopedCFTypeRef<CVPixelBufferRef>(pixel_buffer, - base::scoped_policy::RETAIN); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>( + pixel_buffer, base::scoped_policy::RETAIN); } // Create destination buffer from pool. - base::ScopedCFTypeRef<CVPixelBufferRef> destination_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination_pixel_buffer = destination_pixel_buffer_pool_->CreateBuffer(); if (!destination_pixel_buffer) { // Most likely the buffer count was exceeded, but other errors are possible. LOG(ERROR) << "Failed to create a destination buffer"; - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } // Do pixel transfer or libyuv conversion + rescale. TransformPixelBuffer(pixel_buffer, destination_pixel_buffer); return destination_pixel_buffer; } -base::ScopedCFTypeRef<CVPixelBufferRef> SampleBufferTransformer::Transform( - CMSampleBufferRef sample_buffer) { +base::apple::ScopedCFTypeRef<CVPixelBufferRef> +SampleBufferTransformer::Transform(CMSampleBufferRef sample_buffer) { DCHECK(transformer_ != Transformer::kNotConfigured); DCHECK(sample_buffer); // If the sample buffer has a pixel buffer, run the pixel buffer path instead. @@ -569,43 +569,43 @@ return Transform(pixel_buffer); } // Create destination buffer from pool. - base::ScopedCFTypeRef<CVPixelBufferRef> destination_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> destination_pixel_buffer = destination_pixel_buffer_pool_->CreateBuffer(); if (!destination_pixel_buffer) { // Most likely the buffer count was exceeded, but other errors are possible. LOG(ERROR) << "Failed to create a destination buffer"; - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } // Sample buffer path - it's MJPEG. Do libyuv conversion + rescale. if (!TransformSampleBuffer(sample_buffer, destination_pixel_buffer)) { LOG(ERROR) << "Failed to transform sample buffer."; - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } return destination_pixel_buffer; } #if BUILDFLAG(IS_IOS) -base::ScopedCFTypeRef<CVPixelBufferRef> SampleBufferTransformer::Rotate( +base::apple::ScopedCFTypeRef<CVPixelBufferRef> SampleBufferTransformer::Rotate( CVPixelBufferRef source_pixel_buffer) { DCHECK(source_pixel_buffer); DCHECK(pixel_buffer_rotator_); // Create destination buffer from pool. - base::ScopedCFTypeRef<CVPixelBufferRef> rotated_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> rotated_pixel_buffer = rotated_destination_pixel_buffer_pool_->CreateBuffer(); if (!rotated_pixel_buffer) { // Most likely the buffer count was exceeded, but other errors are possible. LOG(ERROR) << "Failed to create a destination buffer"; - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } // The rotated_pixel_buffer might not be the same size as source_pixel_buffer // since source_pixel_buffer gets rotated by rotation_angle_. if (pixel_buffer_rotator_->Rotate(source_pixel_buffer, rotated_pixel_buffer, rotation_angle_)) { - return base::ScopedCFTypeRef<CVPixelBufferRef>(rotated_pixel_buffer); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(rotated_pixel_buffer); } else { - return base::ScopedCFTypeRef<CVPixelBufferRef>(); + return base::apple::ScopedCFTypeRef<CVPixelBufferRef>(); } } #endif
diff --git a/media/capture/video/apple/sample_buffer_transformer.h b/media/capture/video/apple/sample_buffer_transformer.h index 615e400..12f325f 100644 --- a/media/capture/video/apple/sample_buffer_transformer.h +++ b/media/capture/video/apple/sample_buffer_transformer.h
@@ -65,14 +65,14 @@ // Converts the input buffer to an IOSurface-backed pixel buffer according to // current configurations. If no transformation is needed (input format is the // same as the configured output format), the input pixel buffer is returned. - base::ScopedCFTypeRef<CVPixelBufferRef> Transform( + base::apple::ScopedCFTypeRef<CVPixelBufferRef> Transform( CVPixelBufferRef pixel_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> Transform( + base::apple::ScopedCFTypeRef<CVPixelBufferRef> Transform( CMSampleBufferRef sample_buffer); #if BUILDFLAG(IS_IOS) // Rotates a source pixel buffer and returns rotated pixel buffer as a output. - base::ScopedCFTypeRef<CVPixelBufferRef> Rotate( + base::apple::ScopedCFTypeRef<CVPixelBufferRef> Rotate( CVPixelBufferRef source_pixel_buffer); #endif
diff --git a/media/capture/video/apple/sample_buffer_transformer_unittest.mm b/media/capture/video/apple/sample_buffer_transformer_unittest.mm index 9181fc50..8f793c7 100644 --- a/media/capture/video/apple/sample_buffer_transformer_unittest.mm +++ b/media/capture/video/apple/sample_buffer_transformer_unittest.mm
@@ -127,17 +127,18 @@ return MacFourCCToString(info.param); } -base::ScopedCFTypeRef<CVPixelBufferRef> CreatePixelBuffer(OSType pixel_format, - int width, - int height, - uint8_t r, - uint8_t g, - uint8_t b) { +base::apple::ScopedCFTypeRef<CVPixelBufferRef> CreatePixelBuffer( + OSType pixel_format, + int width, + int height, + uint8_t r, + uint8_t g, + uint8_t b) { // Create a YUVS buffer in main memory. std::unique_ptr<ByteArrayPixelBuffer> yuvs_buffer = CreateYuvsPixelBufferFromSingleRgbColor(width, height, r, g, b); // Convert and/or transfer to a pixel buffer that has an IOSurface. - base::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer = PixelBufferPool::Create(pixel_format, width, height, 1)->CreateBuffer(); PixelBufferTransferer transferer; bool success = @@ -179,7 +180,7 @@ } } -base::ScopedCFTypeRef<CVPixelBufferRef> AddPadding( +base::apple::ScopedCFTypeRef<CVPixelBufferRef> AddPadding( CVPixelBufferRef pixel_buffer, OSType pixel_format, int width, @@ -231,7 +232,7 @@ CVPixelBufferUnlockBaseAddress(pixel_buffer, kCVPixelBufferLock_ReadOnly), kCVReturnSuccess); - base::ScopedCFTypeRef<CVPixelBufferRef> padded_pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> padded_pixel_buffer; CVReturn create_buffer_result; if (CVPixelBufferIsPlanar(pixel_buffer)) { // Without some memory block the callback won't be called and we leak the @@ -252,7 +253,7 @@ return padded_pixel_buffer; } -base::ScopedCFTypeRef<CMSampleBufferRef> CreateSampleBuffer( +base::apple::ScopedCFTypeRef<CMSampleBufferRef> CreateSampleBuffer( OSType pixel_format, int width, int height, @@ -261,7 +262,7 @@ uint8_t b, PixelBufferType pixel_buffer_type, size_t padding = 0) { - base::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer = CreatePixelBuffer(pixel_format, width, height, r, g, b); if (padding != 0) { CHECK_EQ(pixel_buffer_type, PixelBufferType::kIoSurfaceMissing) @@ -271,7 +272,7 @@ // Our pixel buffer currently has an IOSurface. To get rid of it, we perform // a pixel buffer transfer to a destination pixel buffer that is not backed // by an IOSurface. The resulting pixel buffer will have the desired color. - base::ScopedCFTypeRef<CVPixelBufferRef> iosurfaceless_pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> iosurfaceless_pixel_buffer; CVReturn create_buffer_result = CVPixelBufferCreate(nullptr, width, height, pixel_format, nullptr, iosurfaceless_pixel_buffer.InitializeInto()); @@ -290,7 +291,7 @@ } // Wrap the pixel buffer in a sample buffer. - base::ScopedCFTypeRef<CMFormatDescriptionRef> format_description; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format_description; OSStatus status = CMVideoFormatDescriptionCreateForImageBuffer( nil, pixel_buffer, format_description.InitializeInto()); DCHECK(status == noErr); @@ -302,7 +303,7 @@ timing_info.duration = CMTimeMake(33 * NSEC_PER_MSEC, CMTimeScale(NSEC_PER_SEC)); // 30 fps - base::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; status = CMSampleBufferCreateForImageBuffer( nil, pixel_buffer, YES, nil, nullptr, format_description, &timing_info, sample_buffer.InitializeInto()); @@ -310,7 +311,7 @@ return sample_buffer; } -base::ScopedCFTypeRef<CMSampleBufferRef> CreateMjpegSampleBuffer( +base::apple::ScopedCFTypeRef<CMSampleBufferRef> CreateMjpegSampleBuffer( const uint8_t* mjpeg_data, size_t mjpeg_data_size, size_t width, @@ -322,14 +323,14 @@ // test code. }; - base::ScopedCFTypeRef<CMBlockBufferRef> data_buffer; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> data_buffer; OSStatus status = CMBlockBufferCreateWithMemoryBlock( nil, const_cast<void*>(static_cast<const void*>(mjpeg_data)), mjpeg_data_size, nil, &source, 0, mjpeg_data_size, 0, data_buffer.InitializeInto()); DCHECK(status == noErr); - base::ScopedCFTypeRef<CMFormatDescriptionRef> format_description; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format_description; status = CMVideoFormatDescriptionCreate(nil, kCMVideoCodecType_JPEG_OpenDML, width, height, nil, format_description.InitializeInto()); @@ -342,7 +343,7 @@ timing_info.duration = CMTimeMake(33 * NSEC_PER_MSEC, CMTimeScale(NSEC_PER_SEC)); // 30 fps - base::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; status = CMSampleBufferCreateReady(nil, data_buffer, format_description, 1, 1, &timing_info, 1, &kExampleJpegDataSize, sample_buffer.InitializeInto()); @@ -350,7 +351,8 @@ return sample_buffer; } -base::ScopedCFTypeRef<CMSampleBufferRef> CreateExampleMjpegSampleBuffer() { +base::apple::ScopedCFTypeRef<CMSampleBufferRef> +CreateExampleMjpegSampleBuffer() { // Sanity-check the example data. int width; int height; @@ -363,7 +365,8 @@ kExampleJpegWidth, kExampleJpegHeight); } -base::ScopedCFTypeRef<CMSampleBufferRef> CreateInvalidMjpegSampleBuffer() { +base::apple::ScopedCFTypeRef<CMSampleBufferRef> +CreateInvalidMjpegSampleBuffer() { return CreateMjpegSampleBuffer(kInvalidJpegData, kInvalidJpegDataSize, kExampleJpegWidth, kExampleJpegHeight); } @@ -379,7 +382,7 @@ CanRotateBy90DegreesClockwise) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); @@ -391,9 +394,9 @@ output_pixel_format, gfx::Size(kFullResolutionWidth, kFullResolutionHeight), /*rotation_angle*/ 90, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> roatated_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> roatated_pixel_buffer = transformer->Rotate(output_pixel_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(roatated_pixel_buffer)); EXPECT_EQ(kFullResolutionWidth, @@ -406,7 +409,7 @@ TEST_P(SampleBufferTransformerPixelTransferTest, CanConvertFullScale) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); @@ -416,7 +419,7 @@ SampleBufferTransformer::Transformer::kPixelBufferTransfer, output_pixel_format, gfx::Size(kFullResolutionWidth, kFullResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -429,7 +432,7 @@ TEST_P(SampleBufferTransformerPixelTransferTest, CanConvertAndScaleDown) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); @@ -439,7 +442,7 @@ SampleBufferTransformer::Transformer::kPixelBufferTransfer, output_pixel_format, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -455,7 +458,7 @@ CanConvertAndScaleDownWhenIoSurfaceIsMissing) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing); @@ -465,7 +468,7 @@ SampleBufferTransformer::Transformer::kPixelBufferTransfer, output_pixel_format, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -480,7 +483,7 @@ TEST_P(SampleBufferTransformerPixelTransferTest, CanConvertWithPaddingFullScale) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing, /*padding*/ 100); @@ -490,7 +493,7 @@ SampleBufferTransformer::Transformer::kPixelBufferTransfer, output_pixel_format, gfx::Size(kFullResolutionWidth, kFullResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -503,7 +506,7 @@ TEST_P(SampleBufferTransformerPixelTransferTest, CanConvertAndScaleWithPadding) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing, /*padding*/ 100); @@ -513,7 +516,7 @@ SampleBufferTransformer::Transformer::kPixelBufferTransfer, output_pixel_format, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -538,7 +541,7 @@ TEST_P(SampleBufferTransformerLibyuvTest, CanConvertFullScale) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); @@ -547,7 +550,7 @@ transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kFullResolutionWidth, kFullResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -560,7 +563,7 @@ TEST_P(SampleBufferTransformerLibyuvTest, CanConvertAndScaleDown) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); @@ -569,7 +572,7 @@ transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -583,7 +586,7 @@ TEST_P(SampleBufferTransformerLibyuvTest, CanConvertWithPaddingFullScale) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing, /*padding*/ 100); @@ -592,7 +595,7 @@ transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kFullResolutionWidth, kFullResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -604,7 +607,7 @@ TEST_P(SampleBufferTransformerLibyuvTest, CanConvertAndScaleWithPadding) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing, /*padding*/ 100); @@ -613,7 +616,7 @@ transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -629,7 +632,7 @@ CanConvertAndScaleDownWhenIoSurfaceIsMissing) { auto [input_pixel_format, output_pixel_format] = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateSampleBuffer(input_pixel_format, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing); @@ -638,7 +641,7 @@ transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_pixel_buffer)); @@ -663,14 +666,14 @@ TEST_P(SampleBufferTransformerMjpegTest, CanConvertFullScale) { OSType output_pixel_format = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateExampleMjpegSampleBuffer(); std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kExampleJpegWidth, kExampleJpegHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_EQ(kExampleJpegWidth, CVPixelBufferGetWidth(output_pixel_buffer)); @@ -688,7 +691,7 @@ TEST_P(SampleBufferTransformerMjpegTest, MAYBE_CanConvertAndScaleDown) { OSType output_pixel_format = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateExampleMjpegSampleBuffer(); std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); @@ -696,7 +699,7 @@ SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kExampleJpegScaledDownWidth, kExampleJpegScaledDownHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_EQ(kExampleJpegScaledDownWidth, @@ -711,14 +714,14 @@ AttemptingToTransformInvalidMjpegFailsGracefully) { OSType output_pixel_format = GetParam(); - base::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = + base::apple::ScopedCFTypeRef<CMSampleBufferRef> input_sample_buffer = CreateInvalidMjpegSampleBuffer(); std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); transformer->Reconfigure( SampleBufferTransformer::Transformer::kLibyuv, output_pixel_format, gfx::Size(kExampleJpegWidth, kExampleJpegHeight), 0, 1); - base::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_pixel_buffer = transformer->Transform(input_sample_buffer); EXPECT_FALSE(output_pixel_buffer); } @@ -733,14 +736,14 @@ std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); - base::ScopedCFTypeRef<CMSampleBufferRef> sample0 = CreateSampleBuffer( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample0 = CreateSampleBuffer( kPixelFormatNv12, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing); transformer->Reconfigure( SampleBufferTransformer::GetBestTransformerForNv12Output(sample0), kPixelFormatNv12, media::GetSampleBufferSize(sample0), 0); - base::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = transformer->Transform(sample0); EXPECT_EQ(gfx::Size(kFullResolutionWidth, kFullResolutionHeight), @@ -752,7 +755,7 @@ // the transformer. EXPECT_NE(output_buffer.get(), CMSampleBufferGetImageBuffer(sample0.get())); - base::ScopedCFTypeRef<CMSampleBufferRef> sample1 = CreateSampleBuffer( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample1 = CreateSampleBuffer( kPixelFormatNv12, kScaledDownResolutionWidth, kScaledDownResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); @@ -777,7 +780,7 @@ std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); - base::ScopedCFTypeRef<CMSampleBufferRef> sample0 = CreateSampleBuffer( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample0 = CreateSampleBuffer( kPixelFormatNv12, kFullResolutionWidth, kFullResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceMissing); CVPixelBufferRef pixel0 = CMSampleBufferGetImageBuffer(sample0); @@ -786,7 +789,7 @@ transformer->Reconfigure( SampleBufferTransformer::kBestTransformerForPixelBufferToNv12Output, kPixelFormatNv12, media::GetPixelBufferSize(pixel0), 0); - base::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = transformer->Transform(pixel0); EXPECT_EQ(gfx::Size(kFullResolutionWidth, kFullResolutionHeight), @@ -798,7 +801,7 @@ // the transformer. EXPECT_NE(output_buffer.get(), pixel0); - base::ScopedCFTypeRef<CMSampleBufferRef> sample1 = CreateSampleBuffer( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample1 = CreateSampleBuffer( kPixelFormatNv12, kScaledDownResolutionWidth, kScaledDownResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); CVPixelBufferRef pixel1 = CMSampleBufferGetImageBuffer(sample1); @@ -823,9 +826,10 @@ std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); - base::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer = CreateSampleBuffer( - kPixelFormatNv12, kFullResolutionWidth, kFullResolutionHeight, kColorR, - kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer = + CreateSampleBuffer(kPixelFormatNv12, kFullResolutionWidth, + kFullResolutionHeight, kColorR, kColorG, kColorB, + PixelBufferType::kIoSurfaceBacked); CVPixelBufferRef pixel_buffer = CMSampleBufferGetImageBuffer(sample_buffer); ASSERT_TRUE(pixel_buffer); @@ -833,7 +837,7 @@ SampleBufferTransformer::kBestTransformerForPixelBufferToNv12Output, kPixelFormatNv12, gfx::Size(kScaledDownResolutionWidth, kScaledDownResolutionHeight), 0); - base::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = transformer->Transform(pixel_buffer); EXPECT_TRUE(CVPixelBufferGetIOSurface(output_buffer)); @@ -848,13 +852,13 @@ std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); - base::ScopedCFTypeRef<CMSampleBufferRef> sample = CreateSampleBuffer( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample = CreateSampleBuffer( kPixelFormatNv12, kScaledDownResolutionWidth, kScaledDownResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); transformer->Reconfigure( SampleBufferTransformer::GetBestTransformerForNv12Output(sample), kPixelFormatNv12, media::GetSampleBufferSize(sample), 0); - base::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = transformer->Transform(sample); EXPECT_EQ(kPixelFormatNv12, transformer->destination_pixel_format()); EXPECT_EQ(kPixelFormatNv12, @@ -908,13 +912,13 @@ std::unique_ptr<SampleBufferTransformer> transformer = SampleBufferTransformer::Create(); - base::ScopedCFTypeRef<CMSampleBufferRef> sample = CreateSampleBuffer( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample = CreateSampleBuffer( kPixelFormatNv12, kScaledDownResolutionWidth, kScaledDownResolutionHeight, kColorR, kColorG, kColorB, PixelBufferType::kIoSurfaceBacked); transformer->Reconfigure( SampleBufferTransformer::GetBestTransformerForNv12Output(sample), kPixelFormatNv12, media::GetSampleBufferSize(sample), 0); - base::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> output_buffer = transformer->Transform(sample); EXPECT_EQ(SampleBufferTransformer::Transformer::kPixelBufferTransfer, transformer->transformer());
diff --git a/media/capture/video/apple/test/fake_av_capture_device_format.mm b/media/capture/video/apple/test/fake_av_capture_device_format.mm index 58f1112..e75ae4e 100644 --- a/media/capture/video/apple/test/fake_av_capture_device_format.mm +++ b/media/capture/video/apple/test/fake_av_capture_device_format.mm
@@ -24,7 +24,7 @@ @end @implementation FakeAVCaptureDeviceFormat { - base::ScopedCFTypeRef<CMVideoFormatDescriptionRef> _formatDescription; + base::apple::ScopedCFTypeRef<CMVideoFormatDescriptionRef> _formatDescription; FakeAVFrameRateRange* __strong _frameRateRange1; FakeAVFrameRateRange* __strong _frameRateRange2; }
diff --git a/media/capture/video/apple/test/pixel_buffer_test_utils.cc b/media/capture/video/apple/test/pixel_buffer_test_utils.cc index 621fe103..f5ecb0d 100644 --- a/media/capture/video/apple/test/pixel_buffer_test_utils.cc +++ b/media/capture/video/apple/test/pixel_buffer_test_utils.cc
@@ -193,7 +193,7 @@ uint8_t g, uint8_t b) { OSType pixel_format = CVPixelBufferGetPixelFormatType(pixel_buffer); - base::ScopedCFTypeRef<CVPixelBufferRef> yuvs_pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> yuvs_pixel_buffer; if (pixel_format == kPixelFormatYuvs) { // The pixel buffer is already YUVS, so we know how to check its color. yuvs_pixel_buffer.reset(pixel_buffer, base::scoped_policy::RETAIN);
diff --git a/media/capture/video/apple/test/pixel_buffer_test_utils.h b/media/capture/video/apple/test/pixel_buffer_test_utils.h index 87e051149..a451114 100644 --- a/media/capture/video/apple/test/pixel_buffer_test_utils.h +++ b/media/capture/video/apple/test/pixel_buffer_test_utils.h
@@ -21,7 +21,7 @@ ~ByteArrayPixelBuffer(); std::vector<uint8_t> byte_array; - base::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixel_buffer; }; // All pixels of the resulting buffer have the specified RGB. Alpha is 255.
diff --git a/media/capture/video/apple/video_capture_device_avfoundation.mm b/media/capture/video/apple/video_capture_device_avfoundation.mm index 2d422acda..3cd16d5 100644 --- a/media/capture/video/apple/video_capture_device_avfoundation.mm +++ b/media/capture/video/apple/video_capture_device_avfoundation.mm
@@ -1017,7 +1017,7 @@ kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, media::GetSampleBufferSize(sampleBuffer), _rotation, kPixelBufferPoolSize); - base::ScopedCFTypeRef<CVPixelBufferRef> pixelBuffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> pixelBuffer = _sampleBufferTransformer->Transform(sampleBuffer); if (!pixelBuffer) { LOG(ERROR) << "Failed to transform captured frame. Dropping frame."; @@ -1025,15 +1025,16 @@ } #if BUILDFLAG(IS_MAC) - base::ScopedCFTypeRef<CVPixelBufferRef> final_pixel_buffer = pixelBuffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> final_pixel_buffer = + pixelBuffer; #else // The rotated_pixelBuffer might not be the same size as the source // pixelBuffer as it gets rotated by rotation_angle_. In order to restore // the original size, rotated_pixelBuffer need to scale it to its original // size by transforming it. - base::ScopedCFTypeRef<CVPixelBufferRef> rotated_pixelBuffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> rotated_pixelBuffer = _sampleBufferTransformer->Rotate(pixelBuffer); - base::ScopedCFTypeRef<CVPixelBufferRef> final_pixel_buffer = + base::apple::ScopedCFTypeRef<CVPixelBufferRef> final_pixel_buffer = _sampleBufferTransformer->Transform(rotated_pixelBuffer); #endif
diff --git a/media/capture/video/apple/video_capture_device_factory_apple.mm b/media/capture/video/apple/video_capture_device_factory_apple.mm index ad07dc8..749758309 100644 --- a/media/capture/video/apple/video_capture_device_factory_apple.mm +++ b/media/capture/video/apple/video_capture_device_factory_apple.mm
@@ -30,7 +30,7 @@ void EnsureRunsOnCFRunLoopEnabledThread() { static bool has_checked_cfrunloop_for_video_capture = false; if (!has_checked_cfrunloop_for_video_capture) { - base::ScopedCFTypeRef<CFRunLoopMode> mode( + base::apple::ScopedCFTypeRef<CFRunLoopMode> mode( CFRunLoopCopyCurrentMode(CFRunLoopGetCurrent())); CHECK(mode != nullptr) << "The MacOS video capture code must be run on a CFRunLoop-enabled "
diff --git a/media/capture/video/ios/pixel_buffer_rotator.h b/media/capture/video/ios/pixel_buffer_rotator.h index 4250bbb..f698a66f 100644 --- a/media/capture/video/ios/pixel_buffer_rotator.h +++ b/media/capture/video/ios/pixel_buffer_rotator.h
@@ -34,7 +34,7 @@ int rotation); private: - base::ScopedCFTypeRef<VTPixelRotationSessionRef> rotation_session_; + base::apple::ScopedCFTypeRef<VTPixelRotationSessionRef> rotation_session_; }; } // namespace media
diff --git a/media/capture/video/mac/uvc_control_mac.mm b/media/capture/video/mac/uvc_control_mac.mm index 0e2b8d7b..b10f1b1e 100644 --- a/media/capture/video/mac/uvc_control_mac.mm +++ b/media/capture/video/mac/uvc_control_mac.mm
@@ -174,7 +174,7 @@ int product_id, io_iterator_t* usb_iterator) { // Compose a search dictionary with vendor and product ID. - base::ScopedCFTypeRef<CFMutableDictionaryRef> query_dictionary( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query_dictionary( IOServiceMatching(kIOUSBDeviceClassName)); CFDictionarySetValue(query_dictionary, CFSTR(kUSBVendorName), base::apple::NSToCFPtrCast(@(vendor_id)));
diff --git a/media/capture/video/mac/video_capture_metrics_mac_unittest.mm b/media/capture/video/mac/video_capture_metrics_mac_unittest.mm index 5184301..9143d237 100644 --- a/media/capture/video/mac/video_capture_metrics_mac_unittest.mm +++ b/media/capture/video/mac/video_capture_metrics_mac_unittest.mm
@@ -30,7 +30,7 @@ TEST(VideoCaptureMetricsMacTest, LogRequestedPixelFormat) { base::HistogramTester histogram_tester; - base::ScopedCFTypeRef<CMFormatDescriptionRef> requested_format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> requested_format; OSStatus status = CMVideoFormatDescriptionCreate( kCFAllocatorDefault, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange /*NV12*/, 320, 180, @@ -49,7 +49,7 @@ TEST(VideoCaptureMetricsMacTest, LogFirstFrameWhenAsRequested) { base::HistogramTester histogram_tester; - base::ScopedCFTypeRef<CMFormatDescriptionRef> requested_format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> requested_format; OSStatus status = CMVideoFormatDescriptionCreate( kCFAllocatorDefault, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange /*NV12*/, 320, 180, @@ -59,7 +59,7 @@ OCMStub([capture_format formatDescription]).andReturn(requested_format.get()); // First frame equal. - base::ScopedCFTypeRef<CMSampleBufferRef> first_frame; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> first_frame; status = CMSampleBufferCreate(kCFAllocatorDefault, nullptr, false, nullptr, nullptr, requested_format, 0, 0, nullptr, 0, nullptr, first_frame.InitializeInto());
diff --git a/media/cast/encoding/h264_vt_encoder.cc b/media/cast/encoding/h264_vt_encoder.cc index d1d5763..fb3a9186 100644 --- a/media/cast/encoding/h264_vt_encoder.cc +++ b/media/cast/encoding/h264_vt_encoder.cc
@@ -93,7 +93,7 @@ } // Allocate a pixel buffer from the pool and return a wrapper VideoFrame. - base::ScopedCFTypeRef<CVPixelBufferRef> buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> buffer; auto status = CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, pool_, buffer.InitializeInto()); if (status != kCVReturnSuccess) { @@ -105,7 +105,7 @@ return VideoFrame::WrapCVPixelBuffer(buffer, timestamp); } - void Update(const base::ScopedCFTypeRef<CVPixelBufferPoolRef>& pool, + void Update(const base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef>& pool, const gfx::Size& frame_size) { base::AutoLock auto_lock(lock_); pool_ = pool; @@ -117,7 +117,7 @@ ~VideoFrameFactoryImpl() override {} base::Lock lock_; - base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool_; + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef> pool_; gfx::Size pool_frame_size_; // Weak back reference to the encoder and the cast envrionment so we can @@ -221,7 +221,7 @@ // On OS X, allow the hardware encoder. Don't require it, it does not support // all configurations (some of which are used for testing). - base::ScopedCFTypeRef<CFDictionaryRef> encoder_spec; + base::apple::ScopedCFTypeRef<CFDictionaryRef> encoder_spec; #if !BUILDFLAG(IS_IOS) encoder_spec = video_toolbox::DictionaryWithKeyValue( kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder, @@ -245,7 +245,7 @@ video_toolbox::DictionaryWithKeysAndValues( attachments_keys, attachments_values, std::size(attachments_keys)) .release()}; - const base::ScopedCFTypeRef<CFDictionaryRef> buffer_attributes = + const base::apple::ScopedCFTypeRef<CFDictionaryRef> buffer_attributes = video_toolbox::DictionaryWithKeysAndValues( buffer_attributes_keys, buffer_attributes_values, std::size(buffer_attributes_keys)); @@ -289,7 +289,7 @@ ConfigureCompressionSession(); // Update the video frame factory. - base::ScopedCFTypeRef<CVPixelBufferPoolRef> pool( + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef> pool( VTCompressionSessionGetPixelBufferPool(compression_session_), base::scoped_policy::RETAIN); video_frame_factory_->Update(pool, frame_size_); @@ -348,7 +348,8 @@ // (ex: the dtor). if (compression_session_) { video_frame_factory_->Update( - base::ScopedCFTypeRef<CVPixelBufferPoolRef>(nullptr), frame_size_); + base::apple::ScopedCFTypeRef<CVPixelBufferPoolRef>(nullptr), + frame_size_); VTCompressionSessionInvalidate(compression_session_); compression_session_.reset(); } @@ -404,7 +405,7 @@ reference_time, std::move(frame_encoded_callback))); // Build a suitable frame properties dictionary for keyframes. - base::ScopedCFTypeRef<CFDictionaryRef> frame_props; + base::apple::ScopedCFTypeRef<CFDictionaryRef> frame_props; if (encode_next_frame_as_keyframe_) { frame_props = video_toolbox::DictionaryWithKeyValue( kVTEncodeFrameOptionKey_ForceKeyFrame, kCFBooleanTrue);
diff --git a/media/cast/encoding/h264_vt_encoder.h b/media/cast/encoding/h264_vt_encoder.h index 34f7dd8..9bc7a82 100644 --- a/media/cast/encoding/h264_vt_encoder.h +++ b/media/cast/encoding/h264_vt_encoder.h
@@ -116,7 +116,7 @@ THREAD_CHECKER(thread_checker_); // The compression session. - base::ScopedCFTypeRef<VTCompressionSessionRef> compression_session_; + base::apple::ScopedCFTypeRef<VTCompressionSessionRef> compression_session_; // Video frame factory tied to the encoder. scoped_refptr<VideoFrameFactoryImpl> video_frame_factory_;
diff --git a/media/filters/mac/audio_toolbox_audio_decoder.h b/media/filters/mac/audio_toolbox_audio_decoder.h index 2c267a4..0811cc8 100644 --- a/media/filters/mac/audio_toolbox_audio_decoder.h +++ b/media/filters/mac/audio_toolbox_audio_decoder.h
@@ -51,7 +51,8 @@ static void Release(AudioConverterRef converter); }; using ScopedAudioConverterRef = - base::ScopedTypeRef<AudioConverterRef, ScopedAudioConverterRefTraits>; + base::apple::ScopedTypeRef<AudioConverterRef, + ScopedAudioConverterRefTraits>; bool CreateDecoder(const AudioDecoderConfig& config);
diff --git a/media/gpu/mac/video_toolbox_decompression_interface.cc b/media/gpu/mac/video_toolbox_decompression_interface.cc index b2ce9a13..19c1ae1 100644 --- a/media/gpu/mac/video_toolbox_decompression_interface.cc +++ b/media/gpu/mac/video_toolbox_decompression_interface.cc
@@ -52,7 +52,7 @@ } void VideoToolboxDecompressionInterface::Decode( - base::ScopedCFTypeRef<CMSampleBufferRef> sample, + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample, std::unique_ptr<VideoToolboxDecodeMetadata> metadata) { DVLOG(3) << __func__; DCHECK(task_runner_->RunsTasksInCurrentSequence()); @@ -120,7 +120,7 @@ } while (!pending_decodes_.empty()) { - base::ScopedCFTypeRef<CMSampleBufferRef>& sample = + base::apple::ScopedCFTypeRef<CMSampleBufferRef>& sample = pending_decodes_.front().first; std::unique_ptr<VideoToolboxDecodeMetadata>& metadata = pending_decodes_.front().second; @@ -169,7 +169,7 @@ DCHECK(task_runner_->RunsTasksInCurrentSequence()); DCHECK(!decompression_session_->IsValid()); - base::ScopedCFTypeRef<CFMutableDictionaryRef> decoder_config( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> decoder_config( CFDictionaryCreateMutable(kCFAllocatorDefault, 1, // capacity &kCFTypeDictionaryKeyCallBacks, @@ -216,7 +216,7 @@ void* context, OSStatus status, VTDecodeInfoFlags flags, - base::ScopedCFTypeRef<CVImageBufferRef> image) { + base::apple::ScopedCFTypeRef<CVImageBufferRef> image) { DVLOG(4) << __func__; DCHECK(task_runner_->RunsTasksInCurrentSequence());
diff --git a/media/gpu/mac/video_toolbox_decompression_interface.h b/media/gpu/mac/video_toolbox_decompression_interface.h index c71d92a..918c309a 100644 --- a/media/gpu/mac/video_toolbox_decompression_interface.h +++ b/media/gpu/mac/video_toolbox_decompression_interface.h
@@ -32,7 +32,7 @@ class MEDIA_GPU_EXPORT VideoToolboxDecompressionInterface { public: using OutputCB = base::RepeatingCallback<void( - base::ScopedCFTypeRef<CVImageBufferRef>, + base::apple::ScopedCFTypeRef<CVImageBufferRef>, std::unique_ptr<VideoToolboxDecodeMetadata> metadata)>; using ErrorCB = base::OnceCallback<void(DecoderStatus)>; @@ -45,7 +45,7 @@ ~VideoToolboxDecompressionInterface(); // Decode |sample|, tagged with |context|. - void Decode(base::ScopedCFTypeRef<CMSampleBufferRef> sample, + void Decode(base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample, std::unique_ptr<VideoToolboxDecodeMetadata> metadata); // Discards decodes that have not been output yet. @@ -62,7 +62,7 @@ void OnOutput(void* context, OSStatus status, VTDecodeInfoFlags flags, - base::ScopedCFTypeRef<CVImageBufferRef> image); + base::apple::ScopedCFTypeRef<CVImageBufferRef> image); private: // Shut down and call |error_cb_|. @@ -87,12 +87,12 @@ ErrorCB error_cb_; // |!error_cb_| indicates an error state. // Decodes that have not been sent to VideoToolbox. - base::queue<std::pair<base::ScopedCFTypeRef<CMSampleBufferRef>, + base::queue<std::pair<base::apple::ScopedCFTypeRef<CMSampleBufferRef>, std::unique_ptr<VideoToolboxDecodeMetadata>>> pending_decodes_; std::unique_ptr<VideoToolboxDecompressionSession> decompression_session_; - base::ScopedCFTypeRef<CMFormatDescriptionRef> active_format_; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> active_format_; base::flat_map<void*, std::unique_ptr<VideoToolboxDecodeMetadata>> active_decodes_;
diff --git a/media/gpu/mac/video_toolbox_decompression_interface_unittest.cc b/media/gpu/mac/video_toolbox_decompression_interface_unittest.cc index ccc8312..92f2fd6 100644 --- a/media/gpu/mac/video_toolbox_decompression_interface_unittest.cc +++ b/media/gpu/mac/video_toolbox_decompression_interface_unittest.cc
@@ -33,8 +33,8 @@ return metadata; } -base::ScopedCFTypeRef<CMFormatDescriptionRef> CreateFormat() { - base::ScopedCFTypeRef<CMFormatDescriptionRef> format; +base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> CreateFormat() { + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format; OSStatus status = CMFormatDescriptionCreate(kCFAllocatorDefault, kCMMediaType_Video, 'test', nullptr, format.InitializeInto()); @@ -42,9 +42,9 @@ return format; } -base::ScopedCFTypeRef<CMSampleBufferRef> CreateSample( +base::apple::ScopedCFTypeRef<CMSampleBufferRef> CreateSample( CMFormatDescriptionRef format) { - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; OSStatus status = CMSampleBufferCreate( kCFAllocatorDefault, nullptr, true, nullptr, nullptr, format, 0, 0, nullptr, 0, nullptr, sample.InitializeInto()); @@ -52,8 +52,8 @@ return sample; } -base::ScopedCFTypeRef<CVImageBufferRef> CreateImage() { - base::ScopedCFTypeRef<CVImageBufferRef> image; +base::apple::ScopedCFTypeRef<CVImageBufferRef> CreateImage() { + base::apple::ScopedCFTypeRef<CVImageBufferRef> image; OSStatus status = CVPixelBufferCreate(kCFAllocatorDefault, /*width=*/16, /*height=*/16, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, @@ -106,7 +106,7 @@ void* context = pending_decodes_.front(); OSStatus status = noErr; VTDecodeInfoFlags flags = 0; - base::ScopedCFTypeRef<CVImageBufferRef> image = CreateImage(); + base::apple::ScopedCFTypeRef<CVImageBufferRef> image = CreateImage(); pending_decodes_.pop(); output_cb_.Run(context, status, flags, std::move(image)); @@ -119,7 +119,7 @@ void* context = pending_decodes_.front(); OSStatus status = -1; VTDecodeInfoFlags flags = 0; - base::ScopedCFTypeRef<CVImageBufferRef> image; + base::apple::ScopedCFTypeRef<CVImageBufferRef> image; pending_decodes_.pop(); output_cb_.Run(context, status, flags, std::move(image)); @@ -153,7 +153,7 @@ protected: MOCK_METHOD1(OnError, void(DecoderStatus)); MOCK_METHOD2(OnOutput, - void(base::ScopedCFTypeRef<CVImageBufferRef>, + void(base::apple::ScopedCFTypeRef<CVImageBufferRef>, std::unique_ptr<VideoToolboxDecodeMetadata>)); base::test::TaskEnvironment task_environment_;
diff --git a/media/gpu/mac/video_toolbox_decompression_session.cc b/media/gpu/mac/video_toolbox_decompression_session.cc index c26effe0..92d4e1e 100644 --- a/media/gpu/mac/video_toolbox_decompression_session.cc +++ b/media/gpu/mac/video_toolbox_decompression_session.cc
@@ -29,7 +29,7 @@ static_cast<VideoToolboxDecompressionSessionImpl*>( decompression_output_refcon); vtdsi->OnOutputOnAnyThread(source_frame_refcon, status, info_flags, - base::ScopedCFTypeRef<CVImageBufferRef>( + base::apple::ScopedCFTypeRef<CVImageBufferRef>( image_buffer, base::scoped_policy::RETAIN)); } @@ -134,7 +134,7 @@ void* context, OSStatus status, VTDecodeInfoFlags flags, - base::ScopedCFTypeRef<CVImageBufferRef> image) { + base::apple::ScopedCFTypeRef<CVImageBufferRef> image) { DVLOG(4) << __func__; task_runner_->PostTask( FROM_HERE, @@ -146,7 +146,7 @@ void* context, OSStatus status, VTDecodeInfoFlags flags, - base::ScopedCFTypeRef<CVImageBufferRef> image) { + base::apple::ScopedCFTypeRef<CVImageBufferRef> image) { DVLOG(3) << __func__; DCHECK(task_runner_->RunsTasksInCurrentSequence()); CHECK(session_);
diff --git a/media/gpu/mac/video_toolbox_decompression_session.h b/media/gpu/mac/video_toolbox_decompression_session.h index e5ffc9e..b1938e9 100644 --- a/media/gpu/mac/video_toolbox_decompression_session.h +++ b/media/gpu/mac/video_toolbox_decompression_session.h
@@ -44,11 +44,11 @@ class MEDIA_GPU_EXPORT VideoToolboxDecompressionSessionImpl : public VideoToolboxDecompressionSession { public: - using OutputCB = - base::RepeatingCallback<void(void*, - OSStatus, - VTDecodeInfoFlags, - base::ScopedCFTypeRef<CVImageBufferRef>)>; + using OutputCB = base::RepeatingCallback<void( + void*, + OSStatus, + VTDecodeInfoFlags, + base::apple::ScopedCFTypeRef<CVImageBufferRef>)>; VideoToolboxDecompressionSessionImpl( scoped_refptr<base::SequencedTaskRunner> task_runner, @@ -65,22 +65,23 @@ bool DecodeFrame(CMSampleBufferRef sample, void* context) override; // Called by OnOutputThunk(). - void OnOutputOnAnyThread(void* context, - OSStatus status, - VTDecodeInfoFlags flags, - base::ScopedCFTypeRef<CVImageBufferRef> image); + void OnOutputOnAnyThread( + void* context, + OSStatus status, + VTDecodeInfoFlags flags, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image); private: void OnOutput(void* context, OSStatus status, VTDecodeInfoFlags flags, - base::ScopedCFTypeRef<CVImageBufferRef> image); + base::apple::ScopedCFTypeRef<CVImageBufferRef> image); scoped_refptr<base::SequencedTaskRunner> task_runner_; std::unique_ptr<MediaLog> media_log_; OutputCB output_cb_; - base::ScopedCFTypeRef<VTDecompressionSessionRef> session_; + base::apple::ScopedCFTypeRef<VTDecompressionSessionRef> session_; // Used in OnOutputOnAnyThread() to hop to |task_runner_|. base::WeakPtr<VideoToolboxDecompressionSessionImpl> weak_this_;
diff --git a/media/gpu/mac/video_toolbox_frame_converter.cc b/media/gpu/mac/video_toolbox_frame_converter.cc index b34f6a79..069bd08 100644 --- a/media/gpu/mac/video_toolbox_frame_converter.cc +++ b/media/gpu/mac/video_toolbox_frame_converter.cc
@@ -132,7 +132,7 @@ } void VideoToolboxFrameConverter::Convert( - base::ScopedCFTypeRef<CVImageBufferRef> image, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image, std::unique_ptr<VideoToolboxDecodeMetadata> metadata, OutputCB output_cb) { DVLOG(3) << __func__; @@ -233,7 +233,7 @@ void VideoToolboxFrameConverter::OnVideoFrameReleased( base::OnceCallback<void(const gpu::SyncToken&)> destroy_shared_image_cb, - base::ScopedCFTypeRef<CVImageBufferRef> image, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image, const gpu::SyncToken& sync_token) { DVLOG(4) << __func__; DCHECK(gpu_task_runner_->RunsTasksInCurrentSequence());
diff --git a/media/gpu/mac/video_toolbox_frame_converter.h b/media/gpu/mac/video_toolbox_frame_converter.h index 57abd70..5d1a06b 100644 --- a/media/gpu/mac/video_toolbox_frame_converter.h +++ b/media/gpu/mac/video_toolbox_frame_converter.h
@@ -50,7 +50,7 @@ std::unique_ptr<MediaLog> media_log, GetCommandBufferStubCB get_stub_cb); - void Convert(base::ScopedCFTypeRef<CVImageBufferRef> image, + void Convert(base::apple::ScopedCFTypeRef<CVImageBufferRef> image, std::unique_ptr<VideoToolboxDecodeMetadata> metadata, OutputCB output_cb); @@ -68,7 +68,7 @@ void OnVideoFrameReleased( base::OnceCallback<void(const gpu::SyncToken&)> destroy_shared_image_cb, - base::ScopedCFTypeRef<CVImageBufferRef> image, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image, const gpu::SyncToken& sync_token); scoped_refptr<base::SequencedTaskRunner> gpu_task_runner_;
diff --git a/media/gpu/mac/video_toolbox_h264_accelerator.cc b/media/gpu/mac/video_toolbox_h264_accelerator.cc index 1a2a37c7..8ba9016 100644 --- a/media/gpu/mac/video_toolbox_h264_accelerator.cc +++ b/media/gpu/mac/video_toolbox_h264_accelerator.cc
@@ -132,7 +132,7 @@ } // Allocate a buffer. - base::ScopedCFTypeRef<CMBlockBufferRef> data; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> data; OSStatus status = CMBlockBufferCreateWithMemoryBlock( kCFAllocatorDefault, nullptr, // memory_block @@ -187,7 +187,7 @@ } // Wrap in a sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; status = CMSampleBufferCreate(kCFAllocatorDefault, data, // data_buffer true, // data_ready
diff --git a/media/gpu/mac/video_toolbox_h264_accelerator.h b/media/gpu/mac/video_toolbox_h264_accelerator.h index 75c6dfa..13fb40d 100644 --- a/media/gpu/mac/video_toolbox_h264_accelerator.h +++ b/media/gpu/mac/video_toolbox_h264_accelerator.h
@@ -26,9 +26,9 @@ class MEDIA_GPU_EXPORT VideoToolboxH264Accelerator : public H264Decoder::H264Accelerator { public: - using DecodeCB = - base::RepeatingCallback<void(base::ScopedCFTypeRef<CMSampleBufferRef>, - scoped_refptr<CodecPicture>)>; + using DecodeCB = base::RepeatingCallback<void( + base::apple::ScopedCFTypeRef<CMSampleBufferRef>, + scoped_refptr<CodecPicture>)>; using OutputCB = base::RepeatingCallback<void(scoped_refptr<CodecPicture>)>; VideoToolboxH264Accelerator(std::unique_ptr<MediaLog> media_log, @@ -77,7 +77,7 @@ std::vector<uint8_t> active_sps_data_; std::vector<uint8_t> active_pps_data_; - base::ScopedCFTypeRef<CMFormatDescriptionRef> active_format_; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> active_format_; // Accumulated slice data for the current frame. std::vector<base::span<const uint8_t>> slice_nalu_data_;
diff --git a/media/gpu/mac/video_toolbox_h264_accelerator_unittest.cc b/media/gpu/mac/video_toolbox_h264_accelerator_unittest.cc index 96954ad4..a922bcb 100644 --- a/media/gpu/mac/video_toolbox_h264_accelerator_unittest.cc +++ b/media/gpu/mac/video_toolbox_h264_accelerator_unittest.cc
@@ -45,7 +45,7 @@ protected: MOCK_METHOD2(OnDecode, - void(base::ScopedCFTypeRef<CMSampleBufferRef>, + void(base::apple::ScopedCFTypeRef<CMSampleBufferRef>, scoped_refptr<CodecPicture>)); MOCK_METHOD1(OnOutput, void(scoped_refptr<CodecPicture>)); @@ -78,7 +78,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample)); accelerator_->SubmitDecode(pic); @@ -115,7 +115,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample0; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample0; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample0)); accelerator_->SubmitDecode(pic0); @@ -128,7 +128,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample1; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample1; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample1)); accelerator_->SubmitDecode(pic1); @@ -156,7 +156,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample0; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample0; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample0)); accelerator_->SubmitDecode(pic0); @@ -172,7 +172,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample1; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample1; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample1)); accelerator_->SubmitDecode(pic1); @@ -200,7 +200,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample0; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample0; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample0)); accelerator_->SubmitDecode(pic0); @@ -213,7 +213,7 @@ kSliceData, sizeof(kSliceData), subsamples); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample1; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample1; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample1)); accelerator_->SubmitDecode(pic1);
diff --git a/media/gpu/mac/video_toolbox_video_decoder.cc b/media/gpu/mac/video_toolbox_video_decoder.cc index 75d99c5d..fca8dd5 100644 --- a/media/gpu/mac/video_toolbox_video_decoder.cc +++ b/media/gpu/mac/video_toolbox_video_decoder.cc
@@ -294,7 +294,7 @@ } void VideoToolboxVideoDecoder::OnAcceleratorDecode( - base::ScopedCFTypeRef<CMSampleBufferRef> sample, + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample, scoped_refptr<CodecPicture> picture) { DVLOG(4) << __func__; DCHECK(active_decode_); @@ -323,7 +323,7 @@ } void VideoToolboxVideoDecoder::OnVideoToolboxOutput( - base::ScopedCFTypeRef<CVImageBufferRef> image, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image, std::unique_ptr<VideoToolboxDecodeMetadata> metadata) { DVLOG(4) << __func__;
diff --git a/media/gpu/mac/video_toolbox_video_decoder.h b/media/gpu/mac/video_toolbox_video_decoder.h index efe39ca7..25ea580 100644 --- a/media/gpu/mac/video_toolbox_video_decoder.h +++ b/media/gpu/mac/video_toolbox_video_decoder.h
@@ -83,13 +83,14 @@ void ReleaseDecodeCallbacks(); // |accelerator_| callbacks. - void OnAcceleratorDecode(base::ScopedCFTypeRef<CMSampleBufferRef> sample, - scoped_refptr<CodecPicture> picture); + void OnAcceleratorDecode( + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample, + scoped_refptr<CodecPicture> picture); void OnAcceleratorOutput(scoped_refptr<CodecPicture> picture); // |video_toolbox_| callbacks. void OnVideoToolboxOutput( - base::ScopedCFTypeRef<CVImageBufferRef> image, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image, std::unique_ptr<VideoToolboxDecodeMetadata> metadata); void OnVideoToolboxError(DecoderStatus status);
diff --git a/media/gpu/mac/video_toolbox_vp9_accelerator.cc b/media/gpu/mac/video_toolbox_vp9_accelerator.cc index 6f3386b0..891f1c8 100644 --- a/media/gpu/mac/video_toolbox_vp9_accelerator.cc +++ b/media/gpu/mac/video_toolbox_vp9_accelerator.cc
@@ -174,7 +174,7 @@ coded_size != active_coded_size_) { active_format_.reset(); - base::ScopedCFTypeRef<CFDictionaryRef> format_config = + base::apple::ScopedCFTypeRef<CFDictionaryRef> format_config = CreateFormatExtensions(kCMVideoCodecType_VP9, profile, color_space, hdr_metadata); if (!format_config) { @@ -183,7 +183,7 @@ return false; } - base::ScopedCFTypeRef<CMFormatDescriptionRef> format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format; OSStatus status = CMVideoFormatDescriptionCreate( kCFAllocatorDefault, kCMVideoCodecType_VP9, coded_size.width(), coded_size.height(), format_config, active_format_.InitializeInto()); @@ -213,7 +213,7 @@ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Take the current superframe. - base::ScopedCFTypeRef<CMBlockBufferRef> frame_data; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> frame_data; std::vector<size_t> frame_sizes; frame_data.swap(frame_data_); frame_sizes.swap(frame_sizes_); @@ -258,7 +258,7 @@ } // Wrap the frame data in a sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; size_t size = CMBlockBufferGetDataLength(frame_data); OSStatus status = CMSampleBufferCreate(kCFAllocatorDefault, frame_data, // data_buffer
diff --git a/media/gpu/mac/video_toolbox_vp9_accelerator.h b/media/gpu/mac/video_toolbox_vp9_accelerator.h index 4777b7bf..f29ec31 100644 --- a/media/gpu/mac/video_toolbox_vp9_accelerator.h +++ b/media/gpu/mac/video_toolbox_vp9_accelerator.h
@@ -35,9 +35,9 @@ class MEDIA_GPU_EXPORT VideoToolboxVP9Accelerator : public VP9Decoder::VP9Accelerator { public: - using DecodeCB = - base::RepeatingCallback<void(base::ScopedCFTypeRef<CMSampleBufferRef>, - scoped_refptr<CodecPicture>)>; + using DecodeCB = base::RepeatingCallback<void( + base::apple::ScopedCFTypeRef<CMSampleBufferRef>, + scoped_refptr<CodecPicture>)>; using OutputCB = base::RepeatingCallback<void(scoped_refptr<CodecPicture>)>; VideoToolboxVP9Accelerator(std::unique_ptr<MediaLog> media_log, @@ -79,10 +79,10 @@ absl::optional<gfx::HDRMetadata> active_hdr_metadata_; gfx::Size active_coded_size_; - base::ScopedCFTypeRef<CMFormatDescriptionRef> active_format_; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> active_format_; // The superframe currently being built. - base::ScopedCFTypeRef<CMBlockBufferRef> frame_data_; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> frame_data_; std::vector<size_t> frame_sizes_; SEQUENCE_CHECKER(sequence_checker_);
diff --git a/media/gpu/mac/video_toolbox_vp9_accelerator_unittest.cc b/media/gpu/mac/video_toolbox_vp9_accelerator_unittest.cc index 0cf730b..ea202094 100644 --- a/media/gpu/mac/video_toolbox_vp9_accelerator_unittest.cc +++ b/media/gpu/mac/video_toolbox_vp9_accelerator_unittest.cc
@@ -24,7 +24,7 @@ protected: MOCK_METHOD2(OnDecode, - void(base::ScopedCFTypeRef<CMSampleBufferRef>, + void(base::apple::ScopedCFTypeRef<CMSampleBufferRef>, scoped_refptr<CodecPicture>)); MOCK_METHOD1(OnOutput, void(scoped_refptr<CodecPicture>)); @@ -54,7 +54,7 @@ pic->frame_hdr->frame_size = 1; // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample)); EXPECT_CALL(*this, OnOutput(_)); accelerator_->SubmitDecode(pic, segm_params, lf_params, reference_frames, @@ -90,7 +90,7 @@ pic2->frame_hdr->frame_size = sizeof(frame_data2); // Save the resulting sample. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; EXPECT_CALL(*this, OnDecode(_, _)).WillOnce(SaveArg<0>(&sample)); EXPECT_CALL(*this, OnOutput(_)); accelerator_->SubmitDecode(pic1, segm_params, lf_params, reference_frames,
diff --git a/media/gpu/mac/vp9_super_frame_bitstream_filter.h b/media/gpu/mac/vp9_super_frame_bitstream_filter.h index c6ddf20..f1b3b86 100644 --- a/media/gpu/mac/vp9_super_frame_bitstream_filter.h +++ b/media/gpu/mac/vp9_super_frame_bitstream_filter.h
@@ -31,7 +31,7 @@ void Flush(); // Releases any prepared buffer. Returns null if no buffers are available. - base::ScopedCFTypeRef<CMBlockBufferRef> take_buffer() { + base::apple::ScopedCFTypeRef<CMBlockBufferRef> take_buffer() { return std::move(data_); } @@ -48,7 +48,7 @@ // Prepared CMBlockBuffer -- either by assembling |partial_buffers_| or when // a super frame is unnecessary, just by passing through DecoderBuffer. - base::ScopedCFTypeRef<CMBlockBufferRef> data_; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> data_; // Partial buffers which need to be assembled into a super frame. std::vector<scoped_refptr<DecoderBuffer>> partial_buffers_;
diff --git a/media/gpu/mac/vt_config_util.h b/media/gpu/mac/vt_config_util.h index 6ad5733..8289e4b 100644 --- a/media/gpu/mac/vt_config_util.h +++ b/media/gpu/mac/vt_config_util.h
@@ -17,11 +17,11 @@ namespace media { -MEDIA_GPU_EXPORT base::ScopedCFTypeRef<CFDictionaryRef> CreateFormatExtensions( - CMVideoCodecType codec_type, - VideoCodecProfile profile, - const VideoColorSpace& color_space, - absl::optional<gfx::HDRMetadata> hdr_metadata); +MEDIA_GPU_EXPORT base::apple::ScopedCFTypeRef<CFDictionaryRef> +CreateFormatExtensions(CMVideoCodecType codec_type, + VideoCodecProfile profile, + const VideoColorSpace& color_space, + absl::optional<gfx::HDRMetadata> hdr_metadata); } // namespace media
diff --git a/media/gpu/mac/vt_config_util.mm b/media/gpu/mac/vt_config_util.mm index 4b40fe2..cb4f8f5 100644 --- a/media/gpu/mac/vt_config_util.mm +++ b/media/gpu/mac/vt_config_util.mm
@@ -198,7 +198,7 @@ namespace media { -base::ScopedCFTypeRef<CFDictionaryRef> CreateFormatExtensions( +base::apple::ScopedCFTypeRef<CFDictionaryRef> CreateFormatExtensions( CMVideoCodecType codec_type, VideoCodecProfile profile, const VideoColorSpace& color_space, @@ -244,7 +244,7 @@ if (profile >= VP9PROFILE_MIN && profile <= VP9PROFILE_MAX) SetVp9CodecConfigurationBox(extensions, profile, color_space); - return base::ScopedCFTypeRef<CFDictionaryRef>( + return base::apple::ScopedCFTypeRef<CFDictionaryRef>( base::apple::NSToCFOwnershipCast(extensions)); }
diff --git a/media/gpu/mac/vt_config_util_unittest.cc b/media/gpu/mac/vt_config_util_unittest.cc index a9d3afd1..378f4ca 100644 --- a/media/gpu/mac/vt_config_util_unittest.cc +++ b/media/gpu/mac/vt_config_util_unittest.cc
@@ -57,19 +57,19 @@ return GetDataValue(nested_dict, key2); } -base::ScopedCFTypeRef<CVImageBufferRef> CreateCVImageBuffer( +base::apple::ScopedCFTypeRef<CVImageBufferRef> CreateCVImageBuffer( media::VideoColorSpace cs) { - base::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( kCMVideoCodecType_H264, media::H264PROFILE_MAIN, cs, gfx::HDRMetadata()); - base::ScopedCFTypeRef<CVImageBufferRef> image_buffer; + base::apple::ScopedCFTypeRef<CVImageBufferRef> image_buffer; OSStatus err = CVPixelBufferCreate(kCFAllocatorDefault, 16, 16, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, nullptr, image_buffer.InitializeInto()); if (err != noErr) { EXPECT_EQ(err, noErr); - return base::ScopedCFTypeRef<CVImageBufferRef>(); + return base::apple::ScopedCFTypeRef<CVImageBufferRef>(); } CVBufferSetAttachments(image_buffer.get(), fmt, @@ -77,11 +77,11 @@ return image_buffer; } -base::ScopedCFTypeRef<CMFormatDescriptionRef> CreateFormatDescription( +base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> CreateFormatDescription( CFStringRef primaries, CFStringRef transfer, CFStringRef matrix) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> extensions( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> extensions( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -98,7 +98,7 @@ CFDictionarySetValue(extensions, kCMFormatDescriptionExtension_YCbCrMatrix, matrix); } - base::ScopedCFTypeRef<CMFormatDescriptionRef> result; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> result; CMFormatDescriptionCreate(nullptr, kCMMediaType_Video, kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, extensions.get(), result.InitializeInto()); @@ -145,7 +145,7 @@ namespace media { TEST(VTConfigUtil, CreateFormatExtensions_H264_BT709) { - base::ScopedCFTypeRef<CFDictionaryRef> fmt = + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions(kCMVideoCodecType_H264, H264PROFILE_MAIN, VideoColorSpace::REC709(), absl::nullopt); @@ -168,7 +168,7 @@ } TEST(VTConfigUtil, CreateFormatExtensions_H264_BT2020_PQ) { - base::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( kCMVideoCodecType_H264, H264PROFILE_MAIN, VideoColorSpace(VideoColorSpace::PrimaryID::BT2020, VideoColorSpace::TransferID::SMPTEST2084, @@ -189,7 +189,7 @@ } TEST(VTConfigUtil, CreateFormatExtensions_H264_BT2020_HLG) { - base::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( kCMVideoCodecType_H264, H264PROFILE_MAIN, VideoColorSpace(VideoColorSpace::PrimaryID::BT2020, VideoColorSpace::TransferID::ARIB_STD_B67, @@ -219,7 +219,7 @@ /*luminance_min=*/0); const auto& cv_metadata = hdr_meta.smpte_st_2086.value(); - base::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( kCMVideoCodecType_H264, H264PROFILE_MAIN, VideoColorSpace(VideoColorSpace::PrimaryID::BT2020, VideoColorSpace::TransferID::SMPTEST2084, @@ -269,7 +269,7 @@ TEST(VTConfigUtil, CreateFormatExtensions_VP9Profile0) { constexpr VideoCodecProfile kTestProfile = VP9PROFILE_PROFILE0; const auto kTestColorSpace = VideoColorSpace::REC709(); - base::ScopedCFTypeRef<CFDictionaryRef> fmt(CreateFormatExtensions( + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt(CreateFormatExtensions( kCMVideoCodecType_VP9, kTestProfile, kTestColorSpace, absl::nullopt)); EXPECT_EQ(8, GetIntValue(fmt, base::SysUTF8ToCFStringRef(kBitDepthKey))); @@ -291,7 +291,7 @@ VideoColorSpace::PrimaryID::BT2020, VideoColorSpace::TransferID::SMPTEST2084, VideoColorSpace::MatrixID::BT2020_NCL, gfx::ColorSpace::RangeID::LIMITED); - base::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( + base::apple::ScopedCFTypeRef<CFDictionaryRef> fmt = CreateFormatExtensions( kCMVideoCodecType_VP9, kTestProfile, kTestColorSpace, absl::nullopt); EXPECT_EQ(10, GetIntValue(fmt, base::SysUTF8ToCFStringRef(kBitDepthKey)));
diff --git a/media/gpu/mac/vt_video_decode_accelerator_mac.cc b/media/gpu/mac/vt_video_decode_accelerator_mac.cc index c90d411..23053a72 100644 --- a/media/gpu/mac/vt_video_decode_accelerator_mac.cc +++ b/media/gpu/mac/vt_video_decode_accelerator_mac.cc
@@ -140,11 +140,11 @@ #endif // BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) // Build an |image_config| dictionary for VideoToolbox initialization. -base::ScopedCFTypeRef<CFMutableDictionaryRef> BuildImageConfig( +base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> BuildImageConfig( CMVideoDimensions coded_dimensions, bool is_hbd, bool has_alpha) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> image_config; + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> image_config; // Note that 4:2:0 textures cannot be used directly as RGBA in OpenGL, but are // lower power than 4:2:2 when composited directly by CoreAnimation. @@ -157,9 +157,12 @@ pixel_format = kCVPixelFormatType_420YpCbCr8VideoRange_8A_TriPlanar; #define CFINT(i) CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &i) - base::ScopedCFTypeRef<CFNumberRef> cf_pixel_format(CFINT(pixel_format)); - base::ScopedCFTypeRef<CFNumberRef> cf_width(CFINT(coded_dimensions.width)); - base::ScopedCFTypeRef<CFNumberRef> cf_height(CFINT(coded_dimensions.height)); + base::apple::ScopedCFTypeRef<CFNumberRef> cf_pixel_format( + CFINT(pixel_format)); + base::apple::ScopedCFTypeRef<CFNumberRef> cf_width( + CFINT(coded_dimensions.width)); + base::apple::ScopedCFTypeRef<CFNumberRef> cf_height( + CFINT(coded_dimensions.height)); #undef CFINT if (!cf_pixel_format.get() || !cf_width.get() || !cf_height.get()) return image_config; @@ -181,7 +184,7 @@ #if BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) // Create a CMFormatDescription using the provided |param_sets|. -base::ScopedCFTypeRef<CMFormatDescriptionRef> CreateVideoFormatHEVC( +base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> CreateVideoFormatHEVC( ParameterSets param_sets) { DCHECK(!param_sets.empty()); @@ -200,7 +203,7 @@ // we could get an OSStatus=-12906 kVTCouldNotFindVideoDecoderErr after // calling VTDecompressionSessionCreate(), so macOS 11+ is necessary // (https://crbug.com/1300444#c9) - base::ScopedCFTypeRef<CMFormatDescriptionRef> format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format; if (__builtin_available(macOS 11.0, *)) { OSStatus status = CMVideoFormatDescriptionCreateFromHEVCParameterSets( kCFAllocatorDefault, @@ -217,7 +220,7 @@ #endif // BUILDFLAG(ENABLE_HEVC_PARSER_AND_HW_DECODER) // Create a CMFormatDescription using the provided |pps| and |sps|. -base::ScopedCFTypeRef<CMFormatDescriptionRef> CreateVideoFormatH264( +base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> CreateVideoFormatH264( const std::vector<uint8_t>& sps, const std::vector<uint8_t>& spsext, const std::vector<uint8_t>& pps) { @@ -239,7 +242,7 @@ nalu_data_sizes.push_back(pps.size()); // Construct a new format description from the parameter sets. - base::ScopedCFTypeRef<CMFormatDescriptionRef> format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format; OSStatus status = CMVideoFormatDescriptionCreateFromH264ParameterSets( kCFAllocatorDefault, nalu_data_ptrs.size(), // parameter_set_count @@ -252,15 +255,16 @@ return format; } -base::ScopedCFTypeRef<CMFormatDescriptionRef> CreateVideoFormatVP9( +base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> CreateVideoFormatVP9( media::VideoColorSpace color_space, media::VideoCodecProfile profile, absl::optional<gfx::HDRMetadata> hdr_metadata, const gfx::Size& coded_size) { - base::ScopedCFTypeRef<CFDictionaryRef> format_config = CreateFormatExtensions( - kCMVideoCodecType_VP9, profile, color_space, hdr_metadata); + base::apple::ScopedCFTypeRef<CFDictionaryRef> format_config = + CreateFormatExtensions(kCMVideoCodecType_VP9, profile, color_space, + hdr_metadata); - base::ScopedCFTypeRef<CMFormatDescriptionRef> format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format; if (!format_config) { DLOG(ERROR) << "Failed to configure vp9 decoder."; return format; @@ -282,10 +286,10 @@ bool is_hbd, bool has_alpha, const VTDecompressionOutputCallbackRecord* callback, - base::ScopedCFTypeRef<VTDecompressionSessionRef>* session, + base::apple::ScopedCFTypeRef<VTDecompressionSessionRef>* session, gfx::Size* configured_size) { // Prepare VideoToolbox configuration dictionaries. - base::ScopedCFTypeRef<CFMutableDictionaryRef> decoder_config( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> decoder_config( CFDictionaryCreateMutable(kCFAllocatorDefault, 1, // capacity &kCFTypeDictionaryKeyCallBacks, @@ -315,7 +319,7 @@ CMVideoDimensions visible_dimensions = { base::ClampFloor(visible_rect.size.width), base::ClampFloor(visible_rect.size.height)}; - base::ScopedCFTypeRef<CFMutableDictionaryRef> image_config( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> image_config( BuildImageConfig(visible_dimensions, is_hbd, has_alpha)); if (!image_config) { DLOG(ERROR) << "Failed to create decoder image configuration"; @@ -677,7 +681,7 @@ DVLOG(2) << __func__; DCHECK(decoder_task_runner_->RunsTasksInCurrentSequence()); - base::ScopedCFTypeRef<CMFormatDescriptionRef> format; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format; switch (codec_) { case VideoCodec::kH264: format = CreateVideoFormatH264(active_sps_, active_spsext_, active_pps_); @@ -741,7 +745,7 @@ // Report whether hardware decode is being used. bool using_hardware = false; - base::ScopedCFTypeRef<CFBooleanRef> cf_using_hardware; + base::apple::ScopedCFTypeRef<CFBooleanRef> cf_using_hardware; if (VTSessionCopyProperty( session_, // kVTDecompressionPropertyKey_UsingHardwareAcceleratedVideoDecoder @@ -807,7 +811,7 @@ } // Package the data in a CMSampleBuffer. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; OSStatus status = CMSampleBufferCreateReady(kCFAllocatorDefault, data, // data_buffer format_, // format_description @@ -1138,7 +1142,7 @@ // Create a memory-backed CMBlockBuffer for the translated data. // TODO(sandersd): Pool of memory blocks. - base::ScopedCFTypeRef<CMBlockBufferRef> data; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> data; OSStatus status = CMBlockBufferCreateWithMemoryBlock( kCFAllocatorDefault, nullptr, // &memory_block @@ -1189,7 +1193,7 @@ } // Package the data in a CMSampleBuffer. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; status = CMSampleBufferCreate(kCFAllocatorDefault, data, // data_buffer true, // data_ready @@ -1571,7 +1575,7 @@ // Create a memory-backed CMBlockBuffer for the translated data. // TODO(sandersd): Pool of memory blocks. - base::ScopedCFTypeRef<CMBlockBufferRef> data; + base::apple::ScopedCFTypeRef<CMBlockBufferRef> data; OSStatus status = CMBlockBufferCreateWithMemoryBlock( kCFAllocatorDefault, nullptr, // &memory_block @@ -1622,7 +1626,7 @@ } // Package the data in a CMSampleBuffer. - base::ScopedCFTypeRef<CMSampleBufferRef> sample; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample; status = CMSampleBufferCreate(kCFAllocatorDefault, data, // data_buffer true, // data_ready @@ -2159,7 +2163,7 @@ // will not reuse the IOSurface as long as the SharedImage is alive. auto destroy_shared_image_lambda = [](gpu::SharedImageStub::SharedImageDestructionCallback callback, - base::ScopedCFTypeRef<CVImageBufferRef> image, + base::apple::ScopedCFTypeRef<CVImageBufferRef> image, scoped_refptr<base::SingleThreadTaskRunner> task_runner) { task_runner->PostTask( FROM_HERE, base::BindOnce(std::move(callback), gpu::SyncToken()));
diff --git a/media/gpu/mac/vt_video_decode_accelerator_mac.h b/media/gpu/mac/vt_video_decode_accelerator_mac.h index 698ccd3..2c4057b6 100644 --- a/media/gpu/mac/vt_video_decode_accelerator_mac.h +++ b/media/gpu/mac/vt_video_decode_accelerator_mac.h
@@ -143,7 +143,7 @@ gfx::Size image_size; // Decoded image, if decoding was successful. - base::ScopedCFTypeRef<CVImageBufferRef> image; + base::apple::ScopedCFTypeRef<CVImageBufferRef> image; // Dynamic HDR metadata, if any. absl::optional<gfx::HDRMetadata> hdr_metadata; @@ -289,8 +289,8 @@ // Decoder thread state. // VTDecompressionOutputCallbackRecord callback_; - base::ScopedCFTypeRef<CMFormatDescriptionRef> format_; - base::ScopedCFTypeRef<VTDecompressionSessionRef> session_; + base::apple::ScopedCFTypeRef<CMFormatDescriptionRef> format_; + base::apple::ScopedCFTypeRef<VTDecompressionSessionRef> session_; H264Parser h264_parser_; // SPSs and PPSs seen in the bitstream.
diff --git a/media/gpu/mac/vt_video_encode_accelerator_mac.cc b/media/gpu/mac/vt_video_encode_accelerator_mac.cc index d3a5e67..06e1d31 100644 --- a/media/gpu/mac/vt_video_encode_accelerator_mac.cc +++ b/media/gpu/mac/vt_video_encode_accelerator_mac.cc
@@ -121,7 +121,7 @@ #if BUILDFLAG(IS_MAC) info.is_hardware_accelerated = false; - base::ScopedCFTypeRef<CFBooleanRef> cf_using_hardware; + base::apple::ScopedCFTypeRef<CFBooleanRef> cf_using_hardware; if (VTSessionCopyProperty( compression_session, kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder, @@ -134,7 +134,7 @@ #endif absl::optional<int> max_frame_delay_property; - base::ScopedCFTypeRef<CFNumberRef> max_frame_delay_count; + base::apple::ScopedCFTypeRef<CFNumberRef> max_frame_delay_count; if (VTSessionCopyProperty( compression_session, kVTCompressionPropertyKey_MaxFrameDelayCount, kCFAllocatorDefault, max_frame_delay_count.InitializeInto()) == 0) { @@ -194,7 +194,7 @@ EncodeOutput& operator=(const EncodeOutput&) = delete; const VTEncodeInfoFlags info; - const base::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; + const base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; const base::TimeDelta capture_timestamp; const gfx::ColorSpace encoded_color_space; }; @@ -448,7 +448,7 @@ } } - base::ScopedCFTypeRef<CFDictionaryRef> frame_props = + base::apple::ScopedCFTypeRef<CFDictionaryRef> frame_props = video_toolbox::DictionaryWithKeyValue( kVTEncodeFrameOptionKey_ForceKeyFrame, force_keyframe ? kCFBooleanTrue : kCFBooleanFalse); @@ -758,7 +758,7 @@ encoder_values.push_back(kCFBooleanTrue); } } - base::ScopedCFTypeRef<CFDictionaryRef> encoder_spec = + base::apple::ScopedCFTypeRef<CFDictionaryRef> encoder_spec = video_toolbox::DictionaryWithKeysAndValues( encoder_keys.data(), encoder_values.data(), encoder_keys.size());
diff --git a/media/gpu/mac/vt_video_encode_accelerator_mac.h b/media/gpu/mac/vt_video_encode_accelerator_mac.h index 51f62ed3..663f36a 100644 --- a/media/gpu/mac/vt_video_encode_accelerator_mac.h +++ b/media/gpu/mac/vt_video_encode_accelerator_mac.h
@@ -109,7 +109,7 @@ base::TimeDelta AssignMonotonicTimestamp(); - base::ScopedCFTypeRef<VTCompressionSessionRef> compression_session_; + base::apple::ScopedCFTypeRef<VTCompressionSessionRef> compression_session_; gfx::Size input_visible_size_; size_t bitstream_buffer_size_ = 0;
diff --git a/media/gpu/test/video_decode_accelerator_tests.cc b/media/gpu/test/video_decode_accelerator_tests.cc index 7c26b99..8e12167 100644 --- a/media/gpu/test/video_decode_accelerator_tests.cc +++ b/media/gpu/test/video_decode_accelerator_tests.cc
@@ -245,10 +245,14 @@ static const base::NoDestructor<base::CPU> cpuid; constexpr int kPentiumAndLaterFamily = 0x06; constexpr int kGeminiLakeModelId = 0x7A; + constexpr int kApolloLakeModelId = 0x5c; static const bool is_glk_device = cpuid->family() == kPentiumAndLaterFamily && cpuid->model() == kGeminiLakeModelId; - return is_glk_device; + static const bool is_apl_device = + cpuid->family() == kPentiumAndLaterFamily && + cpuid->model() == kApolloLakeModelId; + return is_glk_device || is_apl_device; } // TODO(hiroh): Move this to Video class or video_frame_helpers.h.
diff --git a/net/base/net_string_util_icu_alternatives_ios.mm b/net/base/net_string_util_icu_alternatives_ios.mm index df52f5c..725b7ffa 100644 --- a/net/base/net_string_util_icu_alternatives_ios.mm +++ b/net/base/net_string_util_icu_alternatives_ios.mm
@@ -44,7 +44,7 @@ if (!CharsetToCFStringEncoding(charset, &encoding)) return false; - base::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytes( + base::apple::ScopedCFTypeRef<CFStringRef> cfstring(CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(text.data()), base::checked_cast<CFIndex>(text.length()), encoding, /*isExternalRepresentation=*/false)); @@ -77,9 +77,9 @@ } bool ToUpper(base::StringPiece16 str, std::u16string* output) { - base::ScopedCFTypeRef<CFStringRef> cfstring = + base::apple::ScopedCFTypeRef<CFStringRef> cfstring = base::SysUTF16ToCFStringRef(str); - base::ScopedCFTypeRef<CFMutableStringRef> mutable_cfstring( + base::apple::ScopedCFTypeRef<CFMutableStringRef> mutable_cfstring( CFStringCreateMutableCopy(kCFAllocatorDefault, /*maxLength=*/0, cfstring.get())); CFStringUppercase(mutable_cfstring.get(), /*locale=*/nullptr);
diff --git a/net/base/network_change_notifier_mac.h b/net/base/network_change_notifier_mac.h index be9949c..058d5ce 100644 --- a/net/base/network_change_notifier_mac.h +++ b/net/base/network_change_notifier_mac.h
@@ -73,8 +73,8 @@ bool connection_type_initialized_ = false; mutable base::Lock connection_type_lock_; mutable base::ConditionVariable initial_connection_type_cv_; - base::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability_; - base::ScopedCFTypeRef<CFRunLoopRef> run_loop_; + base::apple::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability_; + base::apple::ScopedCFTypeRef<CFRunLoopRef> run_loop_; Forwarder forwarder_; std::unique_ptr<const NetworkConfigWatcherMac> config_watcher_;
diff --git a/net/base/network_change_notifier_mac.mm b/net/base/network_change_notifier_mac.mm index 9391ef2..c2d7e670 100644 --- a/net/base/network_change_notifier_mac.mm +++ b/net/base/network_change_notifier_mac.mm
@@ -263,9 +263,9 @@ // SCDynamicStore API does not exist on iOS. NOTREACHED(); #else - base::ScopedCFTypeRef<CFMutableArrayRef> notification_keys( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> notification_keys( CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)); - base::ScopedCFTypeRef<CFStringRef> key( + base::apple::ScopedCFTypeRef<CFStringRef> key( SCDynamicStoreKeyCreateNetworkGlobalEntity( nullptr, kSCDynamicStoreDomainState, kSCEntNetInterface)); CFArrayAppendValue(notification_keys.get(), key.get());
diff --git a/net/base/network_change_notifier_win.cc b/net/base/network_change_notifier_win.cc index 17fffeff..1f128c16 100644 --- a/net/base/network_change_notifier_win.cc +++ b/net/base/network_change_notifier_win.cc
@@ -19,6 +19,7 @@ #include "base/task/thread_pool.h" #include "base/threading/thread.h" #include "base/time/time.h" +#include "base/win/windows_version.h" #include "net/base/winsock_init.h" #include "net/base/winsock_util.h" @@ -152,6 +153,43 @@ return params; } +// static +NetworkChangeNotifier::ConnectionType +NetworkChangeNotifierWin::RecomputeCurrentConnectionTypeModern() { + using GetNetworkConnectivityHintType = + decltype(&::GetNetworkConnectivityHint); + + // This API is only available on Windows 10 Build 19041. However, it works + // inside the Network Service Sandbox, so is preferred. See + GetNetworkConnectivityHintType get_network_connectivity_hint = + reinterpret_cast<GetNetworkConnectivityHintType>(::GetProcAddress( + ::GetModuleHandleA("iphlpapi.dll"), "GetNetworkConnectivityHint")); + if (!get_network_connectivity_hint) { + return NetworkChangeNotifier::CONNECTION_UNKNOWN; + } + NL_NETWORK_CONNECTIVITY_HINT hint; + // https://learn.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-getnetworkconnectivityhint. + auto ret = get_network_connectivity_hint(&hint); + if (ret != NO_ERROR) { + return NetworkChangeNotifier::CONNECTION_UNKNOWN; + } + + switch (hint.ConnectivityLevel) { + case NetworkConnectivityLevelHintUnknown: + return NetworkChangeNotifier::CONNECTION_UNKNOWN; + case NetworkConnectivityLevelHintNone: + case NetworkConnectivityLevelHintHidden: + return NetworkChangeNotifier::CONNECTION_NONE; + case NetworkConnectivityLevelHintLocalAccess: + case NetworkConnectivityLevelHintInternetAccess: + case NetworkConnectivityLevelHintConstrainedInternetAccess: + // TODO(droger): Return something more detailed than CONNECTION_UNKNOWN. + return ConnectionTypeFromInterfaces(); + } + + NOTREACHED_NORETURN(); +} + // This implementation does not return the actual connection type but merely // determines if the user is "online" (in which case it returns // CONNECTION_UNKNOWN) or "offline" (and then it returns CONNECTION_NONE). @@ -203,6 +241,10 @@ // static NetworkChangeNotifier::ConnectionType NetworkChangeNotifierWin::RecomputeCurrentConnectionType() { + if (base::win::GetVersion() >= base::win::Version::WIN10_20H1) { + return RecomputeCurrentConnectionTypeModern(); + } + EnsureWinsockInit(); // The following code was adapted from:
diff --git a/net/base/network_change_notifier_win.h b/net/base/network_change_notifier_win.h index c448665e..055db7354 100644 --- a/net/base/network_change_notifier_win.h +++ b/net/base/network_change_notifier_win.h
@@ -72,8 +72,13 @@ // Must only be called on the sequence |this| was created on. void OnObjectSignaled(HANDLE object) override; - // Does the actual work to determine the current connection type. - // It is not thread safe, see crbug.com/324913. + // Recompute the current connection type on newer versions of Windows (Win10 + // Build 19041 and above). + static ConnectionType RecomputeCurrentConnectionTypeModern(); + + // Does the actual work to determine the current connection type. This will + // call into RecomputeCurrentConnectionTypeModern on modern OS. It is not + // thread safe, see crbug.com/324913. static ConnectionType RecomputeCurrentConnectionType(); // Calls RecomputeCurrentConnectionTypeImpl on the DNS sequence and runs
diff --git a/net/base/network_config_watcher_mac.cc b/net/base/network_config_watcher_mac.cc index 312801d0..5dbcb96a 100644 --- a/net/base/network_config_watcher_mac.cc +++ b/net/base/network_config_watcher_mac.cc
@@ -61,7 +61,7 @@ // Returns whether initializing notifications has succeeded. bool InitNotificationsHelper(); - base::ScopedCFTypeRef<CFRunLoopSourceRef> run_loop_source_; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> run_loop_source_; const raw_ptr<NetworkConfigWatcherMac::Delegate> delegate_; #if !BUILDFLAG(IS_IOS) int num_retry_ = 0; @@ -135,7 +135,7 @@ nullptr, // This is not reference counted. No release function. nullptr, // No description for this. }; - base::ScopedCFTypeRef<SCDynamicStoreRef> store(SCDynamicStoreCreate( + base::apple::ScopedCFTypeRef<SCDynamicStoreRef> store(SCDynamicStoreCreate( nullptr, CFSTR("org.chromium"), DynamicStoreCallback, &context)); if (!store) { int error = SCError();
diff --git a/net/base/platform_mime_util_mac.mm b/net/base/platform_mime_util_mac.mm index 111c659..4eac8e2 100644 --- a/net/base/platform_mime_util_mac.mm +++ b/net/base/platform_mime_util_mac.mm
@@ -50,19 +50,19 @@ MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0) || \ (BUILDFLAG(IS_IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_14_0) else { - base::ScopedCFTypeRef<CFStringRef> ext_ref( + base::apple::ScopedCFTypeRef<CFStringRef> ext_ref( base::SysUTF8ToCFStringRef(ext_nodot)); if (!ext_ref) { return false; } - base::ScopedCFTypeRef<CFStringRef> uti( + base::apple::ScopedCFTypeRef<CFStringRef> uti( UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext_ref, /*inConformingToUTI=*/nullptr)); if (!uti) { return false; } - base::ScopedCFTypeRef<CFStringRef> mime_ref( + base::apple::ScopedCFTypeRef<CFStringRef> mime_ref( UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)); if (!mime_ref) { return false; @@ -97,18 +97,18 @@ MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0) || \ (BUILDFLAG(IS_IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_14_0) else { - base::ScopedCFTypeRef<CFStringRef> mime_ref( + base::apple::ScopedCFTypeRef<CFStringRef> mime_ref( base::SysUTF8ToCFStringRef(mime_type)); if (!mime_ref) { return false; } - base::ScopedCFTypeRef<CFStringRef> uti( + base::apple::ScopedCFTypeRef<CFStringRef> uti( UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime_ref, /*inConformingToUTI=*/nullptr)); if (!uti) { return false; } - base::ScopedCFTypeRef<CFStringRef> ext_ref( + base::apple::ScopedCFTypeRef<CFStringRef> ext_ref( UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension)); if (!ext_ref) { return false; @@ -166,15 +166,16 @@ MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_11_0) || \ (BUILDFLAG(IS_IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_14_0) else { - base::ScopedCFTypeRef<CFStringRef> mime_ref( + base::apple::ScopedCFTypeRef<CFStringRef> mime_ref( base::SysUTF8ToCFStringRef(mime_type)); if (mime_ref) { bool extensions_found = false; - base::ScopedCFTypeRef<CFArrayRef> types(UTTypeCreateAllIdentifiersForTag( - kUTTagClassMIMEType, mime_ref, nullptr)); + base::apple::ScopedCFTypeRef<CFArrayRef> types( + UTTypeCreateAllIdentifiersForTag(kUTTagClassMIMEType, mime_ref, + nullptr)); if (types) { for (CFIndex i = 0; i < CFArrayGetCount(types); i++) { - base::ScopedCFTypeRef<CFArrayRef> extensions_list( + base::apple::ScopedCFTypeRef<CFArrayRef> extensions_list( UTTypeCopyAllTagsWithClass(base::apple::CFCast<CFStringRef>( CFArrayGetValueAtIndex(types, i)), kUTTagClassFilenameExtension));
diff --git a/net/cert/cert_verify_proc_ios.cc b/net/cert/cert_verify_proc_ios.cc index 853b7b6..ab6fe5b1 100644 --- a/net/cert/cert_verify_proc_ios.cc +++ b/net/cert/cert_verify_proc_ios.cc
@@ -23,7 +23,7 @@ #include "net/cert/x509_util.h" #include "net/cert/x509_util_apple.h" -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; namespace net { @@ -145,7 +145,8 @@ if (!local_policies) return errSecAllocate; - base::ScopedCFTypeRef<SecPolicyRef> ssl_policy(SecPolicyCreateBasicX509()); + base::apple::ScopedCFTypeRef<SecPolicyRef> ssl_policy( + SecPolicyCreateBasicX509()); CFArrayAppendValue(local_policies, ssl_policy); ssl_policy.reset(SecPolicyCreateSSL(/*server=*/true, /*hostname=*/nullptr)); CFArrayAppendValue(local_policies, ssl_policy); @@ -230,8 +231,8 @@ void GetCertChainInfo(CFArrayRef cert_chain, CertVerifyResult* verify_result) { DCHECK_LT(0, CFArrayGetCount(cert_chain)); - base::ScopedCFTypeRef<SecCertificateRef> verified_cert; - std::vector<base::ScopedCFTypeRef<SecCertificateRef>> verified_chain; + base::apple::ScopedCFTypeRef<SecCertificateRef> verified_cert; + std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>> verified_chain; for (CFIndex i = 0, count = CFArrayGetCount(cert_chain); i < count; ++i) { SecCertificateRef chain_cert = reinterpret_cast<SecCertificateRef>( const_cast<void*>(CFArrayGetValueAtIndex(cert_chain, i))); @@ -241,7 +242,7 @@ verified_chain.emplace_back(chain_cert, base::scoped_policy::RETAIN); } - base::ScopedCFTypeRef<CFDataRef> der_data( + base::apple::ScopedCFTypeRef<CFDataRef> der_data( SecCertificateCopyData(chain_cert)); if (!der_data) { verify_result->cert_status |= CERT_STATUS_INVALID; @@ -287,7 +288,8 @@ if (!error) return CERT_STATUS_INVALID; - base::ScopedCFTypeRef<CFStringRef> error_domain(CFErrorGetDomain(error)); + base::apple::ScopedCFTypeRef<CFStringRef> error_domain( + CFErrorGetDomain(error)); CFIndex error_code = CFErrorGetCode(error); if (error_domain != kCFErrorDomainOSStatus) { @@ -315,7 +317,8 @@ CertStatus CertVerifyProcIOS::GetCertFailureStatusFromTrust(SecTrustRef trust) { CertStatus reason = 0; - base::ScopedCFTypeRef<CFArrayRef> properties(SecTrustCopyProperties(trust)); + base::apple::ScopedCFTypeRef<CFArrayRef> properties( + SecTrustCopyProperties(trust)); if (!properties) return CERT_STATUS_INVALID;
diff --git a/net/cert/internal/trust_store_mac.cc b/net/cert/internal/trust_store_mac.cc index f19f49e..79d83ce 100644 --- a/net/cert/internal/trust_store_mac.cc +++ b/net/cert/internal/trust_store_mac.cc
@@ -132,7 +132,7 @@ *debug_info |= TrustStoreMac::TRUST_SETTINGS_DICT_INVALID_POLICY_TYPE; return TrustStatus::UNSPECIFIED; } - base::ScopedCFTypeRef<CFDictionaryRef> policy_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> policy_dict( SecPolicyCopyProperties(policy_ref)); // kSecPolicyOid is guaranteed to be present in the policy dictionary. @@ -221,7 +221,7 @@ int* debug_info) { crypto::GetMacSecurityServicesLock().AssertAcquired(); - base::ScopedCFTypeRef<CFArrayRef> trust_settings; + base::apple::ScopedCFTypeRef<CFArrayRef> trust_settings; OSStatus err = SecTrustSettingsCopyTrustSettings( cert_handle, trust_domain, trust_settings.InitializeInto()); @@ -254,7 +254,7 @@ // a cert will have trust settings in only zero or one domains, and when in // more than one domain it would generally be because one domain is // overriding the setting in the next, so it would only get done once anyway. - base::ScopedCFTypeRef<SecCertificateRef> cert_handle = + base::apple::ScopedCFTypeRef<SecCertificateRef> cert_handle = x509_util::CreateSecCertificateFromBytes(cert->der_cert().UnsafeData(), cert->der_cert().Length()); if (!cert_handle) @@ -280,7 +280,7 @@ // admin (and both override the system domain, but we don't check that). for (const auto& trust_domain : {kSecTrustSettingsDomainUser, kSecTrustSettingsDomainAdmin}) { - base::ScopedCFTypeRef<CFArrayRef> trust_settings; + base::apple::ScopedCFTypeRef<CFArrayRef> trust_settings; OSStatus err; err = SecTrustSettingsCopyTrustSettings(cert_handle, trust_domain, trust_settings.InitializeInto()); @@ -307,7 +307,7 @@ TrustStatus IsCertificateTrustedForPolicy(const ParsedCertificate* cert, const CFStringRef policy_oid, int* debug_info) { - base::ScopedCFTypeRef<SecCertificateRef> cert_handle = + base::apple::ScopedCFTypeRef<SecCertificateRef> cert_handle = x509_util::CreateSecCertificateFromBytes(cert->der_cert().UnsafeData(), cert->der_cert().Length()); @@ -378,7 +378,7 @@ trust_status_cache_.clear(); cert_issuer_source_.Clear(); - base::ScopedCFTypeRef<CFArrayRef> cert_array; + base::apple::ScopedCFTypeRef<CFArrayRef> cert_array; OSStatus rv; { base::AutoLock lock(crypto::GetMacSecurityServicesLock()); @@ -396,7 +396,8 @@ for (CFIndex i = 0, size = CFArrayGetCount(cert_array); i < size; ++i) { SecCertificateRef cert = reinterpret_cast<SecCertificateRef>( const_cast<void*>(CFArrayGetValueAtIndex(cert_array, i))); - base::ScopedCFTypeRef<CFDataRef> der_data(SecCertificateCopyData(cert)); + base::apple::ScopedCFTypeRef<CFDataRef> der_data( + SecCertificateCopyData(cert)); if (!der_data) { LOG(ERROR) << "SecCertificateCopyData error"; continue; @@ -774,7 +775,7 @@ intermediates_cert_issuer_source_.Clear(); - base::ScopedCFTypeRef<CFMutableDictionaryRef> query( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -784,7 +785,8 @@ base::AutoLock lock(crypto::GetMacSecurityServicesLock()); - base::ScopedCFTypeRef<CFArrayRef> scoped_alternate_keychain_search_list; + base::apple::ScopedCFTypeRef<CFArrayRef> + scoped_alternate_keychain_search_list; if (TestKeychainSearchList::HasInstance()) { OSStatus status = TestKeychainSearchList::GetInstance()->CopySearchList( scoped_alternate_keychain_search_list.InitializeInto()); @@ -797,7 +799,7 @@ scoped_alternate_keychain_search_list.get()); } - base::ScopedCFTypeRef<CFTypeRef> matching_items; + base::apple::ScopedCFTypeRef<CFTypeRef> matching_items; OSStatus err = SecItemCopyMatching(query, matching_items.InitializeInto()); if (err == errSecItemNotFound) { RecordCachedIntermediatesHistograms(0, timer.Elapsed()); @@ -826,7 +828,7 @@ continue; } - base::ScopedCFTypeRef<CFDataRef> der_data( + base::apple::ScopedCFTypeRef<CFDataRef> der_data( SecCertificateCopyData(match_cert_handle)); if (!der_data) { LOG(ERROR) << "SecCertificateCopyData error"; @@ -871,7 +873,7 @@ keychain_trust_observer_; const std::unique_ptr<KeychainCertsObserver, base::OnTaskRunnerDeleter> keychain_certs_observer_; - const base::ScopedCFTypeRef<CFStringRef> policy_oid_; + const base::apple::ScopedCFTypeRef<CFStringRef> policy_oid_; base::Lock cache_lock_; // |cache_lock_| must be held while accessing any following members. @@ -956,7 +958,7 @@ trust_status_cache_.clear(); cert_issuer_source_.Clear(); - base::ScopedCFTypeRef<CFMutableDictionaryRef> query( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -966,7 +968,8 @@ base::AutoLock lock(crypto::GetMacSecurityServicesLock()); - base::ScopedCFTypeRef<CFArrayRef> scoped_alternate_keychain_search_list; + base::apple::ScopedCFTypeRef<CFArrayRef> + scoped_alternate_keychain_search_list; if (TestKeychainSearchList::HasInstance()) { OSStatus status = TestKeychainSearchList::GetInstance()->CopySearchList( scoped_alternate_keychain_search_list.InitializeInto()); @@ -979,7 +982,7 @@ scoped_alternate_keychain_search_list.get()); } - base::ScopedCFTypeRef<CFTypeRef> matching_items; + base::apple::ScopedCFTypeRef<CFTypeRef> matching_items; OSStatus err = SecItemCopyMatching(query, matching_items.InitializeInto()); if (err == errSecItemNotFound) { RecordHistograms(0, timer.Elapsed()); @@ -999,7 +1002,7 @@ SecCertificateRef sec_cert = base::apple::CFCastStrict<SecCertificateRef>( CFArrayGetValueAtIndex(matching_items_array, i)); - base::ScopedCFTypeRef<CFDataRef> der_data( + base::apple::ScopedCFTypeRef<CFDataRef> der_data( SecCertificateCopyData(sec_cert)); if (!der_data) { LOG(ERROR) << "SecCertificateCopyData error"; @@ -1059,7 +1062,7 @@ const std::unique_ptr<KeychainTrustOrCertsObserver, base::OnTaskRunnerDeleter> keychain_observer_; - const base::ScopedCFTypeRef<CFStringRef> policy_oid_; + const base::apple::ScopedCFTypeRef<CFStringRef> policy_oid_; base::Lock cache_lock_; // |cache_lock_| must be held while accessing any following members. @@ -1132,7 +1135,8 @@ return; } - base::ScopedCFTypeRef<CFDataRef> name_data = GetMacNormalizedIssuer(cert); + base::apple::ScopedCFTypeRef<CFDataRef> name_data = + GetMacNormalizedIssuer(cert); if (!name_data) return; @@ -1198,7 +1202,7 @@ TrustStoreMac::FindMatchingCertificatesForMacNormalizedSubject( CFDataRef name_data) { std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> matching_cert_buffers; - base::ScopedCFTypeRef<CFMutableDictionaryRef> query( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> query( CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -1209,7 +1213,8 @@ base::AutoLock lock(crypto::GetMacSecurityServicesLock()); - base::ScopedCFTypeRef<CFArrayRef> scoped_alternate_keychain_search_list; + base::apple::ScopedCFTypeRef<CFArrayRef> + scoped_alternate_keychain_search_list; if (TestKeychainSearchList::HasInstance()) { OSStatus status = TestKeychainSearchList::GetInstance()->CopySearchList( scoped_alternate_keychain_search_list.InitializeInto()); @@ -1225,7 +1230,7 @@ scoped_alternate_keychain_search_list.get()); } - base::ScopedCFTypeRef<CFArrayRef> matching_items; + base::apple::ScopedCFTypeRef<CFArrayRef> matching_items; OSStatus err = SecItemCopyMatching( query, reinterpret_cast<CFTypeRef*>(matching_items.InitializeInto())); if (err == errSecItemNotFound) { @@ -1242,7 +1247,7 @@ SecCertificateRef match_cert_handle = reinterpret_cast<SecCertificateRef>( const_cast<void*>(CFArrayGetValueAtIndex(matching_items, i))); - base::ScopedCFTypeRef<CFDataRef> der_data( + base::apple::ScopedCFTypeRef<CFDataRef> der_data( SecCertificateCopyData(match_cert_handle)); if (!der_data) { LOG(ERROR) << "SecCertificateCopyData error"; @@ -1257,13 +1262,13 @@ } // static -base::ScopedCFTypeRef<CFDataRef> TrustStoreMac::GetMacNormalizedIssuer( +base::apple::ScopedCFTypeRef<CFDataRef> TrustStoreMac::GetMacNormalizedIssuer( const ParsedCertificate* cert) { - base::ScopedCFTypeRef<CFDataRef> name_data; + base::apple::ScopedCFTypeRef<CFDataRef> name_data; base::AutoLock lock(crypto::GetMacSecurityServicesLock()); // There does not appear to be any public API to get the normalized version // of a Name without creating a SecCertificate. - base::ScopedCFTypeRef<SecCertificateRef> cert_handle( + base::apple::ScopedCFTypeRef<SecCertificateRef> cert_handle( x509_util::CreateSecCertificateFromBytes(cert->der_cert().UnsafeData(), cert->der_cert().Length())); if (!cert_handle) {
diff --git a/net/cert/internal/trust_store_mac.h b/net/cert/internal/trust_store_mac.h index 7ac4c587..ac2b299 100644 --- a/net/cert/internal/trust_store_mac.h +++ b/net/cert/internal/trust_store_mac.h
@@ -145,7 +145,7 @@ // macOS internally uses a normalized form of subject/issuer names for // comparing, roughly similar to RFC3280's normalization scheme. The // normalized form is used for any database lookups and comparisons. - static base::ScopedCFTypeRef<CFDataRef> GetMacNormalizedIssuer( + static base::apple::ScopedCFTypeRef<CFDataRef> GetMacNormalizedIssuer( const ParsedCertificate* cert); std::unique_ptr<TrustImpl> trust_cache_;
diff --git a/net/cert/internal/trust_store_mac_unittest.cc b/net/cert/internal/trust_store_mac_unittest.cc index eb1faeb1..09fad31 100644 --- a/net/cert/internal/trust_store_mac_unittest.cc +++ b/net/cert/internal/trust_store_mac_unittest.cc
@@ -191,7 +191,7 @@ // SecKeychainOpen does not fail if the file doesn't exist, so assert it here // for easier debugging. ASSERT_TRUE(base::PathExists(keychain_path)); - base::ScopedCFTypeRef<SecKeychainRef> keychain; + base::apple::ScopedCFTypeRef<SecKeychainRef> keychain; OSStatus status = SecKeychainOpen(keychain_path.MaybeAsASCII().c_str(), keychain.InitializeInto()); ASSERT_EQ(errSecSuccess, status); @@ -309,7 +309,8 @@ base::HistogramTester histogram_tester; TrustStoreMac trust_store(kSecPolicyAppleX509Basic, trust_impl); - base::ScopedCFTypeRef<SecPolicyRef> sec_policy(SecPolicyCreateBasicX509()); + base::apple::ScopedCFTypeRef<SecPolicyRef> sec_policy( + SecPolicyCreateBasicX509()); ASSERT_TRUE(sec_policy); std::vector<std::string> all_certs; std::set_union(find_certificate_default_search_list_certs.begin(), @@ -339,7 +340,7 @@ continue; } - base::ScopedCFTypeRef<SecCertificateRef> cert_handle( + base::apple::ScopedCFTypeRef<SecCertificateRef> cert_handle( x509_util::CreateSecCertificateFromBytes(cert->der_cert().UnsafeData(), cert->der_cert().Length())); if (!cert_handle) { @@ -357,7 +358,7 @@ } // Check if this cert is considered a trust anchor by the OS. - base::ScopedCFTypeRef<SecTrustRef> trust; + base::apple::ScopedCFTypeRef<SecTrustRef> trust; { base::AutoLock lock(crypto::GetMacSecurityServicesLock()); ASSERT_EQ(noErr,
diff --git a/net/cert/test_keychain_search_list_mac.h b/net/cert/test_keychain_search_list_mac.h index caaffdad..77b8819 100644 --- a/net/cert/test_keychain_search_list_mac.h +++ b/net/cert/test_keychain_search_list_mac.h
@@ -40,7 +40,7 @@ private: TestKeychainSearchList(); - base::ScopedCFTypeRef<CFMutableArrayRef> scoped_keychain_search_list; + base::apple::ScopedCFTypeRef<CFMutableArrayRef> scoped_keychain_search_list; }; } // namespace net
diff --git a/net/cert/test_root_certs.h b/net/cert/test_root_certs.h index f49c24a..ffab56b0 100644 --- a/net/cert/test_root_certs.h +++ b/net/cert/test_root_certs.h
@@ -82,7 +82,7 @@ void ClearImpl(); #if BUILDFLAG(IS_IOS) - base::ScopedCFTypeRef<CFMutableArrayRef> temporary_roots_; + base::apple::ScopedCFTypeRef<CFMutableArrayRef> temporary_roots_; #endif TrustStoreInMemory test_trust_store_;
diff --git a/net/cert/test_root_certs_ios.cc b/net/cert/test_root_certs_ios.cc index dd4477a7..cddabe7 100644 --- a/net/cert/test_root_certs_ios.cc +++ b/net/cert/test_root_certs_ios.cc
@@ -15,7 +15,7 @@ namespace net { bool TestRootCerts::AddImpl(X509Certificate* certificate) { - base::ScopedCFTypeRef<SecCertificateRef> os_cert( + base::apple::ScopedCFTypeRef<SecCertificateRef> os_cert( x509_util::CreateSecCertificateFromX509Certificate(certificate)); if (!os_cert) { return false;
diff --git a/net/cert/x509_util_apple.cc b/net/cert/x509_util_apple.cc index 164a79b..415acbd 100644 --- a/net/cert/x509_util_apple.cc +++ b/net/cert/x509_util_apple.cc
@@ -27,7 +27,8 @@ if (!sec_cert) { return nullptr; } - base::ScopedCFTypeRef<CFDataRef> der_data(SecCertificateCopyData(sec_cert)); + base::apple::ScopedCFTypeRef<CFDataRef> der_data( + SecCertificateCopyData(sec_cert)); if (!der_data) { return nullptr; } @@ -38,53 +39,53 @@ } // namespace -base::ScopedCFTypeRef<SecCertificateRef> CreateSecCertificateFromBytes( +base::apple::ScopedCFTypeRef<SecCertificateRef> CreateSecCertificateFromBytes( const uint8_t* data, size_t length) { - base::ScopedCFTypeRef<CFDataRef> cert_data( + base::apple::ScopedCFTypeRef<CFDataRef> cert_data( CFDataCreate(kCFAllocatorDefault, reinterpret_cast<const UInt8*>(data), base::checked_cast<CFIndex>(length))); if (!cert_data) - return base::ScopedCFTypeRef<SecCertificateRef>(); + return base::apple::ScopedCFTypeRef<SecCertificateRef>(); - return base::ScopedCFTypeRef<SecCertificateRef>( + return base::apple::ScopedCFTypeRef<SecCertificateRef>( SecCertificateCreateWithData(nullptr, cert_data)); } -base::ScopedCFTypeRef<SecCertificateRef> +base::apple::ScopedCFTypeRef<SecCertificateRef> CreateSecCertificateFromX509Certificate(const X509Certificate* cert) { return CreateSecCertificateFromBytes(CRYPTO_BUFFER_data(cert->cert_buffer()), CRYPTO_BUFFER_len(cert->cert_buffer())); } -base::ScopedCFTypeRef<CFMutableArrayRef> +base::apple::ScopedCFTypeRef<CFMutableArrayRef> CreateSecCertificateArrayForX509Certificate(X509Certificate* cert) { return CreateSecCertificateArrayForX509Certificate( cert, InvalidIntermediateBehavior::kFail); } -base::ScopedCFTypeRef<CFMutableArrayRef> +base::apple::ScopedCFTypeRef<CFMutableArrayRef> CreateSecCertificateArrayForX509Certificate( X509Certificate* cert, InvalidIntermediateBehavior invalid_intermediate_behavior) { - base::ScopedCFTypeRef<CFMutableArrayRef> cert_list( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> cert_list( CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)); if (!cert_list) - return base::ScopedCFTypeRef<CFMutableArrayRef>(); + return base::apple::ScopedCFTypeRef<CFMutableArrayRef>(); std::string bytes; - base::ScopedCFTypeRef<SecCertificateRef> sec_cert( + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert( CreateSecCertificateFromBytes(CRYPTO_BUFFER_data(cert->cert_buffer()), CRYPTO_BUFFER_len(cert->cert_buffer()))); if (!sec_cert) - return base::ScopedCFTypeRef<CFMutableArrayRef>(); + return base::apple::ScopedCFTypeRef<CFMutableArrayRef>(); CFArrayAppendValue(cert_list, sec_cert); for (const auto& intermediate : cert->intermediate_buffers()) { - base::ScopedCFTypeRef<SecCertificateRef> intermediate_cert( + base::apple::ScopedCFTypeRef<SecCertificateRef> intermediate_cert( CreateSecCertificateFromBytes(CRYPTO_BUFFER_data(intermediate.get()), CRYPTO_BUFFER_len(intermediate.get()))); if (!intermediate_cert) { if (invalid_intermediate_behavior == InvalidIntermediateBehavior::kFail) - return base::ScopedCFTypeRef<CFMutableArrayRef>(); + return base::apple::ScopedCFTypeRef<CFMutableArrayRef>(); LOG(WARNING) << "error parsing intermediate"; continue; } @@ -94,14 +95,16 @@ } scoped_refptr<X509Certificate> CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef> sec_cert, - const std::vector<base::ScopedCFTypeRef<SecCertificateRef>>& sec_chain) { + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert, + const std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>>& + sec_chain) { return CreateX509CertificateFromSecCertificate(sec_cert, sec_chain, {}); } scoped_refptr<X509Certificate> CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef> sec_cert, - const std::vector<base::ScopedCFTypeRef<SecCertificateRef>>& sec_chain, + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert, + const std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>>& + sec_chain, X509Certificate::UnsafeCreateOptions options) { bssl::UniquePtr<CRYPTO_BUFFER> cert_handle = CertBufferFromSecCertificate(sec_cert); @@ -127,7 +130,8 @@ SHA256HashValue sha256; memset(sha256.data, 0, sizeof(sha256.data)); - base::ScopedCFTypeRef<CFDataRef> cert_data(SecCertificateCopyData(cert)); + base::apple::ScopedCFTypeRef<CFDataRef> cert_data( + SecCertificateCopyData(cert)); if (!cert_data) { return sha256; } @@ -141,10 +145,10 @@ return sha256; } -base::ScopedCFTypeRef<CFArrayRef> CertificateChainFromSecTrust( +base::apple::ScopedCFTypeRef<CFArrayRef> CertificateChainFromSecTrust( SecTrustRef trust) { if (__builtin_available(macOS 12.0, iOS 15.0, *)) { - return base::ScopedCFTypeRef<CFArrayRef>( + return base::apple::ScopedCFTypeRef<CFArrayRef>( SecTrustCopyCertificateChain(trust)); } @@ -152,19 +156,19 @@ #if (BUILDFLAG(IS_MAC) && \ MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_VERSION_12_0) || \ (BUILDFLAG(IS_IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_15_0) - base::ScopedCFTypeRef<CFMutableArrayRef> chain( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> chain( CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks)); const CFIndex chain_length = SecTrustGetCertificateCount(trust); for (CFIndex i = 0; i < chain_length; ++i) { CFArrayAppendValue(chain, SecTrustGetCertificateAtIndex(trust, i)); } - return base::ScopedCFTypeRef<CFArrayRef>(chain.release()); + return base::apple::ScopedCFTypeRef<CFArrayRef>(chain.release()); #else // The other logic paths should be used, this is just to make the compiler // happy. NOTREACHED(); - return base::ScopedCFTypeRef<CFArrayRef>(nullptr); + return base::apple::ScopedCFTypeRef<CFArrayRef>(nullptr); #endif // (BUILDFLAG(IS_MAC) && MAC_OS_X_VERSION_MIN_REQUIRED < // MAC_OS_VERSION_12_0) // || (BUILDFLAG(IS_IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED <
diff --git a/net/cert/x509_util_apple.h b/net/cert/x509_util_apple.h index 5b939d55..775be2b 100644 --- a/net/cert/x509_util_apple.h +++ b/net/cert/x509_util_apple.h
@@ -19,11 +19,11 @@ // Creates a SecCertificate handle from the DER-encoded representation. // Returns NULL on failure. -NET_EXPORT base::ScopedCFTypeRef<SecCertificateRef> +NET_EXPORT base::apple::ScopedCFTypeRef<SecCertificateRef> CreateSecCertificateFromBytes(const uint8_t* data, size_t length); // Returns a SecCertificate representing |cert|, or NULL on failure. -NET_EXPORT base::ScopedCFTypeRef<SecCertificateRef> +NET_EXPORT base::apple::ScopedCFTypeRef<SecCertificateRef> CreateSecCertificateFromX509Certificate(const X509Certificate* cert); // Returns a new CFMutableArrayRef containing this certificate and its @@ -31,7 +31,7 @@ // and Keychain Services, or NULL on failure. // The first item in the array will be this certificate, followed by its // intermediates, if any. -NET_EXPORT base::ScopedCFTypeRef<CFMutableArrayRef> +NET_EXPORT base::apple::ScopedCFTypeRef<CFMutableArrayRef> CreateSecCertificateArrayForX509Certificate(X509Certificate* cert); // Specify behavior if an intermediate certificate fails SecCertificate @@ -45,7 +45,7 @@ // and Keychain Services. Returns NULL if the certificate could not be // converted. |invalid_intermediate_behavior| specifies behavior if // intermediates of |cert| could not be converted. -NET_EXPORT base::ScopedCFTypeRef<CFMutableArrayRef> +NET_EXPORT base::apple::ScopedCFTypeRef<CFMutableArrayRef> CreateSecCertificateArrayForX509Certificate( X509Certificate* cert, InvalidIntermediateBehavior invalid_intermediate_behavior); @@ -54,15 +54,17 @@ // |sec_chain|. NET_EXPORT scoped_refptr<X509Certificate> CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef> sec_cert, - const std::vector<base::ScopedCFTypeRef<SecCertificateRef>>& sec_chain); + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert, + const std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>>& + sec_chain); // Creates an X509Certificate with non-standard parsing options. // Do not use without consulting //net owners. NET_EXPORT scoped_refptr<X509Certificate> CreateX509CertificateFromSecCertificate( - base::ScopedCFTypeRef<SecCertificateRef> sec_cert, - const std::vector<base::ScopedCFTypeRef<SecCertificateRef>>& sec_chain, + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert, + const std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>>& + sec_chain, X509Certificate::UnsafeCreateOptions options); // Calculates the SHA-256 fingerprint of the certificate. Returns an empty @@ -70,7 +72,7 @@ NET_EXPORT SHA256HashValue CalculateFingerprint256(SecCertificateRef cert); // Returns a new CFArrayRef containing the certificate chain built in |trust|. -base::ScopedCFTypeRef<CFArrayRef> CertificateChainFromSecTrust( +base::apple::ScopedCFTypeRef<CFArrayRef> CertificateChainFromSecTrust( SecTrustRef trust); } // namespace x509_util
diff --git a/net/cert/x509_util_apple_unittest.cc b/net/cert/x509_util_apple_unittest.cc index 683827a7..2dc617b 100644 --- a/net/cert/x509_util_apple_unittest.cc +++ b/net/cert/x509_util_apple_unittest.cc
@@ -19,7 +19,8 @@ std::string BytesForSecCert(SecCertificateRef sec_cert) { std::string result; - base::ScopedCFTypeRef<CFDataRef> der_data(SecCertificateCopyData(sec_cert)); + base::apple::ScopedCFTypeRef<CFDataRef> der_data( + SecCertificateCopyData(sec_cert)); if (!der_data) { ADD_FAILURE(); return result; @@ -43,7 +44,7 @@ ASSERT_TRUE(cert); EXPECT_EQ(3U, cert->intermediate_buffers().size()); - base::ScopedCFTypeRef<CFMutableArrayRef> sec_certs( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> sec_certs( CreateSecCertificateArrayForX509Certificate(cert.get())); ASSERT_TRUE(sec_certs); ASSERT_EQ(4, CFArrayGetCount(sec_certs.get())); @@ -87,7 +88,7 @@ // With InvalidIntermediateBehavior::kIgnore, invalid intermediate certs // should be silently dropped. - base::ScopedCFTypeRef<CFMutableArrayRef> sec_certs( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> sec_certs( CreateSecCertificateArrayForX509Certificate( cert_with_intermediates.get(), InvalidIntermediateBehavior::kIgnore)); ASSERT_TRUE(sec_certs); @@ -143,26 +144,26 @@ std::string bytes_cert3( x509_util::CryptoBufferAsStringPiece(certs[3]->cert_buffer())); - base::ScopedCFTypeRef<SecCertificateRef> sec_cert0( + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert0( CreateSecCertificateFromBytes( reinterpret_cast<const uint8_t*>(bytes_cert0.data()), bytes_cert0.length())); ASSERT_TRUE(sec_cert0); EXPECT_EQ(bytes_cert0, BytesForSecCert(sec_cert0)); - base::ScopedCFTypeRef<SecCertificateRef> sec_cert1( + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert1( CreateSecCertificateFromBytes( reinterpret_cast<const uint8_t*>(bytes_cert1.data()), bytes_cert1.length())); ASSERT_TRUE(sec_cert1); EXPECT_EQ(bytes_cert1, BytesForSecCert(sec_cert1)); - base::ScopedCFTypeRef<SecCertificateRef> sec_cert2( + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert2( CreateSecCertificateFromX509Certificate(certs[2].get())); ASSERT_TRUE(sec_cert2); EXPECT_EQ(bytes_cert2, BytesForSecCert(sec_cert2)); - base::ScopedCFTypeRef<SecCertificateRef> sec_cert3( + base::apple::ScopedCFTypeRef<SecCertificateRef> sec_cert3( CreateSecCertificateFromX509Certificate(certs[3].get())); ASSERT_TRUE(sec_cert3); EXPECT_EQ(bytes_cert3, BytesForSecCert(sec_cert3));
diff --git a/net/proxy_resolution/proxy_config_service_ios.cc b/net/proxy_resolution/proxy_config_service_ios.cc index 1547de7..28ae2aa 100644 --- a/net/proxy_resolution/proxy_config_service_ios.cc +++ b/net/proxy_resolution/proxy_config_service_ios.cc
@@ -39,7 +39,7 @@ void GetCurrentProxyConfig(const NetworkTrafficAnnotationTag traffic_annotation, ProxyConfigWithAnnotation* config) { - base::ScopedCFTypeRef<CFDictionaryRef> config_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> config_dict( CFNetworkCopySystemProxySettings()); DCHECK(config_dict); ProxyConfig proxy_config;
diff --git a/net/proxy_resolution/proxy_config_service_mac.cc b/net/proxy_resolution/proxy_config_service_mac.cc index df67d961..fdfbf40 100644 --- a/net/proxy_resolution/proxy_config_service_mac.cc +++ b/net/proxy_resolution/proxy_config_service_mac.cc
@@ -44,7 +44,7 @@ void GetCurrentProxyConfig(const NetworkTrafficAnnotationTag traffic_annotation, ProxyConfigWithAnnotation* config) { - base::ScopedCFTypeRef<CFDictionaryRef> config_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> config_dict( SCDynamicStoreCopyProxies(nullptr)); DCHECK(config_dict); ProxyConfig proxy_config; @@ -241,9 +241,9 @@ SCDynamicStoreRef store) { // Called on notifier thread. - base::ScopedCFTypeRef<CFStringRef> proxies_key( + base::apple::ScopedCFTypeRef<CFStringRef> proxies_key( SCDynamicStoreKeyCreateProxies(nullptr)); - base::ScopedCFTypeRef<CFArrayRef> key_array(CFArrayCreate( + base::apple::ScopedCFTypeRef<CFArrayRef> key_array(CFArrayCreate( nullptr, (const void**)(&proxies_key), 1, &kCFTypeArrayCallBacks)); bool ret =
diff --git a/net/proxy_resolution/proxy_resolver_mac.cc b/net/proxy_resolution/proxy_resolver_mac.cc index 45fcfda..1f1d4fc 100644 --- a/net/proxy_resolution/proxy_resolver_mac.cc +++ b/net/proxy_resolution/proxy_resolver_mac.cc
@@ -130,7 +130,7 @@ // avoid double locking and releasing. bool lock_acquired_ = false; // The underlying CFRunLoopObserverRef structure wrapped by this instance. - base::ScopedCFTypeRef<CFRunLoopObserverRef> observer_; + base::apple::ScopedCFTypeRef<CFRunLoopObserverRef> observer_; // Validates that all methods of this class are executed on the same thread. base::ThreadChecker thread_checker_; }; @@ -242,17 +242,17 @@ mutable_query_url = query_url.ReplaceComponents(replacements); } - base::ScopedCFTypeRef<CFStringRef> query_ref( + base::apple::ScopedCFTypeRef<CFStringRef> query_ref( base::SysUTF8ToCFStringRef(mutable_query_url.spec())); - base::ScopedCFTypeRef<CFURLRef> query_url_ref( + base::apple::ScopedCFTypeRef<CFURLRef> query_url_ref( CFURLCreateWithString(kCFAllocatorDefault, query_ref.get(), nullptr)); if (!query_url_ref.get()) return ERR_FAILED; - base::ScopedCFTypeRef<CFStringRef> pac_ref(base::SysUTF8ToCFStringRef( + base::apple::ScopedCFTypeRef<CFStringRef> pac_ref(base::SysUTF8ToCFStringRef( script_data_->type() == PacFileData::TYPE_AUTO_DETECT ? std::string() : script_data_->url().spec())); - base::ScopedCFTypeRef<CFURLRef> pac_url_ref( + base::apple::ScopedCFTypeRef<CFURLRef> pac_url_ref( CFURLCreateWithString(kCFAllocatorDefault, pac_ref.get(), nullptr)); if (!pac_url_ref.get()) return ERR_FAILED; @@ -261,9 +261,9 @@ // CFNetworkCopyProxiesForURL initializes some state within CFNetwork that is // required by CFNetworkExecuteProxyAutoConfigurationURL. - base::ScopedCFTypeRef<CFDictionaryRef> empty_dictionary( + base::apple::ScopedCFTypeRef<CFDictionaryRef> empty_dictionary( CFDictionaryCreate(nullptr, nullptr, nullptr, 0, nullptr, nullptr)); - base::ScopedCFTypeRef<CFArrayRef> dummy_result( + base::apple::ScopedCFTypeRef<CFArrayRef> dummy_result( CFNetworkCopyProxiesForURL(query_url_ref.get(), empty_dictionary)); // We cheat here. We need to act as if we were synchronous, so we pump the @@ -273,7 +273,7 @@ CFTypeRef result = nullptr; CFStreamClientContext context = {0, &result, nullptr, nullptr, nullptr}; - base::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source( + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source( CFNetworkExecuteProxyAutoConfigurationURL( pac_url_ref.get(), query_url_ref.get(), ResultCallback, &context)); #if LEAK_SANITIZER @@ -319,7 +319,7 @@ CFRelease(result); return ERR_FAILED; } - base::ScopedCFTypeRef<CFArrayRef> proxy_array_ref( + base::apple::ScopedCFTypeRef<CFArrayRef> proxy_array_ref( base::apple::CFCastStrict<CFArrayRef>(result)); DCHECK(proxy_array_ref != nullptr);
diff --git a/net/ssl/client_cert_identity_mac.cc b/net/ssl/client_cert_identity_mac.cc index 664bda6..3d3b95fa 100644 --- a/net/ssl/client_cert_identity_mac.cc +++ b/net/ssl/client_cert_identity_mac.cc
@@ -14,7 +14,7 @@ ClientCertIdentityMac::ClientCertIdentityMac( scoped_refptr<net::X509Certificate> cert, - base::ScopedCFTypeRef<SecIdentityRef> sec_identity) + base::apple::ScopedCFTypeRef<SecIdentityRef> sec_identity) : ClientCertIdentity(std::move(cert)), identity_(std::move(sec_identity)) {} ClientCertIdentityMac::~ClientCertIdentityMac() = default; @@ -24,7 +24,7 @@ private_key_callback) { // This only adds a ref to and returns the private key from `identity_`, so it // doesn't need to run on a worker thread. - base::ScopedCFTypeRef<SecKeyRef> key; + base::apple::ScopedCFTypeRef<SecKeyRef> key; OSStatus status = SecIdentityCopyPrivateKey(identity_.get(), key.InitializeInto()); if (status != noErr) {
diff --git a/net/ssl/client_cert_identity_mac.h b/net/ssl/client_cert_identity_mac.h index 6549bae..51bae787 100644 --- a/net/ssl/client_cert_identity_mac.h +++ b/net/ssl/client_cert_identity_mac.h
@@ -16,8 +16,9 @@ class NET_EXPORT_PRIVATE ClientCertIdentityMac : public ClientCertIdentity { public: - ClientCertIdentityMac(scoped_refptr<net::X509Certificate> cert, - base::ScopedCFTypeRef<SecIdentityRef> sec_identity); + ClientCertIdentityMac( + scoped_refptr<net::X509Certificate> cert, + base::apple::ScopedCFTypeRef<SecIdentityRef> sec_identity); ~ClientCertIdentityMac() override; SecIdentityRef sec_identity_ref() const { return identity_.get(); } @@ -26,7 +27,7 @@ private_key_callback) override; private: - base::ScopedCFTypeRef<SecIdentityRef> identity_; + base::apple::ScopedCFTypeRef<SecIdentityRef> identity_; }; } // namespace net
diff --git a/net/ssl/client_cert_store_mac.cc b/net/ssl/client_cert_store_mac.cc index 82d8f5e..db92d1c 100644 --- a/net/ssl/client_cert_store_mac.cc +++ b/net/ssl/client_cert_store_mac.cc
@@ -34,7 +34,7 @@ #include "net/ssl/client_cert_identity_mac.h" #include "net/ssl/ssl_platform_key_util.h" -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; namespace net { @@ -47,8 +47,9 @@ // including the intermediate and finally root certificates (if any). // This function calls SecTrust but doesn't actually pay attention to the trust // result: it shouldn't be used to determine trust, just to traverse the chain. -OSStatus CopyCertChain(SecCertificateRef cert_handle, - base::ScopedCFTypeRef<CFArrayRef>* out_cert_chain) { +OSStatus CopyCertChain( + SecCertificateRef cert_handle, + base::apple::ScopedCFTypeRef<CFArrayRef>* out_cert_chain) { DCHECK(cert_handle); DCHECK(out_cert_chain); @@ -98,7 +99,7 @@ os_cert.InitializeInto()); if (err != noErr) return false; - base::ScopedCFTypeRef<CFArrayRef> cert_chain; + base::apple::ScopedCFTypeRef<CFArrayRef> cert_chain; OSStatus result = CopyCertChain(os_cert.get(), &cert_chain); if (result) { OSSTATUS_LOG(ERROR, result) << "CopyCertChain error"; @@ -108,7 +109,7 @@ if (!cert_chain) return false; - std::vector<base::ScopedCFTypeRef<SecCertificateRef>> intermediates; + std::vector<base::apple::ScopedCFTypeRef<SecCertificateRef>> intermediates; for (CFIndex i = 1, chain_count = CFArrayGetCount(cert_chain); i < chain_count; ++i) { SecCertificateRef sec_cert = reinterpret_cast<SecCertificateRef>(
diff --git a/net/ssl/client_cert_store_mac_unittest.cc b/net/ssl/client_cert_store_mac_unittest.cc index 27d9256..d9ddc3b 100644 --- a/net/ssl/client_cert_store_mac_unittest.cc +++ b/net/ssl/client_cert_store_mac_unittest.cc
@@ -35,7 +35,7 @@ identities.reserve(certs.size()); for (const auto& cert : certs) { identities.push_back(std::make_unique<ClientCertIdentityMac>( - cert, base::ScopedCFTypeRef<SecIdentityRef>())); + cert, base::apple::ScopedCFTypeRef<SecIdentityRef>())); } return identities; } @@ -100,7 +100,7 @@ const SSLCertRequestInfo& request, ClientCertIdentityList* selected_certs) { auto preferred_identity = std::make_unique<ClientCertIdentityMac>( - preferred_cert, base::ScopedCFTypeRef<SecIdentityRef>()); + preferred_cert, base::apple::ScopedCFTypeRef<SecIdentityRef>()); return store_.SelectClientCertsGivenPreferredForTesting( std::move(preferred_identity),
diff --git a/net/ssl/ssl_platform_key_mac.cc b/net/ssl/ssl_platform_key_mac.cc index 81029fe..9a818c9 100644 --- a/net/ssl/ssl_platform_key_mac.cc +++ b/net/ssl/ssl_platform_key_mac.cc
@@ -136,12 +136,12 @@ digest = *pss_storage; } - base::ScopedCFTypeRef<CFDataRef> digest_ref( + base::apple::ScopedCFTypeRef<CFDataRef> digest_ref( CFDataCreate(kCFAllocatorDefault, digest.data(), base::checked_cast<CFIndex>(digest.size()))); - base::ScopedCFTypeRef<CFErrorRef> error; - base::ScopedCFTypeRef<CFDataRef> signature_ref(SecKeyCreateSignature( + base::apple::ScopedCFTypeRef<CFErrorRef> error; + base::apple::ScopedCFTypeRef<CFDataRef> signature_ref(SecKeyCreateSignature( key_, sec_algorithm, digest_ref, error.InitializeInto())); if (!signature_ref) { LOG(ERROR) << error; @@ -180,7 +180,7 @@ std::vector<uint16_t> preferences_; bssl::UniquePtr<EVP_PKEY> pubkey_; - base::ScopedCFTypeRef<SecKeyRef> key_; + base::apple::ScopedCFTypeRef<SecKeyRef> key_; }; } // namespace
diff --git a/net/ssl/ssl_platform_key_mac_unittest.cc b/net/ssl/ssl_platform_key_mac_unittest.cc index b9475a99..7262298 100644 --- a/net/ssl/ssl_platform_key_mac_unittest.cc +++ b/net/ssl/ssl_platform_key_mac_unittest.cc
@@ -50,25 +50,26 @@ return params.param.name; } -base::ScopedCFTypeRef<SecKeyRef> SecKeyFromPKCS8(base::StringPiece pkcs8) { +base::apple::ScopedCFTypeRef<SecKeyRef> SecKeyFromPKCS8( + base::StringPiece pkcs8) { CBS cbs; CBS_init(&cbs, reinterpret_cast<const uint8_t*>(pkcs8.data()), pkcs8.size()); bssl::UniquePtr<EVP_PKEY> openssl_key(EVP_parse_private_key(&cbs)); if (!openssl_key || CBS_len(&cbs) != 0) - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); // `SecKeyCreateWithData` expects PKCS#1 for RSA keys, and a concatenated // format for EC keys. See `SecKeyCopyExternalRepresentation` for details. CFStringRef key_type; bssl::ScopedCBB cbb; if (!CBB_init(cbb.get(), 0)) { - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); } if (EVP_PKEY_id(openssl_key.get()) == EVP_PKEY_RSA) { key_type = kSecAttrKeyTypeRSA; if (!RSA_marshal_private_key(cbb.get(), EVP_PKEY_get0_RSA(openssl_key.get()))) { - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); } } else if (EVP_PKEY_id(openssl_key.get()) == EVP_PKEY_EC) { key_type = kSecAttrKeyTypeECSECPrimeRandom; @@ -81,23 +82,24 @@ POINT_CONVERSION_UNCOMPRESSED, nullptr) || !CBB_add_space(cbb.get(), &out, priv_len) || EC_KEY_priv2oct(ec_key, out, priv_len) != priv_len) { - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); } } else { - return base::ScopedCFTypeRef<SecKeyRef>(); + return base::apple::ScopedCFTypeRef<SecKeyRef>(); } - base::ScopedCFTypeRef<CFMutableDictionaryRef> attrs(CFDictionaryCreateMutable( - kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks)); + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> attrs( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks)); CFDictionarySetValue(attrs, kSecAttrKeyClass, kSecAttrKeyClassPrivate); CFDictionarySetValue(attrs, kSecAttrKeyType, key_type); - base::ScopedCFTypeRef<CFDataRef> data( + base::apple::ScopedCFTypeRef<CFDataRef> data( CFDataCreate(kCFAllocatorDefault, CBB_data(cbb.get()), base::checked_cast<CFIndex>(CBB_len(cbb.get())))); - return base::ScopedCFTypeRef<SecKeyRef>( + return base::apple::ScopedCFTypeRef<SecKeyRef>( SecKeyCreateWithData(data, attrs, nullptr)); } @@ -119,7 +121,7 @@ base::FilePath pkcs8_path = GetTestCertsDirectory().AppendASCII(test_key.key_file); ASSERT_TRUE(base::ReadFileToString(pkcs8_path, &pkcs8)); - base::ScopedCFTypeRef<SecKeyRef> sec_key = SecKeyFromPKCS8(pkcs8); + base::apple::ScopedCFTypeRef<SecKeyRef> sec_key = SecKeyFromPKCS8(pkcs8); ASSERT_TRUE(sec_key); // Make an `SSLPrivateKey` backed by `sec_key`.
diff --git a/net/websockets/websocket_basic_handshake_stream.cc b/net/websockets/websocket_basic_handshake_stream.cc index df98043f..05e627d 100644 --- a/net/websockets/websocket_basic_handshake_stream.cc +++ b/net/websockets/websocket_basic_handshake_stream.cc
@@ -5,7 +5,9 @@ #include "net/websockets/websocket_basic_handshake_stream.h" #include <stddef.h> + #include <algorithm> +#include <array> #include <iterator> #include <set> #include <utility> @@ -70,11 +72,9 @@ } std::string GenerateHandshakeChallenge() { - std::string raw_challenge(websockets::kRawChallengeLength, '\0'); - crypto::RandBytes(std::data(raw_challenge), raw_challenge.length()); - std::string encoded_challenge; - base::Base64Encode(raw_challenge, &encoded_challenge); - return encoded_challenge; + std::array<uint8_t, websockets::kRawChallengeLength> raw_challenge = {}; + crypto::RandBytes(raw_challenge); + return base::Base64Encode(raw_challenge); } GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
diff --git a/net/websockets/websocket_handshake_constants.cc b/net/websockets/websocket_handshake_constants.cc index 32239d1d..49744a7c 100644 --- a/net/websockets/websocket_handshake_constants.cc +++ b/net/websockets/websocket_handshake_constants.cc
@@ -8,8 +8,6 @@ const char kHttpProtocolVersion[] = "HTTP/1.1"; -const size_t kRawChallengeLength = 16; - const char kSecWebSocketProtocol[] = "Sec-WebSocket-Protocol"; const char kSecWebSocketExtensions[] = "Sec-WebSocket-Extensions"; const char kSecWebSocketKey[] = "Sec-WebSocket-Key";
diff --git a/net/websockets/websocket_handshake_constants.h b/net/websockets/websocket_handshake_constants.h index 1a5955a..971b129 100644 --- a/net/websockets/websocket_handshake_constants.h +++ b/net/websockets/websocket_handshake_constants.h
@@ -26,7 +26,7 @@ extern const char kHttpProtocolVersion[]; // The Sec-WebSockey-Key challenge is 16 random bytes, base64 encoded. -extern const size_t kRawChallengeLength; +inline constexpr size_t kRawChallengeLength = 16; // "Sec-WebSocket-Protocol" extern const char kSecWebSocketProtocol[];
diff --git a/printing/pdf_metafile_cg_mac.cc b/printing/pdf_metafile_cg_mac.cc index c9c65b3..4d9cebb 100644 --- a/printing/pdf_metafile_cg_mac.cc +++ b/printing/pdf_metafile_cg_mac.cc
@@ -18,7 +18,7 @@ #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" -using base::ScopedCFTypeRef; +using base::apple::ScopedCFTypeRef; namespace {
diff --git a/printing/pdf_metafile_cg_mac.h b/printing/pdf_metafile_cg_mac.h index 65e0d13..40d910df 100644 --- a/printing/pdf_metafile_cg_mac.h +++ b/printing/pdf_metafile_cg_mac.h
@@ -56,13 +56,13 @@ CGPDFDocumentRef GetPDFDocument() const; // Context for rendering to the pdf. - base::ScopedCFTypeRef<CGContextRef> context_; + base::apple::ScopedCFTypeRef<CGContextRef> context_; // PDF backing store. - base::ScopedCFTypeRef<CFMutableDataRef> pdf_data_; + base::apple::ScopedCFTypeRef<CFMutableDataRef> pdf_data_; // Lazily-created CGPDFDocument representation of `pdf_data_`. - mutable base::ScopedCFTypeRef<CGPDFDocumentRef> pdf_doc_; + mutable base::apple::ScopedCFTypeRef<CGPDFDocumentRef> pdf_doc_; // Whether or not a page is currently open. bool page_is_open_ = false;
diff --git a/printing/pdf_metafile_cg_mac_unittest.cc b/printing/pdf_metafile_cg_mac_unittest.cc index c69be741..ecde8aba 100644 --- a/printing/pdf_metafile_cg_mac_unittest.cc +++ b/printing/pdf_metafile_cg_mac_unittest.cc
@@ -78,9 +78,9 @@ constexpr size_t kBytesPerPixel = 4; const size_t kStride = dest_size.width() * kBytesPerPixel; std::vector<uint8_t> rendered_bitmap(dest_size.height() * kStride); - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( rendered_bitmap.data(), dest_size.width(), dest_size.height(), kBitsPerComponent, kStride, color_space, uint32_t{kCGImageAlphaPremultipliedFirst} | kCGBitmapByteOrder32Little));
diff --git a/printing/printing_context_mac.mm b/printing/printing_context_mac.mm index fd057c4f..5acb259 100644 --- a/printing/printing_context_mac.mm +++ b/printing/printing_context_mac.mm
@@ -259,7 +259,7 @@ if (!current_printer_id) return false; - base::ScopedCFTypeRef<CFStringRef> new_printer_id( + base::apple::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF8ToCFStringRef(device_name)); if (!new_printer_id.get()) return false; @@ -291,7 +291,7 @@ double page_width = 0.0; double page_height = 0.0; - base::ScopedCFTypeRef<CFStringRef> paper_name; + base::apple::ScopedCFTypeRef<CFStringRef> paper_name; PMPaperMargins margins = {0}; const PrintSettings::RequestedMedia& media = settings_->requested_media(); @@ -463,8 +463,9 @@ base::StringPiece value) { PMPrintSettings print_settings = static_cast<PMPrintSettings>([print_info_ PMPrintSettings]); - base::ScopedCFTypeRef<CFStringRef> cf_key = base::SysUTF8ToCFStringRef(key); - base::ScopedCFTypeRef<CFStringRef> cf_value = + base::apple::ScopedCFTypeRef<CFStringRef> cf_key = + base::SysUTF8ToCFStringRef(key); + base::apple::ScopedCFTypeRef<CFStringRef> cf_value = base::SysUTF8ToCFStringRef(value); return PMPrintSettingsSetValue(print_settings, cf_key.get(), cf_value.get(), @@ -499,7 +500,7 @@ PMPageFormat page_format = static_cast<PMPageFormat>([print_info_ PMPageFormat]); - base::ScopedCFTypeRef<CFStringRef> job_title = + base::apple::ScopedCFTypeRef<CFStringRef> job_title = base::SysUTF16ToCFStringRef(document_name); PMPrintSettingsSetJobName(print_settings, job_title.get());
diff --git a/remoting/host/audio_capturer_mac.cc b/remoting/host/audio_capturer_mac.cc index 2350586..7f35fc3f 100644 --- a/remoting/host/audio_capturer_mac.cc +++ b/remoting/host/audio_capturer_mac.cc
@@ -135,7 +135,7 @@ // Get the device name. property_address.mSelector = kAudioObjectPropertyName; - base::ScopedCFTypeRef<CFStringRef> device_name; + base::apple::ScopedCFTypeRef<CFStringRef> device_name; property_size = sizeof(CFStringRef); result = AudioObjectGetPropertyData(device_id, &property_address, 0, NULL, &property_size, @@ -150,7 +150,7 @@ // Now find out its UID. property_address.mSelector = kAudioDevicePropertyDeviceUID; - base::ScopedCFTypeRef<CFStringRef> device_uid; + base::apple::ScopedCFTypeRef<CFStringRef> device_uid; property_size = sizeof(CFStringRef); result = AudioObjectGetPropertyData(device_id, &property_address, 0, NULL, @@ -298,7 +298,7 @@ // Use the loopback device for input. HOST_LOG << "Using loopback device: " << audio_device_uid_; - base::ScopedCFTypeRef<CFStringRef> device_uid = + base::apple::ScopedCFTypeRef<CFStringRef> device_uid = base::SysUTF8ToCFStringRef(audio_device_uid_); CFStringRef unowned_device_uid = device_uid.get(); err = AudioQueueSetProperty(input_queue_, kAudioQueueProperty_CurrentDevice,
diff --git a/remoting/host/curtain_mode_mac.cc b/remoting/host/curtain_mode_mac.cc index c3a336c..4070eb7 100644 --- a/remoting/host/curtain_mode_mac.cc +++ b/remoting/host/curtain_mode_mac.cc
@@ -160,7 +160,7 @@ return; } - base::ScopedCFTypeRef<CFDictionaryRef> session( + base::apple::ScopedCFTypeRef<CFDictionaryRef> session( CGSessionCopyCurrentDictionary()); // CGSessionCopyCurrentDictionary has been observed to return nullptr in some
diff --git a/remoting/host/desktop_resizer_mac.cc b/remoting/host/desktop_resizer_mac.cc index 64f8966..91239c33 100644 --- a/remoting/host/desktop_resizer_mac.cc +++ b/remoting/host/desktop_resizer_mac.cc
@@ -44,7 +44,7 @@ bool GetSoleDisplayId(CGDirectDisplayID* display); void GetSupportedModesAndResolutions( - base::ScopedCFTypeRef<CFMutableArrayRef>* modes, + base::apple::ScopedCFTypeRef<CFMutableArrayRef>* modes, std::list<ScreenResolution>* resolutions); }; @@ -63,7 +63,7 @@ std::list<ScreenResolution> DesktopResizerMac::GetSupportedResolutions( const ScreenResolution& preferred, webrtc::ScreenId screen_id) { - base::ScopedCFTypeRef<CFMutableArrayRef> modes; + base::apple::ScopedCFTypeRef<CFMutableArrayRef> modes; std::list<ScreenResolution> resolutions; GetSupportedModesAndResolutions(&modes, &resolutions); return resolutions; @@ -76,7 +76,7 @@ return; } - base::ScopedCFTypeRef<CFMutableArrayRef> modes; + base::apple::ScopedCFTypeRef<CFMutableArrayRef> modes; std::list<ScreenResolution> resolutions; GetSupportedModesAndResolutions(&modes, &resolutions); // There may be many modes with the requested resolution. Pick the one with @@ -93,7 +93,7 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // TODO(https://crbug.com/1394415): Find non-deprecated replacement. - base::ScopedCFTypeRef<CFStringRef> encoding( + base::apple::ScopedCFTypeRef<CFStringRef> encoding( CGDisplayModeCopyPixelEncoding(mode)); #pragma clang diagnostic pop if (CFStringCompare(encoding, CFSTR(IO32BitDirectPixels), @@ -134,14 +134,14 @@ } void DesktopResizerMac::GetSupportedModesAndResolutions( - base::ScopedCFTypeRef<CFMutableArrayRef>* modes, + base::apple::ScopedCFTypeRef<CFMutableArrayRef>* modes, std::list<ScreenResolution>* resolutions) { CGDirectDisplayID display; if (!GetSoleDisplayId(&display)) { return; } - base::ScopedCFTypeRef<CFArrayRef> all_modes( + base::apple::ScopedCFTypeRef<CFArrayRef> all_modes( CGDisplayCopyAllDisplayModes(display, nullptr)); if (!all_modes) { return;
diff --git a/remoting/host/input_injector_mac.cc b/remoting/host/input_injector_mac.cc index f6c38d60..063b9a247 100644 --- a/remoting/host/input_injector_mac.cc +++ b/remoting/host/input_injector_mac.cc
@@ -44,7 +44,7 @@ bool pressed, uint64_t flags, const std::u16string& unicode) { - base::ScopedCFTypeRef<CGEventRef> eventRef( + base::apple::ScopedCFTypeRef<CGEventRef> eventRef( CGEventCreateKeyboardEvent(nullptr, keycode, pressed)); if (eventRef) { CGEventSetFlags(eventRef, static_cast<CGEventFlags>(flags)); @@ -85,8 +85,9 @@ // Must be called on UI thread. void CreateAndPostScrollWheelEvent(int32_t delta_x, int32_t delta_y) { - base::ScopedCFTypeRef<CGEventRef> eventRef(CGEventCreateScrollWheelEvent( - nullptr, kCGScrollEventUnitPixel, 2, delta_y, delta_x)); + base::apple::ScopedCFTypeRef<CGEventRef> eventRef( + CGEventCreateScrollWheelEvent(nullptr, kCGScrollEventUnitPixel, 2, + delta_y, delta_x)); if (eventRef) { CGEventPost(kCGSessionEventTap, eventRef); }
diff --git a/remoting/host/input_monitor/local_mouse_input_monitor_mac.mm b/remoting/host/input_monitor/local_mouse_input_monitor_mac.mm index 88b16f6..d319acb8 100644 --- a/remoting/host/input_monitor/local_mouse_input_monitor_mac.mm +++ b/remoting/host/input_monitor/local_mouse_input_monitor_mac.mm
@@ -59,8 +59,8 @@ @interface LocalInputMonitorManager : NSObject { @private - base::ScopedCFTypeRef<CFRunLoopSourceRef> _mouseRunLoopSource; - base::ScopedCFTypeRef<CFMachPortRef> _mouseMachPort; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> _mouseRunLoopSource; + base::apple::ScopedCFTypeRef<CFMachPortRef> _mouseMachPort; raw_ptr<remoting::LocalMouseInputMonitorMac::EventHandler> _monitor; }
diff --git a/remoting/host/keyboard_layout_monitor_mac.cc b/remoting/host/keyboard_layout_monitor_mac.cc index 8c92307..fe4f18b 100644 --- a/remoting/host/keyboard_layout_monitor_mac.cc +++ b/remoting/host/keyboard_layout_monitor_mac.cc
@@ -106,8 +106,8 @@ // Store the callback context pointer in a local variable so the block // captures it directly instead of capturing this. CallbackContext* callback_context = callback_context_.get(); - base::ScopedCFTypeRef<CFRunLoopRef> main_loop(CFRunLoopGetMain(), - base::scoped_policy::RETAIN); + base::apple::ScopedCFTypeRef<CFRunLoopRef> main_loop( + CFRunLoopGetMain(), base::scoped_policy::RETAIN); CFRunLoopPerformBlock(main_loop, kCFRunLoopCommonModes, ^(void) { QueryLayoutOnMainLoop(callback_context); }); @@ -133,9 +133,9 @@ // static void KeyboardLayoutMonitorMac::QueryLayoutOnMainLoop( KeyboardLayoutMonitorMac::CallbackContext* callback_context) { - base::ScopedCFTypeRef<TISInputSourceRef> input_source( + base::apple::ScopedCFTypeRef<TISInputSourceRef> input_source( TISCopyCurrentKeyboardLayoutInputSource()); - base::ScopedCFTypeRef<CFDataRef> layout_data( + base::apple::ScopedCFTypeRef<CFDataRef> layout_data( static_cast<CFDataRef>(TISGetInputSourceProperty( input_source, kTISPropertyUnicodeKeyLayoutData)), base::scoped_policy::RETAIN);
diff --git a/remoting/ios/app/remoting_view_controller.mm b/remoting/ios/app/remoting_view_controller.mm index 2d57c1f..13a51ce 100644 --- a/remoting/ios/app/remoting_view_controller.mm +++ b/remoting/ios/app/remoting_view_controller.mm
@@ -55,7 +55,7 @@ struct sockaddr_in addr = {0}; addr.sin_len = sizeof(addr); addr.sin_family = AF_INET; - base::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability( + base::apple::ScopedCFTypeRef<SCNetworkReachabilityRef> reachability( SCNetworkReachabilityCreateWithAddress( kCFAllocatorDefault, reinterpret_cast<struct sockaddr*>(&addr))); SCNetworkReachabilityFlags flags;
diff --git a/remoting/ios/persistence/remoting_keychain.cc b/remoting/ios/persistence/remoting_keychain.cc index b657985..fd48caaa 100644 --- a/remoting/ios/persistence/remoting_keychain.cc +++ b/remoting/ios/persistence/remoting_keychain.cc
@@ -15,13 +15,15 @@ namespace { -using ScopedMutableDictionary = base::ScopedCFTypeRef<CFMutableDictionaryRef>; +using ScopedMutableDictionary = + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef>; const char kServicePrefix[] = "com.google.ChromeRemoteDesktop."; -base::ScopedCFTypeRef<CFDataRef> CFDataFromStdString(const std::string& data) { +base::apple::ScopedCFTypeRef<CFDataRef> CFDataFromStdString( + const std::string& data) { const UInt8* data_pointer = reinterpret_cast<const UInt8*>(data.data()); - return base::ScopedCFTypeRef<CFDataRef>( + return base::apple::ScopedCFTypeRef<CFDataRef>( CFDataCreate(kCFAllocatorDefault, data_pointer, data.size())); } @@ -35,10 +37,10 @@ const std::string& account) { ScopedMutableDictionary dictionary = CreateScopedMutableDictionary(); CFDictionarySetValue(dictionary.get(), kSecClass, kSecClassGenericPassword); - base::ScopedCFTypeRef<CFStringRef> service_cf( + base::apple::ScopedCFTypeRef<CFStringRef> service_cf( base::SysUTF8ToCFStringRef(service)); CFDictionarySetValue(dictionary.get(), kSecAttrService, service_cf.get()); - base::ScopedCFTypeRef<CFStringRef> account_cf( + base::apple::ScopedCFTypeRef<CFStringRef> account_cf( base::SysUTF8ToCFStringRef(account)); CFDictionarySetValue(dictionary.get(), kSecAttrAccount, account_cf.get()); @@ -113,7 +115,7 @@ std::string service = KeyToService(key); ScopedMutableDictionary query = CreateQueryForLookup(service, account); - base::ScopedCFTypeRef<CFDataRef> cf_result; + base::apple::ScopedCFTypeRef<CFDataRef> cf_result; OSStatus status = SecItemCopyMatching(query, (CFTypeRef*)cf_result.InitializeInto()); if (status == errSecItemNotFound) {
diff --git a/remoting/ios/persistence/remoting_keychain_unittest.mm b/remoting/ios/persistence/remoting_keychain_unittest.mm index 1f15c0ac..cb8cd73 100644 --- a/remoting/ios/persistence/remoting_keychain_unittest.mm +++ b/remoting/ios/persistence/remoting_keychain_unittest.mm
@@ -47,7 +47,7 @@ (__bridge NSString*)kSecAttrService : KeyToService(key), (__bridge NSString*)kSecReturnData : @YES, }; - base::ScopedCFTypeRef<CFTypeRef> cf_result; + base::apple::ScopedCFTypeRef<CFTypeRef> cf_result; OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)get_all_query, cf_result.InitializeInto()); ASSERT_EQ(errSecItemNotFound, status);
diff --git a/rlz/mac/lib/machine_id_mac.cc b/rlz/mac/lib/machine_id_mac.cc index 9dc4845..c8be4506 100644 --- a/rlz/mac/lib/machine_id_mac.cc +++ b/rlz/mac/lib/machine_id_mac.cc
@@ -27,14 +27,13 @@ // The caller is responsible for freeing |matching_services|. bool FindEthernetInterfaces(io_iterator_t* matching_services) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> matching_dict( IOServiceMatching(kIOEthernetInterfaceClass)); if (!matching_dict) return false; - base::ScopedCFTypeRef<CFMutableDictionaryRef> primary_interface( - CFDictionaryCreateMutable(kCFAllocatorDefault, - 0, + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> primary_interface( + CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); if (!primary_interface) @@ -72,11 +71,10 @@ if (!success) continue; - base::ScopedCFTypeRef<CFTypeRef> mac_data( + base::apple::ScopedCFTypeRef<CFTypeRef> mac_data( IORegistryEntryCreateCFProperty(primary_interface_parent, CFSTR(kIOMACAddress), - kCFAllocatorDefault, - 0)); + kCFAllocatorDefault, 0)); CFDataRef mac_data_data = base::apple::CFCast<CFDataRef>(mac_data); if (mac_data_data) { CFDataGetBytes(
diff --git a/sandbox/policy/features.cc b/sandbox/policy/features.cc index 0d75b6be..1b238e7 100644 --- a/sandbox/policy/features.cc +++ b/sandbox/policy/features.cc
@@ -8,6 +8,10 @@ #include "build/chromeos_buildflags.h" #include "sandbox/features.h" +#if BUILDFLAG(IS_WIN) +#include "base/win/windows_version.h" +#endif + namespace sandbox::policy::features { #if !BUILDFLAG(IS_MAC) && !BUILDFLAG(IS_FUCHSIA) @@ -112,8 +116,21 @@ #if BUILDFLAG(IS_WIN) bool IsNetworkSandboxSupported() { - // Delegate to the sandbox for support, for now. - return sandbox::features::IsAppContainerSandboxSupported(); + // Network service sandbox uses GetNetworkConnectivityHint which is only + // supported on Windows 10 Build 19041 (20H1) so versions before that wouldn't + // have a working network change notifier when running in the sandbox. + // TODO(crbug.com/1450754): Move this to an API that works earlier than 20H1 + // and also works in the LPAC sandbox. + static const bool supported = + base::win::GetVersion() >= base::win::Version::WIN10_20H1; + if (!supported) { + return false; + } + + // App container must be already supported on 20H1, but double check it here. + CHECK(sandbox::features::IsAppContainerSandboxSupported()); + + return true; } #endif // BUILDFLAG(IS_WIN)
diff --git a/sandbox/policy/linux/bpf_network_policy_linux.cc b/sandbox/policy/linux/bpf_network_policy_linux.cc index e47b1f8..ed1582d7 100644 --- a/sandbox/policy/linux/bpf_network_policy_linux.cc +++ b/sandbox/policy/linux/bpf_network_policy_linux.cc
@@ -104,8 +104,8 @@ SO_SNDBUF, SO_BROADCAST}, Allow()) .Default(CrashSIGSYSSockopt()); - // glibc's getaddrinfo() needs to enable icmp with IP_RECVERR, for both ipv4 - // and ipv6. + // glibc's getaddrinfo() needs to enable icmp with IP[V6]_RECVERR, for both + // ipv4 and ipv6. // // A number of optnames are for APIs of pepper and extensions. These include: // * IP[V6[_MULTICAST_LOOP for UDPSocketPosix::SetMulticastOptions(). @@ -126,7 +126,7 @@ .Default(CrashSIGSYSSockopt()); ResultExpr ipv6_optname_switch = Switch(optname) - .Cases({IP_RECVERR, IPV6_MTU_DISCOVER, IPV6_MULTICAST_LOOP, + .Cases({IPV6_RECVERR, IPV6_MTU_DISCOVER, IPV6_MULTICAST_LOOP, IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF, IPV6_JOIN_GROUP, IPV6_LEAVE_GROUP, IPV6_TCLASS, IPV6_V6ONLY}, Allow())
diff --git a/services/device/battery/battery_status_manager_mac.cc b/services/device/battery/battery_status_manager_mac.cc index f6e7129..b58aa8a 100644 --- a/services/device/battery/battery_status_manager_mac.cc +++ b/services/device/battery/battery_status_manager_mac.cc
@@ -109,8 +109,8 @@ std::vector<mojom::BatteryStatus> GetInternalBatteriesStates() { std::vector<mojom::BatteryStatus> internal_sources; - base::ScopedCFTypeRef<CFTypeRef> info(IOPSCopyPowerSourcesInfo()); - base::ScopedCFTypeRef<CFArrayRef> power_sources_list( + base::apple::ScopedCFTypeRef<CFTypeRef> info(IOPSCopyPowerSourcesInfo()); + base::apple::ScopedCFTypeRef<CFArrayRef> power_sources_list( IOPSCopyPowerSourcesList(info)); CFIndex count = CFArrayGetCount(power_sources_list); @@ -198,7 +198,7 @@ } BatteryCallback callback_; - base::ScopedCFTypeRef<CFRunLoopSourceRef> notifier_run_loop_source_; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> notifier_run_loop_source_; }; class BatteryStatusManagerMac : public BatteryStatusManager {
diff --git a/services/device/hid/hid_connection_mac.cc b/services/device/hid/hid_connection_mac.cc index 5f88d2d..641c140 100644 --- a/services/device/hid/hid_connection_mac.cc +++ b/services/device/hid/hid_connection_mac.cc
@@ -26,10 +26,11 @@ } // namespace -HidConnectionMac::HidConnectionMac(base::ScopedCFTypeRef<IOHIDDeviceRef> device, - scoped_refptr<HidDeviceInfo> device_info, - bool allow_protected_reports, - bool allow_fido_reports) +HidConnectionMac::HidConnectionMac( + base::apple::ScopedCFTypeRef<IOHIDDeviceRef> device, + scoped_refptr<HidDeviceInfo> device_info, + bool allow_protected_reports, + bool allow_fido_reports) : HidConnection(device_info, allow_protected_reports, allow_fido_reports), device_(std::move(device)), task_runner_(base::SingleThreadTaskRunner::GetCurrentDefault()),
diff --git a/services/device/hid/hid_connection_mac.h b/services/device/hid/hid_connection_mac.h index 2f572a9..f8a26d2 100644 --- a/services/device/hid/hid_connection_mac.h +++ b/services/device/hid/hid_connection_mac.h
@@ -22,7 +22,7 @@ class HidConnectionMac : public HidConnection { public: - HidConnectionMac(base::ScopedCFTypeRef<IOHIDDeviceRef> device, + HidConnectionMac(base::apple::ScopedCFTypeRef<IOHIDDeviceRef> device, scoped_refptr<HidDeviceInfo> device_info, bool allow_protected_reports, bool allow_fido_reports); @@ -54,7 +54,7 @@ WriteCallback callback); void ReturnAsyncResult(base::OnceClosure callback); - base::ScopedCFTypeRef<IOHIDDeviceRef> device_; + base::apple::ScopedCFTypeRef<IOHIDDeviceRef> device_; const scoped_refptr<base::SequencedTaskRunner> task_runner_; const scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; std::vector<uint8_t> inbound_buffer_;
diff --git a/services/device/hid/hid_service_mac.cc b/services/device/hid/hid_service_mac.cc index ee25b7ea..c60da49 100644 --- a/services/device/hid/hid_service_mac.cc +++ b/services/device/hid/hid_service_mac.cc
@@ -31,7 +31,7 @@ bool TryGetHidDataProperty(io_service_t service, CFStringRef key, std::vector<uint8_t>* result) { - base::ScopedCFTypeRef<CFDataRef> ref(base::apple::CFCast<CFDataRef>( + base::apple::ScopedCFTypeRef<CFDataRef> ref(base::apple::CFCast<CFDataRef>( IORegistryEntryCreateCFProperty(service, key, kCFAllocatorDefault, 0))); if (!ref) return false; @@ -142,17 +142,17 @@ } // static -base::ScopedCFTypeRef<IOHIDDeviceRef> HidServiceMac::OpenOnBlockingThread( - scoped_refptr<HidDeviceInfo> device_info) { +base::apple::ScopedCFTypeRef<IOHIDDeviceRef> +HidServiceMac::OpenOnBlockingThread(scoped_refptr<HidDeviceInfo> device_info) { DCHECK_EQ(device_info->platform_device_id_map().size(), 1u); const auto& platform_device_id = device_info->platform_device_id_map().front().platform_device_id; - base::ScopedCFTypeRef<CFDictionaryRef> matching_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> matching_dict( IORegistryEntryIDMatching(platform_device_id)); if (!matching_dict.get()) { HID_LOG(DEBUG) << "Failed to create matching dictionary for ID: " << platform_device_id; - return base::ScopedCFTypeRef<IOHIDDeviceRef>(); + return base::apple::ScopedCFTypeRef<IOHIDDeviceRef>(); } // IOServiceGetMatchingService consumes a reference to the matching dictionary @@ -161,20 +161,20 @@ kIOMasterPortDefault, matching_dict.release())); if (!service.get()) { HID_LOG(DEBUG) << "IOService not found for ID: " << platform_device_id; - return base::ScopedCFTypeRef<IOHIDDeviceRef>(); + return base::apple::ScopedCFTypeRef<IOHIDDeviceRef>(); } - base::ScopedCFTypeRef<IOHIDDeviceRef> hid_device( + base::apple::ScopedCFTypeRef<IOHIDDeviceRef> hid_device( IOHIDDeviceCreate(kCFAllocatorDefault, service)); if (!hid_device) { HID_LOG(DEBUG) << "Unable to create IOHIDDevice object."; - return base::ScopedCFTypeRef<IOHIDDeviceRef>(); + return base::apple::ScopedCFTypeRef<IOHIDDeviceRef>(); } IOReturn result = IOHIDDeviceOpen(hid_device, kIOHIDOptionsTypeNone); if (result != kIOReturnSuccess) { HID_LOG(DEBUG) << "Failed to open device: " << HexErrorCode(result); - return base::ScopedCFTypeRef<IOHIDDeviceRef>(); + return base::apple::ScopedCFTypeRef<IOHIDDeviceRef>(); } return hid_device; @@ -185,7 +185,7 @@ bool allow_protected_reports, bool allow_fido_reports, ConnectCallback callback, - base::ScopedCFTypeRef<IOHIDDeviceRef> hid_device) { + base::apple::ScopedCFTypeRef<IOHIDDeviceRef> hid_device) { if (hid_device) { std::move(callback).Run(base::MakeRefCounted<HidConnectionMac>( std::move(hid_device), std::move(device_info), allow_protected_reports,
diff --git a/services/device/hid/hid_service_mac.h b/services/device/hid/hid_service_mac.h index 358fdd8..c228057c 100644 --- a/services/device/hid/hid_service_mac.h +++ b/services/device/hid/hid_service_mac.h
@@ -34,13 +34,13 @@ base::WeakPtr<HidService> GetWeakPtr() override; private: - static base::ScopedCFTypeRef<IOHIDDeviceRef> OpenOnBlockingThread( + static base::apple::ScopedCFTypeRef<IOHIDDeviceRef> OpenOnBlockingThread( scoped_refptr<HidDeviceInfo> device_info); void DeviceOpened(scoped_refptr<HidDeviceInfo> device_info, bool allow_protected_reports, bool allow_fido_reports, ConnectCallback callback, - base::ScopedCFTypeRef<IOHIDDeviceRef> hid_device); + base::apple::ScopedCFTypeRef<IOHIDDeviceRef> hid_device); // IOService matching callbacks. static void FirstMatchCallback(void* context, io_iterator_t iterator);
diff --git a/services/device/usb/usb_device_handle_mac.cc b/services/device/usb/usb_device_handle_mac.cc index 0467f8d..646017bd 100644 --- a/services/device/usb/usb_device_handle_mac.cc +++ b/services/device/usb/usb_device_handle_mac.cc
@@ -265,7 +265,7 @@ } interfaces_[interface_number] = interface_interface; - base::ScopedCFTypeRef<CFRunLoopSourceRef> run_loop_source; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> run_loop_source; kr = (*interface_interface) ->CreateInterfaceAsyncEventSource( interface_interface, run_loop_source.InitializeInto());
diff --git a/services/device/usb/usb_device_handle_mac.h b/services/device/usb/usb_device_handle_mac.h index 7f1e144..f4d69f3 100644 --- a/services/device/usb/usb_device_handle_mac.h +++ b/services/device/usb/usb_device_handle_mac.h
@@ -136,12 +136,13 @@ transfers_; ScopedIOUSBDeviceInterface device_interface_; - base::ScopedCFTypeRef<CFRunLoopSourceRef> device_source_; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> device_source_; scoped_refptr<UsbDeviceMac> device_; // Both maps take the interface number in as the respective key. base::flat_map<uint8_t, ScopedIOUSBInterfaceInterface> interfaces_; - base::flat_map<uint8_t, base::ScopedCFTypeRef<CFRunLoopSourceRef>> sources_; + base::flat_map<uint8_t, base::apple::ScopedCFTypeRef<CFRunLoopSourceRef>> + sources_; }; } // namespace device
diff --git a/services/device/usb/usb_device_mac.cc b/services/device/usb/usb_device_mac.cc index 6b21fc7..0ef0b4e1 100644 --- a/services/device/usb/usb_device_mac.cc +++ b/services/device/usb/usb_device_mac.cc
@@ -29,7 +29,7 @@ UsbDeviceMac::~UsbDeviceMac() = default; void UsbDeviceMac::Open(OpenCallback callback) { - base::ScopedCFTypeRef<CFDictionaryRef> matching_dict( + base::apple::ScopedCFTypeRef<CFDictionaryRef> matching_dict( IORegistryEntryIDMatching(entry_id())); if (!matching_dict.get()) { USB_LOG(ERROR) << "Failed to create matching dictionary for ID.";
diff --git a/services/device/utils/mac_utils.h b/services/device/utils/mac_utils.h index db17d01..a92f3b1 100644 --- a/services/device/utils/mac_utils.h +++ b/services/device/utils/mac_utils.h
@@ -21,7 +21,7 @@ std::is_same_v<T, int32_t>, "Unsupported template type"); - base::ScopedCFTypeRef<CFNumberRef> cf_number( + base::apple::ScopedCFTypeRef<CFNumberRef> cf_number( base::apple::CFCast<CFNumberRef>(IORegistryEntryCreateCFProperty( service, property, kCFAllocatorDefault, 0))); @@ -56,7 +56,7 @@ std::is_same_v<T, std::string> || std::is_same_v<T, std::u16string>, "Unsupported template type"); - base::ScopedCFTypeRef<CFStringRef> ref( + base::apple::ScopedCFTypeRef<CFStringRef> ref( base::apple::CFCast<CFStringRef>(IORegistryEntryCreateCFProperty( service, property, kCFAllocatorDefault, 0)));
diff --git a/services/device/wake_lock/power_save_blocker/power_save_blocker_mac.cc b/services/device/wake_lock/power_save_blocker/power_save_blocker_mac.cc index e11b55b..483514f 100644 --- a/services/device/wake_lock/power_save_blocker/power_save_blocker_mac.cc +++ b/services/device/wake_lock/power_save_blocker/power_save_blocker_mac.cc
@@ -82,7 +82,7 @@ break; } if (level) { - base::ScopedCFTypeRef<CFStringRef> cf_description( + base::apple::ScopedCFTypeRef<CFStringRef> cf_description( base::SysUTF8ToCFStringRef(description_)); IOReturn result = IOPMAssertionCreateWithName(level, kIOPMAssertionLevelOn, cf_description, &assertion_);
diff --git a/services/preferences/tracked/device_id_mac.cc b/services/preferences/tracked/device_id_mac.cc index 0a60fb6..2569b2dd5 100644 --- a/services/preferences/tracked/device_id_mac.cc +++ b/services/preferences/tracked/device_id_mac.cc
@@ -18,7 +18,7 @@ if (!platform_expert.get()) return MachineIdStatus::FAILURE; - base::ScopedCFTypeRef<CFTypeRef> uuid(IORegistryEntryCreateCFProperty( + base::apple::ScopedCFTypeRef<CFTypeRef> uuid(IORegistryEntryCreateCFProperty( platform_expert, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0)); if (!uuid.get()) return MachineIdStatus::FAILURE;
diff --git a/services/shape_detection/barcode_detection_impl_mac_unittest.mm b/services/shape_detection/barcode_detection_impl_mac_unittest.mm index 3f3385a1..edee13b 100644 --- a/services/shape_detection/barcode_detection_impl_mac_unittest.mm +++ b/services/shape_detection/barcode_detection_impl_mac_unittest.mm
@@ -104,7 +104,7 @@ CIContext* context = [[CIContext alloc] init]; - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( [context createCGImage:qr_code_image fromRect:qr_code_image.extent]); EXPECT_EQ(static_cast<size_t>(size.width()), CGImageGetWidth(cg_image)); EXPECT_EQ(static_cast<size_t>(size.height()), CGImageGetHeight(cg_image));
diff --git a/services/shape_detection/detection_utils_mac.mm b/services/shape_detection/detection_utils_mac.mm index 135ac19..5e690771 100644 --- a/services/shape_detection/detection_utils_mac.mm +++ b/services/shape_detection/detection_utils_mac.mm
@@ -31,7 +31,7 @@ } // First convert SkBitmap to CGImageRef. - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( SkCreateCGImageRefWithColorspace(bitmap, nullptr)); if (!cg_image) { DLOG(ERROR) << "Failed to create CGImageRef";
diff --git a/services/shape_detection/text_detection_impl_mac_unittest.mm b/services/shape_detection/text_detection_impl_mac_unittest.mm index 005de76d..a44531d7 100644 --- a/services/shape_detection/text_detection_impl_mac_unittest.mm +++ b/services/shape_detection/text_detection_impl_mac_unittest.mm
@@ -50,12 +50,12 @@ } impl_ = std::make_unique<TextDetectionImplMac>(); - base::ScopedCFTypeRef<CGColorSpaceRef> rgb_colorspace( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> rgb_colorspace( CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB)); const int width = 200; const int height = 50; - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( nullptr, width, height, 8 /* bitsPerComponent */, width * 4 /* rowBytes */, rgb_colorspace, uint32_t{kCGImageAlphaPremultipliedFirst} | kCGBitmapByteOrder32Host)); @@ -72,14 +72,14 @@ [[NSAttributedString alloc] initWithString:@"https://www.chromium.org" attributes:attributes]; - base::ScopedCFTypeRef<CTLineRef> line( + base::apple::ScopedCFTypeRef<CTLineRef> line( CTLineCreateWithAttributedString(base::apple::NSToCFPtrCast(info))); CGContextSetTextPosition(context, 10.0, height / 2.0); CTLineDraw(line, context); // Extract a CGImage and its raw pixels from |context|. - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGBitmapContextCreateImage(context)); EXPECT_EQ(static_cast<size_t>(width), CGImageGetWidth(cg_image)); EXPECT_EQ(static_cast<size_t>(height), CGImageGetHeight(cg_image));
diff --git a/skia/BUILD.gn b/skia/BUILD.gn index 2ededdaa..cf225d6 100644 --- a/skia/BUILD.gn +++ b/skia/BUILD.gn
@@ -370,7 +370,6 @@ # The imported Skia gni source paths are made absolute by gn. defines = [] sources += skia_sksl_sources - sources += skia_needs_sksl_sources sources += skia_codec_core sources += skia_utils_private sources += skia_xps_sources @@ -721,7 +720,6 @@ defines = [] sources = skia_core_sources sources += skia_colorfilters_sources - sources += skia_colorfilters_sksl_sources sources += skia_effects_sources sources += skia_effects_imagefilter_sources if (skia_support_gpu) {
diff --git a/skia/ext/skia_utils_ios.mm b/skia/ext/skia_utils_ios.mm index 9f55239..765d77e 100644 --- a/skia/ext/skia_utils_ios.mm +++ b/skia/ext/skia_utils_ios.mm
@@ -46,9 +46,9 @@ (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \ && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b)) #if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( data, size.width, size.height, 8, size.width * 4, color_space, uint32_t{kCGImageAlphaPremultipliedFirst} | kCGBitmapByteOrder32Host)); #else @@ -75,7 +75,7 @@ return nil; // First convert SkBitmap to CGImageRef. - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( SkCreateCGImageRefWithColorspace(skia_bitmap, color_space)); // Now convert to UIImage. @@ -97,16 +97,16 @@ bool skip_images_88x88_or_larger = base::ios::IsRunningOnOrLater(8, 1, 1) && EncodesIcoImage(image_data); - base::ScopedCFTypeRef<CFDictionaryRef> empty_dictionary( + base::apple::ScopedCFTypeRef<CFDictionaryRef> empty_dictionary( CFDictionaryCreate(NULL, NULL, NULL, 0, NULL, NULL)); std::vector<SkBitmap> frames; - base::ScopedCFTypeRef<CGImageSourceRef> source( + base::apple::ScopedCFTypeRef<CGImageSourceRef> source( CGImageSourceCreateWithData((CFDataRef)image_data, empty_dictionary)); size_t count = CGImageSourceGetCount(source); for (size_t index = 0; index < count; ++index) { - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGImageSourceCreateImageAtIndex(source, index, empty_dictionary)); CGSize size = CGSizeMake(CGImageGetWidth(cg_image),
diff --git a/skia/ext/skia_utils_mac.h b/skia/ext/skia_utils_mac.h index d567c5b4..fff7a46 100644 --- a/skia/ext/skia_utils_mac.h +++ b/skia/ext/skia_utils_mac.h
@@ -59,7 +59,7 @@ SK_API SkColor CGColorRefToSkColor(CGColorRef color); // Converts a Skia ARGB color to CGColorRef. Assumes sRGB color space. -SK_API base::ScopedCFTypeRef<CGColorRef> CGColorCreateFromSkColor( +SK_API base::apple::ScopedCFTypeRef<CGColorRef> CGColorCreateFromSkColor( SkColor color); #ifdef __OBJC__
diff --git a/skia/ext/skia_utils_mac.mm b/skia/ext/skia_utils_mac.mm index 945a9dd..a8fe2ca2f 100644 --- a/skia/ext/skia_utils_mac.mm +++ b/skia/ext/skia_utils_mac.mm
@@ -40,7 +40,7 @@ (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \ && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b)) #if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( data, size.width, size.height, 8, size.width * 4, color_space, uint32_t{kCGImageAlphaPremultipliedFirst} | kCGBitmapByteOrder32Host)); #else @@ -150,7 +150,7 @@ } SkColor CGColorRefToSkColor(CGColorRef color) { - base::ScopedCFTypeRef<CGColorRef> cg_color( + base::apple::ScopedCFTypeRef<CGColorRef> cg_color( CGColorCreateCopyByMatchingToColorSpace(base::mac::GetSRGBColorSpace(), kCGRenderingIntentDefault, color, nullptr)); @@ -160,11 +160,12 @@ .toSkColor(); } -base::ScopedCFTypeRef<CGColorRef> CGColorCreateFromSkColor(SkColor color) { +base::apple::ScopedCFTypeRef<CGColorRef> CGColorCreateFromSkColor( + SkColor color) { CGFloat components[] = { SkColorGetR(color) / 255.0f, SkColorGetG(color) / 255.0f, SkColorGetB(color) / 255.0f, SkColorGetA(color) / 255.0f}; - return base::ScopedCFTypeRef<CGColorRef>( + return base::apple::ScopedCFTypeRef<CGColorRef>( CGColorCreate(base::mac::GetSRGBColorSpace(), components)); } @@ -227,7 +228,7 @@ const SkBitmap& skiaBitmap, CGColorSpaceRef colorSpace) { // First convert SkBitmap to CGImageRef. - base::ScopedCFTypeRef<CGImageRef> cgimage( + base::apple::ScopedCFTypeRef<CGImageRef> cgimage( SkCreateCGImageRefWithColorspace(skiaBitmap, colorSpace)); if (!cgimage) return nil;
diff --git a/testing/buildbot/chromium.chromiumos.json b/testing/buildbot/chromium.chromiumos.json index 3c914a81..8de16f8 100644 --- a/testing/buildbot/chromium.chromiumos.json +++ b/testing/buildbot/chromium.chromiumos.json
@@ -4886,9 +4886,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -4898,8 +4898,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -5033,9 +5033,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -5045,8 +5045,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -5165,9 +5165,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -5177,8 +5177,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": {
diff --git a/testing/buildbot/chromium.coverage.json b/testing/buildbot/chromium.coverage.json index fe426e1..6d6a35e 100644 --- a/testing/buildbot/chromium.coverage.json +++ b/testing/buildbot/chromium.coverage.json
@@ -25056,9 +25056,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -25068,8 +25068,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -25203,9 +25203,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -25215,8 +25215,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -25335,9 +25335,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -25347,8 +25347,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": {
diff --git a/testing/buildbot/chromium.fyi.json b/testing/buildbot/chromium.fyi.json index 6fe5b3c2..042447ce 100644 --- a/testing/buildbot/chromium.fyi.json +++ b/testing/buildbot/chromium.fyi.json
@@ -43085,9 +43085,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43096,8 +43096,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -43232,9 +43232,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43243,8 +43243,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -43364,9 +43364,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -43375,8 +43375,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -44610,9 +44610,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -44621,8 +44621,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -44757,9 +44757,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -44768,8 +44768,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -44889,9 +44889,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -44900,8 +44900,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -45532,9 +45532,9 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome" + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" }, @@ -45543,8 +45543,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": {
diff --git a/testing/buildbot/chromium.memory.json b/testing/buildbot/chromium.memory.json index 5324d899..36fa614 100644 --- a/testing/buildbot/chromium.memory.json +++ b/testing/buildbot/chromium.memory.json
@@ -16123,12 +16123,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.interactive_ui_tests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -16138,8 +16138,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -16290,12 +16290,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -16305,8 +16305,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": { @@ -16437,12 +16437,12 @@ { "args": [ "--test-launcher-filter-file=../../testing/buildbot/filters/linux-lacros.lacros_chrome_browsertests.skew.filter", - "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome", + "--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome", "--test-launcher-print-test-stdio=always", "--combine-ash-logs-on-bots", "--asan-symbolize-output" ], - "description": "Run with ash-chrome version 118.0.5962.0", + "description": "Run with ash-chrome version 118.0.5963.0", "isolate_profile_data": true, "merge": { "script": "//testing/merge_scripts/standard_gtest_merge.py" @@ -16452,8 +16452,8 @@ "cipd_packages": [ { "cipd_package": "chromium/testing/linux-ash-chromium/x86_64/ash.zip", - "location": "lacros_version_skew_tests_v118.0.5962.0", - "revision": "version:118.0.5962.0" + "location": "lacros_version_skew_tests_v118.0.5963.0", + "revision": "version:118.0.5963.0" } ], "dimensions": {
diff --git a/testing/buildbot/variants.pyl b/testing/buildbot/variants.pyl index ab75cd9..7ceb1d1 100644 --- a/testing/buildbot/variants.pyl +++ b/testing/buildbot/variants.pyl
@@ -16,16 +16,16 @@ }, 'LACROS_VERSION_SKEW_CANARY': { 'identifier': 'Lacros version skew testing ash canary', - 'description': 'Run with ash-chrome version 118.0.5962.0', + 'description': 'Run with ash-chrome version 118.0.5963.0', 'args': [ - '--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5962.0/test_ash_chrome', + '--ash-chrome-path-override=../../lacros_version_skew_tests_v118.0.5963.0/test_ash_chrome', ], 'swarming': { 'cipd_packages': [ { 'cipd_package': 'chromium/testing/linux-ash-chromium/x86_64/ash.zip', - 'location': 'lacros_version_skew_tests_v118.0.5962.0', - 'revision': 'version:118.0.5962.0', + 'location': 'lacros_version_skew_tests_v118.0.5963.0', + 'revision': 'version:118.0.5963.0', }, ], },
diff --git a/testing/variations/fieldtrial_testing_config.json b/testing/variations/fieldtrial_testing_config.json index 03e51830..e730637 100644 --- a/testing/variations/fieldtrial_testing_config.json +++ b/testing/variations/fieldtrial_testing_config.json
@@ -15029,6 +15029,21 @@ ] } ], + "TabStripStartupRefactoring": [ + { + "platforms": [ + "android" + ], + "experiments": [ + { + "name": "Enabled", + "enable_features": [ + "TabStripStartupRefactoring" + ] + } + ] + } + ], "TailoredSecurityIntegration": [ { "platforms": [
diff --git a/third_party/blink/renderer/bindings/BUILD.gn b/third_party/blink/renderer/bindings/BUILD.gn index dc0a0dc..98ab27b 100644 --- a/third_party/blink/renderer/bindings/BUILD.gn +++ b/third_party/blink/renderer/bindings/BUILD.gn
@@ -12,7 +12,6 @@ import("//third_party/blink/renderer/bindings/idl_in_core.gni") import("//third_party/blink/renderer/bindings/idl_in_extensions_chromeos.gni") import("//third_party/blink/renderer/bindings/idl_in_modules.gni") -import("//third_party/blink/renderer/bindings/scripts/scripts.gni") visibility = [ "//third_party/blink/renderer/*" ] @@ -20,7 +19,7 @@ template("collect_idl_files") { action_with_pydeps(target_name) { - script = "${bindings_scripts_dir}/collect_idl_files.py" + script = "scripts/collect_idl_files.py" inputs = invoker.inputs outputs = [ invoker.output ] @@ -100,7 +99,7 @@ action_with_pydeps("web_idl_database") { visibility += [ "//tools/privacy_budget/blink_apis:*" ] - script = "${bindings_scripts_dir}/build_web_idl_database.py" + script = "scripts/build_web_idl_database.py" input_data_files = get_target_outputs(":web_idl_in_core") + get_target_outputs(":web_idl_in_core_for_testing") + @@ -132,7 +131,7 @@ template("generate_bindings") { action_with_pydeps(target_name) { - script = "${bindings_scripts_dir}/generate_bindings.py" + script = "scripts/generate_bindings.py" if (defined(invoker.visibility)) { visibility += invoker.visibility @@ -235,7 +234,7 @@ } action_with_pydeps("check_generated_file_list") { - script = "${bindings_scripts_dir}/check_generated_file_list.py" + script = "scripts/check_generated_file_list.py" web_idl_database_outputs = get_target_outputs(":web_idl_database") web_idl_database = web_idl_database_outputs[0] @@ -402,7 +401,7 @@ } action_with_pydeps("validate_web_idl") { - script = "${bindings_scripts_dir}/validate_web_idl.py" + script = "scripts/validate_web_idl.py" web_idl_database_outputs = get_target_outputs(":web_idl_database") web_idl_database = web_idl_database_outputs[0]
diff --git a/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py b/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py deleted file mode 100755 index 8068b5d0..0000000 --- a/third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py +++ /dev/null
@@ -1,148 +0,0 @@ -#!/usr/bin/env python -# -# Copyright (C) 2013 Google Inc. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -"""Generate event interfaces .json5 file (EventInterfaces.json5). - -The event interfaces .json5 file contains a list of all Event interfaces, i.e., -all interfaces that inherit from Event, including Event itself, -together with certain extended attributes. - -Paths are in POSIX format, and relative to the repository root. - -This list is used in core/ to generate EventFactory and EventNames. -The .json5 format is documented in build/scripts/json5_generator.py. -""" - -from optparse import OptionParser -import os -import posixpath -import sys - -from utilities import (get_file_contents, get_first_interface_name_from_idl, - read_file_to_list, write_file, - get_interface_extended_attributes_from_idl) - -EXPORTED_EXTENDED_ATTRIBUTES = ( - 'ImplementedAs', - 'RuntimeEnabled', -) -module_path = os.path.dirname(os.path.abspath(__file__)) -REPO_ROOT_DIR = os.path.normpath( - os.path.join(module_path, os.pardir, os.pardir, os.pardir, os.pardir, - os.pardir)) - - -def parse_options(): - parser = OptionParser() - parser.add_option( - '--event-idl-files-list', help='file listing event IDL files') - parser.add_option('--event-interfaces-file', help='output file') - parser.add_option( - '--suffix', - help= - 'specify a suffix to the namespace, i.e., "Modules". Default is None.') - parser.add_option( - '--export-macro', - help='specify an export to use for the symbols, i.e.,' - '"MODULES_EXPORT". Default is suffix_EXPORT if --suffix is present or ' - 'CORE_EXPORT if not.') - - options, args = parser.parse_args() - if options.event_idl_files_list is None: - parser.error( - 'Must specify a file listing event IDL files using --event-idl-files-list.' - ) - if options.event_interfaces_file is None: - parser.error( - 'Must specify an output file using --event-interfaces-file.') - if args: - parser.error('No arguments allowed, but %d given.' % len(args)) - return options - - -def write_event_interfaces_file(event_idl_files, destination_filename, suffix, - export_macro): - def interface_line(full_path): - relative_dir_local = os.path.dirname( - os.path.relpath(full_path, REPO_ROOT_DIR)) - relative_dir_posix = relative_dir_local.replace(os.sep, posixpath.sep) - - idl_file_contents = get_file_contents(full_path) - interface_name = get_first_interface_name_from_idl(idl_file_contents) - extended_attributes = get_interface_extended_attributes_from_idl( - idl_file_contents) - extended_attributes_list = [(name, extended_attributes[name]) - for name in EXPORTED_EXTENDED_ATTRIBUTES - if name in extended_attributes] - - return (relative_dir_posix, interface_name, extended_attributes_list) - - lines = ['{', 'metadata: {', ' namespace: "event_interface_names",'] - - if suffix: - lines.append(' suffix: "' + suffix + '",') - - if export_macro: - lines.append(' export: "%s",' % export_macro) - elif suffix: - lines.append(' export: "%s_EXPORT",' % suffix.upper()) - else: - lines.append(' export: "CORE_EXPORT",') - lines.extend(['},', 'data: [']) - interface_lines = [ - interface_line(event_idl_file) for event_idl_file in event_idl_files - ] - interface_lines.sort() - for relative_dir, name, attributes in interface_lines: - lines.extend([ - ' {', - ' name: "%s",' % name, - ' interfaceHeaderDir: "%s",' % relative_dir - ]) - for param, value in attributes: - if param == 'RuntimeEnabled': - value += 'Enabled' - lines.append(' %s: "%s",' % (param, value)) - lines.append(' },') - lines.extend([']', '}']) - write_file('\n'.join(lines), destination_filename) - - -################################################################################ - - -def main(): - options = parse_options() - event_idl_files = read_file_to_list(options.event_idl_files_list) - write_event_interfaces_file(event_idl_files, options.event_interfaces_file, - options.suffix, options.export_macro) - - -if __name__ == '__main__': - sys.exit(main())
diff --git a/third_party/blink/renderer/bindings/scripts/scripts.gni b/third_party/blink/renderer/bindings/scripts/scripts.gni deleted file mode 100644 index 3a7931f..0000000 --- a/third_party/blink/renderer/bindings/scripts/scripts.gni +++ /dev/null
@@ -1,56 +0,0 @@ -# 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. - -import("//build/config/python.gni") -import("//third_party/blink/renderer/build/scripts/scripts.gni") - -bindings_scripts_dir = get_path_info(".", "abspath") -bindings_scripts_output_dir = get_path_info(".", "gen_dir") - -# Calls generate_event_interfaces -# -# Parameters: -# sources = A list of IDL files to process. -# output_file = The .in file to write, relative to the blink_gen_dir. -# suffix = (Optional) String to be passed to script via --suffix -# export_macro = (Optional) String to be passed to script via --export-macro -template("generate_event_interfaces") { - action(target_name) { - # Write the file list to a unique temp file to avoid blowing out the - # command line length limit. - idl_files_list = "$target_gen_dir/${target_name}_file_list.tmp" - write_file(idl_files_list, rebase_path(invoker.sources, root_build_dir)) - - inputs = [ - "//third_party/blink/renderer/bindings/scripts/utilities.py", - idl_files_list, - ] + invoker.sources - - output_file = - "$root_gen_dir/third_party/blink/renderer/" + invoker.output_file - outputs = [ output_file ] - - script = "//third_party/blink/renderer/bindings/scripts/generate_event_interfaces.py" - args = [ - "--event-idl-files-list", - rebase_path(idl_files_list, root_build_dir), - "--event-interfaces-file", - rebase_path(output_file, root_build_dir), - ] - - if (defined(invoker.suffix)) { - args += [ - "--suffix", - invoker.suffix, - ] - } - - if (defined(invoker.export_macro)) { - args += [ - "--export-macro", - invoker.export_macro, - ] - } - } -}
diff --git a/third_party/blink/renderer/bindings/scripts/utilities.py b/third_party/blink/renderer/bindings/scripts/utilities.py deleted file mode 100644 index 2e6669d..0000000 --- a/third_party/blink/renderer/bindings/scripts/utilities.py +++ /dev/null
@@ -1,630 +0,0 @@ -# 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. -"""Utility functions (file reading, simple IDL parsing by regexes) for IDL build. - -Design doc: http://www.chromium.org/developers/design-documents/idl-build -""" - -import os -import re -import shlex -import subprocess -import sys - -if sys.version_info.major == 2: - import cPickle as pickle -else: - import pickle - -sys.path.append( - os.path.join(os.path.dirname(__file__), '..', '..', 'build', 'scripts')) -from blinkbuild.name_style_converter import NameStyleConverter - -KNOWN_COMPONENTS = frozenset(['core', 'modules']) -KNOWN_COMPONENTS_WITH_TESTING = frozenset(['core', 'modules', 'testing']) - - -def idl_filename_to_basename(idl_filename): - """Returns the basename without the extension.""" - return os.path.splitext(os.path.basename(idl_filename))[0] - - -def idl_filename_to_component_with_known_components(idl_filename, - known_components): - path = os.path.dirname(os.path.realpath(idl_filename)) - while path: - dirname, basename = os.path.split(path) - if not basename: - break - if basename.lower() in known_components: - return basename.lower() - path = dirname - raise Exception('Unknown component type for %s' % idl_filename) - - -def idl_filename_to_component(idl_filename): - return idl_filename_to_component_with_known_components( - idl_filename, KNOWN_COMPONENTS) - - -def is_testing_target(idl_filename): - component = idl_filename_to_component_with_known_components( - idl_filename, KNOWN_COMPONENTS_WITH_TESTING) - return component == 'testing' - - -# See whether "component" can depend on "dependency" or not: -# Suppose that we have interface X and Y: -# - if X is a partial interface and Y is the original interface, -# use is_valid_component_dependency(X, Y). -# - if X implements Y, use is_valid_component_dependency(X, Y) -# Suppose that X is a cpp file and Y is a header file: -# - if X includes Y, use is_valid_component_dependency(X, Y) -def is_valid_component_dependency(component, dependency): - assert component in KNOWN_COMPONENTS - assert dependency in KNOWN_COMPONENTS - if component == 'core' and dependency == 'modules': - return False - return True - - -class ComponentInfoProvider(object): - """Base class of information provider which provides component-specific - information. - """ - - def __init__(self): - pass - - @property - def interfaces_info(self): - return {} - - @property - def component_info(self): - return {} - - @property - def enumerations(self): - return {} - - @property - def typedefs(self): - return {} - - @property - def union_types(self): - return set() - - @property - def include_path_for_union_types(self, union_type): - return None - - @property - def callback_functions(self): - return {} - - -class ComponentInfoProviderCore(ComponentInfoProvider): - def __init__(self, interfaces_info, component_info): - super(ComponentInfoProviderCore, self).__init__() - self._interfaces_info = interfaces_info - self._component_info = component_info - - @property - def interfaces_info(self): - return self._interfaces_info - - @property - def component_info(self): - return self._component_info - - @property - def enumerations(self): - return self._component_info['enumerations'] - - @property - def typedefs(self): - return self._component_info['typedefs'] - - @property - def union_types(self): - return self._component_info['union_types'] - - def include_path_for_union_types(self, union_type): - name = to_snake_case(shorten_union_name(union_type)) - return 'bindings/core/v8/%s.h' % name - - @property - def callback_functions(self): - return self._component_info['callback_functions'] - - @property - def specifier_for_export(self): - return 'CORE_EXPORT ' - - @property - def include_path_for_export(self): - return 'core/core_export.h' - - -class ComponentInfoProviderModules(ComponentInfoProvider): - def __init__(self, interfaces_info, component_info_core, - component_info_modules): - super(ComponentInfoProviderModules, self).__init__() - self._interfaces_info = interfaces_info - self._component_info_core = component_info_core - self._component_info_modules = component_info_modules - - @property - def interfaces_info(self): - return self._interfaces_info - - @property - def component_info(self): - return self._component_info_modules - - @property - def enumerations(self): - enums = self._component_info_core['enumerations'].copy() - enums.update(self._component_info_modules['enumerations']) - return enums - - @property - def typedefs(self): - typedefs = self._component_info_core['typedefs'].copy() - typedefs.update(self._component_info_modules['typedefs']) - return typedefs - - @property - def union_types(self): - # Remove duplicate union types from component_info_modules to avoid - # generating multiple container generation. - return (self._component_info_modules['union_types'] - - self._component_info_core['union_types']) - - def include_path_for_union_types(self, union_type): - core_union_type_names = [ - core_union_type.name - for core_union_type in self._component_info_core['union_types'] - ] - name = shorten_union_name(union_type) - if union_type.name in core_union_type_names: - return 'bindings/core/v8/%s.h' % to_snake_case(name) - return 'bindings/modules/v8/%s.h' % to_snake_case(name) - - @property - def callback_functions(self): - return dict( - list(self._component_info_core['callback_functions'].items()) + - list(self._component_info_modules['callback_functions'].items())) - - @property - def specifier_for_export(self): - return 'MODULES_EXPORT ' - - @property - def include_path_for_export(self): - return 'modules/modules_export.h' - - -def load_interfaces_info_overall_pickle(info_dir): - with open(os.path.join(info_dir, 'interfaces_info.pickle'), - mode='rb') as interface_info_file: - return pickle.load(interface_info_file) - - -def merge_dict_recursively(target, diff): - """Merges two dicts into one. - |target| will be updated with |diff|. Part of |diff| may be re-used in - |target|. - """ - for key, value in diff.items(): - if key not in target: - target[key] = value - elif type(value) == dict: - merge_dict_recursively(target[key], value) - elif type(value) == list: - target[key].extend(value) - elif type(value) == set: - target[key].update(value) - else: - # Testing IDLs want to overwrite the values. Production code - # doesn't need any overwriting. - target[key] = value - - -def create_component_info_provider_core(info_dir): - interfaces_info = load_interfaces_info_overall_pickle(info_dir) - with open(os.path.join(info_dir, 'core', 'component_info_core.pickle'), - mode='rb') as component_info_file: - component_info = pickle.load(component_info_file) - return ComponentInfoProviderCore(interfaces_info, component_info) - - -def create_component_info_provider_modules(info_dir): - interfaces_info = load_interfaces_info_overall_pickle(info_dir) - with open(os.path.join(info_dir, 'core', 'component_info_core.pickle'), - mode='rb') as component_info_file: - component_info_core = pickle.load(component_info_file) - with open(os.path.join(info_dir, 'modules', - 'component_info_modules.pickle'), - mode='rb') as component_info_file: - component_info_modules = pickle.load(component_info_file) - return ComponentInfoProviderModules(interfaces_info, component_info_core, - component_info_modules) - - -def create_component_info_provider(info_dir, component): - if component == 'core': - return create_component_info_provider_core(info_dir) - elif component == 'modules': - return create_component_info_provider_modules(info_dir) - else: - return ComponentInfoProvider() - - -################################################################################ -# Basic file reading/writing -################################################################################ - - -def get_file_contents(filename): - with open(filename, encoding='utf-8') as f: - return f.read() - - -def read_file_to_list(filename): - """Returns a list of (stripped) lines for a given filename.""" - with open(filename, encoding='utf-8') as f: - return [line.rstrip('\n') for line in f] - - -def resolve_cygpath(cygdrive_names): - if not cygdrive_names: - return [] - cmd = ['cygpath', '-f', '-', '-wa'] - process = subprocess.Popen( - cmd, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT) - idl_file_names = [] - for file_name in cygdrive_names: - process.stdin.write('%s\n' % file_name) - process.stdin.flush() - idl_file_names.append(process.stdout.readline().rstrip()) - process.stdin.close() - process.wait() - return idl_file_names - - -def read_idl_files_list_from_file(filename): - """Similar to read_file_to_list, but also resolves cygpath.""" - with open(filename, encoding='utf-8') as input_file: - file_names = sorted(shlex.split(input_file)) - idl_file_names = [ - file_name for file_name in file_names - if not file_name.startswith('/cygdrive') - ] - cygdrive_names = [ - file_name for file_name in file_names - if file_name.startswith('/cygdrive') - ] - idl_file_names.extend(resolve_cygpath(cygdrive_names)) - return idl_file_names - - -def read_pickle_files(pickle_filenames): - for pickle_filename in pickle_filenames: - yield read_pickle_file(pickle_filename) - - -def read_pickle_file(pickle_filename): - with open(pickle_filename, 'rb') as pickle_file: - return pickle.load(pickle_file) - - -def write_file(new_text, destination_filename): - # If |new_text| is same with the file content, we skip updating. - if os.path.isfile(destination_filename): - with open(destination_filename, encoding='utf-8') as destination_file: - if destination_file.read() == new_text: - return - - destination_dirname = os.path.dirname(destination_filename) - if destination_dirname and not os.path.exists(destination_dirname): - os.makedirs(destination_dirname) - # Write file in binary so that when run on Windows, line endings are not - # converted - with open(destination_filename, 'wb') as destination_file: - destination_file.write(new_text.encode('utf-8')) - - -def write_pickle_file(pickle_filename, data): - # If |data| is same with the file content, we skip updating. - if os.path.isfile(pickle_filename): - with open(pickle_filename, 'rb') as pickle_file: - try: - if pickle.load(pickle_file) == data: - return - except Exception: - # If trouble unpickling, overwrite - pass - with open(pickle_filename, 'wb') as pickle_file: - pickle.dump(data, pickle_file) - - -################################################################################ -# IDL parsing -# -# TODO(bashi): We use regular expressions for parsing; this is incorrect -# (Web IDL is not a regular language) and broken. Remove these functions and -# always use the parser and ASTs. -# Leading and trailing context (e.g. following '{') used to avoid false matches. -################################################################################ - - -def is_non_legacy_callback_interface_from_idl(file_contents): - """Returns True if the specified IDL is a non-legacy callback interface.""" - match = re.search(r'callback\s+interface\s+\w+\s*{', file_contents) - # Having constants means it's a legacy callback interface. - # https://webidl.spec.whatwg.org/#legacy-callback-interface-object - return bool(match) and not re.search(r'\s+const\b', file_contents) - - -def is_interface_mixin_from_idl(file_contents): - """Returns True if the specified IDL is an interface mixin.""" - match = re.search(r'interface\s+mixin\s+\w+\s*{', file_contents) - return bool(match) - - -def should_generate_impl_file_from_idl(file_contents): - """True when a given IDL file contents could generate .h/.cpp files.""" - # FIXME: This would be error-prone and we should use AST rather than - # improving the regexp pattern. - match = re.search(r'(interface|dictionary)\s+\w+', file_contents) - return bool(match) - - -def match_interface_extended_attributes_and_name_from_idl(file_contents): - # Strip comments - # re.compile needed b/c Python 2.6 doesn't support flags in re.sub - single_line_comment_re = re.compile(r'//.*$', flags=re.MULTILINE) - block_comment_re = re.compile(r'/\*.*?\*/', flags=re.MULTILINE | re.DOTALL) - file_contents = re.sub(single_line_comment_re, '', file_contents) - file_contents = re.sub(block_comment_re, '', file_contents) - - match = re.search( - r'(?:\[([^{};]*)\]\s*)?' - r'(interface|interface\s+mixin|callback\s+interface|partial\s+interface|dictionary)\s+' - r'(\w+)\s*' - r'(:\s*\w+\s*)?' - r'{', - file_contents, - flags=re.DOTALL) - return match - - -def get_interface_extended_attributes_from_idl(file_contents): - match = match_interface_extended_attributes_and_name_from_idl( - file_contents) - if not match or not match.group(1): - return {} - - extended_attributes_string = match.group(1).strip() - parts = [ - extended_attribute.strip() - for extended_attribute in re.split(',', extended_attributes_string) - # Discard empty parts, which may exist due to trailing comma - if extended_attribute.strip() - ] - - # Joins |parts| with commas as far as the parences are not balanced, - # and then converts a (joined) term to a dict entry. - # ex. ['ab=c', 'ab(cd', 'ef', 'gh)', 'f=(a', 'b)'] - # => {'ab': 'c', 'ab(cd,ef,gh)': '', 'f': '(a,b)'} - extended_attributes = {} - concatenated = None - for part in parts: - concatenated = (concatenated + ', ' + part) if concatenated else part - parences = concatenated.count('(') - concatenated.count(')') - square_brackets = concatenated.count('[') - concatenated.count(']') - if parences < 0 or square_brackets < 0: - raise ValueError('You have more close braces than open braces.') - if parences == 0 and square_brackets == 0: - name, _, value = map(str.strip, concatenated.partition('=')) - extended_attributes[name] = value - concatenated = None - return extended_attributes - - -def get_interface_exposed_arguments(file_contents): - match = match_interface_extended_attributes_and_name_from_idl( - file_contents) - if not match or not match.group(1): - return None - - extended_attributes_string = match.group(1) - match = re.search(r'[^=]\bExposed\(([^)]*)\)', file_contents) - if not match: - return None - arguments = [] - for argument in map(str.strip, match.group(1).split(',')): - exposed, runtime_enabled = argument.split() - arguments.append({ - 'exposed': exposed, - 'runtime_enabled': runtime_enabled - }) - - return arguments - - -def get_first_interface_name_from_idl(file_contents): - match = match_interface_extended_attributes_and_name_from_idl( - file_contents) - if match: - return match.group(3) - return None - - -# Workaround for crbug.com/611437 and crbug.com/711464 -# TODO(bashi): Remove this hack once we resolve too-long generated file names. -# pylint: disable=line-too-long -def shorten_union_name(union_type): - aliases = { - # modules/canvas2d/CanvasRenderingContext2D.idl - 'CSSImageValueOrHTMLImageElementOrSVGImageElementOrHTMLVideoElementOrHTMLCanvasElementOrImageBitmapOrOffscreenCanvasOrVideoFrame': - 'CanvasImageSource', - # modules/canvas/htmlcanvas/html_canvas_element_module.idl - 'CanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrImageBitmapRenderingContextOrGPUCanvasContext': - 'RenderingContext', - # core/frame/window_or_worker_global_scope.idl - 'HTMLImageElementOrSVGImageElementOrHTMLVideoElementOrHTMLCanvasElementOrBlobOrImageDataOrImageBitmapOrOffscreenCanvasOrVideoFrame': - 'ImageBitmapSource', - # bindings/tests/idls/core/TestTypedefs.idl - 'NodeOrLongSequenceOrEventOrXMLHttpRequestOrStringOrStringByteStringOrNodeListRecord': - 'NestedUnionType', - # modules/canvas/offscreencanvas/offscreen_canvas_module.idl - 'OffscreenCanvasRenderingContext2DOrWebGLRenderingContextOrWebGL2RenderingContextOrImageBitmapRenderingContextOrGPUCanvasContext': - 'OffscreenRenderingContext', - # core/xmlhttprequest/xml_http_request.idl - 'DocumentOrBlobOrArrayBufferOrArrayBufferViewOrFormDataOrURLSearchParamsOrUSVString': - 'DocumentOrXMLHttpRequestBodyInit', - # modules/beacon/navigator_beacon.idl - 'ReadableStreamOrBlobOrArrayBufferOrArrayBufferViewOrFormDataOrURLSearchParamsOrUSVString': - 'ReadableStreamOrXMLHttpRequestBodyInit', - # modules/mediasource/source_buffer.idl - 'EncodedAudioChunkOrEncodedVideoChunkSequenceOrEncodedAudioChunkOrEncodedVideoChunk': - 'EncodedAVChunkSequenceOrEncodedAVChunk', - } - - idl_type = union_type - if union_type.is_nullable: - idl_type = union_type.inner_type - name = idl_type.cpp_type or idl_type.name - alias = aliases.get(name) - if alias: - return alias - if len(name) >= 80: - raise Exception('crbug.com/711464: The union name %s is too long. ' - 'Please add an alias to shorten_union_name()' % name) - return name - - -def to_snake_case(name): - return NameStyleConverter(name).to_snake_case() - - -def to_header_guard(path): - return NameStyleConverter(path).to_header_guard() - - -def normalize_path(path): - return path.replace("\\", "/") - - -def format_remove_duplicates(text, patterns): - """Removes duplicated line-basis patterns. - - Based on simple pattern matching, removes duplicated lines in a block - of lines. Lines that match with a same pattern are considered as - duplicates. - - Designed to be used as a filter function for Jinja2. - - Args: - text: A str of multi-line text. - patterns: A list of str where each str represents a simple - pattern. The patterns are not considered as regexp, and - exact match is applied. - - Returns: - A formatted str with duplicates removed. - """ - pattern_founds = [False] * len(patterns) - output = [] - for line in text.split('\n'): - to_be_removed = False - for i, pattern in enumerate(patterns): - if pattern not in line: - continue - if pattern_founds[i]: - to_be_removed = True - else: - pattern_founds[i] = True - if to_be_removed: - continue - output.append(line) - - # Let |'\n'.join| emit the last newline. - if output: - output.append('') - - return '\n'.join(output) - - -def format_blink_cpp_source_code(text): - """Formats C++ source code. - - Supported modifications are: - - Reduces successive empty lines into a single empty line. - - Removes empty lines just after an open brace or before closing brace. - This rule does not apply to namespaces. - - Designed to be used as a filter function for Jinja2. - - Args: - text: A str of C++ source code. - - Returns: - A formatted str of the source code. - """ - re_empty_line = re.compile(r'^\s*$') - re_first_brace = re.compile(r'(?P<first>[{}])') - re_last_brace = re.compile(r'.*(?P<last>[{}]).*?$') - was_open_brace = True # Trick to remove the empty lines at the beginning. - was_empty_line = False - output = [] - for line in text.split('\n'): - # Skip empty lines. - if line == '' or re_empty_line.match(line): - was_empty_line = True - continue - - # Emit a single empty line if needed. - if was_empty_line: - was_empty_line = False - if '}' in line: - match = re_first_brace.search(line) - else: - match = None - - if was_open_brace: - # No empty line just after an open brace. - pass - elif (match and match.group('first') == '}' - and 'namespace' not in line): - # No empty line just before a closing brace. - pass - else: - # Preserve a single empty line. - output.append('') - - # Emit the line itself. - output.append(line) - - # Remember an open brace. - if '{' in line: - match = re_last_brace.search(line) - else: - match = None - was_open_brace = (match and match.group('last') == '{' - and 'namespace' not in line) - - # Let |'\n'.join| emit the last newline. - if output: - output.append('') - - return '\n'.join(output)
diff --git a/third_party/blink/renderer/core/editing/substring_util.h b/third_party/blink/renderer/core/editing/substring_util.h index 9a055eb4..ad54579 100644 --- a/third_party/blink/renderer/core/editing/substring_util.h +++ b/third_party/blink/renderer/core/editing/substring_util.h
@@ -56,7 +56,7 @@ // - the left baseline point of that word in `baseline_point` // // Returns nil on failure. - CORE_EXPORT static base::ScopedCFTypeRef<CFAttributedStringRef> + CORE_EXPORT static base::apple::ScopedCFTypeRef<CFAttributedStringRef> AttributedWordAtPoint(WebFrameWidgetImpl*, gfx::Point, gfx::Point& baseline_point); @@ -68,7 +68,7 @@ // - the left baseline point of that substring in `baseline_point` // // Returns nil on failure. - CORE_EXPORT static base::ScopedCFTypeRef<CFAttributedStringRef> + CORE_EXPORT static base::apple::ScopedCFTypeRef<CFAttributedStringRef> AttributedSubstringInRange(LocalFrame*, wtf_size_t location, wtf_size_t length,
diff --git a/third_party/blink/renderer/core/editing/substring_util.mm b/third_party/blink/renderer/core/editing/substring_util.mm index a422be0e..187d6699 100644 --- a/third_party/blink/renderer/core/editing/substring_util.mm +++ b/third_party/blink/renderer/core/editing/substring_util.mm
@@ -181,20 +181,20 @@ } // namespace -base::ScopedCFTypeRef<CFAttributedStringRef> +base::apple::ScopedCFTypeRef<CFAttributedStringRef> SubstringUtil::AttributedWordAtPoint(WebFrameWidgetImpl* frame_widget, gfx::Point point, gfx::Point& baseline_point) { HitTestResult result = frame_widget->CoreHitTestResultAt(gfx::PointF(point)); if (!result.InnerNode()) { - return base::ScopedCFTypeRef<CFAttributedStringRef>(); + return base::apple::ScopedCFTypeRef<CFAttributedStringRef>(); } LocalFrame* frame = result.InnerNode()->GetDocument().GetFrame(); EphemeralRange range = frame->GetEditor().RangeForPoint(result.RoundedPointInInnerNodeFrame()); if (range.IsNull()) { - return base::ScopedCFTypeRef<CFAttributedStringRef>(); + return base::apple::ScopedCFTypeRef<CFAttributedStringRef>(); } // Expand to word under point. @@ -206,11 +206,11 @@ // Convert to CFAttributedStringRef. NSAttributedString* string = AttributedSubstringFromRange(frame, word_range); baseline_point = GetBaselinePoint(frame->View(), word_range, string); - return base::ScopedCFTypeRef<CFAttributedStringRef>( + return base::apple::ScopedCFTypeRef<CFAttributedStringRef>( base::apple::NSToCFOwnershipCast(string)); } -base::ScopedCFTypeRef<CFAttributedStringRef> +base::apple::ScopedCFTypeRef<CFAttributedStringRef> SubstringUtil::AttributedSubstringInRange(LocalFrame* frame, wtf_size_t location, wtf_size_t length, @@ -219,18 +219,18 @@ Element* editable = frame->Selection().RootEditableElementOrDocumentElement(); if (!editable) { - return base::ScopedCFTypeRef<CFAttributedStringRef>(); + return base::apple::ScopedCFTypeRef<CFAttributedStringRef>(); } const EphemeralRange ephemeral_range( PlainTextRange(location, location + length).CreateRange(*editable)); if (ephemeral_range.IsNull()) { - return base::ScopedCFTypeRef<CFAttributedStringRef>(); + return base::apple::ScopedCFTypeRef<CFAttributedStringRef>(); } NSAttributedString* string = AttributedSubstringFromRange(frame, ephemeral_range); baseline_point = GetBaselinePoint(frame->View(), ephemeral_range, string); - return base::ScopedCFTypeRef<CFAttributedStringRef>( + return base::apple::ScopedCFTypeRef<CFAttributedStringRef>( base::apple::NSToCFOwnershipCast(string)); }
diff --git a/third_party/blink/renderer/core/editing/substring_util_test.mm b/third_party/blink/renderer/core/editing/substring_util_test.mm index c5da51b..db800d7 100644 --- a/third_party/blink/renderer/core/editing/substring_util_test.mm +++ b/third_party/blink/renderer/core/editing/substring_util_test.mm
@@ -53,7 +53,7 @@ static_cast<WebLocalFrameImpl*>(web_view->MainFrame()); gfx::Point baseline_point; - base::ScopedCFTypeRef<CFAttributedStringRef> result = + base::apple::ScopedCFTypeRef<CFAttributedStringRef> result = SubstringUtil::AttributedSubstringInRange(frame->GetFrame(), 10, 3, baseline_point); ASSERT_TRUE(result); @@ -105,7 +105,7 @@ static_cast<WebLocalFrameImpl*>(web_view->MainFrame()); gfx::Point baseline_point; - base::ScopedCFTypeRef<CFAttributedStringRef> result = + base::apple::ScopedCFTypeRef<CFAttributedStringRef> result = SubstringUtil::AttributedSubstringInRange(frame->GetFrame(), 10, 3, baseline_point); ASSERT_TRUE(result); @@ -137,7 +137,7 @@ To<LocalFrame>(main_frame->GetFrame()->Tree().FirstChild())); gfx::Point baseline_point; - base::ScopedCFTypeRef<CFAttributedStringRef> result = + base::apple::ScopedCFTypeRef<CFAttributedStringRef> result = SubstringUtil::AttributedSubstringInRange(child_frame->GetFrame(), 11, 7, baseline_point); ASSERT_NE(result, nullptr);
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 fe7f19e..21d04b2f 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
@@ -984,7 +984,7 @@ GetStringForRangeCallback callback) { gfx::Point baseline_point; ui::mojom::blink::AttributedStringPtr attributed_string = nullptr; - base::ScopedCFTypeRef<CFAttributedStringRef> string = + base::apple::ScopedCFTypeRef<CFAttributedStringRef> string = SubstringUtil::AttributedSubstringInRange( frame_, base::checked_cast<WTF::wtf_size_t>(range.start()), base::checked_cast<WTF::wtf_size_t>(range.length()), baseline_point);
diff --git a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc index 10398e3..492f56d 100644 --- a/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc +++ b/third_party/blink/renderer/core/frame/web_frame_widget_impl.cc
@@ -671,7 +671,7 @@ GetStringAtPointCallback callback) { gfx::Point baseline_point; ui::mojom::blink::AttributedStringPtr attributed_string = nullptr; - base::ScopedCFTypeRef<CFAttributedStringRef> string = + base::apple::ScopedCFTypeRef<CFAttributedStringRef> string = SubstringUtil::AttributedWordAtPoint(this, point_in_local_root, baseline_point); if (string) {
diff --git a/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm b/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm index 7f69c26..2f8aa88 100644 --- a/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm +++ b/third_party/blink/renderer/platform/fonts/mac/font_matcher_mac.mm
@@ -126,11 +126,11 @@ base::apple::CFToNSPtrCast(kCTFontNameAttribute) : desired_name, base::apple::CFToNSPtrCast(kCTFontSizeAttribute) : @(size) }; - base::ScopedCFTypeRef<CTFontDescriptorRef> descriptor( + base::apple::ScopedCFTypeRef<CTFontDescriptorRef> descriptor( CTFontDescriptorCreateWithAttributes( base::apple::NSToCFPtrCast(attributes))); - base::ScopedCFTypeRef<CTFontRef> matched_font( + base::apple::ScopedCFTypeRef<CTFontRef> matched_font( CTFontCreateWithFontDescriptor(descriptor, 0, nullptr)); DCHECK(matched_font);
diff --git a/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm b/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm index 5ec9feb..5a613d9 100644 --- a/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm +++ b/third_party/blink/renderer/platform/fonts/mac/font_platform_data_mac.mm
@@ -92,7 +92,7 @@ } static bool CanLoadInProcess(NSFont* ns_font) { - base::ScopedCFTypeRef<CGFontRef> cg_font(CTFontCopyGraphicsFont( + base::apple::ScopedCFTypeRef<CGFontRef> cg_font(CTFontCopyGraphicsFont( base::apple::NSToCFPtrCast(ns_font), /*attributes=*/nullptr)); NSString* font_name = base::apple::CFToNSOwnershipCast(CGFontCopyPostScriptName(cg_font));
diff --git a/third_party/blink/renderer/platform/mac/graphics_context_canvas.h b/third_party/blink/renderer/platform/mac/graphics_context_canvas.h index a9ebc69..f1a0800 100644 --- a/third_party/blink/renderer/platform/mac/graphics_context_canvas.h +++ b/third_party/blink/renderer/platform/mac/graphics_context_canvas.h
@@ -42,7 +42,7 @@ cc::PaintCanvas* canvas_; - base::ScopedCFTypeRef<CGContextRef> cg_context_; + base::apple::ScopedCFTypeRef<CGContextRef> cg_context_; SkBitmap offscreen_; SkScalar bitmap_scale_factor_;
diff --git a/third_party/blink/renderer/platform/mac/graphics_context_canvas.mm b/third_party/blink/renderer/platform/mac/graphics_context_canvas.mm index 68738b1..6e0c32f 100644 --- a/third_party/blink/renderer/platform/mac/graphics_context_canvas.mm +++ b/third_party/blink/renderer/platform/mac/graphics_context_canvas.mm
@@ -49,7 +49,7 @@ // Allocate an offscreen and draw into that, relying on the // compositing step to apply skia's clip. - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateWithName(kCGColorSpaceSRGB)); bool result = offscreen_.tryAllocN32Pixels(
diff --git a/third_party/blink/renderer/platform/text/apple/hyphenation_apple.cc b/third_party/blink/renderer/platform/text/apple/hyphenation_apple.cc index c71ac41..8f101323 100644 --- a/third_party/blink/renderer/platform/text/apple/hyphenation_apple.cc +++ b/third_party/blink/renderer/platform/text/apple/hyphenation_apple.cc
@@ -14,7 +14,7 @@ class HyphenationCF final : public Hyphenation { public: - HyphenationCF(base::ScopedCFTypeRef<CFLocaleRef>& locale_cf) + HyphenationCF(base::apple::ScopedCFTypeRef<CFLocaleRef>& locale_cf) : locale_cf_(locale_cf) { DCHECK(locale_cf_); } @@ -75,14 +75,14 @@ } private: - base::ScopedCFTypeRef<CFLocaleRef> locale_cf_; + base::apple::ScopedCFTypeRef<CFLocaleRef> locale_cf_; }; scoped_refptr<Hyphenation> Hyphenation::PlatformGetHyphenation( const AtomicString& locale) { - base::ScopedCFTypeRef<CFStringRef> locale_cf_string( + base::apple::ScopedCFTypeRef<CFStringRef> locale_cf_string( locale.Impl()->CreateCFString()); - base::ScopedCFTypeRef<CFLocaleRef> locale_cf( + base::apple::ScopedCFTypeRef<CFLocaleRef> locale_cf( CFLocaleCreate(kCFAllocatorDefault, locale_cf_string)); if (!CFStringIsHyphenationAvailableForLocale(locale_cf)) { return nullptr;
diff --git a/third_party/blink/renderer/platform/wtf/text/string_impl.h b/third_party/blink/renderer/platform/wtf/text/string_impl.h index 8bd00547..4bf80b28 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_impl.h +++ b/third_party/blink/renderer/platform/wtf/text/string_impl.h
@@ -478,7 +478,7 @@ wtf_size_t length = UINT_MAX) const; #if BUILDFLAG(IS_APPLE) - base::ScopedCFTypeRef<CFStringRef> CreateCFString(); + base::apple::ScopedCFTypeRef<CFStringRef> CreateCFString(); #endif #ifdef __OBJC__ operator NSString*();
diff --git a/third_party/blink/renderer/platform/wtf/text/string_impl_apple.mm b/third_party/blink/renderer/platform/wtf/text/string_impl_apple.mm index a895b1e..7f04bcd9 100644 --- a/third_party/blink/renderer/platform/wtf/text/string_impl_apple.mm +++ b/third_party/blink/renderer/platform/wtf/text/string_impl_apple.mm
@@ -26,8 +26,8 @@ namespace WTF { -base::ScopedCFTypeRef<CFStringRef> StringImpl::CreateCFString() { - return base::ScopedCFTypeRef<CFStringRef>( +base::apple::ScopedCFTypeRef<CFStringRef> StringImpl::CreateCFString() { + return base::apple::ScopedCFTypeRef<CFStringRef>( Is8Bit() ? CFStringCreateWithBytes( kCFAllocatorDefault,
diff --git a/third_party/blink/tools/blinkpy/common/system/filesystem_mock.py b/third_party/blink/tools/blinkpy/common/system/filesystem_mock.py index 06eab69..a7970371 100644 --- a/third_party/blink/tools/blinkpy/common/system/filesystem_mock.py +++ b/third_party/blink/tools/blinkpy/common/system/filesystem_mock.py
@@ -432,7 +432,7 @@ return dot_dot + rel_path def remove(self, path, retry=True): - if self.files[path] is None: + if self.files.get(path) is None: self._raise_not_found(path) self.files[path] = None self.written_files[path] = None
diff --git a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py index 2892eece..263458b1 100755 --- a/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py +++ b/third_party/blink/tools/blinkpy/presubmit/audit_non_blink_usage.py
@@ -733,7 +733,7 @@ # Useful for platform-specific code. 'base::apple::(CFToNSPtrCast|NSToCFPtrCast|CFToNSOwnershipCast|NSToCFOwnershipCast)', 'base::mac::Is(AtMost|AtLeast)?OS.+', - 'base::ScopedCFTypeRef', + 'base::apple::ScopedCFTypeRef', ], 'disallowed': [ ('base::Bind(|Once|Repeating)',
diff --git a/third_party/blink/tools/blinkpy/tool/commands/update_metadata.py b/third_party/blink/tools/blinkpy/tool/commands/update_metadata.py index 417e68aa..589115a9 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/update_metadata.py +++ b/third_party/blink/tools/blinkpy/tool/commands/update_metadata.py
@@ -6,12 +6,14 @@ import collections import contextlib +import enum import functools import io import json import logging import pathlib import optparse +import os import re from concurrent.futures import Executor from typing import ( @@ -29,8 +31,10 @@ Optional, Set, TypedDict, + Tuple, Union, ) +from urllib.parse import urljoin from blinkpy.common import path_finder from blinkpy.common.host import Host @@ -55,6 +59,7 @@ path_finder.bootstrap_wpt_imports() from manifest import manifest as wptmanifest from wptrunner import ( + expectedtree, manifestupdate, metadata, testloader, @@ -486,11 +491,77 @@ """Exception raised when the update should be aborted.""" +class DisableType(enum.Enum): + """Possible values for the `disabled` key (e.g., disable reasons).""" + ENABLED = '@False' + NEVER_FIX = 'neverfix' + MIGRATED = 'skipped in TestExpectations' + SLOW_TIMEOUT = 'times out even with `timeout=long`' + + +class DisabledUpdate(manifestupdate.PropertyUpdate): + """The algorithm for disabling a test/directory, possibly conditionally. + + This updater overrides the default conditional update algorithm to not + promote the most common `disabled` value to the default value at the end of + the condition chain, as occurs for updating `expected`. This allows + `disabled` to fall back to other `disabled` in parent `__dir__.ini`. + """ + + property_name = 'disabled' + property_builder = manifestupdate.build_conditional_tree + + def updated_value(self, current: str, new: Dict[Optional[str], + int]) -> str: + if not new: + return None + # There shouldn't be more than one disable reason in real usage, so + # arbitrarily pick the most common non-null one. + return max(new, key=lambda reason: (bool(reason), new[reason])) + + def build_tree_conditions(self, + property_tree: expectedtree.Node, + run_info_with_condition: Set[metadata.RunInfo], + prev_default=None): + conditions = list( + self._build_tree_conditions(property_tree, run_info_with_condition, + [])) + # Sort by disable reason first, then by props. + conditions.sort( + key=lambda condition: (condition[1], condition[0] or [])) + conditions = [ + (manifestupdate.make_expr(props, value) if props else None, value) + for props, value in conditions + ] + return conditions, [] + + def _build_tree_conditions(self, node: expectedtree.Node, + run_info_with_condition: Set[metadata.RunInfo], + props: List[Tuple[str, Any]]): + conditions = [] + if node.prop: + props = [*props, (node.prop, node.value)] + if node.result_values and set(node.run_info) - run_info_with_condition: + value = self.updated_value(None, node.result_values) + if value: + # A falsy `props` represents an unconditional value. + yield (props, value) + for child in node.children: + yield from self._build_tree_conditions(child, + run_info_with_condition, + props) + + class TestInfo(NamedTuple): extra_bugs: Set[str] extra_comments: List[str] + disabled_configs: Dict[metadata.RunInfo, DisableType] slow: bool = False + @property + def needs_migration(self) -> bool: + return self.extra_bugs or self.extra_comments or self.disabled_configs + TestFileMap = Mapping[str, metadata.TestFileData] # Note: Unlike `TestFileMap`, `TestInfoMap`'s values are set on a per-test ID @@ -524,7 +595,17 @@ 'product', ] self._dependent_properties = dependent_properties or { - 'product': ['os'], + # TODO(crbug.com/1152503): Modify the condition-building algorithm + # `wptrunner.expectedtree.build_tree(...)` to support a chain of + # dependent properties product -> virtual_suite -> os. + # + # https://chromium-review.googlesource.com/c/chromium/src/+/4749449/comment/43744bf3_eaa0fdd2/ + # sketches out a proposed solution. + # + # TODO(crbug.com/1466002): See if we can speed up updates when a + # test is run in few or no virtual suites. See also: + # https://chromium-review.googlesource.com/c/chromium/src/+/4749449/comment/d30d43e6_50cf4045/ + 'product': ['os', 'virtual_suite'], 'os': ['port', 'flag_specific'], } self._overwrite_conditions = overwrite_conditions @@ -558,7 +639,7 @@ include=include, exclude=exclude) test_files = {} - test_info = collections.defaultdict(lambda: TestInfo(set(), [])) + test_info = collections.defaultdict(lambda: TestInfo(set(), [], {})) for manifest, paths in manifests.items(): # Unfortunately, test filtering is tightly coupled to the # `testloader.TestLoader` API. Monkey-patching here is the cleanest @@ -567,23 +648,38 @@ itertypes = manifest.itertypes try: manifest.itertypes = _compose(test_filter, manifest.itertypes) + # `metadata.create_test_tree(...)` creates test files for + # `__dir__.ini` with pseudo-IDs like `wpt_internal/a/b/__dir__`. + # Note the lack of a leading `/`, so we normalize them to start + # with one later. test_files.update( metadata.create_test_tree(paths['metadata_path'], manifest)) for test in _tests(manifest): - if getattr(test, 'timeout', None) == 'long': - test_info[test.id] = TestInfo(set(), [], slow=True) + slow = getattr(test, 'timeout', None) == 'long' + test_info[test.id] = TestInfo(set(), [], {}, slow) finally: manifest.itertypes = itertypes if options.pop('migrate', False): - cls._load_expectations_for_migration(default_port, test_info) + cls._load_comments_and_bugs_to_migrate(test_info, default_port) + cls._load_disables_to_migrate(test_info, configs) + + test_files = { + urljoin('/', test_id): test_file + for test_id, test_file in test_files.items() + } return cls(test_files, test_info, configs, **options) @staticmethod - def _load_expectations_for_migration(default_port: Port, - test_info: TestInfoMap): + def _load_comments_and_bugs_to_migrate(test_infos: TestInfoMap, + default_port: Port): contents = default_port.all_expectations_dict() + # It doesn't matter what `default_port` we pass to `TestExpectations` + # because we're only using `expectations` to scan the literal lines of + # each file in `contents`. Comments and bugs aren't exposed thorugh + # `TestExpectations`'s high-level API because they aren't semantically + # significant. expectations = TestExpectations(default_port, contents) comments_buffer = [] for path in contents: @@ -591,24 +687,23 @@ lines.extend(expectations.get_updated_lines(path)) for prev_line, line in zip(lines[:-1], lines[1:]): if line.test: - for wpt_dir, url_prefix in Port.WPT_DIRS.items(): - base_test = default_port.lookup_virtual_test_base( - line.test) or line.test - wpt_dir += '/' - if base_test.startswith(wpt_dir): - test_id = base_test.replace(wpt_dir, url_prefix, 1) - # Ensure that `comment_buffers` is only added once - # for a block listing the same test multiple times. - if not set(comments_buffer) <= set( - test_info[test_id].extra_comments): - test_info[test_id].extra_comments.extend( - comments_buffer) - comment = _strip_comment(line.trailing_comments) - if comment: - test_info[test_id].extra_comments.append( - comment) - test_info[test_id].extra_bugs.update( - line.reason.strip().split()) + base_test = default_port.lookup_virtual_test_base( + line.test) or line.test + test_id = _exp_test_to_wpt_url(base_test) + if not test_id: + continue + test_info = test_infos.get(test_id) + if not test_info: + continue + # Ensure that `comment_buffers` is only added once for a + # block listing the same test multiple times. + if not set(comments_buffer) <= set( + test_info.extra_comments): + test_info.extra_comments.extend(comments_buffer) + comment = _strip_comment(line.trailing_comments) + if comment: + test_info.extra_comments.append(comment) + test_info.extra_bugs.update(line.reason.strip().split()) else: comment_or_empty = _strip_comment(line.to_string()) if not comment_or_empty or prev_line.test: @@ -616,8 +711,64 @@ if comment_or_empty: comments_buffer.append(comment_or_empty) # TODO(crbug.com/1464393): - # * Import `[ Skip ]` expectations too. - # * Handle glob lines. + # * Handle glob lines for comments. + + @staticmethod + def _load_disables_to_migrate(test_info: TestInfoMap, + configs: wpt_metadata.TestConfigurations): + """Read `TestExpectation` files for tests to disable in WPT metadata. + + For each test configuration: + 1. Translate applicable globs that cover a directory into + `__dir__.ini` disables. Remove these glob lines from + TestExpectations resolution, so as not to create redundant + per-test disables. + 2. Any test/directory with just `[ Pass ]` will be turned into an + explicit enable (i.e., `disabled: @False`), which can override + `__dir__.ini`. + 3. Translate non-glob lines into per-test `disabled values`. + """ + for config, port in configs.items(): + virtual_suite = config.data.get('virtual_suite', '') + virtual_prefix = f'virtual/{virtual_suite}/' if virtual_suite else '' + + expectations = TestExpectations(port) + for path in expectations.expectations_dict: + glob_lines_to_remove = [] + for line in expectations.get_updated_lines(path): + if not line.test or not line.test.startswith( + virtual_prefix): + continue + test_id = _exp_test_to_wpt_url( + line.test[len(virtual_prefix):]) + unsatisfied_tags = line.tags - port.get_platform_tags() - { + port.get_option('configuration').lower() + } + if not test_id or unsatisfied_tags: + continue + if line.results == {typ_types.ResultType.Pass}: + test_info[test_id].disabled_configs[ + config] = DisableType.ENABLED + elif line.is_glob and line.results == { + typ_types.ResultType.Skip + }: + # Handle non-glob skips later, since virtual lines can + # inherit from nonvirtual ones. + reason = DisableType.MIGRATED + if path == port.path_to_never_fix_tests_file(): + reason = DisableType.NEVER_FIX + test_info[test_id].disabled_configs[config] = reason + glob_lines_to_remove.append(line) + expectations.remove_expectations(path, glob_lines_to_remove) + + for test_id, test in test_info.items(): + test_name = urljoin(virtual_prefix, + _wpt_url_to_exp_test(test_id)) + if port.skipped_in_never_fix_tests(test_name): + test.disabled_configs[config] = DisableType.NEVER_FIX + elif expectations.matches_an_expected_result( + test_name, typ_types.ResultType.Skip): + test.disabled_configs[config] = DisableType.MIGRATED def collect_results(self, reports: Iterable[io.TextIOBase]) -> Set[str]: """Parse and record test results.""" @@ -656,8 +807,8 @@ def test_files_to_update(self) -> List[metadata.TestFileData]: test_files = { test_file - for test_file in self._updater.id_test_map.values() - if not test_file.test_path.endswith('__dir__') + for test_id, test_file in self._updater.id_test_map.items() + if test_id in self._test_info } return sorted(test_files, key=lambda test_file: test_file.test_path) @@ -776,9 +927,10 @@ Returns: Whether the test file's metadata was modified. """ - test_infos = [self._test_info[test_id] for test_id in test_file.tests] - needs_migration = any(test_info.extra_bugs or test_info.extra_comments - for test_info in test_infos) + needs_migration = any(self._test_info[test_id].needs_migration + for test_id in test_file.tests) + if test_file.test_path.endswith('__dir__'): + needs_migration = True if not test_file.data and not needs_migration: # Without test results and no TestExpectations to migrate, skip the # general update case, which is slow and unnecessary. See @@ -799,9 +951,10 @@ update_intermittent=(not self._disable_intermittent), remove_intermittent=(not self._keep_statuses)) if expected: - self._disable_slow_timeouts(test_file, expected) self._remove_orphaned_tests(expected) - self._migrate_expectations(expected) + self._mark_slow_timeouts_for_disabling(test_file, expected) + self._migrate_disables(expected, test_file.metadata_path) + self._migrate_comments(expected) if self._bug: for test in expected.iterchildren(): if test.modified: @@ -814,11 +967,9 @@ metadata.write_new_expected(test_file.metadata_path, expected) return modified - def _disable_slow_timeouts( - self, - test_file: metadata.TestFileData, - expected: manifestupdate.ExpectedManifest, - message: str = 'times out even with extended deadline'): + def _mark_slow_timeouts_for_disabling( + self, test_file: metadata.TestFileData, + expected: manifestupdate.ExpectedManifest): """Disable tests that are simultaneously slow and consistently time out. Such tests provide too little value for the large amount of time/compute @@ -835,13 +986,11 @@ statuses_by_config[config].add(status) if known_intermittent: statuses_by_config[config].update(known_intermittent) - # Writing a conditional `disabled` value is complicated, so just - # disable the test unconditionally if any configuration times out - # consistently. - if any(statuses == {'TIMEOUT'} - for statuses in statuses_by_config.values()): - test.set('disabled', message) - test.modified = True + + disabled_configs = self._test_info[test.id].disabled_configs + for config, statuses in statuses_by_config.items(): + if statuses == {'TIMEOUT'}: + disabled_configs[config] = DisableType.SLOW_TIMEOUT def _remove_orphaned_tests(self, expected: manifestupdate.ExpectedManifest): @@ -851,7 +1000,33 @@ test.remove() expected.modified = True - def _migrate_expectations(self, expected: manifestupdate.ExpectedManifest): + def _migrate_disables(self, expected: manifestupdate.ExpectedManifest, + metadata_root: str): + nodes = [] + if expected.test_path.endswith('__dir__'): + dir_id = urljoin(expected.url_base, + expected.test_path.replace(os.path.sep, '/')) + # Updates the root section in `__dir__.ini`. + nodes.append((expected, self._test_info[dir_id])) + else: + nodes.extend((test, self._test_info[test.id]) + for test in expected.iterchildren()) + + for node, test_info in nodes: + if not test_info.disabled_configs: + continue + update = DisabledUpdate(node) + for config in self._configs: + try: + # Attempt to preserve existing values for `disabled`. + reason = node.get('disabled', config) + except KeyError: + reason = test_info.disabled_configs.get(config) + reason = reason.value if reason else None + update.set(config, reason) + update.update(full_update=True, disable_intermittent=False) + + def _migrate_comments(self, expected: manifestupdate.ExpectedManifest): for test in expected.iterchildren(): if test.is_empty: continue @@ -889,6 +1064,27 @@ return '' +def _exp_test_to_wpt_url(test: str) -> Optional[str]: + for wpt_dir, url_prefix in Port.WPT_DIRS.items(): + if test.startswith(wpt_dir): + test = test.replace(wpt_dir + '/', url_prefix, 1) + # Directory globs in TestExpectations resolve to a "pseudo-test ID". + # Do not give an ID for non-directory globs. + if test.endswith('/*'): + test = test[:-len('*')] + '__dir__' + elif test.endswith('*'): + return None + return test + return None + + +def _wpt_url_to_exp_test(test: str) -> str: + for wpt_dir, url_prefix in Port.WPT_DIRS.items(): + if test.startswith(url_prefix): + return test.replace(url_prefix, wpt_dir + '/', 1) + raise ValueError('no matching WPT roots found') + + def sort_metadata_ast(node: wptnode.DataNode) -> None: """Sort the metadata abstract syntax tree to create a stable rendering.
diff --git a/third_party/blink/tools/blinkpy/tool/commands/update_metadata_unittest.py b/third_party/blink/tools/blinkpy/tool/commands/update_metadata_unittest.py index 8644b47..789be13b 100644 --- a/third_party/blink/tools/blinkpy/tool/commands/update_metadata_unittest.py +++ b/third_party/blink/tools/blinkpy/tool/commands/update_metadata_unittest.py
@@ -7,7 +7,7 @@ import json import textwrap import unittest -from unittest.mock import Mock, patch +from unittest.mock import Mock, call, patch from blinkpy.common import path_finder from blinkpy.common.net.git_cl import TryJobStatus @@ -191,6 +191,7 @@ 'port': 'mac12', 'product': 'content_shell', 'flag_specific': '', + 'virtual_suite': '', 'debug': False, }, 'results': [{ @@ -266,6 +267,7 @@ 'port': 'mac12', 'product': 'content_shell', 'flag_specific': '', + 'virtual_suite': '', 'debug': False, }, 'results': [{ @@ -619,6 +621,7 @@ 'os': 'mac', 'port': 'mac12', 'flag_specific': '', + 'virtual_suite': '', 'debug': False, **(report.get('run_info') or {}), } @@ -732,6 +735,207 @@ expected: ERROR """) + def test_migrate_disables(self): + self.write_contents( + 'external/wpt/variant.html.ini', """\ + [variant.html?foo=bar/abc] + disabled: + if os == "win": overwrite this + """) + self.write_contents( + 'NeverFixTests', """\ + # tags: [ Linux Mac Win ] + # results: [ Skip ] + [ Mac ] external/wpt/variant.html?foo=bar/abc [ Skip ] + """) + self.write_contents( + 'TestExpectations', """\ + # tags: [ Linux Mac Win ] + # results: [ Skip ] + virtual/fake-vts/external/wpt/variant.html?foo=baz [ Skip ] + """) + self.update( + { + 'run_info': { + 'product': 'content_shell', + 'os': 'mac', + 'virtual_suite': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-mac-mac10.11'), + }, { + 'run_info': { + 'product': 'content_shell', + 'os': 'linux', + 'virtual_suite': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, { + 'run_info': { + 'product': 'chrome', + 'os': 'linux', + 'virtual_suite': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, { + 'run_info': { + 'product': 'content_shell', + 'os': 'linux', + 'virtual_suite': 'fake-vts', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, + migrate=True) + self.assert_contents( + 'external/wpt/variant.html.ini', """\ + [variant.html?foo=bar/abc] + disabled: + if (product == "content_shell") and (os == "mac"): neverfix + + [variant.html?foo=baz] + disabled: + if (product == "content_shell") and (virtual_suite == "fake-vts"): skipped in TestExpectations + """) + + def test_migrate_disables_glob_flag_specific(self): + self.write_contents('FlagSpecificConfig', + json.dumps([{ + 'name': 'fake-flag', + 'args': [], + }])) + self.write_contents( + 'FlagExpectations/fake-flag', """\ + # results: [ Pass Skip ] + wpt_internal/dir/* [ Skip ] + wpt_internal/dir/multiglob.https.any.worker.html [ Pass ] + """) + flag_port = self.tool.port_factory.get('test-linux-trusty') + flag_port.set_option_default('flag_specific', 'fake-flag') + self.update( + { + 'run_info': { + 'product': 'content_shell', + 'os': 'mac', + 'flag_specific': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-mac-mac10.11'), + }, { + 'run_info': { + 'product': 'content_shell', + 'os': 'linux', + 'flag_specific': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, { + 'run_info': { + 'product': 'chrome', + 'os': 'linux', + 'flag_specific': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, { + 'run_info': { + 'product': 'content_shell', + 'os': 'linux', + 'flag_specific': 'fake-flag', + }, + 'results': [], + 'test_port': flag_port, + }, + migrate=True) + self.assert_contents( + 'wpt_internal/dir/__dir__.ini', """\ + disabled: + if (product == "content_shell") and (os == "linux") and (flag_specific == "fake-flag"): skipped in TestExpectations + """) + self.assert_contents( + 'wpt_internal/dir/multiglob.https.any.js.ini', """\ + [multiglob.https.any.worker.html] + disabled: + if (product == "content_shell") and (os == "linux") and (flag_specific == "fake-flag"): @False + """) + + def test_migrate_disables_glob_virtual(self): + self.write_contents( + 'TestExpectations', """\ + # results: [ Pass Skip ] + wpt_internal/dir/* [ Skip ] + virtual/fake-vts/wpt_internal/dir/* [ Pass ] + """) + self.update( + { + 'run_info': { + 'product': 'chrome', + 'os': 'linux', + 'virtual_suite': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, { + 'run_info': { + 'product': 'content_shell', + 'os': 'linux', + 'virtual_suite': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, { + 'run_info': { + 'product': 'content_shell', + 'os': 'linux', + 'virtual_suite': 'fake-vts', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, + migrate=True) + self.assert_contents( + 'wpt_internal/dir/__dir__.ini', """\ + disabled: + if (product == "content_shell") and (virtual_suite == "fake-vts"): @False + if product == "chrome": skipped in TestExpectations + if (product == "content_shell") and (virtual_suite == ""): skipped in TestExpectations + """) + + def test_migrate_disables_non_directory_glob(self): + self.write_contents( + 'TestExpectations', """\ + # results: [ Pass Failure Skip ] + wpt_internal/dir/* [ Failure ] + wpt_internal/dir/multiglob* [ Skip ] + """) + self.update( + { + 'run_info': { + 'os': 'mac', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-mac-mac10.11'), + }, { + 'run_info': { + 'os': 'linux', + 'virtual_suite': '', + }, + 'results': [], + 'test_port': self.tool.port_factory.get('test-linux-trusty'), + }, + migrate=True) + self.assertFalse(self.exists('wpt_internal/dir/__dir__.ini')) + self.assert_contents( + 'wpt_internal/dir/multiglob.https.any.js.ini', """\ + [multiglob.https.any.window.html] + disabled: skipped in TestExpectations + + [multiglob.https.any.worker.html] + disabled: skipped in TestExpectations + """) + def test_remove_all_pass(self): """The updater removes metadata for a test that became all-pass.""" self.write_contents( @@ -1056,8 +1260,8 @@ }, 'results': [{ 'test': '/fail.html', - 'status': 'OK', - 'expected': 'OK', + 'status': 'PASS', + 'expected': 'PASS', }], }, overwrite_conditions='yes') @@ -1069,7 +1273,6 @@ expected: if (product == "content_shell") and (os == "win"): FAIL if (product == "content_shell") and (os == "mac"): TIMEOUT - OK """) # TODO(crbug.com/1299650): The branch order appears unstable, which we # should fix upstream to avoid create spurious diffs. @@ -1267,8 +1470,9 @@ if product == "content_shell": needs webdriver expected: FAIL """) - smoke_test_port.skipped_due_to_smoke_tests.assert_called_once_with( - 'external/wpt/variant.html?foo=baz') + smoke_test_port.skipped_due_to_smoke_tests.assert_has_calls([ + call('external/wpt/variant.html?foo=baz'), + ]) def test_no_fill_for_unsupported_configs(self): from wptrunner.browsers import content_shell @@ -1401,7 +1605,8 @@ self.assert_contents( 'external/wpt/variant.html.ini', """\ [variant.html?foo=baz] - disabled: times out even with extended deadline + disabled: + if product == "chrome": times out even with `timeout=long` expected: if product == "chrome": TIMEOUT """)
diff --git a/third_party/blink/tools/blinkpy/w3c/wpt_metadata.py b/third_party/blink/tools/blinkpy/w3c/wpt_metadata.py index 32456b6..e35f04ea 100644 --- a/third_party/blink/tools/blinkpy/w3c/wpt_metadata.py +++ b/third_party/blink/tools/blinkpy/w3c/wpt_metadata.py
@@ -124,6 +124,9 @@ 'port': port.version(), 'debug': debug, 'flag_specific': flag_specific or '', + # TODO(crbug.com/1152503): Fully support virtual suites. + # Will be addressed by crrev.com/c/4717388. + 'virtual_suite': '', }) configs[config] = port return cls(host.filesystem, configs)
diff --git a/third_party/blink/web_tests/TestExpectations b/third_party/blink/web_tests/TestExpectations index bdf9319..e992bd4 100644 --- a/third_party/blink/web_tests/TestExpectations +++ b/third_party/blink/web_tests/TestExpectations
@@ -4243,6 +4243,7 @@ # Temporarily disabled to land https://crrev.com/c/4797648 crbug.com/1468875 http/tests/devtools/network/network-search.js [ Failure Pass ] crbug.com/1468875 http/tests/devtools/search/sources-search-scope-in-files.js [ Failure Pass ] +crbug.com/1468875 http/tests/devtools/search/sources-search-scope-many-projects.js [ Failure Pass ] # Sheriff 2019-10-18 crbug.com/1015975 media/video-currentTime.html [ Failure Pass ] @@ -6777,3 +6778,9 @@ crbug.com/1473373 [ Mac13 ] wpt_internal/scheduler/task-signal-any-memory-abort.any.worker.html [ Pass Timeout ] crbug.com/1473373 [ Mac13-arm64 ] wpt_internal/scheduler/task-signal-any-memory-abort.any.worker.html [ Pass Timeout ] crbug.com/1473474 [ Mac13 ] wpt_internal/mediastream/mediastreamtrackprocessor-transfer-to-worker.html [ Failure Pass ] + +# Disable the following tests to land and reenable after the land. +crbug.com/1470610 http/tests/devtools/application-panel/resources-panel-on-navigation.js [ Failure Pass ] +crbug.com/1470610 http/tests/devtools/application-panel/resources-panel-resource-preview.js [ Failure Pass ] +crbug.com/1470610 http/tests/devtools/application-panel/resources-panel-selection-on-reload.js [ Failure Pass ] +crbug.com/1470610 http/tests/devtools/application-panel/resources-panel-websql.js [ Failure Pass ]
diff --git a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json index 4d3316e..70d35c7 100644 --- a/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json +++ b/third_party/blink/web_tests/external/WPT_BASE_MANIFEST_8.json
@@ -6966,6 +6966,13 @@ {} ] ], + "chrome-bug-1474157.html": [ + "c852b0aa018571a988e39af8be0d0b742d71038d", + [ + null, + {} + ] + ], "firefox-bug-1688293.html": [ "9ab1a88312683a66798cb52693c2ba4389222ff4", [ @@ -95509,6 +95516,19 @@ {} ] ], + "soft-break-before-margin-001.html": [ + "6907c33586af3fa6e058fb95560d95d3799bb690", + [ + null, + [ + [ + "/css/reference/ref-filled-green-100px-square.xht", + "==" + ] + ], + {} + ] + ], "svg-with-transform.html": [ "3aa7facf2d6a08e18a792b8739341b9bcc5014e5", [ @@ -108689,7 +108709,7 @@ ] }, "counter-scoping-001.html": [ - "f7d40dc5a0850919f1b86ca31e9ebd44ec96b72d", + "ab948e19081e1383fdc68ef8b27f2b6db0e30e95", [ null, [ @@ -279168,16 +279188,6 @@ } }, "support": { - ".cache": { - "gitignore2.json": [ - "8255d56e28ea8016caa9878ae2ff41ec27918276", - [] - ], - "mtime.json": [ - "525d90ac737a92d22edaed8a2618bd68a7662c2f", - [] - ] - }, ".gitignore": [ "d93e645d547894b50149d3726de2654957b6e06f", [] @@ -366550,7 +366560,7 @@ [] ], "scroll_support.js": [ - "52c2f58723a2a39e9d652036d82d59475497c76e", + "e8792cc6ca06979b399f8ab1973ed3d5bcc11597", [] ], "scrollend-event-fired-after-sequence-of-scrolls.tentative.html.ini": [ @@ -366594,7 +366604,7 @@ [] ], "scrollend-user-scroll-common.js": [ - "34af4ce921e72386491149f0f47f754481a3cf3e", + "5c278784d83916beda046e9c6b760429c3dc9804", [] ] }, @@ -507603,7 +507613,7 @@ ] ], "scrollend-event-fires-to-iframe-window.html": [ - "1a20751bd53b1d4e838fd13d8eed09bf9b3f6dfb", + "4e53158087018884a82e5086ca6bdaf2d12661be", [ null, {
diff --git a/third_party/blink/web_tests/external/wpt/css/css-contain/counter-scoping-001.html b/third_party/blink/web_tests/external/wpt/css/css-contain/counter-scoping-001.html index f7d40dc5a..ab948e1 100644 --- a/third_party/blink/web_tests/external/wpt/css/css-contain/counter-scoping-001.html +++ b/third_party/blink/web_tests/external/wpt/css/css-contain/counter-scoping-001.html
@@ -11,7 +11,7 @@ <style> div { contain: style; - counter-increment: n; + counter-increment: n; } div::before, div::after { content: counters(n, '.') " ";
diff --git a/third_party/blink/web_tests/http/tests/devtools/components/segmented-range.js b/third_party/blink/web_tests/http/tests/devtools/components/segmented-range.js index d981a07..05f3f12 100644 --- a/third_party/blink/web_tests/http/tests/devtools/components/segmented-range.js +++ b/third_party/blink/web_tests/http/tests/devtools/components/segmented-range.js
@@ -5,6 +5,8 @@ import {TestRunner} from 'test_runner'; import {DataGridTestRunner} from 'data_grid_test_runner'; +import * as Common from 'devtools/core/common/common.js'; + (async function() { TestRunner.addResult(`Tests SegmentedRange\n`); @@ -12,13 +14,13 @@ TestRunner.addResult('Test case: ' + testName); TestRunner.addResult('Input Segments: ' + JSON.stringify(data)); - var forwardRange = new Common.SegmentedRange(merge); - data.map(entry => new Common.Segment(entry[0], entry[1], entry[2])).forEach(forwardRange.append, forwardRange); + var forwardRange = new Common.SegmentedRange.SegmentedRange(merge); + data.map(entry => new Common.SegmentedRange.Segment(entry[0], entry[1], entry[2])).forEach(forwardRange.append, forwardRange); var forward = forwardRange.segments(); - var backwardRange = new Common.SegmentedRange(merge); + var backwardRange = new Common.SegmentedRange.SegmentedRange(merge); data.reverse() - .map(entry => new Common.Segment(entry[0], entry[1], entry[2])) + .map(entry => new Common.SegmentedRange.Segment(entry[0], entry[1], entry[2])) .forEach(backwardRange.append, backwardRange); var backward = backwardRange.segments();
diff --git a/third_party/crashpad/README.chromium b/third_party/crashpad/README.chromium index 5cc9120..8850052 100644 --- a/third_party/crashpad/README.chromium +++ b/third_party/crashpad/README.chromium
@@ -2,7 +2,7 @@ Short Name: crashpad URL: https://crashpad.chromium.org/ Version: unknown -Revision: 13e3accfe82059b0028844b5a05c690f730a36ba +Revision: a736f7d070c872a4cc786c31755fd769fb2e50b3 License: Apache 2.0 License File: crashpad/LICENSE Security Critical: yes
diff --git a/third_party/crashpad/crashpad/DEPS b/third_party/crashpad/crashpad/DEPS index d268bd9..2c67a68 100644 --- a/third_party/crashpad/crashpad/DEPS +++ b/third_party/crashpad/crashpad/DEPS
@@ -47,7 +47,7 @@ '9719c1e1e676814c456b55f5f070eabad6709d31', 'crashpad/third_party/mini_chromium/mini_chromium': Var('chromium_git') + '/chromium/mini_chromium@' + - 'e35fc73aa87bb27e10306900b15a18b0e9c7ca42', + '0c540fd5462a266277e86fa32a230cad4a859037', 'crashpad/third_party/libfuzzer/src': Var('chromium_git') + '/chromium/llvm-project/compiler-rt/lib/fuzzer.git@' + 'fda403cf93ecb8792cb1d061564d89a6553ca020',
diff --git a/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn b/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn index 7594c1c..51aa43b 100644 --- a/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn +++ b/third_party/crashpad/crashpad/third_party/fuchsia/BUILD.gn
@@ -18,7 +18,7 @@ group("fuchsia") { public_deps = [ "//sdk/lib/fdio", - "//zircon/public/lib/zx", + "//zircon/system/ulib/zx", ] } } else if (crashpad_is_in_chromium) {
diff --git a/third_party/crashpad/crashpad/util/mac/launchd.mm b/third_party/crashpad/crashpad/util/mac/launchd.mm index c711747..d295ffc6 100644 --- a/third_party/crashpad/crashpad/util/mac/launchd.mm +++ b/third_party/crashpad/crashpad/util/mac/launchd.mm
@@ -130,7 +130,7 @@ base::apple::CFCastStrict<CFDataRef>(property_cf)); data_launch = LaunchDataNewOpaque([data_ns bytes], [data_ns length]); } else { - base::ScopedCFTypeRef<CFStringRef> type_name_cf( + base::apple::ScopedCFTypeRef<CFStringRef> type_name_cf( CFCopyTypeIDDescription(type_id_cf)); DLOG(ERROR) << "unable to convert CFTypeID " << type_id_cf << " (" << base::SysCFStringRefToUTF8(type_name_cf) << ")";
diff --git a/third_party/crashpad/crashpad/util/mac/mac_util.cc b/third_party/crashpad/crashpad/util/mac/mac_util.cc index f189862..c74fbf3 100644 --- a/third_party/crashpad/crashpad/util/mac/mac_util.cc +++ b/third_party/crashpad/crashpad/util/mac/mac_util.cc
@@ -166,7 +166,7 @@ std::string IORegistryEntryDataPropertyAsString(io_registry_entry_t entry, CFStringRef key) { - base::ScopedCFTypeRef<CFTypeRef> property( + base::apple::ScopedCFTypeRef<CFTypeRef> property( IORegistryEntryCreateCFProperty(entry, key, kCFAllocatorDefault, 0)); CFDataRef data = base::apple::CFCast<CFDataRef>(property); if (data && CFDataGetLength(data) > 0) { @@ -235,7 +235,7 @@ int* bugfix, std::string* build, std::string* version_string) { - base::ScopedCFTypeRef<CFDictionaryRef> dictionary( + base::apple::ScopedCFTypeRef<CFDictionaryRef> dictionary( TryCFCopySystemVersionDictionary()); if (!dictionary) { LOG(ERROR) << "_CFCopySystemVersionDictionary failed";
diff --git a/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc b/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc index 2f3fce8..24442ad 100644 --- a/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc +++ b/third_party/sudden_motion_sensor/sudden_motion_sensor_mac.cc
@@ -338,7 +338,7 @@ const SensorDescriptor* sensor_candidate = nullptr; // Look for the current model in the supported sensor list. - base::ScopedCFTypeRef<CFDataRef> board_id_data; + base::apple::ScopedCFTypeRef<CFDataRef> board_id_data; const int kNumSensors = std::size(kSupportedSensors); for (int i = 0; i < kNumSensors; ++i) {
diff --git a/tools/mac/power/power_sampler/battery_sampler.mm b/tools/mac/power/power_sampler/battery_sampler.mm index 4078459..047bda3b 100644 --- a/tools/mac/power/power_sampler/battery_sampler.mm +++ b/tools/mac/power/power_sampler/battery_sampler.mm
@@ -128,7 +128,7 @@ // static absl::optional<BatterySampler::BatteryData> BatterySampler::MaybeGetBatteryData( io_service_t power_source) { - base::ScopedCFTypeRef<CFMutableDictionaryRef> dict; + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> dict; kern_return_t result = IORegistryEntryCreateCFProperties( power_source, dict.InitializeInto(), 0, 0); if (result != KERN_SUCCESS) {
diff --git a/tools/mac/power/power_sampler/m1_sampler_unittest.mm b/tools/mac/power/power_sampler/m1_sampler_unittest.mm index 3f6fdd3..17b4432 100644 --- a/tools/mac/power/power_sampler/m1_sampler_unittest.mm +++ b/tools/mac/power/power_sampler/m1_sampler_unittest.mm
@@ -24,7 +24,7 @@ public: TestM1SensorsReader() : power_metrics::M1SensorsReader( - base::ScopedCFTypeRef<IOHIDEventSystemClientRef>()) {} + base::apple::ScopedCFTypeRef<IOHIDEventSystemClientRef>()) {} void set_temperatures(TemperaturesCelsius temperatures) { temperatures_ = temperatures;
diff --git a/tools/metrics/histograms/enums.xml b/tools/metrics/histograms/enums.xml index 25941fe..1edfb7a 100644 --- a/tools/metrics/histograms/enums.xml +++ b/tools/metrics/histograms/enums.xml
@@ -63675,6 +63675,7 @@ label="LinkManagedNoticeToChromeUIManagementURL:disabled"/> <int value="-364587218" label="ResourceLoadScheduler:enabled"/> <int value="-364510698" label="MultiProfileAccountConsistency:disabled"/> + <int value="-364449609" label="RenameJourneys:enabled"/> <int value="-364325011" label="enable-files-quick-view"/> <int value="-364267715" label="disable-native-cups"/> <int value="-363885137" label="StoragePressureEvent:disabled"/> @@ -64789,6 +64790,7 @@ <int value="198386935" label="OmitCorsClientCert:enabled"/> <int value="198719062" label="WebAssemblyLazyCompilation:disabled"/> <int value="198762155" label="SharingPeerConnectionSender:enabled"/> + <int value="199237368" label="RenameJourneys:disabled"/> <int value="200347243" label="WebVRExperimentalRendering:disabled"/> <int value="201077617" label="FedCmAutoReauthnFlag:disabled"/> <int value="201203491"
diff --git a/tools/metrics/histograms/metadata/autofill/histograms.xml b/tools/metrics/histograms/metadata/autofill/histograms.xml index 3cd0dd5..96817138 100644 --- a/tools/metrics/histograms/metadata/autofill/histograms.xml +++ b/tools/metrics/histograms/metadata/autofill/histograms.xml
@@ -153,7 +153,9 @@ <variants name="Autofill.ProgressDialog.FlowType"> <variant name="AndroidFIDO" summary="Progress dialog while authenticating with FIDO on Android"/> - <variant name="CardUnmask" + <variant name="ServerCardUnmask" + summary="Progress dialog for the credit card risk-based unmask flow"/> + <variant name="VirtualCardUnmask" summary="Progress dialog for the VCN Card Unmask Flow"/> </variants>
diff --git a/tools/metrics/histograms/metadata/content/histograms.xml b/tools/metrics/histograms/metadata/content/histograms.xml index 67c47cfc..be3d444b7 100644 --- a/tools/metrics/histograms/metadata/content/histograms.xml +++ b/tools/metrics/histograms/metadata/content/histograms.xml
@@ -1215,6 +1215,17 @@ </summary> </histogram> +<histogram name="ContentSuggestions.Feed.ResourceFetchStatus" + enum="CombinedHttpResponseAndNetErrorCode" expires_after="2024-06-30"> + <owner>jianli@chromium.org</owner> + <owner>feed@chromium.org</owner> + <summary> + Android: Status of resource fetches for the feed. Recorded for each resource + fetch. Fetches happen when the specific resource is needed to enhance the + feed content while the feed is being displayed. + </summary> +</histogram> + <histogram name="ContentSuggestions.Feed.SendFeedback" enum="FeedSendFeedbackType" expires_after="2024-01-23"> <owner>carlosk@chromium.org</owner>
diff --git a/tools/metrics/histograms/metadata/omnibox/histograms.xml b/tools/metrics/histograms/metadata/omnibox/histograms.xml index 32158d64..00340c83 100644 --- a/tools/metrics/histograms/metadata/omnibox/histograms.xml +++ b/tools/metrics/histograms/metadata/omnibox/histograms.xml
@@ -549,18 +549,20 @@ </histogram> <histogram name="Omnibox.ClipboardSuggestionRemovedAge" units="ms" - expires_after="2022-09-11"> + expires_after="2024-08-01"> <owner>gangwu@chromium.org</owner> - <owner>fgorski@chromium.org</owner> + <owner>jdonnelly@chromium.org</owner> <summary> Recorded every time the clipboard suggestion is removed from omnibox suggestion list and the system clipboard. The value indicates the estimated age of the clipboard. + + Note: recording gap between 2022/09 and 2023/08. </summary> </histogram> <histogram name="Omnibox.ClipboardSuggestionShownAge" units="ms" - expires_after="2023-12-24"> + expires_after="2024-08-01"> <owner>gangwu@chromium.org</owner> <owner>jdonnelly@chromium.org</owner> <summary> @@ -578,7 +580,7 @@ </histogram> <histogram name="Omnibox.ClipboardSuggestionShownNumTimes" units="units" - expires_after="2023-12-24"> + expires_after="2024-08-01"> <owner>gangwu@chromium.org</owner> <owner>jdonnelly@chromium.org</owner> <summary> @@ -608,7 +610,7 @@ </histogram> <histogram name="Omnibox.ClipboardSuggestionShownWithCurrentURL" - enum="BooleanPresent" expires_after="2022-10-01"> + enum="BooleanPresent" expires_after="2024-08-01"> <owner>gangwu@chromium.org</owner> <owner>jdonnelly@chromium.org</owner> <summary> @@ -629,6 +631,8 @@ compared with the count in the clipboard bucket of the Omnibox.SuggestionUsed.Provider histogram to determine the clickthrough rate on these suggestions. + + Note: recording gap between 2022/10 and 2023/08. </summary> </histogram>
diff --git a/tools/metrics/histograms/metadata/page/histograms.xml b/tools/metrics/histograms/metadata/page/histograms.xml index 897d7a5..663864f 100644 --- a/tools/metrics/histograms/metadata/page/histograms.xml +++ b/tools/metrics/histograms/metadata/page/histograms.xml
@@ -1112,7 +1112,7 @@ <histogram name="PageLoad.Clients.ServiceWorker2.PaintTiming.{Timing}.{HandlerType}" - units="ms" expires_after="2023-10-01"> + units="ms" expires_after="2024-01-31"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary>
diff --git a/tools/metrics/histograms/metadata/service/histograms.xml b/tools/metrics/histograms/metadata/service/histograms.xml index d651a441..18fa388 100644 --- a/tools/metrics/histograms/metadata/service/histograms.xml +++ b/tools/metrics/histograms/metadata/service/histograms.xml
@@ -228,7 +228,7 @@ </histogram> <histogram name="ServiceWorker.CacheStorageInstalledScript.CachedMetadataSize" - units="bytes" expires_after="2023-10-01"> + units="bytes" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -239,7 +239,7 @@ <histogram name="ServiceWorker.CacheStorageInstalledScript.CachedMetadataTotalSize" - units="bytes" expires_after="2023-10-01"> + units="bytes" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -249,7 +249,7 @@ </histogram> <histogram name="ServiceWorker.CacheStorageInstalledScript.Count" units="count" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -259,7 +259,7 @@ </histogram> <histogram name="ServiceWorker.CacheStorageInstalledScript.ScriptSize" - units="bytes" expires_after="2024-02-04"> + units="bytes" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -269,7 +269,7 @@ </histogram> <histogram name="ServiceWorker.CacheStorageInstalledScript.ScriptTotalSize" - units="bytes" expires_after="2024-01-28"> + units="bytes" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -327,7 +327,7 @@ </histogram> <histogram name="ServiceWorker.DiskCache.InitResult" units="units" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chikamune@chromium.org</owner> <owner>chrome-worker@google.com</owner> @@ -1038,7 +1038,7 @@ </histogram> <histogram name="ServiceWorker.MaybeStartWorker.RunningStatus" - enum="EmbeddedWorkerStatus" expires_after="2024-02-05"> + enum="EmbeddedWorkerStatus" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1054,7 +1054,7 @@ <histogram name="ServiceWorker.MaybeStartWorker.RunningStatusByPurpose_{ServiceWorkerEventType}" - enum="EmbeddedWorkerStatus" expires_after="2023-10-01"> + enum="EmbeddedWorkerStatus" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1101,7 +1101,7 @@ </histogram> <histogram name="ServiceWorker.OnStarted.UpdatedFetchHandlerType" - enum="ServiceWorkerFetchHandlerType" expires_after="2023-10-01"> + enum="ServiceWorkerFetchHandlerType" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1120,7 +1120,7 @@ <histogram name="ServiceWorker.OnStarted.UpdatedFetchHandlerTypeBySourceType_{SourceType}" - enum="ServiceWorkerFetchHandlerType" expires_after="2023-10-01"> + enum="ServiceWorkerFetchHandlerType" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1250,7 +1250,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.ClockConsistency" - enum="CrossProcessTimeDelta" expires_after="2024-02-04"> + enum="CrossProcessTimeDelta" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1269,7 +1269,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.Duration" units="ms" - expires_after="2024-02-04"> + expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1286,7 +1286,7 @@ <histogram name="ServiceWorker.StartTiming.ReceivedStartWorkerToScriptEvaluationStart" - units="ms" expires_after="2024-02-04"> + units="ms" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1297,7 +1297,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.ScriptEvaluationEndToEnd" units="ms" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1310,7 +1310,7 @@ <histogram name="ServiceWorker.StartTiming.ScriptEvaluationStartToScriptEvaluationEnd" - units="ms" expires_after="2023-10-01"> + units="ms" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1322,7 +1322,7 @@ <histogram name="ServiceWorker.StartTiming.SentStartWorkerToReceivedStartWorker" - units="ms" expires_after="2023-10-01"> + units="ms" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1333,7 +1333,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.StartToReceivedStartWorker" - units="ms" expires_after="2023-10-23"> + units="ms" expires_after="2024-06-01"> <owner>chikamune@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1346,7 +1346,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.StartToScriptEvaluationEnd" - units="ms" expires_after="2023-10-01"> + units="ms" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1359,7 +1359,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.StartToScriptEvaluationStart" - units="ms" expires_after="2023-10-01"> + units="ms" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1372,7 +1372,7 @@ </histogram> <histogram name="ServiceWorker.StartTiming.StartToSentStartWorker" units="ms" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1395,7 +1395,7 @@ </histogram> <histogram name="ServiceWorker.StartWorker.Status" - enum="ServiceWorkerStatusCode" expires_after="2024-02-11"> + enum="ServiceWorkerStatusCode" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chikamune@chromium.org</owner> <owner>chrome-worker@google.com</owner> @@ -1408,7 +1408,7 @@ <histogram name="ServiceWorker.StartWorker.StatusByPurpose_{ServiceWorkerEventType}" - enum="ServiceWorkerStatusCode" expires_after="2023-10-01"> + enum="ServiceWorkerStatusCode" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1457,7 +1457,7 @@ </histogram> <histogram name="ServiceWorker.Storage.DeleteAndStartOverResult" - enum="ServiceWorkerDeleteAndStartOverResult" expires_after="2023-10-01"> + enum="ServiceWorkerDeleteAndStartOverResult" expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chikamune@chromium.org</owner> <owner>chrome-worker@google.com</owner> @@ -1520,7 +1520,7 @@ </histogram> <histogram name="ServiceWorker.Storage.RetryCountForRecovery" units="retries" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@chromium.org</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1543,7 +1543,7 @@ </histogram> <histogram name="ServiceWorker.Subresource.Fallbacked.Type2" - enum="ResourceType" expires_after="2023-10-01"> + enum="ResourceType" expires_after="2024-06-01"> <owner>yyanagisawa@google.com</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1556,7 +1556,7 @@ </histogram> <histogram name="ServiceWorker.Subresource.Handled.Type2" enum="ResourceType" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@google.com</owner> <owner>chrome-worker@google.com</owner> <summary> @@ -1569,7 +1569,7 @@ </histogram> <histogram name="ServiceWorker.WorkaroundForCrBug1342408Applied" units="cases" - expires_after="2023-10-01"> + expires_after="2024-06-01"> <owner>yyanagisawa@google.com</owner> <owner>chrome-worker@google.com</owner> <summary>
diff --git a/tools/traffic_annotation/summary/annotations.xml b/tools/traffic_annotation/summary/annotations.xml index d716c15..f69ea5e3 100644 --- a/tools/traffic_annotation/summary/annotations.xml +++ b/tools/traffic_annotation/summary/annotations.xml
@@ -431,4 +431,5 @@ <item id="passkey_enclave_client" added_in_milestone="117" content_hash_code="06c3fa70" os_list="linux,windows" file_path="device/fido/enclave/enclave_http_client.cc" /> <item id="iwa_update_discovery_update_manifest" added_in_milestone="117" type="partial" second_id="iwa_update_manifest_fetcher" content_hash_code="021e8cdf" os_list="chromeos" semantics_fields="1,2,3,7,8,9" policy_fields="3,4" file_path="chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.cc" /> <item id="iwa_update_discovery_web_bundle" added_in_milestone="117" type="partial" second_id="iwa_bundle_downloader" content_hash_code="044a85c3" os_list="chromeos" semantics_fields="1,2,3,7,8,9" policy_fields="3,4" file_path="chrome/browser/web_applications/isolated_web_apps/isolated_web_app_update_discovery_task.cc" /> + <item id="interest_feedv2_resource_send" added_in_milestone="118" content_hash_code="04189a4f" os_list="linux,windows,android,chromeos" file_path="components/feed/core/v2/resource_fetcher.cc" /> </annotations>
diff --git a/tools/traffic_annotation/summary/grouping.xml b/tools/traffic_annotation/summary/grouping.xml index 51b802c..7521654 100644 --- a/tools/traffic_annotation/summary/grouping.xml +++ b/tools/traffic_annotation/summary/grouping.xml
@@ -38,6 +38,7 @@ <sender name="Feed Library"> <annotation id="interest_feedv2_send"/> <annotation id="interest_feedv2_image_send"/> + <annotation id="interest_feedv2_resource_send"/> </sender> <sender name="Phone as a Security Key"> <annotation id="cablev2_websocket_from_client"/>
diff --git a/ui/accelerated_widget_mac/ca_layer_tree_unittest_mac.mm b/ui/accelerated_widget_mac/ca_layer_tree_unittest_mac.mm index 78c3f87..a2a1a9a 100644 --- a/ui/accelerated_widget_mac/ca_layer_tree_unittest_mac.mm +++ b/ui/accelerated_widget_mac/ca_layer_tree_unittest_mac.mm
@@ -44,15 +44,15 @@ unsigned filter = GL_LINEAR; gfx::ScopedIOSurface io_surface; gfx::ColorSpace color_space; - base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer; bool allow_av_layers = true; bool allow_solid_color_layers = true; }; -base::ScopedCFTypeRef<CVPixelBufferRef> CreateCVPixelBuffer( +base::apple::ScopedCFTypeRef<CVPixelBufferRef> CreateCVPixelBuffer( gfx::ScopedIOSurface io_surface) { - base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer; CVPixelBufferCreateWithIOSurface(nullptr, io_surface, nullptr, cv_pixel_buffer.InitializeInto()); return cv_pixel_buffer;
diff --git a/ui/accelerated_widget_mac/ca_renderer_layer_tree.h b/ui/accelerated_widget_mac/ca_renderer_layer_tree.h index 0e51fa7..a627f52 100644 --- a/ui/accelerated_widget_mac/ca_renderer_layer_tree.h +++ b/ui/accelerated_widget_mac/ca_renderer_layer_tree.h
@@ -226,8 +226,8 @@ class ContentLayer { public: ContentLayer(TransformLayer* parent_layer, - base::ScopedCFTypeRef<IOSurfaceRef> io_surface, - base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer, + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface, + base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer, const gfx::RectF& contents_rect, const gfx::Rect& rect, SkColor4f background_color, @@ -259,7 +259,7 @@ // When they are committed to the window server, that will also increment // their use count. const gfx::ScopedInUseIOSurface io_surface_; - const base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer_; + const base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer_; scoped_refptr<SolidColorContents> solid_color_contents_; gfx::RectF contents_rect_; gfx::RectF rect_;
diff --git a/ui/accelerated_widget_mac/ca_renderer_layer_tree.mm b/ui/accelerated_widget_mac/ca_renderer_layer_tree.mm index 4767f09..2f94646 100644 --- a/ui/accelerated_widget_mac/ca_renderer_layer_tree.mm +++ b/ui/accelerated_widget_mac/ca_renderer_layer_tree.mm
@@ -94,7 +94,7 @@ bool AVSampleBufferDisplayLayerEnqueueCVPixelBuffer( AVSampleBufferDisplayLayer* av_layer, CVPixelBufferRef cv_pixel_buffer) { - base::ScopedCFTypeRef<CMVideoFormatDescriptionRef> video_info; + base::apple::ScopedCFTypeRef<CMVideoFormatDescriptionRef> video_info; OSStatus os_status = CMVideoFormatDescriptionCreateForImageBuffer( nullptr, cv_pixel_buffer, video_info.InitializeInto()); if (os_status != noErr) { @@ -108,7 +108,7 @@ CMTime frame_time = CMTimeMake(0, 1); CMSampleTimingInfo timing_info = {frame_time, frame_time, kCMTimeInvalid}; - base::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; + base::apple::ScopedCFTypeRef<CMSampleBufferRef> sample_buffer; os_status = CMSampleBufferCreateForImageBuffer( nullptr, cv_pixel_buffer, YES, nullptr, nullptr, video_info, &timing_info, sample_buffer.InitializeInto()); @@ -168,7 +168,7 @@ absl::optional<gfx::HDRMetadata> hdr_metadata) { CVReturn cv_return = kCVReturnSuccess; - base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer; + base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer; cv_return = CVPixelBufferCreateWithIOSurface( nullptr, io_surface, /*pixelBufferAttributes=*/nullptr, cv_pixel_buffer.InitializeInto()); @@ -249,7 +249,7 @@ friend class base::RefCounted<SolidColorContents>; SolidColorContents(SkColor4f color, - base::ScopedCFTypeRef<IOSurfaceRef> io_surface); + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface); ~SolidColorContents(); using Map = std::map<SkColor4f, @@ -258,7 +258,7 @@ static Map* GetMap(); const SkColor4f color_; - base::ScopedCFTypeRef<IOSurfaceRef> io_surface_; + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface_; }; // static @@ -283,7 +283,7 @@ color_space = gfx::ColorSpace::CreateDisplayP3D65(); } - base::ScopedCFTypeRef<IOSurfaceRef> io_surface = + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface = CreateIOSurface(size, buffer_format); if (!io_surface) return nullptr; @@ -316,7 +316,7 @@ CARendererLayerTree::SolidColorContents::SolidColorContents( SkColor4f color, - base::ScopedCFTypeRef<IOSurfaceRef> io_surface) + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface) : color_(color), io_surface_(std::move(io_surface)) { auto* map = GetMap(); DCHECK(map->find(color_) == map->end()); @@ -746,8 +746,8 @@ CARendererLayerTree::ContentLayer::ContentLayer( TransformLayer* parent_layer, - base::ScopedCFTypeRef<IOSurfaceRef> io_surface, - base::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer, + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface, + base::apple::ScopedCFTypeRef<CVPixelBufferRef> cv_pixel_buffer, const gfx::RectF& contents_rect, const gfx::Rect& rect, SkColor4f background_color, @@ -935,7 +935,7 @@ void CARendererLayerTree::TransformLayer::AddContentLayer( const CARendererLayerParams& params) { content_layers_.emplace_back( - this, params.io_surface, base::ScopedCFTypeRef<CVPixelBufferRef>(), + this, params.io_surface, base::apple::ScopedCFTypeRef<CVPixelBufferRef>(), params.contents_rect, params.rect, params.background_color, params.io_surface_color_space, params.edge_aa_mask, params.opacity, params.nearest_neighbor_filter, params.hdr_metadata, @@ -1270,9 +1270,9 @@ background_color_.fB, background_color_.fA, }; - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB)); - base::ScopedCFTypeRef<CGColorRef> srgb_background_color( + base::apple::ScopedCFTypeRef<CGColorRef> srgb_background_color( CGColorCreate(color_space.get(), rgba_color_components)); ca_layer_.backgroundColor = srgb_background_color; } @@ -1352,7 +1352,7 @@ is_render_pass_draw_quad_ ? 6 : (update_anything ? 2 : 1); // Set the layer color based on usage. - base::ScopedCFTypeRef<CGColorRef> color( + base::apple::ScopedCFTypeRef<CGColorRef> color( CGColorCreateGenericRGB(red, green, blue, alpha)); ca_layer_.borderColor = color;
diff --git a/ui/accelerated_widget_mac/display_ca_layer_tree.h b/ui/accelerated_widget_mac/display_ca_layer_tree.h index e88d0a2..73f18b8 100644 --- a/ui/accelerated_widget_mac/display_ca_layer_tree.h +++ b/ui/accelerated_widget_mac/display_ca_layer_tree.h
@@ -35,7 +35,7 @@ private: void GotCALayerFrame(uint32_t ca_context_id); - void GotIOSurfaceFrame(base::ScopedCFTypeRef<IOSurfaceRef> io_surface, + void GotIOSurfaceFrame(base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface, const gfx::Size& dip_size, float scale_factor);
diff --git a/ui/accelerated_widget_mac/display_ca_layer_tree.mm b/ui/accelerated_widget_mac/display_ca_layer_tree.mm index a5006db..3ff0469 100644 --- a/ui/accelerated_widget_mac/display_ca_layer_tree.mm +++ b/ui/accelerated_widget_mac/display_ca_layer_tree.mm
@@ -89,7 +89,7 @@ // IOSurfaces can be sent from software compositing, or if remote layers are // manually disabled. if (ca_layer_params.io_surface_mach_port) { - base::ScopedCFTypeRef<IOSurfaceRef> io_surface( + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface( IOSurfaceLookupFromMachPort(ca_layer_params.io_surface_mach_port)); if (io_surface) { GotIOSurfaceFrame(io_surface, dip_size, ca_layer_params.scale_factor); @@ -152,7 +152,7 @@ } void DisplayCALayerTree::GotIOSurfaceFrame( - base::ScopedCFTypeRef<IOSurfaceRef> io_surface, + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface, const gfx::Size& dip_size, float scale_factor) { DCHECK(io_surface);
diff --git a/ui/accelerated_widget_mac/io_surface_context.h b/ui/accelerated_widget_mac/io_surface_context.h index 34cd952..e2f4d6f 100644 --- a/ui/accelerated_widget_mac/io_surface_context.h +++ b/ui/accelerated_widget_mac/io_surface_context.h
@@ -49,11 +49,11 @@ IOSurfaceContext( Type type, - base::ScopedTypeRef<CGLContextObj> clg_context_strong); + base::apple::ScopedTypeRef<CGLContextObj> clg_context_strong); ~IOSurfaceContext() override; Type type_; - base::ScopedTypeRef<CGLContextObj> cgl_context_; + base::apple::ScopedTypeRef<CGLContextObj> cgl_context_; bool poisoned_ = false; };
diff --git a/ui/accelerated_widget_mac/io_surface_context.mm b/ui/accelerated_widget_mac/io_surface_context.mm index 9ae3218..c185458 100644 --- a/ui/accelerated_widget_mac/io_surface_context.mm +++ b/ui/accelerated_widget_mac/io_surface_context.mm
@@ -15,7 +15,7 @@ #include "ui/gl/gl_switches.h" #include "ui/gl/gpu_switching_manager.h" -namespace base { +namespace base::apple { template <> struct ScopedTypeRefTraits<CGLContextObj> { @@ -37,7 +37,7 @@ } }; -} // namespace base +} // namespace base::apple namespace ui { @@ -66,7 +66,7 @@ return found->second; } - base::ScopedTypeRef<CGLContextObj> cgl_context; + base::apple::ScopedTypeRef<CGLContextObj> cgl_context; CGLError error = kCGLNoError; // Create the pixel format object for the context. @@ -77,7 +77,7 @@ attribs.push_back(kCGLPFAAllowOfflineRenderers); attribs.push_back(static_cast<CGLPixelFormatAttribute>(0)); GLint number_virtual_screens = 0; - base::ScopedTypeRef<CGLPixelFormatObj> pixel_format; + base::apple::ScopedTypeRef<CGLPixelFormatObj> pixel_format; error = CGLChoosePixelFormat(&attribs.front(), pixel_format.InitializeInto(), &number_virtual_screens); @@ -114,7 +114,7 @@ IOSurfaceContext::IOSurfaceContext( Type type, - base::ScopedTypeRef<CGLContextObj> cgl_context) + base::apple::ScopedTypeRef<CGLContextObj> cgl_context) : type_(type), cgl_context_(cgl_context) { auto* type_map = GetTypeMap(); DCHECK(type_map->find(type_) == type_map->end());
diff --git a/ui/accessibility/platform/ax_utils_mac.mm b/ui/accessibility/platform/ax_utils_mac.mm index 18c98d97..e99f7bb 100644 --- a/ui/accessibility/platform/ax_utils_mac.mm +++ b/ui/accessibility/platform/ax_utils_mac.mm
@@ -91,10 +91,10 @@ AXPlatformNodeDelegate::SerializedPosition serialized_focus = range.focus()->Serialize(); - base::ScopedCFTypeRef<AXTextMarkerRef> start_marker(AXTextMarkerCreate( + base::apple::ScopedCFTypeRef<AXTextMarkerRef> start_marker(AXTextMarkerCreate( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(&serialized_anchor), sizeof(AXPlatformNodeDelegate::SerializedPosition))); - base::ScopedCFTypeRef<AXTextMarkerRef> end_marker(AXTextMarkerCreate( + base::apple::ScopedCFTypeRef<AXTextMarkerRef> end_marker(AXTextMarkerCreate( kCFAllocatorDefault, reinterpret_cast<const UInt8*>(&serialized_focus), sizeof(AXPlatformNodeDelegate::SerializedPosition)));
diff --git a/ui/accessibility/platform/inspect/ax_element_wrapper_mac.mm b/ui/accessibility/platform/inspect/ax_element_wrapper_mac.mm index c2cabca..76792e92 100644 --- a/ui/accessibility/platform/inspect/ax_element_wrapper_mac.mm +++ b/ui/accessibility/platform/inspect/ax_element_wrapper_mac.mm
@@ -83,7 +83,7 @@ return [node_ children]; if (IsAXUIElement()) { - base::ScopedCFTypeRef<CFTypeRef> children_ref; + base::apple::ScopedCFTypeRef<CFTypeRef> children_ref; if ((AXUIElementCopyAttributeValue( (__bridge AXUIElementRef)node_, kAXChildrenAttribute, children_ref.InitializeInto())) == kAXErrorSuccess) { @@ -151,7 +151,7 @@ } if (IsAXUIElement()) { - base::ScopedCFTypeRef<CFArrayRef> attributes_ref; + base::apple::ScopedCFTypeRef<CFArrayRef> attributes_ref; AXError result = AXUIElementCopyAttributeNames( (__bridge AXUIElementRef)node_, attributes_ref.InitializeInto()); if (AXSuccess(result, "AXAttributeNamesOf")) { @@ -171,7 +171,7 @@ } if (IsAXUIElement()) { - base::ScopedCFTypeRef<CFArrayRef> attributes_ref; + base::apple::ScopedCFTypeRef<CFArrayRef> attributes_ref; AXError result = AXUIElementCopyParameterizedAttributeNames( (__bridge AXUIElementRef)node_, attributes_ref.InitializeInto()); if (AXSuccess(result, "AXParameterizedAttributeNamesOf")) { @@ -192,7 +192,7 @@ } if (IsAXUIElement()) { - base::ScopedCFTypeRef<CFTypeRef> value_ref; + base::apple::ScopedCFTypeRef<CFTypeRef> value_ref; AXError result = AXUIElementCopyAttributeValue( (__bridge AXUIElementRef)node_, (__bridge CFStringRef)attribute, value_ref.InitializeInto()); @@ -212,7 +212,8 @@ forParameter:parameter]); if (IsAXUIElement()) { - base::ScopedCFTypeRef<CFTypeRef> parameter_ref(CFBridgingRetain(parameter)); + base::apple::ScopedCFTypeRef<CFTypeRef> parameter_ref( + CFBridgingRetain(parameter)); if ([parameter isKindOfClass:[NSValue class]] && !strcmp([parameter objCType], @encode(NSRange))) { NSRange range = [parameter rangeValue]; @@ -220,7 +221,7 @@ } // Get value. - base::ScopedCFTypeRef<CFTypeRef> value_ref; + base::apple::ScopedCFTypeRef<CFTypeRef> value_ref; AXError result = AXUIElementCopyParameterizedAttributeValue( (__bridge AXUIElementRef)node_, (__bridge CFStringRef)attribute, parameter_ref, value_ref.InitializeInto()); @@ -286,7 +287,7 @@ return [node_ accessibilityActionNames]; if (IsAXUIElement()) { - base::ScopedCFTypeRef<CFArrayRef> attributes_ref; + base::apple::ScopedCFTypeRef<CFArrayRef> attributes_ref; if ((AXUIElementCopyActionNames((__bridge AXUIElementRef)node_, attributes_ref.InitializeInto())) == kAXErrorSuccess) {
diff --git a/ui/accessibility/platform/inspect/ax_event_recorder_mac.h b/ui/accessibility/platform/inspect/ax_event_recorder_mac.h index 2bf1e09..4cf923ca 100644 --- a/ui/accessibility/platform/inspect/ax_event_recorder_mac.h +++ b/ui/accessibility/platform/inspect/ax_event_recorder_mac.h
@@ -40,10 +40,10 @@ void AddNotification(NSString* notification); // The AXUIElement for the application. - base::ScopedCFTypeRef<AXUIElementRef> application_; + base::apple::ScopedCFTypeRef<AXUIElementRef> application_; // The AXObserver we use to monitor AX notifications. - base::ScopedCFTypeRef<AXObserverRef> observer_ref_; + base::apple::ScopedCFTypeRef<AXObserverRef> observer_ref_; CFRunLoopSourceRef observer_run_loop_source_; };
diff --git a/ui/accessibility/platform/inspect/ax_event_recorder_mac.mm b/ui/accessibility/platform/inspect/ax_event_recorder_mac.mm index 9df34057..ee76ca0 100644 --- a/ui/accessibility/platform/inspect/ax_event_recorder_mac.mm +++ b/ui/accessibility/platform/inspect/ax_event_recorder_mac.mm
@@ -35,7 +35,7 @@ AXEventRecorderMac::AXEventRecorderMac(base::ProcessId pid, const AXTreeSelector& selector) : observer_run_loop_source_(nullptr) { - base::ScopedCFTypeRef<AXUIElementRef> node; + base::apple::ScopedCFTypeRef<AXUIElementRef> node; if (pid) { node.reset(AXUIElementCreateApplication(pid)); if (!node) {
diff --git a/ui/accessibility/platform/inspect/ax_inspect_utils_mac.h b/ui/accessibility/platform/inspect/ax_inspect_utils_mac.h index c15a326..c3bb556 100644 --- a/ui/accessibility/platform/inspect/ax_inspect_utils_mac.h +++ b/ui/accessibility/platform/inspect/ax_inspect_utils_mac.h
@@ -25,18 +25,18 @@ // Return AXElement in a tree by a given criteria. using AXFindCriteria = base::RepeatingCallback<bool(const AXUIElementRef)>; COMPONENT_EXPORT(AX_PLATFORM) -base::ScopedCFTypeRef<AXUIElementRef> FindAXUIElement( +base::apple::ScopedCFTypeRef<AXUIElementRef> FindAXUIElement( const AXUIElementRef node, const AXFindCriteria& criteria); // Returns AXUIElement and its application process id by a given tree selector. COMPONENT_EXPORT(AX_PLATFORM) -std::pair<base::ScopedCFTypeRef<AXUIElementRef>, int> FindAXUIElement( +std::pair<base::apple::ScopedCFTypeRef<AXUIElementRef>, int> FindAXUIElement( const AXTreeSelector&); // Returns AXUIElement for a window having title matching the given pattern. COMPONENT_EXPORT(AX_PLATFORM) -base::ScopedCFTypeRef<AXUIElementRef> FindAXWindowChild( +base::apple::ScopedCFTypeRef<AXUIElementRef> FindAXWindowChild( AXUIElementRef parent, const std::string& pattern);
diff --git a/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm b/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm index 64086279..40c79b9 100644 --- a/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm +++ b/ui/accessibility/platform/inspect/ax_inspect_utils_mac.mm
@@ -100,30 +100,30 @@ return [valid_attributes containsObject:base::SysUTF8ToNSString(attribute)]; } -base::ScopedCFTypeRef<AXUIElementRef> FindAXUIElement( +base::apple::ScopedCFTypeRef<AXUIElementRef> FindAXUIElement( const AXUIElementRef node, const AXFindCriteria& criteria) { if (criteria.Run(node)) { - return base::ScopedCFTypeRef<AXUIElementRef>(node, - base::scoped_policy::RETAIN); + return base::apple::ScopedCFTypeRef<AXUIElementRef>( + node, base::scoped_policy::RETAIN); } NSArray* children = AXChildrenOf((__bridge id)node); for (id child in children) { - base::ScopedCFTypeRef<AXUIElementRef> found = + base::apple::ScopedCFTypeRef<AXUIElementRef> found = FindAXUIElement((__bridge AXUIElementRef)child, criteria); if (found) { return found; } } - return base::ScopedCFTypeRef<AXUIElementRef>(); + return base::apple::ScopedCFTypeRef<AXUIElementRef>(); } -std::pair<base::ScopedCFTypeRef<AXUIElementRef>, int> FindAXUIElement( +std::pair<base::apple::ScopedCFTypeRef<AXUIElementRef>, int> FindAXUIElement( const AXTreeSelector& selector) { if (selector.widget) { - return {base::ScopedCFTypeRef<AXUIElementRef>( + return {base::apple::ScopedCFTypeRef<AXUIElementRef>( AXUIElementCreateApplication(selector.widget)), selector.widget}; } @@ -138,7 +138,7 @@ else if (selector.types & AXTreeSelector::Safari) title = kSafariTitle; else - return {base::ScopedCFTypeRef<AXUIElementRef>(), 0}; + return {base::apple::ScopedCFTypeRef<AXUIElementRef>(), 0}; NSArray* windows = base::apple::CFToNSOwnershipCast(CGWindowListCopyWindowInfo( @@ -151,7 +151,7 @@ std::string window_name = base::SysNSStringToUTF8( base::apple::ObjCCast<NSString>(window_info[@"kCGWindowOwnerName"])); - base::ScopedCFTypeRef<AXUIElementRef> node; + base::apple::ScopedCFTypeRef<AXUIElementRef> node; // Application pre-defined selectors match or application title exact match. bool app_title_match = window_name == selector.pattern; @@ -167,7 +167,7 @@ node.reset(AXUIElementCreateApplication(pid)); } - base::ScopedCFTypeRef<AXUIElementRef> window = + base::apple::ScopedCFTypeRef<AXUIElementRef> window = FindAXWindowChild(node, selector.pattern); if (window) { node = window; @@ -191,15 +191,15 @@ if (node) return {node, pid}; } - return {base::ScopedCFTypeRef<AXUIElementRef>(), 0}; + return {base::apple::ScopedCFTypeRef<AXUIElementRef>(), 0}; } -base::ScopedCFTypeRef<AXUIElementRef> FindAXWindowChild( +base::apple::ScopedCFTypeRef<AXUIElementRef> FindAXWindowChild( AXUIElementRef parent, const std::string& pattern) { NSArray* children = AXChildrenOf((__bridge id)parent); if (children.count == 0) { - return base::ScopedCFTypeRef<AXUIElementRef>(); + return base::apple::ScopedCFTypeRef<AXUIElementRef>(); } id window = children.firstObject; @@ -207,17 +207,17 @@ AXElementWrapper ax_window(window); NSString* role = *ax_window.GetAttributeValue(NSAccessibilityRoleAttribute); if (base::SysNSStringToUTF8(role) != "AXWindow") { - return base::ScopedCFTypeRef<AXUIElementRef>(); + return base::apple::ScopedCFTypeRef<AXUIElementRef>(); } NSString* window_title = *ax_window.GetAttributeValue(NSAccessibilityTitleAttribute); if (base::MatchPattern(base::SysNSStringToUTF8(window_title), pattern)) { - return base::ScopedCFTypeRef<AXUIElementRef>( + return base::apple::ScopedCFTypeRef<AXUIElementRef>( (__bridge AXUIElementRef)window, base::scoped_policy::RETAIN); } - return base::ScopedCFTypeRef<AXUIElementRef>(); + return base::apple::ScopedCFTypeRef<AXUIElementRef>(); } } // namespace ui
diff --git a/ui/accessibility/platform/inspect/ax_tree_formatter_mac.mm b/ui/accessibility/platform/inspect/ax_tree_formatter_mac.mm index 6936c995..b53ed35 100644 --- a/ui/accessibility/platform/inspect/ax_tree_formatter_mac.mm +++ b/ui/accessibility/platform/inspect/ax_tree_formatter_mac.mm
@@ -66,7 +66,7 @@ base::Value::Dict AXTreeFormatterMac::BuildTreeForSelector( const AXTreeSelector& selector) const { - base::ScopedCFTypeRef<AXUIElementRef> node; + base::apple::ScopedCFTypeRef<AXUIElementRef> node; std::tie(node, std::ignore) = FindAXUIElement(selector); if (node == nil) { return base::Value::Dict(); @@ -98,7 +98,7 @@ std::string AXTreeFormatterMac::EvaluateScript( const AXTreeSelector& selector, const AXInspectScenario& scenario) const { - base::ScopedCFTypeRef<AXUIElementRef> root; + base::apple::ScopedCFTypeRef<AXUIElementRef> root; std::tie(root, std::ignore) = FindAXUIElement(selector); if (!root) return "";
diff --git a/ui/base/accelerators/media_keys_listener_mac.mm b/ui/base/accelerators/media_keys_listener_mac.mm index 291cdde5..3450e36ba 100644 --- a/ui/base/accelerators/media_keys_listener_mac.mm +++ b/ui/base/accelerators/media_keys_listener_mac.mm
@@ -66,8 +66,8 @@ raw_ptr<MediaKeysListener::Delegate> delegate_; const Scope scope_; // Event tap for intercepting mac media keys. - base::ScopedCFTypeRef<CFMachPortRef> event_tap_; - base::ScopedCFTypeRef<CFRunLoopSourceRef> event_tap_source_; + base::apple::ScopedCFTypeRef<CFMachPortRef> event_tap_; + base::apple::ScopedCFTypeRef<CFRunLoopSourceRef> event_tap_source_; base::flat_set<KeyboardCode> key_codes_; };
diff --git a/ui/base/clipboard/clipboard_ios.mm b/ui/base/clipboard/clipboard_ios.mm index 71038ee..e4cda7a 100644 --- a/ui/base/clipboard/clipboard_ios.mm +++ b/ui/base/clipboard/clipboard_ios.mm
@@ -439,7 +439,7 @@ // security CHECK. DCHECK_EQ(bitmap.colorType(), kN32_SkColorType); - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); UIImage* image = skia::SkBitmapToUIImageWithColorSpace(bitmap, 1.0f, color_space);
diff --git a/ui/base/clipboard/clipboard_mac_unittest.mm b/ui/base/clipboard/clipboard_mac_unittest.mm index 2333acb5..45b91a7 100644 --- a/ui/base/clipboard/clipboard_mac_unittest.mm +++ b/ui/base/clipboard/clipboard_mac_unittest.mm
@@ -60,13 +60,13 @@ // loses its "retina-ness". uint8_t* buffer = static_cast<uint8_t*>(calloc(pixel_width * pixel_height, 4)); - base::ScopedCFTypeRef<CGDataProviderRef> provider( + base::apple::ScopedCFTypeRef<CGDataProviderRef> provider( CGDataProviderCreateWithData(buffer, buffer, (pixel_width * pixel_height * 4), &CreateImageBufferReleaser)); - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateWithName(kCGColorSpaceSRGB)); - base::ScopedCFTypeRef<CGImageRef> image_ref( + base::apple::ScopedCFTypeRef<CGImageRef> image_ref( CGImageCreate(pixel_width, pixel_height, 8, 32, 4 * pixel_width, color_space.get(), kCGBitmapByteOrderDefault, provider.get(), nullptr, NO, kCGRenderingIntentDefault));
diff --git a/ui/base/cocoa/nsmenuitem_additions.mm b/ui/base/cocoa/nsmenuitem_additions.mm index ddfe5546..4e8e3df 100644 --- a/ui/base/cocoa/nsmenuitem_additions.mm +++ b/ui/base/cocoa/nsmenuitem_additions.mm
@@ -104,7 +104,7 @@ } - (void)updateInputSource { - base::ScopedCFTypeRef<TISInputSourceRef> inputSource( + base::apple::ScopedCFTypeRef<TISInputSourceRef> inputSource( TISCopyCurrentKeyboardInputSource()); NSString* layoutId = base::apple::CFToNSPtrCast( base::apple::CFCast<CFStringRef>(TISGetInputSourceProperty(
diff --git a/ui/base/cocoa/nsmenuitem_additions_unittest.mm b/ui/base/cocoa/nsmenuitem_additions_unittest.mm index 53102fa..1ef8d9a 100644 --- a/ui/base/cocoa/nsmenuitem_additions_unittest.mm +++ b/ui/base/cocoa/nsmenuitem_additions_unittest.mm
@@ -587,7 +587,7 @@ // can be fired on all layouts. NSMenuItem* item = MenuItem(@"m", NSEventModifierFlagCommand); - base::ScopedCFTypeRef<CFMutableDictionaryRef> filter( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> filter( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -596,7 +596,7 @@ // Docs say that including all layouts instead of just the active ones is // slow, but there's no way around that. - base::ScopedCFTypeRef<CFArrayRef> list( + base::apple::ScopedCFTypeRef<CFArrayRef> list( TISCreateInputSourceList(filter, /*includeAllInstalled=*/true)); for (CFIndex i = 0; i < CFArrayGetCount(list); ++i) {
diff --git a/ui/base/cocoa/permissions_utils.mm b/ui/base/cocoa/permissions_utils.mm index 7bbbfdc8..c945394 100644 --- a/ui/base/cocoa/permissions_utils.mm +++ b/ui/base/cocoa/permissions_utils.mm
@@ -67,11 +67,12 @@ // in the applications list in System permissions. Stream creation will // fail if the user denies permission, or if our application is already // in the system permission and is unchecked. - base::ScopedCFTypeRef<CGDisplayStreamRef> stream(wrapCGDisplayStreamCreate( - CGMainDisplayID(), 1, 1, 'BGRA', nullptr, - ^(CGDisplayStreamFrameStatus status, uint64_t displayTime, - IOSurfaceRef frameSurface, CGDisplayStreamUpdateRef updateRef){ - })); + base::apple::ScopedCFTypeRef<CGDisplayStreamRef> stream( + wrapCGDisplayStreamCreate( + CGMainDisplayID(), 1, 1, 'BGRA', nullptr, + ^(CGDisplayStreamFrameStatus status, uint64_t displayTime, + IOSurfaceRef frameSurface, CGDisplayStreamUpdateRef updateRef){ + })); return stream != nullptr; } } @@ -90,7 +91,7 @@ {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, base::BindOnce([] { if (IsScreenCaptureAllowed()) { - base::ScopedCFTypeRef<CGImageRef>(CGWindowListCreateImage( + base::apple::ScopedCFTypeRef<CGImageRef>(CGWindowListCreateImage( CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault)); }
diff --git a/ui/base/resource/resource_bundle_ios.mm b/ui/base/resource/resource_bundle_ios.mm index 2ed9596..ca222920 100644 --- a/ui/base/resource/resource_bundle_ios.mm +++ b/ui/base/resource/resource_bundle_ios.mm
@@ -128,9 +128,9 @@ CGSize source_size = ui_image.size; CGSize target_size = CGSizeMake(source_size.width * target_scale, source_size.height * target_scale); - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( /*data=*/nullptr, target_size.width, target_size.height, 8, target_size.width * 4, color_space, kCGImageAlphaPremultipliedFirst | @@ -141,7 +141,7 @@ CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextDrawImage(context, target_rect, ui_image.CGImage); - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGBitmapContextCreateImage(context)); ui_image = [[UIImage alloc] initWithCGImage:cg_image scale:target_scale
diff --git a/ui/base/test/ios/ui_image_test_utils.mm b/ui/base/test/ios/ui_image_test_utils.mm index b7668604..4a2f432d 100644 --- a/ui/base/test/ios/ui_image_test_utils.mm +++ b/ui/base/test/ios/ui_image_test_utils.mm
@@ -38,9 +38,9 @@ if (!CGSizeEqualToSize(image_1.size, image_2.size)) return false; - base::ScopedCFTypeRef<CFDataRef> data_ref_1( + base::apple::ScopedCFTypeRef<CFDataRef> data_ref_1( CGDataProviderCopyData(CGImageGetDataProvider(image_1.CGImage))); - base::ScopedCFTypeRef<CFDataRef> data_ref_2( + base::apple::ScopedCFTypeRef<CFDataRef> data_ref_2( CGDataProviderCopyData(CGImageGetDataProvider(image_2.CGImage))); CFIndex length_1 = CFDataGetLength(data_ref_1); CFIndex length_2 = CFDataGetLength(data_ref_2);
diff --git a/ui/display/mac/display_link_mac.cc b/ui/display/mac/display_link_mac.cc index 7a99f19..50af6829 100644 --- a/ui/display/mac/display_link_mac.cc +++ b/ui/display/mac/display_link_mac.cc
@@ -15,7 +15,7 @@ #include "base/task/bind_post_task.h" #include "base/trace_event/trace_event.h" -namespace base { +namespace base::apple { template <> struct ScopedTypeRefTraits<CVDisplayLinkRef> { @@ -26,7 +26,7 @@ static void Release(CVDisplayLinkRef object) { CVDisplayLinkRelease(object); } }; -} // namespace base +} // namespace base::apple namespace ui { @@ -120,7 +120,7 @@ // created/destroyed on the same thread. Holding a lock here can result in // deadlock. - base::ScopedTypeRef<CVDisplayLinkRef> display_link; + base::apple::ScopedTypeRef<CVDisplayLinkRef> display_link; ret = CVDisplayLinkCreateWithCGDisplay(display_id, display_link.InitializeInto()); if (ret != kCVReturnSuccess) { @@ -186,7 +186,7 @@ DisplayLinkMac::DisplayLinkMac( CGDirectDisplayID display_id, - base::ScopedTypeRef<CVDisplayLinkRef> display_link) + base::apple::ScopedTypeRef<CVDisplayLinkRef> display_link) : display_id_(display_id), display_link_(display_link) {} DisplayLinkMac::~DisplayLinkMac() {
diff --git a/ui/display/mac/display_link_mac.h b/ui/display/mac/display_link_mac.h index 78cbf4a..d692345 100644 --- a/ui/display/mac/display_link_mac.h +++ b/ui/display/mac/display_link_mac.h
@@ -94,7 +94,7 @@ friend class VSyncCallbackMac; DisplayLinkMac(CGDirectDisplayID display_id, - base::ScopedTypeRef<CVDisplayLinkRef> display_link); + base::apple::ScopedTypeRef<CVDisplayLinkRef> display_link); virtual ~DisplayLinkMac(); void UnregisterCallback(VSyncCallbackMac* callback); @@ -112,7 +112,7 @@ CGDirectDisplayID display_id_; // CVDisplayLink for querying VSync timing info. - base::ScopedTypeRef<CVDisplayLinkRef> display_link_; + base::apple::ScopedTypeRef<CVDisplayLinkRef> display_link_; // Each VSyncCallbackMac holds a reference to `this`. This member may // be accessed on any thread while |globals.lock| is held. But it can only be
diff --git a/ui/display/mac/screen_mac.mm b/ui/display/mac/screen_mac.mm index eb6e483..6130432 100644 --- a/ui/display/mac/screen_mac.mm +++ b/ui/display/mac/screen_mac.mm
@@ -119,7 +119,7 @@ { CGColorSpaceRef cg_color_space = screen.colorSpace.CGColorSpace; if (cg_color_space) { - base::ScopedCFTypeRef<CFDataRef> cf_icc_profile( + base::apple::ScopedCFTypeRef<CFDataRef> cf_icc_profile( CGColorSpaceCopyICCData(cg_color_space)); if (cf_icc_profile) { icc_profile = gfx::ICCProfile::FromData(
diff --git a/ui/display/mac/test/virtual_display_mac_util.mm b/ui/display/mac/test/virtual_display_mac_util.mm index 09c42092..083c20e 100644 --- a/ui/display/mac/test/virtual_display_mac_util.mm +++ b/ui/display/mac/test/virtual_display_mac_util.mm
@@ -247,14 +247,14 @@ void EnsureDisplayWithResolution(CGDirectDisplayID display_id, const gfx::Size& size) { - base::ScopedCFTypeRef<CGDisplayModeRef> current_display_mode( + base::apple::ScopedCFTypeRef<CGDisplayModeRef> current_display_mode( CGDisplayCopyDisplayMode(display_id)); if (gfx::Size(CGDisplayModeGetWidth(current_display_mode), CGDisplayModeGetHeight(current_display_mode)) == size) { return; } - base::ScopedCFTypeRef<CFArrayRef> display_modes( + base::apple::ScopedCFTypeRef<CFArrayRef> display_modes( CGDisplayCopyAllDisplayModes(display_id, nullptr)); DCHECK(display_modes);
diff --git a/ui/events/cocoa/cocoa_event_utils.mm b/ui/events/cocoa/cocoa_event_utils.mm index 5e49377..11bf78d 100644 --- a/ui/events/cocoa/cocoa_event_utils.mm +++ b/ui/events/cocoa/cocoa_event_utils.mm
@@ -136,7 +136,7 @@ } std::vector<uint8_t> EventToData(NSEvent* event) { - base::ScopedCFTypeRef<CFDataRef> cf_data( + base::apple::ScopedCFTypeRef<CFDataRef> cf_data( CGEventCreateData(nullptr, event.CGEvent)); const uint8_t* cf_data_ptr = CFDataGetBytePtr(cf_data.get()); size_t cf_data_size = CFDataGetLength(cf_data.get()); @@ -144,9 +144,9 @@ } NSEvent* EventFromData(const std::vector<uint8_t>& data) { - base::ScopedCFTypeRef<CFDataRef> cf_data( + base::apple::ScopedCFTypeRef<CFDataRef> cf_data( CFDataCreate(nullptr, data.data(), data.size())); - base::ScopedCFTypeRef<CGEventRef> cg_event( + base::apple::ScopedCFTypeRef<CGEventRef> cg_event( CGEventCreateFromData(nullptr, cf_data.get())); return [NSEvent eventWithCGEvent:cg_event.get()]; }
diff --git a/ui/events/cocoa/events_mac_unittest.mm b/ui/events/cocoa/events_mac_unittest.mm index 010da04c..70fae38 100644 --- a/ui/events/cocoa/events_mac_unittest.mm +++ b/ui/events/cocoa/events_mac_unittest.mm
@@ -57,7 +57,7 @@ CGMouseButton other_button = kCGMouseButtonCenter; CGPoint screen_point = cocoa_test_event_utils::ScreenPointFromWindow( Flip(window_location).ToCGPoint(), test_window()); - base::ScopedCFTypeRef<CGEventRef> mouse( + base::apple::ScopedCFTypeRef<CGEventRef> mouse( CGEventCreateMouseEvent(nullptr, type, screen_point, other_button)); CGEventSetFlags(mouse, event_flags); return cocoa_test_event_utils::AttachWindowToCGEvent(mouse, test_window()); @@ -365,7 +365,7 @@ TEST_F(EventsMacTest, NoWindowLocation) { const CGPoint location = CGPointMake(5, 10); - base::ScopedCFTypeRef<CGEventRef> mouse(CGEventCreateMouseEvent( + base::apple::ScopedCFTypeRef<CGEventRef> mouse(CGEventCreateMouseEvent( nullptr, kCGEventMouseMoved, location, kCGMouseButtonLeft)); NSEvent* event = [NSEvent eventWithCGEvent:mouse];
diff --git a/ui/events/keycodes/dom/dom_keyboard_layout_map_mac.mm b/ui/events/keycodes/dom/dom_keyboard_layout_map_mac.mm index b38f45e..df06df4 100644 --- a/ui/events/keycodes/dom/dom_keyboard_layout_map_mac.mm +++ b/ui/events/keycodes/dom/dom_keyboard_layout_map_mac.mm
@@ -51,7 +51,7 @@ UInt32 dead_key_state = 0; uint16_t key_code = ui::KeycodeConverter::DomCodeToNativeKeycode(dom_code); - base::ScopedCFTypeRef<TISInputSourceRef> input_source( + base::apple::ScopedCFTypeRef<TISInputSourceRef> input_source( TISCopyCurrentASCIICapableKeyboardLayoutInputSource()); UniChar char_value = ui::TranslatedUnicodeCharFromKeyCode( input_source.get(), key_code, kUCKeyActionDisplay, 0, LMGetKbdType(),
diff --git a/ui/events/keycodes/keyboard_code_conversion_mac.mm b/ui/events/keycodes/keyboard_code_conversion_mac.mm index c3beb78..593b5c2d 100644 --- a/ui/events/keycodes/keyboard_code_conversion_mac.mm +++ b/ui/events/keycodes/keyboard_code_conversion_mac.mm
@@ -564,7 +564,7 @@ UInt32 modifier_key_state = (unicode_modifiers >> 8) & 0xFF; UInt32 dead_key_state = 0; - base::ScopedCFTypeRef<TISInputSourceRef> input_source( + base::apple::ScopedCFTypeRef<TISInputSourceRef> input_source( TISCopyCurrentKeyboardLayoutInputSource()); UniChar translated_char = TranslatedUnicodeCharFromKeyCode( input_source.get(), static_cast<UInt16>(key_code), kUCKeyActionDown,
diff --git a/ui/events/test/cocoa_test_event_utils.mm b/ui/events/test/cocoa_test_event_utils.mm index a3b8f94..de8f0ca 100644 --- a/ui/events/test/cocoa_test_event_utils.mm +++ b/ui/events/test/cocoa_test_event_utils.mm
@@ -72,7 +72,7 @@ // appropriate buttonNumber field. NSEvent provides no way to create a // mouse event with a buttonNumber directly. CGPoint location = { point.x, point.y }; - base::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateMouseEvent( + base::apple::ScopedCFTypeRef<CGEventRef> cg_event(CGEventCreateMouseEvent( nullptr, kCGEventOtherMouseUp, location, kCGMouseButtonCenter)); // Also specify the modifiers for the middle click case. This makes this // test resilient to external modifiers being pressed. @@ -158,7 +158,7 @@ int32_t wheel2 = static_cast<int>(delta_x); CGScrollEventUnit units = has_precise_deltas ? kCGScrollEventUnitPixel : kCGScrollEventUnitLine; - base::ScopedCFTypeRef<CGEventRef> scroll(CGEventCreateScrollWheelEvent( + base::apple::ScopedCFTypeRef<CGEventRef> scroll(CGEventCreateScrollWheelEvent( nullptr, units, wheel_count, wheel1, wheel2)); CGEventSetLocation(scroll, ScreenPointFromWindow(window_point, window));
diff --git a/ui/events/test/keyboard_layout.h b/ui/events/test/keyboard_layout.h index 884ccc09..daf45edf 100644 --- a/ui/events/test/keyboard_layout.h +++ b/ui/events/test/keyboard_layout.h
@@ -33,7 +33,7 @@ #if BUILDFLAG(IS_WIN) using PlatformKeyboardLayout = HKL; #elif BUILDFLAG(IS_MAC) -using PlatformKeyboardLayout = base::ScopedCFTypeRef<TISInputSourceRef>; +using PlatformKeyboardLayout = base::apple::ScopedCFTypeRef<TISInputSourceRef>; #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
diff --git a/ui/events/test/keyboard_layout_mac.cc b/ui/events/test/keyboard_layout_mac.cc index 98cfd97e..2c01ca2 100644 --- a/ui/events/test/keyboard_layout_mac.cc +++ b/ui/events/test/keyboard_layout_mac.cc
@@ -15,21 +15,21 @@ const char kUsInputSourceId[] = "com.apple.keylayout.US"; - base::ScopedCFTypeRef<CFMutableDictionaryRef> input_source_list_filter( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> input_source_list_filter( CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); - base::ScopedCFTypeRef<CFStringRef> input_source_id_ref( + base::apple::ScopedCFTypeRef<CFStringRef> input_source_id_ref( CFStringCreateWithCString(kCFAllocatorDefault, kUsInputSourceId, kCFStringEncodingUTF8)); CFDictionaryAddValue(input_source_list_filter, kTISPropertyInputSourceID, input_source_id_ref); - base::ScopedCFTypeRef<CFArrayRef> input_source_list( + base::apple::ScopedCFTypeRef<CFArrayRef> input_source_list( TISCreateInputSourceList(input_source_list_filter, true)); if (CFArrayGetCount(input_source_list) != 1) return PlatformKeyboardLayout(); - return base::ScopedCFTypeRef<TISInputSourceRef>( + return base::apple::ScopedCFTypeRef<TISInputSourceRef>( (TISInputSourceRef)CFArrayGetValueAtIndex(input_source_list, 0), base::scoped_policy::RETAIN); }
diff --git a/ui/file_manager/file_manager/background/js/volume_manager_impl.js b/ui/file_manager/file_manager/background/js/volume_manager_impl.js index fa2dfcef..54978cb4 100644 --- a/ui/file_manager/file_manager/background/js/volume_manager_impl.js +++ b/ui/file_manager/file_manager/background/js/volume_manager_impl.js
@@ -11,7 +11,7 @@ import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; import {VolumeInfo} from '../../externs/volume_info.js'; import {VolumeManager} from '../../externs/volume_manager.js'; -import {removeVolume} from '../../state/actions/volumes.js'; +import {removeVolume} from '../../state/ducks/volumes.js'; import {getStore} from '../../state/store.js'; import {EntryLocationImpl} from './entry_location_impl.js';
diff --git a/ui/file_manager/file_manager/background/js/volume_manager_util.js b/ui/file_manager/file_manager/background/js/volume_manager_util.js index 6d73e9e2..39b2505 100644 --- a/ui/file_manager/file_manager/background/js/volume_manager_util.js +++ b/ui/file_manager/file_manager/background/js/volume_manager_util.js
@@ -5,7 +5,7 @@ import {str, util} from '../../common/js/util.js'; import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; import {VolumeInfo} from '../../externs/volume_info.js'; -import {addVolume} from '../../state/actions/volumes.js'; +import {addVolume} from '../../state/ducks/volumes.js'; import {getStore} from '../../state/store.js'; import {VolumeInfoImpl} from './volume_info_impl.js';
diff --git a/ui/file_manager/file_manager/common/js/entry_utils.ts b/ui/file_manager/file_manager/common/js/entry_utils.ts index ec2a426..4d49347 100644 --- a/ui/file_manager/file_manager/common/js/entry_utils.ts +++ b/ui/file_manager/file_manager/common/js/entry_utils.ts
@@ -4,7 +4,7 @@ import {FilesAppEntry} from '../../externs/files_app_entry_interfaces.js'; import {EntryType, FileData} from '../../externs/ts/state.js'; -import {driveRootEntryListKey, myFilesEntryListKey, trashRootKey} from '../../state/reducers/volumes.js'; +import {driveRootEntryListKey, myFilesEntryListKey, trashRootKey} from '../../state/ducks/volumes.js'; import {EntryList, FakeEntryImpl, VolumeEntry} from './files_app_entry_types.js'; import {util} from './util.js';
diff --git a/ui/file_manager/file_manager/containers/cloud_panel_container_unittest.ts b/ui/file_manager/file_manager/containers/cloud_panel_container_unittest.ts index 55e2007..d8611f5 100644 --- a/ui/file_manager/file_manager/containers/cloud_panel_container_unittest.ts +++ b/ui/file_manager/file_manager/containers/cloud_panel_container_unittest.ts
@@ -2,12 +2,15 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../state/store.js'; + import {loadTimeData} from 'chrome://resources/ash/common/load_time_data.m.js'; import {assertEquals, assertFalse} from 'chrome://webui-test/chai_assert.js'; import {waitUntil} from '../common/js/test_error_reporting.js'; -import {updateBulkPinProgress} from '../state/actions/bulk_pinning.js'; import {updatePreferences} from '../state/actions/preferences.js'; +import {updateBulkPinProgress} from '../state/ducks/bulk_pinning.js'; import {waitDeepEquals} from '../state/for_tests.js'; import {getEmptyState, getStore} from '../state/store.js'; import {XfCloudPanel} from '../widgets/xf_cloud_panel.js';
diff --git a/ui/file_manager/file_manager/containers/directory_tree_container.ts b/ui/file_manager/file_manager/containers/directory_tree_container.ts index 934b6556..cb33cdb 100644 --- a/ui/file_manager/file_manager/containers/directory_tree_container.ts +++ b/ui/file_manager/file_manager/containers/directory_tree_container.ts
@@ -22,8 +22,8 @@ import {changeDirectory} from '../state/actions/current_directory.js'; import {refreshNavigationRoots, updateNavigationEntry} from '../state/actions/navigation.js'; import {readSubDirectories} from '../state/actions_producers/all_entries.js'; +import {driveRootEntryListKey} from '../state/ducks/volumes.js'; import {convertEntryToFileData} from '../state/reducers/all_entries.js'; -import {driveRootEntryListKey} from '../state/reducers/volumes.js'; import {getEntry, getFileData, getStore, Store} from '../state/store.js'; import {TreeSelectedChangedEvent, XfTree} from '../widgets/xf_tree.js'; import {TreeItemCollapsedEvent, TreeItemExpandedEvent, XfTreeItem} from '../widgets/xf_tree_item.js';
diff --git a/ui/file_manager/file_manager/containers/directory_tree_container_unittest.ts b/ui/file_manager/file_manager/containers/directory_tree_container_unittest.ts index f0ef703..a1a50737 100644 --- a/ui/file_manager/file_manager/containers/directory_tree_container_unittest.ts +++ b/ui/file_manager/file_manager/containers/directory_tree_container_unittest.ts
@@ -17,10 +17,9 @@ import {MetadataItem} from '../foreground/js/metadata/metadata_item.js'; import {MetadataModel} from '../foreground/js/metadata/metadata_model.js'; import {MockMetadataModel} from '../foreground/js/metadata/mock_metadata.js'; -import {addVolume, removeVolume} from '../state/actions/volumes.js'; +import {addVolume, convertVolumeInfoAndMetadataToVolume, driveRootEntryListKey, removeVolume} from '../state/ducks/volumes.js'; import {createFakeVolumeMetadata, setUpFileManagerOnWindow, setupStore} from '../state/for_tests.js'; import {convertEntryToFileData} from '../state/reducers/all_entries.js'; -import {convertVolumeInfoAndMetadataToVolume, driveRootEntryListKey} from '../state/reducers/volumes.js'; import {getEmptyState, getEntry, getFileData, getStore} from '../state/store.js'; import {XfTree} from '../widgets/xf_tree.js';
diff --git a/ui/file_manager/file_manager/foreground/js/crostini_controller.js b/ui/file_manager/file_manager/foreground/js/crostini_controller.js index 5f9b0c67..aa08ba24 100644 --- a/ui/file_manager/file_manager/foreground/js/crostini_controller.js +++ b/ui/file_manager/file_manager/foreground/js/crostini_controller.js
@@ -9,7 +9,7 @@ import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; import {Crostini} from '../../externs/background/crostini.js'; import {addUiEntry, removeUiEntry} from '../../state/actions/ui_entries.js'; -import {crostiniPlaceHolderKey} from '../../state/reducers/volumes.js'; +import {crostiniPlaceHolderKey} from '../../state/ducks/volumes.js'; import {getStore} from '../../state/store.js'; import {constants} from './constants.js';
diff --git a/ui/file_manager/file_manager/foreground/js/empty_folder_controller.js b/ui/file_manager/file_manager/foreground/js/empty_folder_controller.js index 03a20ed..d610671 100644 --- a/ui/file_manager/file_manager/foreground/js/empty_folder_controller.js +++ b/ui/file_manager/file_manager/foreground/js/empty_folder_controller.js
@@ -10,7 +10,7 @@ import {FakeEntry} from '../../externs/files_app_entry_interfaces.js'; import {PropStatus} from '../../externs/ts/state.js'; import {VolumeInfo} from '../../externs/volume_info.js'; -import {updateIsInteractiveVolume} from '../../state/actions/volumes.js'; +import {updateIsInteractiveVolume} from '../../state/ducks/volumes.js'; import {getStore} from '../../state/store.js'; import {constants} from './constants.js';
diff --git a/ui/file_manager/file_manager/foreground/js/empty_folder_controller_unittest.js b/ui/file_manager/file_manager/foreground/js/empty_folder_controller_unittest.js index 5c8373ac..ced10d3b 100644 --- a/ui/file_manager/file_manager/foreground/js/empty_folder_controller_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/empty_folder_controller_unittest.js
@@ -17,8 +17,8 @@ import {VolumeInfo} from '../../externs/volume_info.js'; import {constants} from '../../foreground/js/constants.js'; import {clearSearch, updateSearch} from '../../state/ducks/search.js'; +import {convertVolumeInfoAndMetadataToVolume} from '../../state/ducks/volumes.js'; import {createFakeVolumeMetadata, setUpFileManagerOnWindow, setupStore} from '../../state/for_tests.js'; -import {convertVolumeInfoAndMetadataToVolume} from '../../state/reducers/volumes.js'; import {getEmptyState, getStore} from '../../state/store.js'; import {DirectoryModel} from './directory_model.js';
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager.js b/ui/file_manager/file_manager/foreground/js/file_manager.js index 296767f..8f41eb3 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager.js
@@ -32,12 +32,12 @@ import {ForegroundWindow} from '../../externs/foreground_window.js'; import {PropStatus} from '../../externs/ts/state.js'; import {Store} from '../../externs/ts/store.js'; -import {updateBulkPinProgress} from '../../state/actions/bulk_pinning.js'; import {updatePreferences} from '../../state/actions/preferences.js'; import {addUiEntry, removeUiEntry} from '../../state/actions/ui_entries.js'; +import {updateBulkPinProgress} from '../../state/ducks/bulk_pinning.js'; import {updateSearch} from '../../state/ducks/search.js'; +import {trashRootKey} from '../../state/ducks/volumes.js'; import {getMyFiles} from '../../state/reducers/all_entries.js'; -import {trashRootKey} from '../../state/reducers/volumes.js'; import {getEmptyState, getStore} from '../../state/store.js'; import {ActionsController} from './actions_controller.js';
diff --git a/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.js b/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.js index 6008ccee..a01c689 100644 --- a/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.js +++ b/ui/file_manager/file_manager/foreground/js/file_manager_commands_unittest.js
@@ -13,10 +13,9 @@ import {util} from '../../common/js/util.js'; import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; import {VolumeInfo} from '../../externs/volume_info.js'; -import {addVolume, updateIsInteractiveVolume} from '../../state/actions/volumes.js'; +import {addVolume, convertVolumeInfoAndMetadataToVolume, trashRootKey, updateIsInteractiveVolume} from '../../state/ducks/volumes.js'; +import {createMyFilesDataWithVolumeEntry} from '../../state/ducks/volumes_unittest.js'; import {createFakeVolumeMetadata, setUpFileManagerOnWindow, setupStore, waitDeepEquals} from '../../state/for_tests.js'; -import {convertVolumeInfoAndMetadataToVolume, trashRootKey} from '../../state/reducers/volumes.js'; -import {createMyFilesDataWithVolumeEntry} from '../../state/reducers/volumes_unittest.js'; import {CommandHandler} from './file_manager_commands.js';
diff --git a/ui/file_manager/file_manager/lib/base_store.ts b/ui/file_manager/file_manager/lib/base_store.ts index c09c5a4..6580750 100644 --- a/ui/file_manager/file_manager/lib/base_store.ts +++ b/ui/file_manager/file_manager/lib/base_store.ts
@@ -217,16 +217,15 @@ (state: StateType, payload: ActionType['payload']) => StateType; /** A map from actions to arrays of reducers. */ -export type ReducerMap<StateType, ActionType extends BaseAction> = +export type ReducersMap<StateType, ActionType extends BaseAction> = Map<ActionType['type'], Array<Reducer<StateType, ActionType>>>; /** * Creates action dispatchers for actions that are handled by a single reducer. */ export function addReducer<StateType, ActionType extends BaseAction>( - type: ActionType['type'], - reducer: Reducer<StateType, ActionType>, - reducerMap: ReducerMap<StateType, ActionType>) { + type: ActionType['type'], reducer: Reducer<StateType, ActionType>, + reducerMap: ReducersMap<StateType, ActionType>) { let reducerList = reducerMap.get(type); if (!reducerList) { reducerList = [];
diff --git a/ui/file_manager/file_manager/state/actions.ts b/ui/file_manager/file_manager/state/actions.ts index 9c457572..74571c2 100644 --- a/ui/file_manager/file_manager/state/actions.ts +++ b/ui/file_manager/file_manager/state/actions.ts
@@ -4,14 +4,14 @@ import {AddChildEntriesAction, ClearStaleCachedEntriesAction, UpdateMetadataAction} from './actions/all_entries.js'; import {AddAndroidAppsAction} from './actions/android_apps.js'; -import {UpdateBulkPinProgressAction} from './actions/bulk_pinning.js'; import {ChangeDirectoryAction, ChangeFileTasksAction, ChangeSelectionAction, UpdateDirectoryContentAction} from './actions/current_directory.js'; import {AddFolderShortcutAction, RefreshFolderShortcutAction, RemoveFolderShortcutAction} from './actions/folder_shortcuts.js'; import {RefreshNavigationRootsAction, UpdateNavigationEntryAction} from './actions/navigation.js'; import {UpdatePreferencesAction} from './actions/preferences.js'; import {AddUiEntryAction, RemoveUiEntryAction} from './actions/ui_entries.js'; -import {AddVolumeAction, RemoveVolumeAction, UpdateIsInteractiveVolumeAction} from './actions/volumes.js'; +import {UpdateBulkPinProgressAction} from './ducks/bulk_pinning.js'; import {SearchAction} from './ducks/search.js'; +import {AddVolumeAction, RemoveVolumeAction, UpdateIsInteractiveVolumeAction} from './ducks/volumes.js'; /** * Union of all types of Actions in Files app.
diff --git a/ui/file_manager/file_manager/state/actions/bulk_pinning.ts b/ui/file_manager/file_manager/state/actions/bulk_pinning.ts deleted file mode 100644 index 800fc7ba..0000000 --- a/ui/file_manager/file_manager/state/actions/bulk_pinning.ts +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {BaseAction} from '../../lib/base_store.js'; -import {ActionType} from '../actions.js'; - -/** - * Actions for Bulk Pinning. - * - * BulkPinProgress is the current state of files that are being pinned when the - * BulkPinning feature is enabled. During bulk pinning, all the users items in - * My drive are pinned and kept available offline. This tracks the progress of - * both the initial operation and any subsequent updates along with any error - * states that may occur. - */ - -/** Action to update the bulk pin progress to the store. */ -export interface UpdateBulkPinProgressAction extends BaseAction { - type: ActionType.UPDATE_BULK_PIN_PROGRESS; - payload: chrome.fileManagerPrivate.BulkPinProgress; -} - -/** Action factory to update the bulk pin progress to the store. */ -export function updateBulkPinProgress( - payload: UpdateBulkPinProgressAction['payload']): - UpdateBulkPinProgressAction { - return { - type: ActionType.UPDATE_BULK_PIN_PROGRESS, - payload, - }; -}
diff --git a/ui/file_manager/file_manager/state/actions/volumes.ts b/ui/file_manager/file_manager/state/actions/volumes.ts deleted file mode 100644 index 379268c4..0000000 --- a/ui/file_manager/file_manager/state/actions/volumes.ts +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -import {VolumeId} from '../../externs/ts/state.js'; -import {VolumeInfo} from '../../externs/volume_info.js'; -import {BaseAction} from '../../lib/base_store.js'; -import {ActionType} from '../actions.js'; - - -/** Action to add single volume into the store. */ -export interface AddVolumeAction extends BaseAction { - type: ActionType.ADD_VOLUME; - payload: { - volumeMetadata: chrome.fileManagerPrivate.VolumeMetadata, - volumeInfo: VolumeInfo, - }; -} - - -/** Action to remove single volume from the store. */ -export interface RemoveVolumeAction extends BaseAction { - type: ActionType.REMOVE_VOLUME; - payload: { - volumeId: VolumeId, - }; -} - -/** Action to update isInteractive for a volume in the store. */ -export interface UpdateIsInteractiveVolumeAction extends BaseAction { - type: ActionType.UPDATE_IS_INTERACTIVE_VOLUME; - payload: { - volumeId: VolumeId, - isInteractive: boolean, - }; -} - -/** Action factory to add single volume into the store. */ -export function addVolume( - {volumeMetadata, volumeInfo}: AddVolumeAction['payload']): AddVolumeAction { - return { - type: ActionType.ADD_VOLUME, - payload: { - volumeMetadata, - volumeInfo, - }, - }; -} - -/** Action factory to remove single volume from the store. */ -export function removeVolume({volumeId}: RemoveVolumeAction['payload']): - RemoveVolumeAction { - return { - type: ActionType.REMOVE_VOLUME, - payload: {volumeId}, - }; -} - -/** Action factory to update isInteractive for a volume in the store. */ -export function updateIsInteractiveVolume( - {volumeId, isInteractive}: UpdateIsInteractiveVolumeAction['payload']): - UpdateIsInteractiveVolumeAction { - return { - type: ActionType.UPDATE_IS_INTERACTIVE_VOLUME, - payload: { - volumeId, - isInteractive, - }, - }; -}
diff --git a/ui/file_manager/file_manager/state/ducks/bulk_pinning.ts b/ui/file_manager/file_manager/state/ducks/bulk_pinning.ts new file mode 100644 index 0000000..b8ecbc4 --- /dev/null +++ b/ui/file_manager/file_manager/state/ducks/bulk_pinning.ts
@@ -0,0 +1,41 @@ +// Copyright 2023 The Chromium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import {State} from '../../externs/ts/state.js'; +import {addReducer, BaseAction, Reducer, ReducersMap} from '../../lib/base_store.js'; +import {Action, ActionType} from '../actions.js'; + +/** + * Actions and reducers for Bulk Pinning. + * + * BulkPinProgress is the current state of files that are being pinned when the + * BulkPinning feature is enabled. During bulk pinning, all the users items in + * My drive are pinned and kept available offline. This tracks the progress of + * both the initial operation and any subsequent updates along with any error + * states that may occur. + * + * This file is checked via TS, so we suppress Closure checks. + * @suppress {checkTypes} + */ + +/** Map of actions to reducers for the bulk pinning slice. */ +export const bulkPinningReducersMap: ReducersMap<State, Action> = new Map(); + +/** Action to update the bulk pin progress to the store. */ +export interface UpdateBulkPinProgressAction extends BaseAction { + type: ActionType.UPDATE_BULK_PIN_PROGRESS; + payload: chrome.fileManagerPrivate.BulkPinProgress; +} + +const updateBulkPinningReducer = + (currentState: State, + bulkPinning: UpdateBulkPinProgressAction['payload']) => ({ + ...currentState, + bulkPinning, + }); + +/** Action factory to update the bulk pin progress to the store. */ +export const updateBulkPinProgress = addReducer( + ActionType.UPDATE_BULK_PIN_PROGRESS, + updateBulkPinningReducer as Reducer<State, Action>, bulkPinningReducersMap);
diff --git a/ui/file_manager/file_manager/state/reducers/bulk_pinning_unittest.ts b/ui/file_manager/file_manager/state/ducks/bulk_pinning_unittest.ts similarity index 95% rename from ui/file_manager/file_manager/state/reducers/bulk_pinning_unittest.ts rename to ui/file_manager/file_manager/state/ducks/bulk_pinning_unittest.ts index a2d6811..f6cf6521 100644 --- a/ui/file_manager/file_manager/state/reducers/bulk_pinning_unittest.ts +++ b/ui/file_manager/file_manager/state/ducks/bulk_pinning_unittest.ts
@@ -4,9 +4,10 @@ import {assertDeepEquals} from 'chrome://webui-test/chromeos/chai_assert.js'; -import {updateBulkPinProgress} from '../actions/bulk_pinning.js'; import {setupStore} from '../for_tests.js'; +import {updateBulkPinProgress} from './bulk_pinning.js'; + /** * Tests that bulk pin progress updates the store and overwrites existing values * on each update.
diff --git a/ui/file_manager/file_manager/state/ducks/search.ts b/ui/file_manager/file_manager/state/ducks/search.ts index df0f856..1abd33c6 100644 --- a/ui/file_manager/file_manager/state/ducks/search.ts +++ b/ui/file_manager/file_manager/state/ducks/search.ts
@@ -3,11 +3,11 @@ // found in the LICENSE file. import {SearchData, SearchLocation, SearchOptions, SearchRecency, State} from '../../externs/ts/state.js'; -import {addReducer, BaseAction, Reducer, ReducerMap as ReducersMap} from '../../lib/base_store.js'; +import {addReducer, BaseAction, Reducer, ReducersMap} from '../../lib/base_store.js'; import {Action, ActionType} from '../actions.js'; /** Map of actions to reducers for the search slice. */ -export const searchReducerMap: ReducersMap<State, Action> = new Map(); +export const searchReducersMap: ReducersMap<State, Action> = new Map(); /** * Helper function that does a deep comparison between two SearchOptions. @@ -71,7 +71,7 @@ const search = addReducer( ActionType.SEARCH, searchReducer as Reducer<State, Action>, - searchReducerMap); + searchReducersMap); /** * Generates a search action based on the supplied data.
diff --git a/ui/file_manager/file_manager/state/reducers/search_unittest.ts b/ui/file_manager/file_manager/state/ducks/search_unittest.ts similarity index 96% rename from ui/file_manager/file_manager/state/reducers/search_unittest.ts rename to ui/file_manager/file_manager/state/ducks/search_unittest.ts index fdaf8aa..c327764e 100644 --- a/ui/file_manager/file_manager/state/reducers/search_unittest.ts +++ b/ui/file_manager/file_manager/state/ducks/search_unittest.ts
@@ -2,10 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {assertDeepEquals, assertFalse, assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {PropStatus, SearchData, SearchLocation, SearchRecency} from '../../externs/ts/state.js'; -import {clearSearch, updateSearch} from '../ducks/search.js'; +import {clearSearch, updateSearch} from './search.js'; import {getEmptyState, getStore, Store} from '../store.js'; let store: Store;
diff --git a/ui/file_manager/file_manager/state/reducers/volumes.ts b/ui/file_manager/file_manager/state/ducks/volumes.ts similarity index 72% rename from ui/file_manager/file_manager/state/reducers/volumes.ts rename to ui/file_manager/file_manager/state/ducks/volumes.ts index 52cc2b62..0f5d5cc 100644 --- a/ui/file_manager/file_manager/state/reducers/volumes.ts +++ b/ui/file_manager/file_manager/state/ducks/volumes.ts
@@ -7,12 +7,15 @@ import {EntryList, VolumeEntry} from '../../common/js/files_app_entry_types.js'; import {util} from '../../common/js/util.js'; import {VolumeManagerCommon} from '../../common/js/volume_manager_types.js'; -import {PropStatus, State, Volume} from '../../externs/ts/state.js'; +import {PropStatus, State, Volume, VolumeId} from '../../externs/ts/state.js'; import {VolumeInfo} from '../../externs/volume_info.js'; -import {AddVolumeAction, RemoveVolumeAction, UpdateIsInteractiveVolumeAction} from '../actions/volumes.js'; +import {addReducer, BaseAction, Reducer, ReducersMap} from '../../lib/base_store.js'; +import {Action, ActionType} from '../actions.js'; +import {getMyFiles} from '../reducers/all_entries.js'; import {getEntry} from '../store.js'; -import {getMyFiles} from './all_entries.js'; +/** Map of actions to reducers for the volumes slice. */ +export const volumesReducersMap: ReducersMap<State, Action> = new Map(); const VolumeType = VolumeManagerCommon.VolumeType; export const myFilesEntryListKey = @@ -86,9 +89,19 @@ }; } -export function addVolume(currentState: State, action: AddVolumeAction): State { - const volumeMetadata = action.payload.volumeMetadata; - const volumeInfo = action.payload.volumeInfo; +/** Action to add single volume into the store. */ +export interface AddVolumeAction extends BaseAction { + type: ActionType.ADD_VOLUME; + payload: { + volumeMetadata: chrome.fileManagerPrivate.VolumeMetadata, + volumeInfo: VolumeInfo, + }; +} + +function addVolumeReducer( + currentState: State, payload: AddVolumeAction['payload']): State { + const volumeMetadata = payload.volumeMetadata; + const volumeInfo = payload.volumeInfo; if (!volumeInfo.fileSystem) { console.error( 'Only add to the store volumes that have successfully resolved.'); @@ -162,9 +175,22 @@ }; } -export function removeVolume( - currentState: State, action: RemoveVolumeAction): State { - delete currentState.volumes[action.payload.volumeId]; +export const addVolume = addReducer( + ActionType.ADD_VOLUME, addVolumeReducer as Reducer<State, Action>, + volumesReducersMap); + + +/** Action to remove single volume from the store. */ +export interface RemoveVolumeAction extends BaseAction { + type: ActionType.REMOVE_VOLUME; + payload: { + volumeId: VolumeId, + }; +} + +function removeVolumeReducer( + currentState: State, payload: RemoveVolumeAction['payload']): State { + delete currentState.volumes[payload.volumeId]; const volumes = { ...currentState.volumes, }; @@ -175,22 +201,42 @@ }; } -export function updateIsInteractiveVolume( - currentState: State, action: UpdateIsInteractiveVolumeAction): State { +export const removeVolume = addReducer( + ActionType.REMOVE_VOLUME, removeVolumeReducer as Reducer<State, Action>, + volumesReducersMap); + + +/** Action to update isInteractive for a volume in the store. */ +export interface UpdateIsInteractiveVolumeAction extends BaseAction { + type: ActionType.UPDATE_IS_INTERACTIVE_VOLUME; + payload: { + volumeId: VolumeId, + isInteractive: boolean, + }; +} + +function updateIsInteractiveVolumeReducer( + currentState: State, + payload: UpdateIsInteractiveVolumeAction['payload']): State { const volumes = { ...currentState.volumes, }; const updatedVolume = { - ...volumes[action.payload.volumeId], - isInteractive: action.payload.isInteractive, + ...volumes[payload.volumeId], + isInteractive: payload.isInteractive, }; return { ...currentState, volumes: { ...volumes, - [action.payload.volumeId]: updatedVolume, + [payload.volumeId]: updatedVolume, }, }; } + +export const updateIsInteractiveVolume = addReducer( + ActionType.UPDATE_IS_INTERACTIVE_VOLUME, + updateIsInteractiveVolumeReducer as Reducer<State, Action>, + volumesReducersMap);
diff --git a/ui/file_manager/file_manager/state/reducers/volumes_unittest.ts b/ui/file_manager/file_manager/state/ducks/volumes_unittest.ts similarity index 98% rename from ui/file_manager/file_manager/state/reducers/volumes_unittest.ts rename to ui/file_manager/file_manager/state/ducks/volumes_unittest.ts index 00aa22e..6d362dc 100644 --- a/ui/file_manager/file_manager/state/reducers/volumes_unittest.ts +++ b/ui/file_manager/file_manager/state/ducks/volumes_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {assertTrue} from 'chrome://webui-test/chromeos/chai_assert.js'; import {MockVolumeManager} from '../../background/js/mock_volume_manager.js'; @@ -12,12 +15,11 @@ import {FileData, State, Volume} from '../../externs/ts/state.js'; import {VolumeInfo} from '../../externs/volume_info.js'; import {constants} from '../../foreground/js/constants.js'; -import {addVolume, removeVolume, updateIsInteractiveVolume} from '../actions/volumes.js'; import {createFakeVolumeMetadata, setUpFileManagerOnWindow, setupStore, waitDeepEquals} from '../for_tests.js'; +import {convertEntryToFileData} from '../reducers/all_entries.js'; import {getEmptyState, getEntry} from '../store.js'; -import {convertEntryToFileData} from './all_entries.js'; -import {convertVolumeInfoAndMetadataToVolume, driveRootEntryListKey} from './volumes.js'; +import {addVolume, convertVolumeInfoAndMetadataToVolume, driveRootEntryListKey, removeVolume, updateIsInteractiveVolume} from './volumes.js'; export function setUp() { setUpFileManagerOnWindow();
diff --git a/ui/file_manager/file_manager/state/reducers/all_entries.ts b/ui/file_manager/file_manager/state/reducers/all_entries.ts index 1af3dccc..de1eb20 100644 --- a/ui/file_manager/file_manager/state/reducers/all_entries.ts +++ b/ui/file_manager/file_manager/state/reducers/all_entries.ts
@@ -15,10 +15,10 @@ import {MetadataItem} from '../../foreground/js/metadata/metadata_item.js'; import {Action, ActionType} from '../actions.js'; import {AddChildEntriesAction, ClearStaleCachedEntriesAction, UpdateMetadataAction} from '../actions/all_entries.js'; +import {driveRootEntryListKey, getVolumeTypesNestedInMyFiles, makeRemovableParentKey, myFilesEntryListKey, recentRootKey, removableGroupKey} from '../ducks/volumes.js'; import {getEntry, getFileData, getStore} from '../store.js'; import {hasDlpDisabledFiles} from './current_directory.js'; -import {driveRootEntryListKey, getVolumeTypesNestedInMyFiles, makeRemovableParentKey, myFilesEntryListKey, recentRootKey, removableGroupKey} from './volumes.js'; /** * Schedules the routine to remove stale entries from `allEntries`.
diff --git a/ui/file_manager/file_manager/state/reducers/all_entries_unittest.ts b/ui/file_manager/file_manager/state/reducers/all_entries_unittest.ts index eeb8a60..342ccec 100644 --- a/ui/file_manager/file_manager/state/reducers/all_entries_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/all_entries_unittest.ts
@@ -16,11 +16,11 @@ import {MockMetadataModel} from '../../foreground/js/metadata/mock_metadata.js'; import {ActionType} from '../actions.js'; import {addChildEntries, ClearStaleCachedEntriesAction} from '../actions/all_entries.js'; +import {convertVolumeInfoAndMetadataToVolume, myFilesEntryListKey} from '../ducks/volumes.js'; import {allEntriesSize, assertAllEntriesEqual, cd, changeSelection, createFakeVolumeMetadata, setUpFileManagerOnWindow, setupStore, updMetadata, waitDeepEquals} from '../for_tests.js'; import {getEmptyState, Store} from '../store.js'; import {clearCachedEntries, convertEntryToFileData, getMyFiles} from './all_entries.js'; -import {convertVolumeInfoAndMetadataToVolume, myFilesEntryListKey} from './volumes.js'; let store: Store; let fileSystem: MockFileSystem;
diff --git a/ui/file_manager/file_manager/state/reducers/android_apps_unittest.ts b/ui/file_manager/file_manager/state/reducers/android_apps_unittest.ts index 923fd4c..0c41351 100644 --- a/ui/file_manager/file_manager/state/reducers/android_apps_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/android_apps_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {State} from '../../externs/ts/state.js'; import {addAndroidApps} from '../actions/android_apps.js'; import {setupStore, waitDeepEquals} from '../for_tests.js';
diff --git a/ui/file_manager/file_manager/state/reducers/bulk_pinning.ts b/ui/file_manager/file_manager/state/reducers/bulk_pinning.ts deleted file mode 100644 index aef1ba2..0000000 --- a/ui/file_manager/file_manager/state/reducers/bulk_pinning.ts +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2023 The Chromium Authors -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Reducer for bulk pinning. - * - * This file is checked via TS, so we suppress Closure checks. - * @suppress {checkTypes} - */ - -import {State} from '../../externs/ts/state.js'; -import {UpdateBulkPinProgressAction} from '../actions/bulk_pinning.js'; - -export function updateBulkPinning( - currentState: State, action: UpdateBulkPinProgressAction): State { - const bulkPinning = action.payload; - - return { - ...currentState, - bulkPinning, - }; -}
diff --git a/ui/file_manager/file_manager/state/reducers/current_directory_unittest.ts b/ui/file_manager/file_manager/state/reducers/current_directory_unittest.ts index 4a5ff97d..0eaa56bd 100644 --- a/ui/file_manager/file_manager/state/reducers/current_directory_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/current_directory_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {assertEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {MockFileSystem} from '../../common/js/mock_entry.js';
diff --git a/ui/file_manager/file_manager/state/reducers/folder_shortcuts_unittest.ts b/ui/file_manager/file_manager/state/reducers/folder_shortcuts_unittest.ts index ef376df..985c3f50 100644 --- a/ui/file_manager/file_manager/state/reducers/folder_shortcuts_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/folder_shortcuts_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {MockFileSystem} from '../../common/js/mock_entry.js'; import {State} from '../../externs/ts/state.js'; import {addFolderShortcut, refreshFolderShortcut, removeFolderShortcut} from '../actions/folder_shortcuts.js';
diff --git a/ui/file_manager/file_manager/state/reducers/navigation.ts b/ui/file_manager/file_manager/state/reducers/navigation.ts index 8a50c2e..ac79341 100644 --- a/ui/file_manager/file_manager/state/reducers/navigation.ts +++ b/ui/file_manager/file_manager/state/reducers/navigation.ts
@@ -8,10 +8,10 @@ import {FilesAppEntry} from '../../externs/files_app_entry_interfaces.js'; import {NavigationKey, NavigationRoot, NavigationSection, NavigationType, State, Volume} from '../../externs/ts/state.js'; import {RefreshNavigationRootsAction, UpdateNavigationEntryAction} from '../actions/navigation.js'; +import {driveRootEntryListKey, recentRootKey, trashRootKey} from '../ducks/volumes.js'; import {getEntry, getFileData} from '../store.js'; import {getMyFiles} from './all_entries.js'; -import {driveRootEntryListKey, recentRootKey, trashRootKey} from './volumes.js'; const VolumeType = VolumeManagerCommon.VolumeType;
diff --git a/ui/file_manager/file_manager/state/reducers/navigation_unittest.ts b/ui/file_manager/file_manager/state/reducers/navigation_unittest.ts index 4460b57..0bef92a 100644 --- a/ui/file_manager/file_manager/state/reducers/navigation_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/navigation_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {MockVolumeManager} from '../../background/js/mock_volume_manager.js'; import {EntryList, FakeEntryImpl, VolumeEntry} from '../../common/js/files_app_entry_types.js'; import {MockFileEntry, MockFileSystem} from '../../common/js/mock_entry.js'; @@ -14,7 +17,7 @@ import {getEmptyState} from '../store.js'; import {convertEntryToFileData} from './all_entries.js'; -import {convertVolumeInfoAndMetadataToVolume, driveRootEntryListKey, myFilesEntryListKey, recentRootKey, trashRootKey} from './volumes.js'; +import {convertVolumeInfoAndMetadataToVolume, driveRootEntryListKey, myFilesEntryListKey, recentRootKey, trashRootKey} from '../ducks/volumes.js'; export function setUp() { setUpFileManagerOnWindow();
diff --git a/ui/file_manager/file_manager/state/reducers/preferences_unittest.ts b/ui/file_manager/file_manager/state/reducers/preferences_unittest.ts index 8013a6a..47aa46b 100644 --- a/ui/file_manager/file_manager/state/reducers/preferences_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/preferences_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {assertDeepEquals} from 'chrome://webui-test/chromeos/chai_assert.js'; import {updatePreferences} from '../actions/preferences.js';
diff --git a/ui/file_manager/file_manager/state/reducers/root.ts b/ui/file_manager/file_manager/state/reducers/root.ts index f2ca9f4..360198d 100644 --- a/ui/file_manager/file_manager/state/reducers/root.ts +++ b/ui/file_manager/file_manager/state/reducers/root.ts
@@ -4,20 +4,21 @@ import {State} from '../../externs/ts/state.js'; import {Action, ActionType} from '../actions.js'; -import {searchReducerMap as searchReducersMap} from '../ducks/search.js'; +import {bulkPinningReducersMap} from '../ducks/bulk_pinning.js'; +import {searchReducersMap} from '../ducks/search.js'; +import {volumesReducersMap} from '../ducks/volumes.js'; import {addChildEntries, cacheEntries, clearCachedEntries, updateMetadata} from './all_entries.js'; import {addAndroidApps} from './android_apps.js'; -import {updateBulkPinning} from './bulk_pinning.js'; import {changeDirectory, updateDirectoryContent, updateFileTasks, updateSelection} from './current_directory.js'; import {addFolderShortcut, refreshFolderShortcut, removeFolderShortcut} from './folder_shortcuts.js'; import {refreshNavigationRoots, updateNavigationEntry} from './navigation.js'; import {updatePreferences} from './preferences.js'; import {addUiEntry, removeUiEntry} from './ui_entries.js'; -import {addVolume, removeVolume, updateIsInteractiveVolume} from './volumes.js'; // Reducers map created from merging together each slice's exported reducersMap. -const rootReducersMap = new Map([...searchReducersMap]); +const rootReducersMap = new Map( + [...searchReducersMap, ...volumesReducersMap, ...bulkPinningReducersMap]); /** * Root reducer for the State for Files app. @@ -51,10 +52,6 @@ return updateDirectoryContent(state, action); case ActionType.UPDATE_METADATA: return updateMetadata(state, action); - case ActionType.ADD_VOLUME: - return addVolume(currentState, action); - case ActionType.REMOVE_VOLUME: - return removeVolume(currentState, action); case ActionType.REFRESH_NAVIGATION_ROOTS: return refreshNavigationRoots(currentState, action); case ActionType.UPDATE_NAVIGATION_ENTRY: @@ -73,12 +70,8 @@ return addAndroidApps(currentState, action); case ActionType.ADD_CHILD_ENTRIES: return addChildEntries(currentState, action); - case ActionType.UPDATE_BULK_PIN_PROGRESS: - return updateBulkPinning(currentState, action); case ActionType.UPDATE_PREFERENCES: return updatePreferences(currentState, action); - case ActionType.UPDATE_IS_INTERACTIVE_VOLUME: - return updateIsInteractiveVolume(currentState, action); default: // Handles ducks reducers. const reducers = rootReducersMap.get(action.type);
diff --git a/ui/file_manager/file_manager/state/reducers/ui_entries_unittest.ts b/ui/file_manager/file_manager/state/reducers/ui_entries_unittest.ts index e9b5644..a36ef624 100644 --- a/ui/file_manager/file_manager/state/reducers/ui_entries_unittest.ts +++ b/ui/file_manager/file_manager/state/reducers/ui_entries_unittest.ts
@@ -2,6 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +// TODO(b/296792757) +import '../store.js'; + import {assertEquals} from 'chrome://webui-test/chai_assert.js'; import {MockVolumeManager} from '../../background/js/mock_volume_manager.js'; @@ -15,7 +18,7 @@ import {getEmptyState} from '../store.js'; import {convertEntryToFileData} from './all_entries.js'; -import {convertVolumeInfoAndMetadataToVolume} from './volumes.js'; +import {convertVolumeInfoAndMetadataToVolume} from '../ducks/volumes.js'; export function setUp() { // sortEntries() from addUiEntry() reducer requires volumeManager and
diff --git a/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog.ts b/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog.ts index d8df37e..8d4da442 100644 --- a/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog.ts +++ b/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog.ts
@@ -66,16 +66,15 @@ new RateLimiter(() => this.updateListedFiles_(), 5000); private updateListedFiles_() { - const {bulkPinning} = this.store_.getState(); - if (bulkPinning?.listedFiles && - this.listedFiles_ !== bulkPinning!.listedFiles) { - this.listedFiles_ = bulkPinning!.listedFiles; - this.$listingFilesText_.innerText = this.listedFiles_ === 1 ? - str('BULK_PINNING_LISTING_WITH_SINGLE_ITEM') : - strf( - 'BULK_PINNING_LISTING_WITH_MULTIPLE_ITEMS', - this.listedFiles_.toLocaleString( - util.getCurrentLocaleOrDefault())); + if (this.listedFiles_ === 0) { + this.$listingFilesText_.innerText = str('BULK_PINNING_LISTING'); + } else if (this.listedFiles_ === 1) { + this.$listingFilesText_.innerText = + str('BULK_PINNING_LISTING_WITH_SINGLE_ITEM'); + } else { + this.$listingFilesText_.innerText = strf( + 'BULK_PINNING_LISTING_WITH_MULTIPLE_ITEMS', + this.listedFiles_.toLocaleString(util.getCurrentLocaleOrDefault())); } } @@ -103,8 +102,9 @@ util.bytesToString(this.freeBytes_)); } - if (bpp.stage === BulkPinStage.LISTING_FILES && + if (bpp.stage === BulkPinStage.LISTING_FILES && bpp.listedFiles > 0 && bpp.listedFiles !== this.listedFiles_) { + this.listedFiles_ = bpp.listedFiles; this.updateListedFilesDebounced_.run(); } @@ -188,6 +188,8 @@ private onClose(_: Event) { this.state = DialogState.CLOSED; + this.listedFiles_ = 0; + this.updateListedFilesDebounced_.runImmediately(); this.store_.unsubscribe(this); }
diff --git a/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog_unittest.ts b/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog_unittest.ts index 7626ab4..82874c2d3 100644 --- a/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog_unittest.ts +++ b/ui/file_manager/file_manager/widgets/xf_bulk_pinning_dialog_unittest.ts
@@ -7,7 +7,7 @@ import {mockUtilVisitURL} from '../common/js/mock_util.js'; import {waitForElementUpdate} from '../common/js/unittest_util.js'; -import {updateBulkPinProgress} from '../state/actions/bulk_pinning.js'; +import {updateBulkPinProgress} from '../state/ducks/bulk_pinning.js'; import {getEmptyState, getStore} from '../state/store.js'; import {BulkPinStage, XfBulkPinningDialog} from './xf_bulk_pinning_dialog.js';
diff --git a/ui/file_manager/file_names.gni b/ui/file_manager/file_names.gni index ca1f1fe1..2b2e7d81 100644 --- a/ui/file_manager/file_names.gni +++ b/ui/file_manager/file_names.gni
@@ -254,13 +254,11 @@ "file_manager/state/actions.ts", "file_manager/state/actions/all_entries.ts", "file_manager/state/actions/android_apps.ts", - "file_manager/state/actions/bulk_pinning.ts", "file_manager/state/actions/current_directory.ts", "file_manager/state/actions/folder_shortcuts.ts", "file_manager/state/actions/navigation.ts", "file_manager/state/actions/preferences.ts", "file_manager/state/actions/ui_entries.ts", - "file_manager/state/actions/volumes.ts", # ActionsProducers. "file_manager/state/actions_producers/all_entries.ts", @@ -270,16 +268,16 @@ "file_manager/state/reducers/root.ts", "file_manager/state/reducers/all_entries.ts", "file_manager/state/reducers/android_apps.ts", - "file_manager/state/reducers/bulk_pinning.ts", "file_manager/state/reducers/current_directory.ts", "file_manager/state/reducers/folder_shortcuts.ts", "file_manager/state/reducers/navigation.ts", "file_manager/state/reducers/preferences.ts", "file_manager/state/reducers/ui_entries.ts", - "file_manager/state/reducers/volumes.ts", # Ducks. + "file_manager/state/ducks/bulk_pinning.ts", "file_manager/state/ducks/search.ts", + "file_manager/state/ducks/volumes.ts", # Containers. "file_manager/containers/breadcrumb_container.ts", @@ -404,14 +402,16 @@ "file_manager/state/for_tests.ts", "file_manager/state/reducers/all_entries_unittest.ts", "file_manager/state/reducers/android_apps_unittest.ts", - "file_manager/state/reducers/bulk_pinning_unittest.ts", "file_manager/state/reducers/current_directory_unittest.ts", "file_manager/state/reducers/folder_shortcuts_unittest.ts", "file_manager/state/reducers/navigation_unittest.ts", "file_manager/state/reducers/preferences_unittest.ts", - "file_manager/state/reducers/search_unittest.ts", "file_manager/state/reducers/ui_entries_unittest.ts", - "file_manager/state/reducers/volumes_unittest.ts", + + # Ducks: + "file_manager/state/ducks/bulk_pinning_unittest.ts", + "file_manager/state/ducks/search_unittest.ts", + "file_manager/state/ducks/volumes_unittest.ts", # Widgets: "file_manager/widgets/xf_breadcrumb_unittest.ts",
diff --git a/ui/gfx/font_fallback_mac.mm b/ui/gfx/font_fallback_mac.mm index 5763e81..27d376f 100644 --- a/ui/gfx/font_fallback_mac.mm +++ b/ui/gfx/font_fallback_mac.mm
@@ -43,7 +43,7 @@ NSArray* languages = [NSUserDefaults.standardUserDefaults stringArrayForKey:@"AppleLanguages"]; CFArrayRef languages_cf = base::apple::NSToCFPtrCast(languages); - base::ScopedCFTypeRef<CFArrayRef> cascade_list( + base::apple::ScopedCFTypeRef<CFArrayRef> cascade_list( CTFontCopyDefaultCascadeListForLanguages(font.GetCTFont(), languages_cf)); std::vector<Font> fallback_fonts; @@ -55,7 +55,7 @@ CTFontDescriptorRef descriptor = base::apple::CFCastStrict<CTFontDescriptorRef>( CFArrayGetValueAtIndex(cascade_list, i)); - base::ScopedCFTypeRef<CTFontRef> fallback_font( + base::apple::ScopedCFTypeRef<CTFontRef> fallback_font( CTFontCreateWithFontDescriptor(descriptor, 0.0, nullptr)); if (fallback_font.get()) { fallback_fonts.emplace_back(fallback_font.get());
diff --git a/ui/gfx/hdr_metadata_mac.h b/ui/gfx/hdr_metadata_mac.h index efe0b277..1646476a 100644 --- a/ui/gfx/hdr_metadata_mac.h +++ b/ui/gfx/hdr_metadata_mac.h
@@ -18,14 +18,14 @@ // This can be used for rendering content using AVSampleBufferDisplayLayer via // the key kCVImageBufferContentLightLevelInfoKey or for rendering content using // a CAMetalLayer via CAEDRMetadata. -COLOR_SPACE_EXPORT base::ScopedCFTypeRef<CFDataRef> +COLOR_SPACE_EXPORT base::apple::ScopedCFTypeRef<CFDataRef> GenerateContentLightLevelInfo( const absl::optional<gfx::HDRMetadata>& hdr_metadata); // This can be used for rendering content using AVSampleBufferDisplayLayer via // the key kCVImageBufferMasteringDisplayColorVolumeKey or for rendering content // using a CAMetalLayer via CAEDRMetadata. -COLOR_SPACE_EXPORT base::ScopedCFTypeRef<CFDataRef> +COLOR_SPACE_EXPORT base::apple::ScopedCFTypeRef<CFDataRef> GenerateMasteringDisplayColorVolume( const absl::optional<gfx::HDRMetadata>& hdr_metadata);
diff --git a/ui/gfx/hdr_metadata_mac.mm b/ui/gfx/hdr_metadata_mac.mm index 16c5003..8eb3da5e 100644 --- a/ui/gfx/hdr_metadata_mac.mm +++ b/ui/gfx/hdr_metadata_mac.mm
@@ -9,12 +9,12 @@ namespace gfx { -base::ScopedCFTypeRef<CFDataRef> GenerateContentLightLevelInfo( +base::apple::ScopedCFTypeRef<CFDataRef> GenerateContentLightLevelInfo( const absl::optional<gfx::HDRMetadata>& hdr_metadata) { if (!hdr_metadata || !hdr_metadata->cta_861_3 || hdr_metadata->cta_861_3->max_content_light_level == 0.f || hdr_metadata->cta_861_3->max_frame_average_light_level == 0.f) { - return base::ScopedCFTypeRef<CFDataRef>(); + return base::apple::ScopedCFTypeRef<CFDataRef>(); } // This is a SMPTEST2086 Content Light Level Information box. @@ -31,11 +31,11 @@ sei.max_frame_average_light_level = __builtin_bswap16(hdr_metadata->cta_861_3->max_frame_average_light_level); - return base::ScopedCFTypeRef<CFDataRef>( + return base::apple::ScopedCFTypeRef<CFDataRef>( CFDataCreate(nullptr, reinterpret_cast<const UInt8*>(&sei), 4)); } -base::ScopedCFTypeRef<CFDataRef> GenerateMasteringDisplayColorVolume( +base::apple::ScopedCFTypeRef<CFDataRef> GenerateMasteringDisplayColorVolume( const absl::optional<gfx::HDRMetadata>& hdr_metadata) { // This is a SMPTEST2086 Mastering Display Color Volume box. struct MasteringDisplayColorVolumeSEI { @@ -78,7 +78,7 @@ sei.luminance_max = __builtin_bswap32(md->luminance_max + 0.5f); sei.luminance_min = __builtin_bswap32(md->luminance_min + 0.5f); - return base::ScopedCFTypeRef<CFDataRef>( + return base::apple::ScopedCFTypeRef<CFDataRef>( CFDataCreate(nullptr, reinterpret_cast<const UInt8*>(&sei), 24)); }
diff --git a/ui/gfx/image/image_ios.mm b/ui/gfx/image/image_ios.mm index cd2a69b2..62347bce0b 100644 --- a/ui/gfx/image/image_ios.mm +++ b/ui/gfx/image/image_ios.mm
@@ -25,9 +25,9 @@ // created from PNG data. Logs error as well. UIImage* CreateErrorUIImage(float scale) { LOG(ERROR) << "Unable to decode PNG into UIImage."; - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( nullptr, // Allow CG to allocate memory. 16, // width 16, // height @@ -38,7 +38,7 @@ static_cast<CGImageAlphaInfo>(kCGBitmapByteOrder32Host))); CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); CGContextFillRect(context, CGRectMake(0.0, 0.0, 16, 16)); - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGBitmapContextCreateImage(context)); return [UIImage imageWithCGImage:cg_image.get() scale:scale
diff --git a/ui/gfx/image/image_ios_unittest.mm b/ui/gfx/image/image_ios_unittest.mm index 3878fe8..1de68b9a 100644 --- a/ui/gfx/image/image_ios_unittest.mm +++ b/ui/gfx/image/image_ios_unittest.mm
@@ -22,9 +22,9 @@ // Create a UIImage directly from a CGImage in order to control the exact // pixel size of the underlying image. - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); - base::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( + base::apple::ScopedCFTypeRef<CGContextRef> context(CGBitmapContextCreate( NULL, target_size.width, target_size.height, 8, target_size.width * 4, color_space, kCGImageAlphaPremultipliedFirst | @@ -35,7 +35,7 @@ CGContextSetFillColorWithColor(context, [[UIColor redColor] CGColor]); CGContextFillRect(context, target_rect); - base::ScopedCFTypeRef<CGImageRef> cg_image( + base::apple::ScopedCFTypeRef<CGImageRef> cg_image( CGBitmapContextCreateImage(context)); return [UIImage imageWithCGImage:cg_image scale:scale
diff --git a/ui/gfx/image/image_skia_util_ios.mm b/ui/gfx/image/image_skia_util_ios.mm index 636a171b..d22b572 100644 --- a/ui/gfx/image/image_skia_util_ios.mm +++ b/ui/gfx/image/image_skia_util_ios.mm
@@ -48,7 +48,7 @@ return nil; float scale = image_skia_rep.scale(); - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); return skia::SkBitmapToUIImageWithColorSpace(image_skia_rep.GetBitmap(), scale, color_space);
diff --git a/ui/gfx/image/image_unittest.cc b/ui/gfx/image/image_unittest.cc index d456a80f..a76786b 100644 --- a/ui/gfx/image/image_unittest.cc +++ b/ui/gfx/image/image_unittest.cc
@@ -42,7 +42,8 @@ #if BUILDFLAG(IS_MAC) bool IsSystemColorSpaceSRGB() { CGColorSpaceRef color_space = base::mac::GetSystemColorSpace(); - base::ScopedCFTypeRef<CFStringRef> name(CGColorSpaceCopyName(color_space)); + base::apple::ScopedCFTypeRef<CFStringRef> name( + CGColorSpaceCopyName(color_space)); return name && CFStringCompare(name, kCGColorSpaceSRGB, 0) == kCFCompareEqualTo; }
diff --git a/ui/gfx/image/image_unittest_util.cc b/ui/gfx/image/image_unittest_util.cc index 10a17878..5e4e849a 100644 --- a/ui/gfx/image/image_unittest_util.cc +++ b/ui/gfx/image/image_unittest_util.cc
@@ -191,7 +191,7 @@ bitmap = CreateBitmap(size, size); } - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); UIImage* image = skia::SkBitmapToUIImageWithColorSpace(bitmap, scale, color_space);
diff --git a/ui/gfx/image/image_unittest_util_apple.mm b/ui/gfx/image/image_unittest_util_apple.mm index 53b95188..d32a7db 100644 --- a/ui/gfx/image/image_unittest_util_apple.mm +++ b/ui/gfx/image/image_unittest_util_apple.mm
@@ -34,20 +34,21 @@ #endif // Start by extracting the target pixel into a 1x1 CGImage. - base::ScopedCFTypeRef<CGImageRef> pixel_image(CGImageCreateWithImageInRect( - image_ref, target_pixel)); + base::apple::ScopedCFTypeRef<CGImageRef> pixel_image( + CGImageCreateWithImageInRect(image_ref, target_pixel)); // Draw that pixel into a 1x1 bitmap context. - base::ScopedCFTypeRef<CGColorSpaceRef> color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> color_space( CGColorSpaceCreateDeviceRGB()); - base::ScopedCFTypeRef<CGContextRef> bitmap_context(CGBitmapContextCreate( - /*data=*/nullptr, - /*width=*/1, - /*height=*/1, - /*bitsPerComponent=*/8, - /*bytesPerRow=*/4, color_space, - kCGImageAlphaPremultipliedFirst | - static_cast<CGImageAlphaInfo>(kCGBitmapByteOrder32Host))); + base::apple::ScopedCFTypeRef<CGContextRef> bitmap_context( + CGBitmapContextCreate( + /*data=*/nullptr, + /*width=*/1, + /*height=*/1, + /*bitsPerComponent=*/8, + /*bytesPerRow=*/4, color_space, + kCGImageAlphaPremultipliedFirst | + static_cast<CGImageAlphaInfo>(kCGBitmapByteOrder32Host))); CGContextDrawImage(bitmap_context, CGRectMake(0, 0, 1, 1), pixel_image); // The CGBitmapContext has the same memory layout as SkColor, so we can just
diff --git a/ui/gfx/mac/display_icc_profiles.cc b/ui/gfx/mac/display_icc_profiles.cc index bc88ef1..59c91821 100644 --- a/ui/gfx/mac/display_icc_profiles.cc +++ b/ui/gfx/mac/display_icc_profiles.cc
@@ -15,10 +15,10 @@ return profiles.get(); } -base::ScopedCFTypeRef<CFDataRef> DisplayICCProfiles::GetDataForColorSpace( - const ColorSpace& color_space) { +base::apple::ScopedCFTypeRef<CFDataRef> +DisplayICCProfiles::GetDataForColorSpace(const ColorSpace& color_space) { UpdateIfNeeded(); - base::ScopedCFTypeRef<CFDataRef> result; + base::apple::ScopedCFTypeRef<CFDataRef> result; auto found = map_.find(color_space); if (found != map_.end()) result = found->second; @@ -41,7 +41,7 @@ map_.clear(); // Always add Apple's sRGB profile. - base::ScopedCFTypeRef<CFDataRef> srgb_icc( + base::apple::ScopedCFTypeRef<CFDataRef> srgb_icc( CGColorSpaceCopyICCData(CGColorSpaceCreateWithName(kCGColorSpaceSRGB))); map_[ColorSpace::CreateSRGB()] = srgb_icc; @@ -61,11 +61,11 @@ return; for (uint32_t i = 0; i < display_count; ++i) { - base::ScopedCFTypeRef<CGColorSpaceRef> cg_color_space( + base::apple::ScopedCFTypeRef<CGColorSpaceRef> cg_color_space( CGDisplayCopyColorSpace(displays[i])); if (!cg_color_space) continue; - base::ScopedCFTypeRef<CFDataRef> icc_data( + base::apple::ScopedCFTypeRef<CFDataRef> icc_data( CGColorSpaceCopyICCData(cg_color_space)); if (!icc_data) continue;
diff --git a/ui/gfx/mac/display_icc_profiles.h b/ui/gfx/mac/display_icc_profiles.h index e6feec1d..e0e0d49 100644 --- a/ui/gfx/mac/display_icc_profiles.h +++ b/ui/gfx/mac/display_icc_profiles.h
@@ -36,7 +36,7 @@ DisplayICCProfiles& operator=(const DisplayICCProfiles&) = delete; // This will return null if |color_space| does not correspond to a display. - base::ScopedCFTypeRef<CFDataRef> GetDataForColorSpace( + base::apple::ScopedCFTypeRef<CFDataRef> GetDataForColorSpace( const ColorSpace& color_space); private: @@ -51,7 +51,7 @@ void UpdateIfNeeded(); - base::flat_map<ColorSpace, base::ScopedCFTypeRef<CFDataRef>> map_; + base::flat_map<ColorSpace, base::apple::ScopedCFTypeRef<CFDataRef>> map_; bool needs_update_ = true; };
diff --git a/ui/gfx/mac/io_surface.cc b/ui/gfx/mac/io_surface.cc index ba37732..af19d04e 100644 --- a/ui/gfx/mac/io_surface.cc +++ b/ui/gfx/mac/io_surface.cc
@@ -32,7 +32,7 @@ void AddIntegerValue(CFMutableDictionaryRef dictionary, const CFStringRef key, int32_t value) { - base::ScopedCFTypeRef<CFNumberRef> number( + base::apple::ScopedCFTypeRef<CFNumberRef> number( CFNumberCreate(nullptr, kCFNumberSInt32Type, &value)); CFDictionaryAddValue(dictionary, key, number.get()); } @@ -215,7 +215,7 @@ // Package it as a CFDataRef and send it to the IOSurface. std::vector<char> icc_profile_data = icc_profile.GetData(); - base::ScopedCFTypeRef<CFDataRef> cf_data_icc_profile(CFDataCreate( + base::apple::ScopedCFTypeRef<CFDataRef> cf_data_icc_profile(CFDataCreate( nullptr, reinterpret_cast<const UInt8*>(icc_profile_data.data()), icc_profile_data.size())); @@ -226,7 +226,7 @@ } // namespace internal -base::ScopedCFTypeRef<IOSurfaceRef> CreateIOSurface( +base::apple::ScopedCFTypeRef<IOSurfaceRef> CreateIOSurface( const gfx::Size& size, gfx::BufferFormat format, bool should_clear, @@ -234,7 +234,7 @@ TRACE_EVENT0("ui", "CreateIOSurface"); base::TimeTicks start_time = base::TimeTicks::Now(); - base::ScopedCFTypeRef<CFMutableDictionaryRef> properties( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> properties( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -249,7 +249,7 @@ // http://crbug.com/527556 size_t num_planes = gfx::NumberOfPlanesForLinearBufferFormat(format); if (num_planes > 1) { - base::ScopedCFTypeRef<CFMutableArrayRef> planes(CFArrayCreateMutable( + base::apple::ScopedCFTypeRef<CFMutableArrayRef> planes(CFArrayCreateMutable( kCFAllocatorDefault, num_planes, &kCFTypeArrayCallBacks)); size_t total_bytes_alloc = 0; for (size_t plane = 0; plane < num_planes; ++plane) { @@ -268,7 +268,7 @@ const size_t plane_offset = IOSurfaceAlignProperty(kIOSurfacePlaneOffset, total_bytes_alloc); - base::ScopedCFTypeRef<CFMutableDictionaryRef> plane_info( + base::apple::ScopedCFTypeRef<CFMutableDictionaryRef> plane_info( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); @@ -301,11 +301,12 @@ AddIntegerValue(properties, kIOSurfaceAllocSize, bytes_alloc); } - base::ScopedCFTypeRef<IOSurfaceRef> surface(IOSurfaceCreate(properties)); + base::apple::ScopedCFTypeRef<IOSurfaceRef> surface( + IOSurfaceCreate(properties)); if (!surface) { LOG(ERROR) << "Failed to allocate IOSurface of size " << size.ToString() << "."; - return base::ScopedCFTypeRef<IOSurfaceRef>(); + return base::apple::ScopedCFTypeRef<IOSurfaceRef>(); } if (should_clear) { @@ -337,9 +338,10 @@ } } -GFX_EXPORT base::ScopedCFTypeRef<IOSurfaceRef> IOSurfaceMachPortToIOSurface( +GFX_EXPORT base::apple::ScopedCFTypeRef<IOSurfaceRef> +IOSurfaceMachPortToIOSurface( ScopedRefCountedIOSurfaceMachPort io_surface_mach_port) { - base::ScopedCFTypeRef<IOSurfaceRef> io_surface; + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface; if (!io_surface_mach_port) { DLOG(ERROR) << "Invalid mach port."; return io_surface;
diff --git a/ui/gfx/mac/io_surface.h b/ui/gfx/mac/io_surface.h index 585091f..1a42e810 100644 --- a/ui/gfx/mac/io_surface.h +++ b/ui/gfx/mac/io_surface.h
@@ -52,7 +52,7 @@ // whereas for non-GL backends (Dawn and Metal) we want the formats to match. // TODO(sunnyps): Revisit this when we switch to ANGLE Metal completely since // wrapping RGBA_8888 can be implemented with Metal quite easily. -GFX_EXPORT base::ScopedCFTypeRef<IOSurfaceRef> CreateIOSurface( +GFX_EXPORT base::apple::ScopedCFTypeRef<IOSurfaceRef> CreateIOSurface( const Size& size, BufferFormat format, bool should_clear = true, @@ -68,15 +68,16 @@ // reference count of the right. On destruction, the reference count is // decremented. using ScopedRefCountedIOSurfaceMachPort = - base::ScopedTypeRef<mach_port_t, internal::IOSurfaceMachPortTraits>; + base::apple::ScopedTypeRef<mach_port_t, internal::IOSurfaceMachPortTraits>; // A scoper for holding a reference to an IOSurface and also incrementing its // in-use counter while the scoper exists. using ScopedInUseIOSurface = - base::ScopedTypeRef<IOSurfaceRef, internal::ScopedInUseIOSurfaceTraits>; + base::apple::ScopedTypeRef<IOSurfaceRef, + internal::ScopedInUseIOSurfaceTraits>; // A scoper for holding a reference to an IOSurface. -using ScopedIOSurface = base::ScopedCFTypeRef<IOSurfaceRef>; +using ScopedIOSurface = base::apple::ScopedCFTypeRef<IOSurfaceRef>; // Return true if there exists a value for IOSurfaceColorSpace or // IOSurfaceICCProfile that will make CoreAnimation render using |color_space|. @@ -94,7 +95,8 @@ bool override_rgba_to_bgra = true); // Return an IOSurface consuming |io_surface_mach_port|. -GFX_EXPORT base::ScopedCFTypeRef<IOSurfaceRef> IOSurfaceMachPortToIOSurface( +GFX_EXPORT base::apple::ScopedCFTypeRef<IOSurfaceRef> +IOSurfaceMachPortToIOSurface( ScopedRefCountedIOSurfaceMachPort io_surface_mach_port); } // namespace gfx
diff --git a/ui/gfx/mac/io_surface_unittest.cc b/ui/gfx/mac/io_surface_unittest.cc index 0d889c47d..c88de2fd 100644 --- a/ui/gfx/mac/io_surface_unittest.cc +++ b/ui/gfx/mac/io_surface_unittest.cc
@@ -10,7 +10,7 @@ namespace { TEST(IOSurface, OddSizeMultiPlanar) { - base::ScopedCFTypeRef<IOSurfaceRef> io_surface = + base::apple::ScopedCFTypeRef<IOSurfaceRef> io_surface = CreateIOSurface(gfx::Size(101, 99), gfx::BufferFormat::YUV_420_BIPLANAR); DCHECK(io_surface); // Plane sizes are rounded up.
diff --git a/ui/gfx/platform_font_mac.h b/ui/gfx/platform_font_mac.h index 6bd868cf..363968b 100644 --- a/ui/gfx/platform_font_mac.h +++ b/ui/gfx/platform_font_mac.h
@@ -89,13 +89,14 @@ void CalculateMetricsAndInitRenderParams(); // Returns a CTFontRef created with the passed-in specifications. - base::ScopedCFTypeRef<CTFontRef> CTFontWithSpec(FontSpec font_spec) const; + base::apple::ScopedCFTypeRef<CTFontRef> CTFontWithSpec( + FontSpec font_spec) const; // The CTFontRef instance for this object. If this object was constructed from // a CTFontRef instance, this holds that instance. Otherwise this instance is // constructed from the name, size, and style. If there is no active font that // matched those criteria a default font is used. - base::ScopedCFTypeRef<CTFontRef> ct_font_; + base::apple::ScopedCFTypeRef<CTFontRef> ct_font_; // If the font is a system font, and if so, what kind. const absl::optional<SystemFontType> system_font_type_;
diff --git a/ui/gfx/platform_font_mac.mm b/ui/gfx/platform_font_mac.mm index b51f376..342409c3 100644 --- a/ui/gfx/platform_font_mac.mm +++ b/ui/gfx/platform_font_mac.mm
@@ -94,7 +94,7 @@ {0.60, 1.0, Weight::BLACK}, // NSFontWeightBlack }; - base::ScopedCFTypeRef<CFDictionaryRef> traits(CTFontCopyTraits(font)); + base::apple::ScopedCFTypeRef<CFDictionaryRef> traits(CTFontCopyTraits(font)); DCHECK(traits); CFNumberRef cf_weight = base::apple::GetValueFromDictionary<CFNumberRef>( traits, kCTFontWeightTrait); @@ -243,7 +243,7 @@ // the provided font. // // TODO(avi, etienneb): Figure out this font stuff. - base::ScopedCFTypeRef<CTFontDescriptorRef> descriptor( + base::apple::ScopedCFTypeRef<CTFontDescriptorRef> descriptor( CTFontCopyFontDescriptor(font)); if (CTFontDescriptorIsSystemUIFont(descriptor.get())) { // Assume it's the standard system font. The fact that this much is known is @@ -352,7 +352,7 @@ base::apple::NSToCFPtrCast(derived), SystemFontType::kToolTip, {font_spec_.name, font_spec_.size + size_delta, style, weight})); } else { - base::ScopedCFTypeRef<CTFontRef> derived = CTFontWithSpec( + base::apple::ScopedCFTypeRef<CTFontRef> derived = CTFontWithSpec( {font_spec_.name, font_spec_.size + size_delta, style, weight}); return Font(new PlatformFontMac( derived, absl::nullopt, @@ -484,7 +484,7 @@ render_params_ = gfx::GetFontRenderParams(query, nullptr); } -base::ScopedCFTypeRef<CTFontRef> PlatformFontMac::CTFontWithSpec( +base::apple::ScopedCFTypeRef<CTFontRef> PlatformFontMac::CTFontWithSpec( FontSpec font_spec) const { // One might think that a font descriptor with the NSFontWeightTrait/ // kCTFontWeightTrait trait could be used to look up a font with a specific @@ -509,7 +509,7 @@ weight:ToNSFontManagerWeight(font_spec.weight) size:font_spec.size]; if (font) { - return base::ScopedCFTypeRef<CTFontRef>( + return base::apple::ScopedCFTypeRef<CTFontRef>( base::apple::NSToCFOwnershipCast(font)); } @@ -531,7 +531,7 @@ font = [NSFont fontWithDescriptor:descriptor size:font_spec.size]; if (font) { - return base::ScopedCFTypeRef<CTFontRef>( + return base::apple::ScopedCFTypeRef<CTFontRef>( base::apple::NSToCFOwnershipCast(font)); } @@ -540,7 +540,7 @@ font = [NSFont systemFontOfSize:font_spec.size weight:ToNSFontWeight(font_spec.weight)]; font = [font_manager convertFont:font toHaveTrait:traits]; - return base::ScopedCFTypeRef<CTFontRef>( + return base::apple::ScopedCFTypeRef<CTFontRef>( base::apple::NSToCFOwnershipCast(font)); }
diff --git a/ui/gfx/platform_font_mac_unittest.mm b/ui/gfx/platform_font_mac_unittest.mm index ae53a18b..a728fd1 100644 --- a/ui/gfx/platform_font_mac_unittest.mm +++ b/ui/gfx/platform_font_mac_unittest.mm
@@ -42,7 +42,7 @@ // |weight_tri| is either -1, 0, or 1 meaning "light", "normal", or "bold". auto CheckExpected = [GetValueFromDictionaryAndWorkAroundMacOS13Bug]( const Font& font, int weight_tri, bool isItalic) { - base::ScopedCFTypeRef<CFDictionaryRef> traits( + base::apple::ScopedCFTypeRef<CFDictionaryRef> traits( CTFontCopyTraits(font.GetCTFont())); DCHECK(traits);
diff --git a/ui/native_theme/caption_style_mac.mm b/ui/native_theme/caption_style_mac.mm index 2144161..a1c195e 100644 --- a/ui/native_theme/caption_style_mac.mm +++ b/ui/native_theme/caption_style_mac.mm
@@ -46,7 +46,7 @@ std::string GetMAForegroundColorAndOpacityAsCSSColor() { MACaptionAppearanceBehavior behavior; - base::ScopedCFTypeRef<CGColorRef> cg_color( + base::apple::ScopedCFTypeRef<CGColorRef> cg_color( MACaptionAppearanceCopyForegroundColor(kUserDomain, &behavior)); bool important = behavior == kMACaptionAppearanceBehaviorUseValue; float opacity = @@ -61,7 +61,7 @@ std::string GetMABackgroundColorAndOpacityAsCSSColor() { MACaptionAppearanceBehavior behavior; - base::ScopedCFTypeRef<CGColorRef> cg_color( + base::apple::ScopedCFTypeRef<CGColorRef> cg_color( MACaptionAppearanceCopyBackgroundColor(kUserDomain, &behavior)); bool important = behavior == kMACaptionAppearanceBehaviorUseValue; float opacity = @@ -127,17 +127,17 @@ // each font face to be used in WebVTT captions, which is not implemented here. void GetMAFontAsCSSFontSpecifiers(std::string* font_family, std::string* font_variant) { - base::ScopedCFTypeRef<CTFontDescriptorRef> ct_font_desc( + base::apple::ScopedCFTypeRef<CTFontDescriptorRef> ct_font_desc( MACaptionAppearanceCopyFontDescriptorForStyle( kUserDomain, nullptr, kMACaptionAppearanceFontStyleDefault)); - base::ScopedCFTypeRef<CFStringRef> ct_font_family_name( + base::apple::ScopedCFTypeRef<CFStringRef> ct_font_family_name( base::apple::CFCast<CFStringRef>(CTFontDescriptorCopyAttribute( ct_font_desc, kCTFontFamilyNameAttribute))); if (ct_font_family_name) *font_family = base::SysCFStringRefToUTF8(ct_font_family_name); - base::ScopedCFTypeRef<CFStringRef> ct_font_face_name( + base::apple::ScopedCFTypeRef<CFStringRef> ct_font_face_name( base::apple::CFCast<CFStringRef>( CTFontDescriptorCopyAttribute(ct_font_desc, kCTFontNameAttribute))); if (ct_font_face_name) @@ -146,7 +146,7 @@ std::string GetMAWindowColorAsCSSColor() { MACaptionAppearanceBehavior behavior; - base::ScopedCFTypeRef<CGColorRef> cg_color( + base::apple::ScopedCFTypeRef<CGColorRef> cg_color( MACaptionAppearanceCopyWindowColor(kUserDomain, &behavior)); bool important = behavior == kMACaptionAppearanceBehaviorUseValue; float opacity = MACaptionAppearanceGetWindowOpacity(kUserDomain, &behavior);
diff --git a/ui/snapshot/snapshot_mac.mm b/ui/snapshot/snapshot_mac.mm index 9ac8dce..459a2e56 100644 --- a/ui/snapshot/snapshot_mac.mm +++ b/ui/snapshot/snapshot_mac.mm
@@ -40,9 +40,10 @@ DCHECK_LE(screen_snapshot_bounds.right(), view_bounds.right()); DCHECK_LE(screen_snapshot_bounds.bottom(), view_bounds.bottom()); - base::ScopedCFTypeRef<CGImageRef> windowSnapshot(CGWindowListCreateImage( - screen_snapshot_bounds.ToCGRect(), kCGWindowListOptionIncludingWindow, - window.windowNumber, kCGWindowImageBoundsIgnoreFraming)); + base::apple::ScopedCFTypeRef<CGImageRef> windowSnapshot( + CGWindowListCreateImage( + screen_snapshot_bounds.ToCGRect(), kCGWindowListOptionIncludingWindow, + window.windowNumber, kCGWindowImageBoundsIgnoreFraming)); if (CGImageGetWidth(windowSnapshot) <= 0) return false;
diff --git a/ui/views/style/platform_style_mac.mm b/ui/views/style/platform_style_mac.mm index 753e5b2..5036a02 100644 --- a/ui/views/style/platform_style_mac.mm +++ b/ui/views/style/platform_style_mac.mm
@@ -70,9 +70,10 @@ if (cursor_position == 0) return gfx::Range(); - base::ScopedCFTypeRef<CFStringRef> cf_string(CFStringCreateWithCharacters( - kCFAllocatorDefault, reinterpret_cast<const UniChar*>(text.data()), - base::checked_cast<CFIndex>(text.size()))); + base::apple::ScopedCFTypeRef<CFStringRef> cf_string( + CFStringCreateWithCharacters( + kCFAllocatorDefault, reinterpret_cast<const UniChar*>(text.data()), + base::checked_cast<CFIndex>(text.size()))); CFRange range_to_delete = CFStringGetRangeOfCharacterClusterAtIndex( cf_string, base::checked_cast<CFIndex>(cursor_position - 1), kCFStringBackwardDeletionCluster);