fml: Use CFRef where possible and add docs (flutter/engine#56436)

Document where CFRef takes over or hands back ownership of the underlying CoreFoundation object memory.

Migrates manual CoreFoundation object management to CFRef in:
* impeller/golden_tests/metal_screenshot.mm
* shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.mm
* shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.mm
* shell/platform/darwin/ios/framework/Source/FlutterView.mm
* shell/platform/darwin/macos/framework/Source/FlutterSurface.mm

Adds a `Retain()` method to take shared ownership of the underlying object, as opposed to Reset, where ownership is transferred to the CFRef wrapper.

Adds a `Get()` method to make dealing with bridged Objective-C casts more convenient:
```objc
  fml::CFRef<CFStringRef> cfString(...);
  NSString* aString = (__bridge NSString*)cfString.Get();
```
as opposed to:
```objc
  fml::CFRef<CFStringRef> cfString(...);
  NSString* aString = (__bridge NSString*)static_cast<CFStringRef>(cfString);
```

I considered making use of `fml::scoped_policy::OwnershipPolicy` to add a second parameter to the ctor and `Reset` but, but I think documentation and addition of a `Retain()` method makes things a little clearer at the call site. It's also more consistent with `sk_cfp`, which we use in some Skia bits of the codebase.

[C++, Objective-C, Java style guides]: https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style
This commit is contained in:
Chris Bracken
2024-11-08 12:55:23 -08:00
committed by GitHub
parent efe78cfd00
commit 88185e0b3e
10 changed files with 141 additions and 59 deletions

View File

@@ -11,53 +11,103 @@
namespace fml {
/// Default retain and release implementations for CFRef.
template <typename T>
struct CFRefTraits {
static void Retain(T instance) { CFRetain(instance); }
static void Release(T instance) { CFRelease(instance); }
};
/// RAII-based smart pointer wrapper for CoreFoundation objects.
///
/// CFRef takes over ownership of the object it wraps and ensures that retain
/// and release are called as appropriate on creation, assignment, and disposal.
template <class T>
class CFRef {
public:
/// Creates a new null CFRef.
CFRef() : instance_(nullptr) {}
// NOLINTNEXTLINE(google-explicit-constructor)
CFRef(T instance) : instance_(instance) {}
/// Takes over ownership of `instance`, which is expected to be already
/// retained.
explicit CFRef(T instance) : instance_(instance) {}
/// Copy ctor: Creates a retained copy of the CoreFoundation object owned by
/// `other`.
CFRef(const CFRef& other) : instance_(other.instance_) {
if (instance_) {
CFRetain(instance_);
CFRefTraits<T>::Retain(instance_);
}
}
/// Move ctor: Takes over ownership of the CoreFoundation object owned
/// by `other`. The object owned by `other` is set to null.
CFRef(CFRef&& other) : instance_(other.instance_) {
other.instance_ = nullptr;
}
/// Takes over ownership of the CoreFoundation object owned by `other`.
CFRef& operator=(CFRef&& other) {
Reset(other.Release());
return *this;
}
/// Releases the underlying CoreFoundation object, if non-null.
~CFRef() {
if (instance_ != nullptr) {
CFRelease(instance_);
if (instance_) {
CFRefTraits<T>::Release(instance_);
}
instance_ = nullptr;
}
/// Takes over ownership of `instance`, null by default. The object is
/// expected to be already retained if non-null.
///
/// Releases the previous object, if non-null.
void Reset(T instance = nullptr) {
if (instance_ != nullptr) {
CFRelease(instance_);
if (instance_) {
CFRefTraits<T>::Release(instance_);
}
instance_ = instance;
}
/// Retains a shared copy of `instance`. The previous object is released if
/// non-null. Has no effect if `instance` is the currently-held object.
void Retain(T instance = nullptr) {
if (instance_ == instance) {
return;
}
if (instance) {
CFRefTraits<T>::Retain(instance);
}
Reset(instance);
}
/// Returns and transfers ownership of the underlying CoreFoundation object
/// to the caller. The caller is responsible for calling `CFRelease` when done
/// with the object.
[[nodiscard]] T Release() {
auto instance = instance_;
instance_ = nullptr;
return instance;
}
/// Returns the underlying CoreFoundation object. Ownership of the returned
/// object follows The Get Rule.
///
/// See:
/// https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-SW1
T Get() const { return instance_; }
/// Returns the underlying CoreFoundation object. Ownership of the returned
/// object follows The Get Rule.
///
/// See:
/// https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html#//apple_ref/doc/uid/20001148-SW1
// NOLINTNEXTLINE(google-explicit-constructor)
operator T() const { return instance_; }
/// Returns true if the underlying CoreFoundation object is non-null.
explicit operator bool() const { return instance_ != nullptr; }
private:

View File

@@ -60,5 +60,28 @@ TEST(CFTest, CanCreateRefs) {
}
}
TEST(CFTest, GetReturnsUnderlyingObject) {
CFMutableStringRef cf_string = CFStringCreateMutable(kCFAllocatorDefault, 100u);
const CFIndex ref_count_before = CFGetRetainCount(cf_string);
CFRef<CFMutableStringRef> string_ref(cf_string);
CFMutableStringRef returned_string = string_ref.Get();
const CFIndex ref_count_after = CFGetRetainCount(cf_string);
EXPECT_EQ(cf_string, returned_string);
EXPECT_EQ(ref_count_before, ref_count_after);
}
TEST(CFTest, RetainSharesOwnership) {
CFMutableStringRef cf_string = CFStringCreateMutable(kCFAllocatorDefault, 100u);
const CFIndex ref_count_before = CFGetRetainCount(cf_string);
CFRef<CFMutableStringRef> string_ref;
string_ref.Retain(cf_string);
const CFIndex ref_count_after = CFGetRetainCount(cf_string);
EXPECT_EQ(cf_string, string_ref);
EXPECT_EQ(ref_count_before + 1u, ref_count_after);
}
} // namespace testing
} // namespace fml

View File

@@ -67,6 +67,7 @@ if (is_mac) {
deps = [
":screenshot",
"//flutter/display_list",
"//flutter/fml",
"//flutter/impeller/display_list",
"//flutter/impeller/playground",
"//flutter/impeller/renderer/backend/metal:metal",

View File

@@ -11,6 +11,19 @@
#include <CoreImage/CoreImage.h>
#include <string>
#include "flutter/fml/platform/darwin/cf_utils.h"
namespace fml {
/// Default retain and release implementations for CGImageRef.
template <>
struct CFRefTraits<CGImageRef> {
static void Retain(CGImageRef instance) { CGImageRetain(instance); }
static void Release(CGImageRef instance) { CGImageRelease(instance); }
};
} // namespace fml
namespace impeller {
namespace testing {
@@ -35,8 +48,8 @@ class MetalScreenshot : public Screenshot {
MetalScreenshot(const MetalScreenshot&) = delete;
MetalScreenshot& operator=(const MetalScreenshot&) = delete;
CGImageRef cg_image_;
CFDataRef pixel_data_;
fml::CFRef<CGImageRef> cg_image_;
fml::CFRef<CFDataRef> pixel_data_;
};
} // namespace testing
} // namespace impeller

View File

@@ -9,13 +9,10 @@ namespace testing {
MetalScreenshot::MetalScreenshot(CGImageRef cgImage) : cg_image_(cgImage) {
CGDataProviderRef data_provider = CGImageGetDataProvider(cgImage);
pixel_data_ = CGDataProviderCopyData(data_provider);
pixel_data_.Reset(CGDataProviderCopyData(data_provider));
}
MetalScreenshot::~MetalScreenshot() {
CFRelease(pixel_data_);
CGImageRelease(cg_image_);
}
MetalScreenshot::~MetalScreenshot() = default;
const uint8_t* MetalScreenshot::GetBytes() const {
return CFDataGetBytePtr(pixel_data_);
@@ -37,17 +34,15 @@ bool MetalScreenshot::WriteToPNG(const std::string& path) const {
bool result = false;
NSURL* output_url =
[NSURL fileURLWithPath:[NSString stringWithUTF8String:path.c_str()]];
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(
(__bridge CFURLRef)output_url, kUTTypePNG, 1, nullptr);
if (destination != nullptr) {
fml::CFRef<CGImageDestinationRef> destination(CGImageDestinationCreateWithURL(
(__bridge CFURLRef)output_url, kUTTypePNG, 1, nullptr));
if (destination) {
CGImageDestinationAddImage(destination, cg_image_,
(__bridge CFDictionaryRef) @{});
if (CGImageDestinationFinalize(destination)) {
result = true;
}
CFRelease(destination);
}
return result;
}

View File

@@ -8,6 +8,7 @@
#include "flutter/common/graphics/persistent_cache.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#include "flutter/shell/common/context_options.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#include "third_party/skia/include/gpu/ganesh/GrDirectContext.h"
@@ -16,7 +17,9 @@
FLUTTER_ASSERT_ARC
@implementation FlutterDarwinContextMetalSkia
@implementation FlutterDarwinContextMetalSkia {
fml::CFRef<CVMetalTextureCacheRef> _textureCache;
}
- (instancetype)initWithDefaultMTLDevice {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
@@ -43,15 +46,19 @@ FLUTTER_ASSERT_ARC
[_commandQueue setLabel:@"Flutter Main Queue"];
CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator
nil, // cache attributes (nil default)
_device, // metal device
nil, // texture attributes (nil default)
&_textureCache // [out] cache
);
if (cvReturn != kCVReturnSuccess) {
FML_DLOG(ERROR) << "Could not create Metal texture cache.";
return nil;
{
CVMetalTextureCacheRef cache = nullptr;
CVReturn cvReturn = CVMetalTextureCacheCreate(kCFAllocatorDefault, // allocator
nil, // cache attributes (nil default)
_device, // metal device
nil, // texture attributes (nil default)
&cache // [out] cache
);
_textureCache.Reset(cache);
if (cvReturn != kCVReturnSuccess) {
FML_DLOG(ERROR) << "Could not create Metal texture cache.";
return nil;
}
}
// The devices are in the same "sharegroup" because they share the same device and command
@@ -96,12 +103,6 @@ FLUTTER_ASSERT_ARC
return GrDirectContexts::MakeMetal(backendContext, contextOptions);
}
- (void)dealloc {
if (_textureCache) {
CFRelease(_textureCache);
}
}
- (FlutterDarwinExternalTextureMetal*)
createExternalTextureWithIdentifier:(int64_t)textureID
texture:(NSObject<FlutterTexture>*)texture {
@@ -111,6 +112,10 @@ FLUTTER_ASSERT_ARC
enableImpeller:NO];
}
- (CVMetalTextureCacheRef)textureCache {
return _textureCache;
}
@end
#endif // !SLIMPELLER

View File

@@ -3,7 +3,9 @@
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h"
#include "flutter/display_list/image/dl_image.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#include "impeller/base/validation.h"
#include "impeller/display_list/aiks_context.h"
#include "impeller/display_list/dl_image_impeller.h"
@@ -23,7 +25,7 @@
FLUTTER_ASSERT_ARC
@implementation FlutterDarwinExternalTextureMetal {
CVMetalTextureCacheRef _textureCache;
fml::CFRef<CVMetalTextureCacheRef> _textureCache;
NSObject<FlutterTexture>* _externalTexture;
BOOL _textureFrameAvailable;
sk_sp<flutter::DlImage> _externalImage;
@@ -37,8 +39,7 @@ FLUTTER_ASSERT_ARC
texture:(NSObject<FlutterTexture>*)texture
enableImpeller:(BOOL)enableImpeller {
if (self = [super init]) {
_textureCache = textureCache;
CFRetain(_textureCache);
_textureCache.Retain(textureCache);
_textureID = textureID;
_externalTexture = texture;
_enableImpeller = enableImpeller;
@@ -50,10 +51,7 @@ FLUTTER_ASSERT_ARC
- (void)dealloc {
CVPixelBufferRelease(_lastPixelBuffer);
if (_textureCache) {
CVMetalTextureCacheFlush(_textureCache, // cache
0 // options (must be zero)
);
CFRelease(_textureCache);
CVMetalTextureCacheFlush(_textureCache, /* options (must be zero) */ 0);
}
}
@@ -107,9 +105,9 @@ FLUTTER_ASSERT_ARC
// buffer will be used to materialize the image in case the application fails to provide a new
// one.
_externalImage.reset();
CVMetalTextureCacheFlush(_textureCache, // cache
0 // options (must be zero)
);
if (_textureCache) {
CVMetalTextureCacheFlush(_textureCache, /* options (must be zero) */ 0);
}
}
- (void)markNewFrameAvailable {

View File

@@ -3,9 +3,9 @@
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h"
#include "flutter/fml/platform/darwin/cf_utils.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h"
FLUTTER_ASSERT_ARC
@@ -107,9 +107,8 @@ static void PrintWideGamutWarningOnce() {
layer.framebufferOnly = flutter::Settings::kSurfaceDataAccessible ? NO : YES;
BOOL isWideGamutSupported = self.isWideGamutSupported;
if (_isWideGamutEnabled && isWideGamutSupported) {
CGColorSpaceRef srgb = CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB);
fml::CFRef<CGColorSpaceRef> srgb(CGColorSpaceCreateWithName(kCGColorSpaceExtendedSRGB));
layer.colorspace = srgb;
CFRelease(srgb);
layer.pixelFormat = MTLPixelFormatBGRA10_XR;
} else if (_isWideGamutEnabled && !isWideGamutSupported) {
PrintWideGamutWarningOnce();

View File

@@ -6,9 +6,11 @@
#import <Metal/Metal.h>
#import "flutter/fml/platform/darwin/cf_utils.h"
@interface FlutterSurface () {
CGSize _size;
IOSurfaceRef _ioSurface;
fml::CFRef<IOSurfaceRef> _ioSurface;
id<MTLTexture> _texture;
// Used for testing.
BOOL _isInUseOverride;
@@ -44,7 +46,7 @@
- (instancetype)initWithSize:(CGSize)size device:(id<MTLDevice>)device {
if (self = [super init]) {
self->_size = size;
self->_ioSurface = [FlutterSurface createIOSurfaceWithSize:size];
self->_ioSurface.Reset([FlutterSurface createIOSurfaceWithSize:size]);
self->_texture = [FlutterSurface createTextureForIOSurface:_ioSurface size:size device:device];
}
return self;
@@ -71,10 +73,6 @@ static void ReleaseSurface(void* surface) {
return (__bridge FlutterSurface*)texture->user_data;
}
- (void)dealloc {
CFRelease(_ioSurface);
}
+ (IOSurfaceRef)createIOSurfaceWithSize:(CGSize)size {
unsigned pixelFormat = 'BGRA';
unsigned bytesPerElement = 4;

View File

@@ -1023,14 +1023,14 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
// Test for pan events.
// Start gesture.
fml::CFRef<CGEventRef> cgEventStart =
CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0);
fml::CFRef<CGEventRef> cgEventStart(
CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0));
CGEventSetType(cgEventStart, kCGEventScrollWheel);
CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventScrollPhase, kCGScrollPhaseBegan);
CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventIsContinuous, 1);
[viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventStart]];
fml::CFRef<CGEventRef> cgEventUpdate = CGEventCreateCopy(cgEventStart);
fml::CFRef<CGEventRef> cgEventUpdate(CGEventCreateCopy(cgEventStart));
CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventScrollPhase, kCGScrollPhaseChanged);
CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis2, 1); // pan_x
CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis1, 2); // pan_y
@@ -1041,7 +1041,7 @@ TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) {
[viewController mouseExited:mouseEvent];
// End gesture.
fml::CFRef<CGEventRef> cgEventEnd = CGEventCreateCopy(cgEventStart);
fml::CFRef<CGEventRef> cgEventEnd(CGEventCreateCopy(cgEventStart));
CGEventSetIntegerValueField(cgEventEnd, kCGScrollWheelEventScrollPhase, kCGScrollPhaseEnded);
[viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventEnd]];