[ios] making objective-C smart pointers support ARC (flutter/engine#47612)

Moving the implementation from https://codereview.chromium.org/1855483004 into the code base, including:

- scoped_nsobject, scoped_nsprotocol, scoped_block will support both mrc and arc
- Added parent class scoped_typeref for shared code between scoped_block and scoped_nsobject
- moving OwnershipPolicy to its own file

The implementation of the smart pointers are almost identical to https://codereview.chromium.org/1855483004 besides some syntax preference differences between chromium and flutter.

This PR also migrated [VsyncWaiterIosTest.mm](https://github.com/flutter/engine/pull/47612/files#diff-c98ce1a2aca65c29bbc444523b66921a53ecce5ff39a420b4eda7dbfe8ca1cc7) to ARC with scoped_nsobject

fixes https://github.com/flutter/flutter/issues/137802

[C++, Objective-C, Java style guides]: https://github.com/flutter/engine/blob/main/CONTRIBUTING.md#style
This commit is contained in:
Chris Yang
2023-11-07 11:25:45 -08:00
committed by GitHub
parent e24e3b5746
commit 5c12a78db9
18 changed files with 640 additions and 147 deletions

View File

@@ -159,6 +159,7 @@ group("unittests") {
"//flutter/display_list:display_list_rendertests",
"//flutter/display_list:display_list_unittests",
"//flutter/flow:flow_unittests",
"//flutter/fml:fml_arc_unittests",
"//flutter/fml:fml_unittests",
"//flutter/lib/ui:ui_unittests",
"//flutter/runtime:dart_plugin_registrant_unittests",

View File

@@ -101,6 +101,8 @@
../../../flutter/fml/message_loop_unittests.cc
../../../flutter/fml/paths_unittests.cc
../../../flutter/fml/platform/darwin/cf_utils_unittests.mm
../../../flutter/fml/platform/darwin/scoped_nsobject_arc_unittests.mm
../../../flutter/fml/platform/darwin/scoped_nsobject_unittests.mm
../../../flutter/fml/platform/darwin/string_range_sanitization_unittests.mm
../../../flutter/fml/platform/win/file_win_unittests.cc
../../../flutter/fml/platform/win/wstring_conversion_unittests.cc

View File

@@ -2795,6 +2795,8 @@ ORIGIN: ../../../flutter/fml/platform/darwin/scoped_nsautorelease_pool.cc + ../.
ORIGIN: ../../../flutter/fml/platform/darwin/scoped_nsautorelease_pool.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/darwin/scoped_nsobject.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/darwin/scoped_nsobject.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/darwin/scoped_policy.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/darwin/scoped_typeref.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/darwin/string_range_sanitization.h + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/darwin/string_range_sanitization.mm + ../../../flutter/LICENSE
ORIGIN: ../../../flutter/fml/platform/fuchsia/message_loop_fuchsia.cc + ../../../flutter/LICENSE
@@ -5549,6 +5551,8 @@ FILE: ../../../flutter/fml/platform/darwin/scoped_nsautorelease_pool.cc
FILE: ../../../flutter/fml/platform/darwin/scoped_nsautorelease_pool.h
FILE: ../../../flutter/fml/platform/darwin/scoped_nsobject.h
FILE: ../../../flutter/fml/platform/darwin/scoped_nsobject.mm
FILE: ../../../flutter/fml/platform/darwin/scoped_policy.h
FILE: ../../../flutter/fml/platform/darwin/scoped_typeref.h
FILE: ../../../flutter/fml/platform/darwin/string_range_sanitization.h
FILE: ../../../flutter/fml/platform/darwin/string_range_sanitization.mm
FILE: ../../../flutter/fml/platform/fuchsia/message_loop_fuchsia.cc

View File

@@ -165,6 +165,8 @@ source_set("fml") {
"platform/darwin/scoped_nsautorelease_pool.h",
"platform/darwin/scoped_nsobject.h",
"platform/darwin/scoped_nsobject.mm",
"platform/darwin/scoped_policy.h",
"platform/darwin/scoped_typeref.h",
"platform/darwin/string_range_sanitization.h",
"platform/darwin/string_range_sanitization.mm",
]
@@ -366,6 +368,10 @@ if (enable_unittests) {
]
}
if (is_mac || is_ios) {
sources += [ "platform/darwin/scoped_nsobject_unittests.mm" ]
}
if (is_win) {
sources += [
"platform/win/file_win_unittests.cc",
@@ -388,4 +394,18 @@ if (enable_unittests) {
[ "${fuchsia_sdk_path}/arch/${target_cpu}/sysroot/lib/libzircon.so" ]
}
}
executable("fml_arc_unittests") {
testonly = true
if (is_mac || is_ios) {
cflags_objcc = flutter_cflags_objc_arc
sources = [ "platform/darwin/scoped_nsobject_arc_unittests.mm" ]
}
deps = [
":fml_fixtures",
"//flutter/fml",
"//flutter/testing",
]
}
}

View File

@@ -8,86 +8,40 @@
#include <Block.h>
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/platform/darwin/scoped_typeref.h"
#if defined(__has_feature) && __has_feature(objc_arc)
#define BASE_MAC_BRIDGE_CAST(TYPE, VALUE) (__bridge TYPE)(VALUE)
#else
#define BASE_MAC_BRIDGE_CAST(TYPE, VALUE) VALUE
#endif
namespace fml {
namespace internal {
template <typename B>
struct ScopedBlockTraits {
static B InvalidValue() { return nullptr; }
static B Retain(B block) {
return BASE_MAC_BRIDGE_CAST(
B, Block_copy(BASE_MAC_BRIDGE_CAST(const void*, block)));
}
static void Release(B block) {
Block_release(BASE_MAC_BRIDGE_CAST(const void*, block));
}
};
} // namespace internal
// ScopedBlock<> is patterned after ScopedCFTypeRef<>, but uses Block_copy() and
// Block_release() instead of CFRetain() and CFRelease().
enum class OwnershipPolicy {
// The scoped object takes ownership of an object by taking over an existing
// ownership claim.
kAssume,
// The scoped object will retain the object and any initial ownership is
// not changed.
kRetain,
};
template <typename B>
class ScopedBlock {
public:
explicit ScopedBlock(B block = nullptr,
OwnershipPolicy policy = OwnershipPolicy::kAssume)
: block_(block) {
if (block_ && policy == OwnershipPolicy::kRetain) {
block_ = Block_copy(block);
}
}
ScopedBlock(const ScopedBlock<B>& that) : block_(that.block_) {
if (block_) {
block_ = Block_copy(block_);
}
}
~ScopedBlock() {
if (block_) {
Block_release(block_);
}
}
ScopedBlock& operator=(const ScopedBlock<B>& that) {
reset(that.get(), OwnershipPolicy::kRetain);
return *this;
}
void reset(B block = nullptr,
OwnershipPolicy policy = OwnershipPolicy::kAssume) {
if (block && policy == OwnershipPolicy::kRetain) {
block = Block_copy(block);
}
if (block_) {
Block_release(block_);
}
block_ = block;
}
bool operator==(B that) const { return block_ == that; }
bool operator!=(B that) const { return block_ != that; }
// NOLINTNEXTLINE(google-explicit-constructor)
operator B() const { return block_; }
B get() const { return block_; }
void swap(ScopedBlock& that) {
B temp = that.block_;
that.block_ = block_;
block_ = temp;
}
[[nodiscard]] B release() {
B temp = block_;
block_ = nullptr;
return temp;
}
private:
B block_;
};
using ScopedBlock = ScopedTypeRef<B, internal::ScopedBlockTraits<B>>;
} // namespace fml
#undef BASE_MAC_BRIDGE_CAST
#endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_BLOCK_H_

View File

@@ -5,6 +5,9 @@
#ifndef FLUTTER_FML_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_
#define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_NSOBJECT_H_
#include <type_traits>
#include <utility>
// Include NSObject.h directly because Foundation.h pulls in many dependencies.
// (Approx 100k lines of code versus 1.5k for NSObject.h). scoped_nsobject gets
// singled out because it is most typically included from other header files.
@@ -12,8 +15,11 @@
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/platform/darwin/scoped_typeref.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
@class NSAutoreleasePool;
#endif
namespace fml {
@@ -36,60 +42,93 @@ namespace fml {
// scoped_nsautorelease_pool.h instead.
// We check for bad uses of scoped_nsobject and NSAutoreleasePool at compile
// time with a template specialization (see below).
//
// If Automatic Reference Counting (aka ARC) is enabled then the ownership
// policy is not controllable by the user as ARC make it really difficult to
// transfer ownership (the reference passed to scoped_nsobject constructor is
// sunk by ARC and __attribute((ns_consumed)) appears to not work correctly
// with Objective-C++ see https://llvm.org/bugs/show_bug.cgi?id=27887). Due to
// that, the policy is always to |RETAIN| when using ARC.
namespace internal {
id ScopedNSProtocolTraitsRetain(__unsafe_unretained id obj)
__attribute((ns_returns_not_retained));
id ScopedNSProtocolTraitsAutoRelease(__unsafe_unretained id obj)
__attribute((ns_returns_not_retained));
void ScopedNSProtocolTraitsRelease(__unsafe_unretained id obj);
// Traits for ScopedTypeRef<>. As this class may be compiled from file with
// Automatic Reference Counting enable or not all methods have annotation to
// enforce the same code generation in both case (in particular, the Retain
// method uses ns_returns_not_retained to prevent ARC to insert a -release
// call on the returned value and thus defeating the -retain).
template <typename NST>
struct ScopedNSProtocolTraits {
static NST InvalidValue() __attribute((ns_returns_not_retained)) {
return nil;
}
static NST Retain(__unsafe_unretained NST nst)
__attribute((ns_returns_not_retained)) {
return ScopedNSProtocolTraitsRetain(nst);
}
static void Release(__unsafe_unretained NST nst) {
ScopedNSProtocolTraitsRelease(nst);
}
};
} // namespace internal
template <typename NST>
class scoped_nsprotocol {
class scoped_nsprotocol
: public ScopedTypeRef<NST, internal::ScopedNSProtocolTraits<NST>> {
public:
explicit scoped_nsprotocol(NST object = nil) : object_(object) {}
using Traits = internal::ScopedNSProtocolTraits<NST>;
scoped_nsprotocol(const scoped_nsprotocol<NST>& that) : object_([that.object_ retain]) {}
#if !defined(__has_feature) || !__has_feature(objc_arc)
explicit scoped_nsprotocol(NST object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume)
: ScopedTypeRef<NST, Traits>(object, policy) {}
#else
explicit scoped_nsprotocol(NST object = Traits::InvalidValue())
: ScopedTypeRef<NST, Traits>(object,
scoped_policy::OwnershipPolicy::kRetain) {}
#endif
template <typename NSU>
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsprotocol(const scoped_nsprotocol<NSU>& that) : object_([that.get() retain]) {}
scoped_nsprotocol(const scoped_nsprotocol<NST>& that)
: ScopedTypeRef<NST, Traits>(that) {}
~scoped_nsprotocol() { [object_ release]; }
template <typename NSR>
explicit scoped_nsprotocol(const scoped_nsprotocol<NSR>& that_as_subclass)
: ScopedTypeRef<NST, Traits>(that_as_subclass) {}
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsprotocol(scoped_nsprotocol<NST>&& that)
: ScopedTypeRef<NST, Traits>(std::move(that)) {}
scoped_nsprotocol& operator=(const scoped_nsprotocol<NST>& that) {
reset([that.get() retain]);
ScopedTypeRef<NST, Traits>::operator=(that);
return *this;
}
void reset(NST object = nil) {
// We intentionally do not check that object != object_ as the caller must
// either already have an ownership claim over whatever it passes to this
// method, or call it with the |RETAIN| policy which will have ensured that
// the object is retained once more when reaching this point.
[object_ release];
object_ = object;
#if !defined(__has_feature) || !__has_feature(objc_arc)
void reset(NST object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume) {
ScopedTypeRef<NST, Traits>::reset(object, policy);
}
bool operator==(NST that) const { return object_ == that; }
bool operator!=(NST that) const { return object_ != that; }
operator NST() const { return object_; } // NOLINT(google-explicit-constructor)
NST get() const { return object_; }
void swap(scoped_nsprotocol& that) {
NST temp = that.object_;
that.object_ = object_;
object_ = temp;
#else
void reset(NST object = Traits::InvalidValue()) {
ScopedTypeRef<NST, Traits>::reset(object,
scoped_policy::OwnershipPolicy::kRetain);
}
#endif
// Shift reference to the autorelease pool to be released later.
NST autorelease() { return [release() autorelease]; }
private:
NST object_;
// scoped_nsprotocol<>::release() is like scoped_ptr<>::release. It is NOT a
// wrapper for [object_ release]. To force a scoped_nsprotocol<> to call
// [object_ release], use scoped_nsprotocol<>::reset().
[[nodiscard]] NST release() {
NST temp = object_;
object_ = nil;
return temp;
NST autorelease() __attribute((ns_returns_not_retained)) {
return internal::ScopedNSProtocolTraitsAutoRelease(this->release());
}
};
@@ -112,46 +151,97 @@ bool operator!=(C p1, const scoped_nsprotocol<C>& p2) {
template <typename NST>
class scoped_nsobject : public scoped_nsprotocol<NST*> {
public:
explicit scoped_nsobject(NST* object = nil) : scoped_nsprotocol<NST*>(object) {}
using Traits = typename scoped_nsprotocol<NST*>::Traits;
scoped_nsobject(const scoped_nsobject<NST>& that) : scoped_nsprotocol<NST*>(that) {}
#if !defined(__has_feature) || !__has_feature(objc_arc)
explicit scoped_nsobject(NST* object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume)
: scoped_nsprotocol<NST*>(object, policy) {}
#else
explicit scoped_nsobject(NST* object = Traits::InvalidValue())
: scoped_nsprotocol<NST*>(object) {}
#endif
template <typename NSU>
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(const scoped_nsobject<NSU>& that) : scoped_nsprotocol<NST*>(that) {}
scoped_nsobject(const scoped_nsobject<NST>& that)
: scoped_nsprotocol<NST*>(that) {}
template <typename NSR>
explicit scoped_nsobject(const scoped_nsobject<NSR>& that_as_subclass)
: scoped_nsprotocol<NST*>(that_as_subclass) {}
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(scoped_nsobject<NST>&& that)
: scoped_nsprotocol<NST*>(std::move(that)) {}
scoped_nsobject& operator=(const scoped_nsobject<NST>& that) {
scoped_nsprotocol<NST*>::operator=(that);
return *this;
}
#if !defined(__has_feature) || !__has_feature(objc_arc)
void reset(NST* object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume) {
scoped_nsprotocol<NST*>::reset(object, policy);
}
#else
void reset(NST* object = Traits::InvalidValue()) {
scoped_nsprotocol<NST*>::reset(object);
}
#endif
#if !defined(__has_feature) || !__has_feature(objc_arc)
static_assert(std::is_same<NST, NSAutoreleasePool>::value == false,
"Use ScopedNSAutoreleasePool instead");
#endif
};
// Specialization to make scoped_nsobject<id> work.
template <>
class scoped_nsobject<id> : public scoped_nsprotocol<id> {
public:
explicit scoped_nsobject(id object = nil) : scoped_nsprotocol<id>(object) {}
using Traits = typename scoped_nsprotocol<id>::Traits;
scoped_nsobject(const scoped_nsobject<id>& that) : scoped_nsprotocol<id>(that) {}
#if !defined(__has_feature) || !__has_feature(objc_arc)
explicit scoped_nsobject(id object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume)
: scoped_nsprotocol<id>(object, policy) {}
#else
explicit scoped_nsobject(id object = Traits::InvalidValue())
: scoped_nsprotocol<id>(object) {}
#endif
template <typename NSU>
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(const scoped_nsobject<NSU>& that) : scoped_nsprotocol<id>(that) {}
scoped_nsobject(const scoped_nsobject<id>& that)
: scoped_nsprotocol<id>(that) {}
template <typename NSR>
explicit scoped_nsobject(const scoped_nsobject<NSR>& that_as_subclass)
: scoped_nsprotocol<id>(that_as_subclass) {}
// NOLINTNEXTLINE(google-explicit-constructor)
scoped_nsobject(scoped_nsobject<id>&& that)
: scoped_nsprotocol<id>(std::move(that)) {}
scoped_nsobject& operator=(const scoped_nsobject<id>& that) {
scoped_nsprotocol<id>::operator=(that);
return *this;
}
};
// Do not use scoped_nsobject for NSAutoreleasePools, use
// ScopedNSAutoreleasePool instead. This is a compile time check. See details
// at top of header.
template <>
class scoped_nsobject<NSAutoreleasePool> {
private:
explicit scoped_nsobject(NSAutoreleasePool* object = nil);
FML_DISALLOW_COPY_AND_ASSIGN(scoped_nsobject);
#if !defined(__has_feature) || !__has_feature(objc_arc)
void reset(id object = Traits::InvalidValue(),
scoped_policy::OwnershipPolicy policy =
scoped_policy::OwnershipPolicy::kAssume) {
scoped_nsprotocol<id>::reset(object, policy);
}
#else
void reset(id object = Traits::InvalidValue()) {
scoped_nsprotocol<id>::reset(object);
}
#endif
};
} // namespace fml

View File

@@ -6,6 +6,19 @@
namespace fml {
//
namespace internal {
id ScopedNSProtocolTraitsRetain(id obj) {
return [obj retain];
}
id ScopedNSProtocolTraitsAutoRelease(id obj) {
return [obj autorelease];
}
void ScopedNSProtocolTraitsRelease(id obj) {
return [obj release];
}
} // namespace internal
} // namespace fml

View File

@@ -0,0 +1,131 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#import <CoreFoundation/CoreFoundation.h>
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "fml/logging.h"
#include "gtest/gtest.h"
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif
namespace {
template <typename NST>
CFIndex GetRetainCount(const fml::scoped_nsobject<NST>& nst) {
@autoreleasepool {
return CFGetRetainCount((__bridge CFTypeRef)nst.get()) - 1;
}
}
#if __has_feature(objc_arc_weak)
TEST(ScopedNSObjectTestARC, DefaultPolicyIsRetain) {
__weak id o;
@autoreleasepool {
fml::scoped_nsprotocol<id> p([[NSObject alloc] init]);
o = p.get();
EXPECT_EQ(o, p.get());
}
EXPECT_EQ(o, nil);
}
#endif
TEST(ScopedNSObjectTestARC, ScopedNSObject) {
fml::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
@autoreleasepool {
EXPECT_TRUE(p1.get());
EXPECT_TRUE(p1.get());
}
EXPECT_EQ(1, GetRetainCount(p1));
EXPECT_EQ(1, GetRetainCount(p1));
fml::scoped_nsobject<NSObject> p2(p1);
@autoreleasepool {
EXPECT_EQ(p1.get(), p2.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
p2.reset();
EXPECT_EQ(nil, p2.get());
EXPECT_EQ(1, GetRetainCount(p1));
{
fml::scoped_nsobject<NSObject> p3 = p1;
@autoreleasepool {
EXPECT_EQ(p1.get(), p3.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
p3 = p1;
@autoreleasepool {
EXPECT_EQ(p1.get(), p3.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
}
EXPECT_EQ(1, GetRetainCount(p1));
fml::scoped_nsobject<NSObject> p4;
@autoreleasepool {
p4 = fml::scoped_nsobject<NSObject>(p1.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
@autoreleasepool {
EXPECT_TRUE(p1 == p1.get());
EXPECT_TRUE(p1 == p1);
EXPECT_FALSE(p1 != p1);
EXPECT_FALSE(p1 != p1.get());
}
fml::scoped_nsobject<NSObject> p5([[NSObject alloc] init]);
@autoreleasepool {
EXPECT_TRUE(p1 != p5);
EXPECT_TRUE(p1 != p5.get());
EXPECT_FALSE(p1 == p5);
EXPECT_FALSE(p1 == p5.get());
}
fml::scoped_nsobject<NSObject> p6 = p1;
EXPECT_EQ(3, GetRetainCount(p6));
@autoreleasepool {
p6.autorelease();
EXPECT_EQ(nil, p6.get());
}
EXPECT_EQ(2, GetRetainCount(p1));
}
TEST(ScopedNSObjectTestARC, ScopedNSObjectInContainer) {
fml::scoped_nsobject<id> p([[NSObject alloc] init]);
@autoreleasepool {
EXPECT_TRUE(p.get());
}
EXPECT_EQ(1, GetRetainCount(p));
@autoreleasepool {
std::vector<fml::scoped_nsobject<id>> objects;
objects.push_back(p);
EXPECT_EQ(2, GetRetainCount(p));
@autoreleasepool {
EXPECT_EQ(p.get(), objects[0].get());
}
objects.push_back(fml::scoped_nsobject<id>([[NSObject alloc] init]));
@autoreleasepool {
EXPECT_TRUE(objects[1].get());
}
EXPECT_EQ(1, GetRetainCount(objects[1]));
}
EXPECT_EQ(1, GetRetainCount(p));
}
TEST(ScopedNSObjectTestARC, ScopedNSObjectFreeFunctions) {
fml::scoped_nsobject<id> p1([[NSObject alloc] init]);
id o1 = p1.get();
EXPECT_TRUE(o1 == p1);
EXPECT_FALSE(o1 != p1);
fml::scoped_nsobject<id> p2([[NSObject alloc] init]);
EXPECT_TRUE(o1 != p2);
EXPECT_FALSE(o1 == p2);
id o2 = p2.get();
swap(p1, p2);
EXPECT_EQ(o2, p1.get());
EXPECT_EQ(o1, p2.get());
}
} // namespace

View File

@@ -0,0 +1,106 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "gtest/gtest.h"
namespace {
// This is to suppress the bugprone-use-after-move warning.
// This strategy is recommanded here:
// https://clang.llvm.org/extra/clang-tidy/checks/bugprone/use-after-move.html#silencing-erroneous-warnings
template <class T>
void IS_INITIALIZED(T&) {}
TEST(ScopedNSObjectTest, ScopedNSObject) {
fml::scoped_nsobject<NSObject> p1([[NSObject alloc] init]);
ASSERT_TRUE(p1.get());
ASSERT_EQ(1u, [p1 retainCount]);
fml::scoped_nsobject<NSObject> p2(p1);
ASSERT_EQ(p1.get(), p2.get());
ASSERT_EQ(2u, [p1 retainCount]);
p2.reset();
ASSERT_EQ(nil, p2.get());
ASSERT_EQ(1u, [p1 retainCount]);
{
fml::scoped_nsobject<NSObject> p3 = p1;
ASSERT_EQ(p1.get(), p3.get());
ASSERT_EQ(2u, [p1 retainCount]);
p3 = p1;
ASSERT_EQ(p1.get(), p3.get());
ASSERT_EQ(2u, [p1 retainCount]);
}
ASSERT_EQ(1u, [p1 retainCount]);
fml::scoped_nsobject<NSObject> p4([p1.get() retain]);
ASSERT_EQ(2u, [p1 retainCount]);
ASSERT_TRUE(p1 == p1.get());
ASSERT_TRUE(p1 == p1);
ASSERT_FALSE(p1 != p1);
ASSERT_FALSE(p1 != p1.get());
fml::scoped_nsobject<NSObject> p5([[NSObject alloc] init]);
ASSERT_TRUE(p1 != p5);
ASSERT_TRUE(p1 != p5.get());
ASSERT_FALSE(p1 == p5);
ASSERT_FALSE(p1 == p5.get());
fml::scoped_nsobject<NSObject> p6 = p1;
ASSERT_EQ(3u, [p6 retainCount]);
{
fml::ScopedNSAutoreleasePool pool;
p6.autorelease();
ASSERT_EQ(nil, p6.get());
ASSERT_EQ(3u, [p1 retainCount]);
}
ASSERT_EQ(2u, [p1 retainCount]);
fml::scoped_nsobject<NSObject> p7([[NSObject alloc] init]);
fml::scoped_nsobject<NSObject> p8(std::move(p7));
ASSERT_TRUE(p8);
ASSERT_EQ(1u, [p8 retainCount]);
IS_INITIALIZED(p7);
ASSERT_FALSE(p7.get());
}
// Instantiating scoped_nsobject<> with T=NSAutoreleasePool should trip a
// static_assert.
#if 0
TEST(ScopedNSObjectTest, FailToCreateScopedNSObjectAutoreleasePool) {
fml::scoped_nsobject<NSAutoreleasePool> pool;
}
#endif
TEST(ScopedNSObjectTest, ScopedNSObjectInContainer) {
fml::scoped_nsobject<id> p([[NSObject alloc] init]);
ASSERT_TRUE(p.get());
ASSERT_EQ(1u, [p retainCount]);
{
std::vector<fml::scoped_nsobject<id>> objects;
objects.push_back(p);
ASSERT_EQ(2u, [p retainCount]);
ASSERT_EQ(p.get(), objects[0].get());
objects.push_back(fml::scoped_nsobject<id>([[NSObject alloc] init]));
ASSERT_TRUE(objects[1].get());
ASSERT_EQ(1u, [objects[1] retainCount]);
}
ASSERT_EQ(1u, [p retainCount]);
}
TEST(ScopedNSObjectTest, ScopedNSObjectFreeFunctions) {
fml::scoped_nsobject<id> p1([[NSObject alloc] init]);
id o1 = p1.get();
ASSERT_TRUE(o1 == p1);
ASSERT_FALSE(o1 != p1);
fml::scoped_nsobject<id> p2([[NSObject alloc] init]);
ASSERT_TRUE(o1 != p2);
ASSERT_FALSE(o1 == p2);
id o2 = p2.get();
swap(p1, p2);
ASSERT_EQ(o2, p1.get());
ASSERT_EQ(o1, p2.get());
}
} // namespace

View File

@@ -0,0 +1,25 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_DARWIN_SCOPED_POLICY_H_
#define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_POLICY_H_
namespace fml {
namespace scoped_policy {
// Defines the ownership policy for a scoped object.
enum OwnershipPolicy {
// The scoped object takes ownership of an object by taking over an existing
// ownership claim.
kAssume,
// The scoped object will retain the the object and any initial ownership is
// not changed.
kRetain
};
} // namespace scoped_policy
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_POLICY_H_

View File

@@ -0,0 +1,147 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_FML_PLATFORM_DARWIN_SCOPED_TYPEREF_H_
#define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_TYPEREF_H_
#include "flutter/fml/compiler_specific.h"
#include "flutter/fml/platform/darwin/scoped_policy.h"
namespace fml {
// ScopedTypeRef<> is patterned after std::unique_ptr<>, but maintains ownership
// of a reference to any type that is maintained by Retain and Release methods.
//
// The Traits structure must provide the Retain and Release methods for type T.
// A default ScopedTypeRefTraits is used but not defined, and should be defined
// for each type to use this interface. For example, an appropriate definition
// of ScopedTypeRefTraits for CGLContextObj would be:
//
// template<>
// struct ScopedTypeRefTraits<CGLContextObj> {
// static CGLContextObj InvalidValue() { return nullptr; }
// static CGLContextObj Retain(CGLContextObj object) {
// CGLContextRetain(object);
// return object;
// }
// static void Release(CGLContextObj object) { CGLContextRelease(object); }
// };
//
// For the many types that have pass-by-pointer create functions, the function
// InitializeInto() is provided to allow direct initialization and assumption
// of ownership of the object. For example, continuing to use the above
// CGLContextObj specialization:
//
// fml::ScopedTypeRef<CGLContextObj> context;
// CGLCreateContext(pixel_format, share_group, context.InitializeInto());
//
// For initialization with an existing object, the caller may specify whether
// the ScopedTypeRef<> being initialized is assuming the caller's existing
// ownership of the object (and should not call Retain in initialization) or if
// it should not assume this ownership and must create its own (by calling
// Retain in initialization). This behavior is based on the |policy| parameter,
// with |kAssume| for the former and |kRetain| for the latter. The default
// policy is to |kAssume|.
template <typename T>
struct ScopedTypeRefTraits;
template <typename T, typename Traits = ScopedTypeRefTraits<T>>
class ScopedTypeRef {
public:
typedef T element_type;
explicit ScopedTypeRef(
__unsafe_unretained T object = Traits::InvalidValue(),
fml::scoped_policy::OwnershipPolicy policy = fml::scoped_policy::kAssume)
: object_(object) {
if (object_ && policy == fml::scoped_policy::kRetain) {
object_ = Traits::Retain(object_);
}
}
// NOLINTNEXTLINE(google-explicit-constructor)
ScopedTypeRef(const ScopedTypeRef<T, Traits>& that) : object_(that.object_) {
if (object_) {
object_ = Traits::Retain(object_);
}
}
// This allows passing an object to a function that takes its superclass.
template <typename R, typename RTraits>
explicit ScopedTypeRef(const ScopedTypeRef<R, RTraits>& that_as_subclass)
: object_(that_as_subclass.get()) {
if (object_) {
object_ = Traits::Retain(object_);
}
}
// NOLINTNEXTLINE(google-explicit-constructor)
ScopedTypeRef(ScopedTypeRef<T, Traits>&& that) : object_(that.object_) {
that.object_ = Traits::InvalidValue();
}
~ScopedTypeRef() {
if (object_) {
Traits::Release(object_);
}
}
ScopedTypeRef& operator=(const ScopedTypeRef<T, Traits>& that) {
reset(that.get(), fml::scoped_policy::kRetain);
return *this;
}
// This is to be used only to take ownership of objects that are created
// by pass-by-pointer create functions. To enforce this, require that the
// object be reset to NULL before this may be used.
[[nodiscard]] T* InitializeInto() {
FML_DCHECK(!object_);
return &object_;
}
void reset(__unsafe_unretained T object = Traits::InvalidValue(),
fml::scoped_policy::OwnershipPolicy policy =
fml::scoped_policy::kAssume) {
if (object && policy == fml::scoped_policy::kRetain) {
object = Traits::Retain(object);
}
if (object_) {
Traits::Release(object_);
}
object_ = object;
}
bool operator==(__unsafe_unretained T that) const { return object_ == that; }
bool operator!=(__unsafe_unretained T that) const { return object_ != that; }
// NOLINTNEXTLINE(google-explicit-constructor)
operator T() const __attribute((ns_returns_not_retained)) { return object_; }
T get() const __attribute((ns_returns_not_retained)) { return object_; }
void swap(ScopedTypeRef& that) {
__unsafe_unretained T temp = that.object_;
that.object_ = object_;
object_ = temp;
}
protected:
// ScopedTypeRef<>::release() is like std::unique_ptr<>::release. It is NOT
// a wrapper for Release(). To force a ScopedTypeRef<> object to call
// Release(), use ScopedTypeRef<>::reset().
[[nodiscard]] T release() __attribute((ns_returns_not_retained)) {
__unsafe_unretained T temp = object_;
object_ = Traits::InvalidValue();
return temp;
}
private:
__unsafe_unretained T object_;
};
} // namespace fml
#endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_TYPEREF_H_

View File

@@ -243,7 +243,6 @@ source_set("ios_test_flutter_mrc") {
"framework/Source/FlutterViewTest.mm",
"framework/Source/SemanticsObjectTestMocks.h",
"framework/Source/SemanticsObjectTest_mrc.mm",
"framework/Source/VsyncWaiterIosTest.mm",
"framework/Source/accessibility_bridge_test.mm",
"platform_message_handler_ios_test.mm",
]
@@ -314,6 +313,7 @@ shared_library("ios_test_flutter") {
"framework/Source/FlutterViewControllerTest.mm",
"framework/Source/SemanticsObjectTest.mm",
"framework/Source/UIViewController_FlutterScreenAndSceneIfLoadedTest.mm",
"framework/Source/VsyncWaiterIosTest.mm",
"framework/Source/connection_collection_test.mm",
]
deps = [

View File

@@ -88,8 +88,8 @@ std::shared_ptr<FlutterPlatformViewLayer> FlutterPlatformViewLayerPool::GetLayer
const std::shared_ptr<IOSContext>& ios_context) {
if (available_layer_index_ >= layers_.size()) {
std::shared_ptr<FlutterPlatformViewLayer> layer;
fml::scoped_nsobject<FlutterOverlayView> overlay_view;
fml::scoped_nsobject<FlutterOverlayView> overlay_view_wrapper;
fml::scoped_nsobject<UIView> overlay_view;
fml::scoped_nsobject<UIView> overlay_view_wrapper;
if (!gr_context) {
overlay_view.reset([[FlutterOverlayView alloc] init]);

View File

@@ -717,7 +717,7 @@ static void SendFakeTouchEvent(UIScreen* screen,
}
- (void)setFlutterViewDidRenderCallback:(void (^)(void))callback {
_flutterViewRenderedCallback.reset(callback, fml::OwnershipPolicy::kRetain);
_flutterViewRenderedCallback.reset(callback, fml::scoped_policy::OwnershipPolicy::kRetain);
}
#pragma mark - Surface creation and teardown updates

View File

@@ -11,7 +11,7 @@
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h"
FLUTTER_ASSERT_NOT_ARC
FLUTTER_ASSERT_ARC
namespace {
fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
auto thread = std::make_unique<fml::Thread>(name);
@@ -34,10 +34,9 @@ fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
- (void)testSetAllowPauseAfterVsyncCorrect {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
VSyncClient* vsyncClient = [[[VSyncClient alloc]
VSyncClient* vsyncClient = [[VSyncClient alloc]
initWithTaskRunner:thread_task_runner
callback:[](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {}]
autorelease];
callback:[](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {}];
CADisplayLink* link = [vsyncClient getDisplayLink];
vsyncClient.allowPauseAfterVsync = NO;
[vsyncClient await];
@@ -60,8 +59,8 @@ fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
VSyncClient* vsyncClient = [[[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback] autorelease];
VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback];
CADisplayLink* link = [vsyncClient getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, maxFrameRate, 0.1);
@@ -82,8 +81,8 @@ fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
VSyncClient* vsyncClient = [[[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback] autorelease];
VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback];
CADisplayLink* link = [vsyncClient getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 0, 0.1);
@@ -100,8 +99,8 @@ fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
id mockDisplayLinkManager = [OCMockObject mockForClass:[DisplayLinkManager class]];
double maxFrameRate = 120;
[[[mockDisplayLinkManager stub] andReturnValue:@(maxFrameRate)] displayRefreshRate];
VSyncClient* vsyncClient = [[[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback] autorelease];
VSyncClient* vsyncClient = [[VSyncClient alloc] initWithTaskRunner:thread_task_runner
callback:callback];
CADisplayLink* link = [vsyncClient getDisplayLink];
if (@available(iOS 15.0, *)) {
XCTAssertEqualWithAccuracy(link.preferredFrameRateRange.maximum, 0, 0.1);
@@ -114,10 +113,9 @@ fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name) {
- (void)testAwaitAndPauseWillWorkCorrectly {
auto thread_task_runner = CreateNewThread("VsyncWaiterIosTest");
VSyncClient* vsyncClient = [[[VSyncClient alloc]
VSyncClient* vsyncClient = [[VSyncClient alloc]
initWithTaskRunner:thread_task_runner
callback:[](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {}]
autorelease];
callback:[](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {}];
CADisplayLink* link = [vsyncClient getDisplayLink];
XCTAssertTrue(link.isPaused);

View File

@@ -9,7 +9,7 @@ namespace flutter {
PlatformMessageResponseDarwin::PlatformMessageResponseDarwin(
PlatformMessageResponseCallback callback,
fml::RefPtr<fml::TaskRunner> platform_task_runner)
: callback_(callback, fml::OwnershipPolicy::kRetain),
: callback_(callback, fml::scoped_policy::OwnershipPolicy::kRetain),
platform_task_runner_(std::move(platform_task_runner)) {}
PlatformMessageResponseDarwin::~PlatformMessageResponseDarwin() = default;

View File

@@ -130,7 +130,8 @@ void PlatformMessageHandlerIos::SetMessageHandler(const std::string& channel,
.task_queue = fml::scoped_nsprotocol(
[static_cast<NSObject<FlutterTaskQueueDispatch>*>(task_queue) retain]),
.handler =
fml::ScopedBlock<FlutterBinaryMessageHandler>{handler, fml::OwnershipPolicy::kRetain},
fml::ScopedBlock<FlutterBinaryMessageHandler>{
handler, fml::scoped_policy::OwnershipPolicy::kRetain},
};
}
}

View File

@@ -403,6 +403,7 @@ def run_cc_tests(build_dir, executable_filter, coverage, capture_core_dump):
make_test('embedder_proctable_unittests'),
make_test('embedder_unittests'),
make_test('fml_unittests'),
make_test('fml_arc_unittests'),
make_test('no_dart_plugin_registrant_unittests'),
make_test('runtime_unittests'),
make_test('testing_unittests'),