text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// 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_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERTEXTURE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERTEXTURE_H_
#import <CoreMedia/CoreMedia.h>
#import <Foundation/Foundation.h>
#import "FlutterMacros.h"
NS_ASSUME_NONNULL_BEGIN
FLUTTER_DARWIN_EXPORT
/**
* Represents a texture that can be shared with Flutter.
*
* See also: https://github.com/flutter/plugins/tree/master/packages/camera
*/
@protocol FlutterTexture <NSObject>
/** Copy the contents of the texture into a `CVPixelBuffer`. */
- (CVPixelBufferRef _Nullable)copyPixelBuffer;
/**
* Called when the texture is unregistered.
*
* Called on the raster thread.
*/
@optional
- (void)onTextureUnregistered:(NSObject<FlutterTexture>*)texture;
@end
FLUTTER_DARWIN_EXPORT
/**
* A collection of registered `FlutterTexture`'s.
*/
@protocol FlutterTextureRegistry <NSObject>
/**
* Registers a `FlutterTexture` for usage in Flutter and returns an id that can be used to reference
* that texture when calling into Flutter with channels. Textures must be registered on the
* platform thread. On success returns the pointer to the registered texture, else returns 0.
*/
- (int64_t)registerTexture:(NSObject<FlutterTexture>*)texture;
/**
* Notifies Flutter that the content of the previously registered texture has been updated.
*
* This will trigger a call to `-[FlutterTexture copyPixelBuffer]` on the raster thread.
*/
- (void)textureFrameAvailable:(int64_t)textureId;
/**
* Unregisters a `FlutterTexture` that has previously regeistered with `registerTexture:`. Textures
* must be unregistered on the platform thread.
*
* @param textureId The result that was previously returned from `registerTexture:`.
*/
- (void)unregisterTexture:(int64_t)textureId;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_COMMON_FRAMEWORK_HEADERS_FLUTTERTEXTURE_H_
| engine/shell/platform/darwin/common/framework/Headers/FlutterTexture.h/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Headers/FlutterTexture.h",
"repo_id": "engine",
"token_count": 644
} | 325 |
// 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.
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h"
#include <CoreFoundation/CoreFoundation.h>
#include "gtest/gtest.h"
FLUTTER_ASSERT_ARC
@interface Pair : NSObject
@property(atomic, readonly, strong, nullable) NSObject* left;
@property(atomic, readonly, strong, nullable) NSObject* right;
- (instancetype)initWithLeft:(NSObject*)first right:(NSObject*)right;
@end
@implementation Pair
- (instancetype)initWithLeft:(NSObject*)left right:(NSObject*)right {
self = [super init];
if (self) {
_left = left;
_right = right;
}
return self;
}
@end
static const UInt8 kDATE = 128;
static const UInt8 kPAIR = 129;
@interface ExtendedWriter : FlutterStandardWriter
- (void)writeValue:(id)value;
@end
@implementation ExtendedWriter
- (void)writeValue:(id)value {
if ([value isKindOfClass:[NSDate class]]) {
[self writeByte:kDATE];
NSDate* date = value;
NSTimeInterval time = date.timeIntervalSince1970;
SInt64 ms = (SInt64)(time * 1000.0);
[self writeBytes:&ms length:8];
} else if ([value isKindOfClass:[Pair class]]) {
Pair* pair = value;
[self writeByte:kPAIR];
[self writeValue:pair.left];
[self writeValue:pair.right];
} else {
[super writeValue:value];
}
}
@end
@interface ExtendedReader : FlutterStandardReader
- (id)readValueOfType:(UInt8)type;
@end
@implementation ExtendedReader
- (id)readValueOfType:(UInt8)type {
switch (type) {
case kDATE: {
SInt64 value;
[self readBytes:&value length:8];
NSTimeInterval time = [NSNumber numberWithLong:value].doubleValue / 1000.0;
return [NSDate dateWithTimeIntervalSince1970:time];
}
case kPAIR: {
return [[Pair alloc] initWithLeft:[self readValue] right:[self readValue]];
}
default:
return [super readValueOfType:type];
}
}
@end
@interface ExtendedReaderWriter : FlutterStandardReaderWriter
- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data;
- (FlutterStandardReader*)readerWithData:(NSData*)data;
@end
@implementation ExtendedReaderWriter
- (FlutterStandardWriter*)writerWithData:(NSMutableData*)data {
return [[ExtendedWriter alloc] initWithData:data];
}
- (FlutterStandardReader*)readerWithData:(NSData*)data {
return [[ExtendedReader alloc] initWithData:data];
}
@end
static void CheckEncodeDecode(id value, NSData* expectedEncoding) {
FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
if (expectedEncoding == nil) {
ASSERT_TRUE(encoded == nil);
} else {
ASSERT_TRUE([encoded isEqual:expectedEncoding]);
}
id decoded = [codec decode:encoded];
if (value == nil || value == [NSNull null]) {
ASSERT_TRUE(decoded == nil);
} else {
ASSERT_TRUE([value isEqual:decoded]);
}
}
static void CheckEncodeDecode(id value) {
FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance];
NSData* encoded = [codec encode:value];
id decoded = [codec decode:encoded];
if (value == nil || value == [NSNull null]) {
ASSERT_TRUE(decoded == nil);
} else {
ASSERT_TRUE([value isEqual:decoded]);
}
}
TEST(FlutterStandardCodec, CanDecodeZeroLength) {
FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance];
id decoded = [codec decode:[NSData data]];
ASSERT_TRUE(decoded == nil);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeNil) {
CheckEncodeDecode(nil, nil);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeNSNull) {
uint8_t bytes[1] = {0x00};
CheckEncodeDecode([NSNull null], [NSData dataWithBytes:bytes length:1]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeYes) {
uint8_t bytes[1] = {0x01};
CheckEncodeDecode(@YES, [NSData dataWithBytes:bytes length:1]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeNo) {
uint8_t bytes[1] = {0x02};
CheckEncodeDecode(@NO, [NSData dataWithBytes:bytes length:1]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeUInt8) {
uint8_t bytes[5] = {0x03, 0xfe, 0x00, 0x00, 0x00};
UInt8 value = 0xfe;
CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeUInt16) {
uint8_t bytes[5] = {0x03, 0xdc, 0xfe, 0x00, 0x00};
UInt16 value = 0xfedc;
CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeUInt32) {
uint8_t bytes[9] = {0x04, 0x09, 0xba, 0xdc, 0xfe, 0x00, 0x00, 0x00, 0x00};
UInt32 value = 0xfedcba09;
CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:9]);
}
TEST(FlutterStandardCodec, CanEncodeUInt64) {
FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance];
UInt64 u64 = 0xfffffffffffffffa;
uint8_t bytes[9] = {0x04, 0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
NSData* encoded = [codec encode:@(u64)];
ASSERT_TRUE([encoded isEqual:[NSData dataWithBytes:bytes length:9]]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt8) {
uint8_t bytes[5] = {0x03, 0xfe, 0xff, 0xff, 0xff};
SInt8 value = 0xfe;
CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt16) {
uint8_t bytes[5] = {0x03, 0xdc, 0xfe, 0xff, 0xff};
SInt16 value = 0xfedc;
CheckEncodeDecode(@(value), [NSData dataWithBytes:bytes length:5]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt32) {
uint8_t bytes[5] = {0x03, 0x78, 0x56, 0x34, 0x12};
CheckEncodeDecode(@(0x12345678), [NSData dataWithBytes:bytes length:5]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeSInt64) {
uint8_t bytes[9] = {0x04, 0xef, 0xcd, 0xab, 0x90, 0x78, 0x56, 0x34, 0x12};
CheckEncodeDecode(@(0x1234567890abcdef), [NSData dataWithBytes:bytes length:9]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat32) {
uint8_t bytes[16] = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x60, 0xfb, 0x21, 0x09, 0x40};
CheckEncodeDecode(@3.1415927f, [NSData dataWithBytes:bytes length:16]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat64) {
uint8_t bytes[16] = {0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40};
CheckEncodeDecode(@3.14159265358979311599796346854, [NSData dataWithBytes:bytes length:16]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeString) {
uint8_t bytes[13] = {0x07, 0x0b, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64};
CheckEncodeDecode(@"hello world", [NSData dataWithBytes:bytes length:13]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeStringWithNonAsciiCodePoint) {
uint8_t bytes[7] = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77};
CheckEncodeDecode(@"h\u263Aw", [NSData dataWithBytes:bytes length:7]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeStringWithNonBMPCodePoint) {
uint8_t bytes[8] = {0x07, 0x06, 0x68, 0xf0, 0x9f, 0x98, 0x82, 0x77};
CheckEncodeDecode(@"h\U0001F602w", [NSData dataWithBytes:bytes length:8]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeIndirectString) {
// This test ensures that an indirect NSString, whose internal string buffer
// can't be simply returned by `CFStringGetCStringPtr`, can be encoded without
// violating the memory sanitizer. This test only works with `--asan` flag.
// See https://github.com/flutter/flutter/issues/142101
uint8_t bytes[7] = {0x07, 0x05, 0x68, 0xe2, 0x98, 0xba, 0x77};
NSString* target = @"h\u263Aw";
// Ensures that this is an indirect string so that this test makes sense.
ASSERT_TRUE(CFStringGetCStringPtr((__bridge CFStringRef)target, kCFStringEncodingUTF8) ==
nullptr);
CheckEncodeDecode(target, [NSData dataWithBytes:bytes length:7]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeArray) {
NSArray* value = @[ [NSNull null], @"hello", @3.14, @47, @{@42 : @"nested"} ];
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeDictionary) {
NSDictionary* value =
@{@"a" : @3.14,
@"b" : @47,
[NSNull null] : [NSNull null],
@3.14 : @[ @"nested" ]};
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeByteArray) {
uint8_t bytes[4] = {0xBA, 0x5E, 0xBA, 0x11};
NSData* data = [NSData dataWithBytes:bytes length:4];
FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithBytes:data];
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeNSData) {
FlutterStandardMessageCodec* codec = [FlutterStandardMessageCodec sharedInstance];
uint8_t bytes[4] = {0xBA, 0x5E, 0xBA, 0x11};
NSData* data = [NSData dataWithBytes:bytes length:4];
FlutterStandardTypedData* standardData = [FlutterStandardTypedData typedDataWithBytes:data];
NSData* encoded = [codec encode:data];
ASSERT_TRUE([encoded isEqual:[codec encode:standardData]]);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeInt32Array) {
uint8_t bytes[8] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:8];
FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithInt32:data];
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeInt64Array) {
uint8_t bytes[8] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:8];
FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithInt64:data];
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat32Array) {
uint8_t bytes[8] = {0xd8, 0x0f, 0x49, 0x40, 0x00, 0x00, 0x7a, 0x44};
NSData* data = [NSData dataWithBytes:bytes length:8];
FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithFloat32:data];
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, CanEncodeAndDecodeFloat64Array) {
uint8_t bytes[16] = {0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff,
0xBA, 0x5E, 0xBA, 0x11, 0xff, 0xff, 0xff, 0xff};
NSData* data = [NSData dataWithBytes:bytes length:16];
FlutterStandardTypedData* value = [FlutterStandardTypedData typedDataWithFloat64:data];
CheckEncodeDecode(value);
}
TEST(FlutterStandardCodec, HandlesMethodCallsWithNilArguments) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"hello" arguments:nil];
NSData* encoded = [codec encodeMethodCall:call];
FlutterMethodCall* decoded = [codec decodeMethodCall:encoded];
ASSERT_TRUE([decoded isEqual:call]);
}
TEST(FlutterStandardCodec, HandlesMethodCallsWithSingleArgument) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"hello" arguments:@42];
NSData* encoded = [codec encodeMethodCall:call];
FlutterMethodCall* decoded = [codec decodeMethodCall:encoded];
ASSERT_TRUE([decoded isEqual:call]);
}
TEST(FlutterStandardCodec, HandlesMethodCallsWithArgumentList) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
NSArray* arguments = @[ @42, @"world" ];
FlutterMethodCall* call = [FlutterMethodCall methodCallWithMethodName:@"hello"
arguments:arguments];
NSData* encoded = [codec encodeMethodCall:call];
FlutterMethodCall* decoded = [codec decodeMethodCall:encoded];
ASSERT_TRUE([decoded isEqual:call]);
}
TEST(FlutterStandardCodec, HandlesSuccessEnvelopesWithNilResult) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
NSData* encoded = [codec encodeSuccessEnvelope:nil];
id decoded = [codec decodeEnvelope:encoded];
ASSERT_TRUE(decoded == nil);
}
TEST(FlutterStandardCodec, HandlesSuccessEnvelopesWithSingleResult) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
NSData* encoded = [codec encodeSuccessEnvelope:@42];
id decoded = [codec decodeEnvelope:encoded];
ASSERT_TRUE([decoded isEqual:@42]);
}
TEST(FlutterStandardCodec, HandlesSuccessEnvelopesWithResultMap) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
NSDictionary* result = @{@"a" : @42, @42 : @"a"};
NSData* encoded = [codec encodeSuccessEnvelope:result];
id decoded = [codec decodeEnvelope:encoded];
ASSERT_TRUE([decoded isEqual:result]);
}
TEST(FlutterStandardCodec, HandlesErrorEnvelopes) {
FlutterStandardMethodCodec* codec = [FlutterStandardMethodCodec sharedInstance];
NSDictionary* details = @{@"a" : @42, @42 : @"a"};
FlutterError* error = [FlutterError errorWithCode:@"errorCode"
message:@"something failed"
details:details];
NSData* encoded = [codec encodeErrorEnvelope:error];
id decoded = [codec decodeEnvelope:encoded];
ASSERT_TRUE([decoded isEqual:error]);
}
TEST(FlutterStandardCodec, HandlesSubclasses) {
ExtendedReaderWriter* extendedReaderWriter = [[ExtendedReaderWriter alloc] init];
FlutterStandardMessageCodec* codec =
[FlutterStandardMessageCodec codecWithReaderWriter:extendedReaderWriter];
Pair* pair = [[Pair alloc] initWithLeft:@1 right:@2];
NSData* encoded = [codec encode:pair];
Pair* decoded = [codec decode:encoded];
ASSERT_TRUE([pair.left isEqual:decoded.left]);
ASSERT_TRUE([pair.right isEqual:decoded.right]);
}
| engine/shell/platform/darwin/common/framework/Source/flutter_standard_codec_unittest.mm/0 | {
"file_path": "engine/shell/platform/darwin/common/framework/Source/flutter_standard_codec_unittest.mm",
"repo_id": "engine",
"token_count": 5317
} | 326 |
// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINEGROUP_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINEGROUP_H_
#import <Foundation/Foundation.h>
#import "FlutterEngine.h"
NS_ASSUME_NONNULL_BEGIN
/** Options that control how a FlutterEngine should be created. */
FLUTTER_DARWIN_EXPORT
@interface FlutterEngineGroupOptions : NSObject
/**
* The name of a top-level function from a Dart library. If this is FlutterDefaultDartEntrypoint
* (or nil); this will default to `main()`. If it is not the app's main() function, that function
* must be decorated with `@pragma(vm:entry-point)` to ensure themethod is not tree-shaken by the
* Dart compiler.
*/
@property(nonatomic, copy, nullable) NSString* entrypoint;
/**
* The URI of the Dart library which contains the entrypoint method. If nil, this will default to
* the same library as the `main()` function in the Dart program.
*/
@property(nonatomic, copy, nullable) NSString* libraryURI;
/**
* The name of the initial Flutter `Navigator` `Route` to load. If this is
* FlutterDefaultInitialRoute (or nil), it will default to the "/" route.
*/
@property(nonatomic, copy, nullable) NSString* initialRoute;
/**
* Arguments passed as a list of string to Dart's entrypoint function.
*/
@property(nonatomic, retain, nullable) NSArray<NSString*>* entrypointArgs;
@end
/**
* Represents a collection of FlutterEngines who share resources which allows
* them to be created with less time const and occupy less memory than just
* creating multiple FlutterEngines.
*
* Deleting a FlutterEngineGroup doesn't invalidate existing FlutterEngines, but
* it eliminates the possibility to create more FlutterEngines in that group.
*
* @warning This class is a work-in-progress and may change.
* @see https://github.com/flutter/flutter/issues/72009
*/
FLUTTER_DARWIN_EXPORT
@interface FlutterEngineGroup : NSObject
- (instancetype)init NS_UNAVAILABLE;
/**
* Initialize a new FlutterEngineGroup.
*
* @param name The name that will present in the threads shared across the
* engines in this group.
* @param project The `FlutterDartProject` that all FlutterEngines in this group
* will be executing.
*/
- (instancetype)initWithName:(NSString*)name
project:(nullable FlutterDartProject*)project NS_DESIGNATED_INITIALIZER;
/**
* Creates a running `FlutterEngine` that shares components with this group.
*
* @param entrypoint The name of a top-level function from a Dart library. If this is
* FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's
* main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the
* method is not tree-shaken by the Dart compiler.
* @param libraryURI The URI of the Dart library which contains the entrypoint method. IF nil,
* this will default to the same library as the `main()` function in the Dart program.
*
* @see FlutterEngineGroup
*/
- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI;
/**
* Creates a running `FlutterEngine` that shares components with this group.
*
* @param entrypoint The name of a top-level function from a Dart library. If this is
* FlutterDefaultDartEntrypoint (or nil); this will default to `main()`. If it is not the app's
* main() function, that function must be decorated with `@pragma(vm:entry-point)` to ensure the
* method is not tree-shaken by the Dart compiler.
* @param libraryURI The URI of the Dart library which contains the entrypoint method. IF nil,
* this will default to the same library as the `main()` function in the Dart program.
* @param initialRoute The name of the initial Flutter `Navigator` `Route` to load. If this is
* FlutterDefaultInitialRoute (or nil), it will default to the "/" route.
*
* @see FlutterEngineGroup
*/
- (FlutterEngine*)makeEngineWithEntrypoint:(nullable NSString*)entrypoint
libraryURI:(nullable NSString*)libraryURI
initialRoute:(nullable NSString*)initialRoute;
/**
* Creates a running `FlutterEngine` that shares components with this group.
*
* @param options Options that control how a FlutterEngine should be created.
*
* @see FlutterEngineGroupOptions
*/
- (FlutterEngine*)makeEngineWithOptions:(nullable FlutterEngineGroupOptions*)options;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_HEADERS_FLUTTERENGINEGROUP_H_
| engine/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Headers/FlutterEngineGroup.h",
"repo_id": "engine",
"token_count": 1490
} | 327 |
// 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.
#define FML_USED_ON_EMBEDDER
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterDartProject_Internal.h"
#include <syslog.h>
#import <Metal/Metal.h>
#include <sstream>
#include <string>
#include "flutter/common/constants.h"
#include "flutter/common/task_runners.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/runtime/dart_vm.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#import "flutter/shell/platform/darwin/common/command_line.h"
#import "flutter/shell/platform/darwin/ios/framework/Headers/FlutterViewController.h"
FLUTTER_ASSERT_NOT_ARC
extern "C" {
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// Used for debugging dart:* sources.
extern const uint8_t kPlatformStrongDill[];
extern const intptr_t kPlatformStrongDillSize;
#endif
}
static const char* kApplicationKernelSnapshotFileName = "kernel_blob.bin";
static BOOL DoesHardwareSupportWideGamut() {
static BOOL result = NO;
static dispatch_once_t once_token = 0;
dispatch_once(&once_token, ^{
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
if (@available(iOS 13.0, *)) {
// MTLGPUFamilyApple2 = A9/A10
result = [device supportsFamily:MTLGPUFamilyApple2];
} else {
// A9/A10 on iOS 10+
result = [device supportsFeatureSet:MTLFeatureSet_iOS_GPUFamily3_v2];
}
[device release];
});
return result;
}
flutter::Settings FLTDefaultSettingsForBundle(NSBundle* bundle, NSProcessInfo* processInfoOrNil) {
auto command_line = flutter::CommandLineFromNSProcessInfo(processInfoOrNil);
// Precedence:
// 1. Settings from the specified NSBundle (except for enable-impeller).
// 2. Settings passed explicitly via command-line arguments.
// 3. Settings from the NSBundle with the default bundle ID.
// 4. Settings from the main NSBundle and default values.
NSBundle* mainBundle = FLTGetApplicationBundle();
NSBundle* engineBundle = [NSBundle bundleForClass:[FlutterViewController class]];
bool hasExplicitBundle = bundle != nil;
if (bundle == nil) {
bundle = FLTFrameworkBundleWithIdentifier([FlutterDartProject defaultBundleIdentifier]);
}
auto settings = flutter::SettingsFromCommandLine(command_line);
settings.task_observer_add = [](intptr_t key, const fml::closure& callback) {
fml::MessageLoop::GetCurrent().AddTaskObserver(key, callback);
};
settings.task_observer_remove = [](intptr_t key) {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
};
settings.log_message_callback = [](const std::string& tag, const std::string& message) {
// TODO(cbracken): replace this with os_log-based approach.
// https://github.com/flutter/flutter/issues/44030
std::stringstream stream;
if (!tag.empty()) {
stream << tag << ": ";
}
stream << message;
std::string log = stream.str();
syslog(LOG_ALERT, "%.*s", (int)log.size(), log.c_str());
};
// The command line arguments may not always be complete. If they aren't, attempt to fill in
// defaults.
// Flutter ships the ICU data file in the bundle of the engine. Look for it there.
if (settings.icu_data_path.empty()) {
NSString* icuDataPath = [engineBundle pathForResource:@"icudtl" ofType:@"dat"];
if (icuDataPath.length > 0) {
settings.icu_data_path = icuDataPath.UTF8String;
}
}
if (flutter::DartVM::IsRunningPrecompiledCode()) {
if (hasExplicitBundle) {
NSString* executablePath = bundle.executablePath;
if ([[NSFileManager defaultManager] fileExistsAtPath:executablePath]) {
settings.application_library_path.push_back(executablePath.UTF8String);
}
}
// No application bundle specified. Try a known location from the main bundle's Info.plist.
if (settings.application_library_path.empty()) {
NSString* libraryName = [mainBundle objectForInfoDictionaryKey:@"FLTLibraryPath"];
NSString* libraryPath = [mainBundle pathForResource:libraryName ofType:@""];
if (libraryPath.length > 0) {
NSString* executablePath = [NSBundle bundleWithPath:libraryPath].executablePath;
if (executablePath.length > 0) {
settings.application_library_path.push_back(executablePath.UTF8String);
}
}
}
// In case the application bundle is still not specified, look for the App.framework in the
// Frameworks directory.
if (settings.application_library_path.empty()) {
NSString* applicationFrameworkPath = [mainBundle pathForResource:@"Frameworks/App.framework"
ofType:@""];
if (applicationFrameworkPath.length > 0) {
NSString* executablePath =
[NSBundle bundleWithPath:applicationFrameworkPath].executablePath;
if (executablePath.length > 0) {
settings.application_library_path.push_back(executablePath.UTF8String);
}
}
}
}
// Checks to see if the flutter assets directory is already present.
if (settings.assets_path.empty()) {
NSString* assetsPath = FLTAssetsPathFromBundle(bundle);
if (assetsPath.length == 0) {
NSLog(@"Failed to find assets path for \"%@\"", bundle);
} else {
settings.assets_path = assetsPath.UTF8String;
// Check if there is an application kernel snapshot in the assets directory we could
// potentially use. Looking for the snapshot makes sense only if we have a VM that can use
// it.
if (!flutter::DartVM::IsRunningPrecompiledCode()) {
NSURL* applicationKernelSnapshotURL =
[NSURL URLWithString:@(kApplicationKernelSnapshotFileName)
relativeToURL:[NSURL fileURLWithPath:assetsPath]];
NSError* error;
if ([applicationKernelSnapshotURL checkResourceIsReachableAndReturnError:&error]) {
settings.application_kernel_asset = applicationKernelSnapshotURL.path.UTF8String;
} else {
NSLog(@"Failed to find snapshot at %@: %@", applicationKernelSnapshotURL.path, error);
}
}
}
}
// Domain network configuration
// Disabled in https://github.com/flutter/flutter/issues/72723.
// Re-enable in https://github.com/flutter/flutter/issues/54448.
settings.may_insecurely_connect_to_all_domains = true;
settings.domain_network_policy = "";
// Whether to enable wide gamut colors.
#if TARGET_OS_SIMULATOR
// As of Xcode 14.1, the wide gamut surface pixel formats are not supported by
// the simulator.
settings.enable_wide_gamut = false;
// Removes unused function warning.
(void)DoesHardwareSupportWideGamut;
#else
NSNumber* nsEnableWideGamut = [mainBundle objectForInfoDictionaryKey:@"FLTEnableWideGamut"];
BOOL enableWideGamut =
(nsEnableWideGamut ? nsEnableWideGamut.boolValue : YES) && DoesHardwareSupportWideGamut();
settings.enable_wide_gamut = enableWideGamut;
#endif
// TODO(dnfield): We should reverse the order for all these settings so that command line options
// are preferred to plist settings. https://github.com/flutter/flutter/issues/124049
// Whether to enable Impeller. If the command line explicitly
// specified an option for this, ignore what's in the plist.
if (!command_line.HasOption("enable-impeller")) {
// Next, look in the app bundle.
NSNumber* enableImpeller = [bundle objectForInfoDictionaryKey:@"FLTEnableImpeller"];
if (enableImpeller == nil) {
// If it isn't in the app bundle, look in the main bundle.
enableImpeller = [mainBundle objectForInfoDictionaryKey:@"FLTEnableImpeller"];
}
// Change the default only if the option is present.
if (enableImpeller != nil) {
settings.enable_impeller = enableImpeller.boolValue;
}
}
NSNumber* enableTraceSystrace = [mainBundle objectForInfoDictionaryKey:@"FLTTraceSystrace"];
// Change the default only if the option is present.
if (enableTraceSystrace != nil) {
settings.trace_systrace = enableTraceSystrace.boolValue;
}
NSNumber* enableDartProfiling = [mainBundle objectForInfoDictionaryKey:@"FLTEnableDartProfiling"];
// Change the default only if the option is present.
if (enableDartProfiling != nil) {
settings.enable_dart_profiling = enableDartProfiling.boolValue;
}
// Leak Dart VM settings, set whether leave or clean up the VM after the last shell shuts down.
NSNumber* leakDartVM = [mainBundle objectForInfoDictionaryKey:@"FLTLeakDartVM"];
// It will change the default leak_vm value in settings only if the key exists.
if (leakDartVM != nil) {
settings.leak_vm = leakDartVM.boolValue;
}
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// There are no ownership concerns here as all mappings are owned by the
// embedder and not the engine.
auto make_mapping_callback = [](const uint8_t* mapping, size_t size) {
return [mapping, size]() { return std::make_unique<fml::NonOwnedMapping>(mapping, size); };
};
settings.dart_library_sources_kernel =
make_mapping_callback(kPlatformStrongDill, kPlatformStrongDillSize);
#endif // FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
// If we even support setting this e.g. from the command line or the plist,
// we should let the user override it.
// Otherwise, we want to set this to a value that will avoid having the OS
// kill us. On most iOS devices, that happens somewhere near half
// the available memory.
// The VM expects this value to be in megabytes.
if (settings.old_gen_heap_size <= 0) {
settings.old_gen_heap_size = std::round([NSProcessInfo processInfo].physicalMemory * .48 /
flutter::kMegaByteSizeInBytes);
}
// This is the formula Android uses.
// https://android.googlesource.com/platform/frameworks/base/+/39ae5bac216757bc201490f4c7b8c0f63006c6cd/libs/hwui/renderthread/CacheManager.cpp#45
CGFloat scale = [UIScreen mainScreen].scale;
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width * scale;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height * scale;
settings.resource_cache_max_bytes_threshold = screenWidth * screenHeight * 12 * 4;
// Whether to enable ios embedder api.
NSNumber* enable_embedder_api =
[mainBundle objectForInfoDictionaryKey:@"FLTEnableIOSEmbedderAPI"];
// Change the default only if the option is present.
if (enable_embedder_api) {
settings.enable_embedder_api = enable_embedder_api.boolValue;
}
return settings;
}
@implementation FlutterDartProject {
flutter::Settings _settings;
}
// This property is marked unavailable on iOS in the common header.
// That doesn't seem to be enough to prevent this property from being synthesized.
// Mark dynamic to avoid warnings.
@dynamic dartEntrypointArguments;
#pragma mark - Override base class designated initializers
- (instancetype)init {
return [self initWithPrecompiledDartBundle:nil];
}
#pragma mark - Designated initializers
- (instancetype)initWithPrecompiledDartBundle:(nullable NSBundle*)bundle {
self = [super init];
if (self) {
_settings = FLTDefaultSettingsForBundle(bundle);
}
return self;
}
- (instancetype)initWithSettings:(const flutter::Settings&)settings {
self = [self initWithPrecompiledDartBundle:nil];
if (self) {
_settings = settings;
}
return self;
}
#pragma mark - PlatformData accessors
- (const flutter::PlatformData)defaultPlatformData {
flutter::PlatformData PlatformData;
PlatformData.lifecycle_state = std::string("AppLifecycleState.detached");
return PlatformData;
}
#pragma mark - Settings accessors
- (const flutter::Settings&)settings {
return _settings;
}
- (flutter::RunConfiguration)runConfiguration {
return [self runConfigurationForEntrypoint:nil];
}
- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil {
return [self runConfigurationForEntrypoint:entrypointOrNil libraryOrNil:nil];
}
- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil
libraryOrNil:(nullable NSString*)dartLibraryOrNil {
return [self runConfigurationForEntrypoint:entrypointOrNil
libraryOrNil:dartLibraryOrNil
entrypointArgs:nil];
}
- (flutter::RunConfiguration)runConfigurationForEntrypoint:(nullable NSString*)entrypointOrNil
libraryOrNil:(nullable NSString*)dartLibraryOrNil
entrypointArgs:
(nullable NSArray<NSString*>*)entrypointArgs {
auto config = flutter::RunConfiguration::InferFromSettings(_settings);
if (dartLibraryOrNil && entrypointOrNil) {
config.SetEntrypointAndLibrary(std::string([entrypointOrNil UTF8String]),
std::string([dartLibraryOrNil UTF8String]));
} else if (entrypointOrNil) {
config.SetEntrypoint(std::string([entrypointOrNil UTF8String]));
}
if (entrypointArgs.count) {
std::vector<std::string> cppEntrypointArgs;
for (NSString* arg in entrypointArgs) {
cppEntrypointArgs.push_back(std::string([arg UTF8String]));
}
config.SetEntrypointArgs(std::move(cppEntrypointArgs));
}
return config;
}
#pragma mark - Assets-related utilities
+ (NSString*)flutterAssetsName:(NSBundle*)bundle {
if (bundle == nil) {
bundle = FLTFrameworkBundleWithIdentifier([FlutterDartProject defaultBundleIdentifier]);
}
return FLTAssetPath(bundle);
}
+ (NSString*)domainNetworkPolicy:(NSDictionary*)appTransportSecurity {
// https://developer.apple.com/documentation/bundleresources/information_property_list/nsapptransportsecurity/nsexceptiondomains
NSDictionary* exceptionDomains = [appTransportSecurity objectForKey:@"NSExceptionDomains"];
if (exceptionDomains == nil) {
return @"";
}
NSMutableArray* networkConfigArray = [[[NSMutableArray alloc] init] autorelease];
for (NSString* domain in exceptionDomains) {
NSDictionary* domainConfiguration = [exceptionDomains objectForKey:domain];
// Default value is false.
bool includesSubDomains =
[[domainConfiguration objectForKey:@"NSIncludesSubdomains"] boolValue];
bool allowsCleartextCommunication =
[[domainConfiguration objectForKey:@"NSExceptionAllowsInsecureHTTPLoads"] boolValue];
[networkConfigArray addObject:@[
domain, includesSubDomains ? @YES : @NO, allowsCleartextCommunication ? @YES : @NO
]];
}
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:networkConfigArray
options:0
error:NULL];
return [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding] autorelease];
}
+ (bool)allowsArbitraryLoads:(NSDictionary*)appTransportSecurity {
return [[appTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"] boolValue];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset {
return [self lookupKeyForAsset:asset fromBundle:nil];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset fromBundle:(nullable NSBundle*)bundle {
NSString* flutterAssetsName = [FlutterDartProject flutterAssetsName:bundle];
return [NSString stringWithFormat:@"%@/%@", flutterAssetsName, asset];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
return [self lookupKeyForAsset:asset fromPackage:package fromBundle:nil];
}
+ (NSString*)lookupKeyForAsset:(NSString*)asset
fromPackage:(NSString*)package
fromBundle:(nullable NSBundle*)bundle {
return [self lookupKeyForAsset:[NSString stringWithFormat:@"packages/%@/%@", package, asset]
fromBundle:bundle];
}
+ (NSString*)defaultBundleIdentifier {
return @"io.flutter.flutter.app";
}
- (BOOL)isWideGamutEnabled {
return _settings.enable_wide_gamut;
}
- (BOOL)isImpellerEnabled {
return _settings.enable_impeller;
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterDartProject.mm",
"repo_id": "engine",
"token_count": 5881
} | 328 |
// 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.
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.h"
#include "flutter/fml/logging.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterMacros.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h"
FLUTTER_ASSERT_ARC;
@implementation FakeUIPressProxy
- (instancetype)initWithData:(UIPressPhase)phase
key:(UIKey*)key
type:(UIEventType)type
timestamp:(NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) {
self = [super init];
if (self) {
_dataPhase = phase;
_dataKey = [key copy];
_dataType = type;
_dataTimestamp = timestamp;
}
return self;
}
- (UIPressPhase)phase API_AVAILABLE(ios(13.4)) {
return _dataPhase;
}
- (UIKey*)key API_AVAILABLE(ios(13.4)) {
return _dataKey;
}
- (UIEventType)type API_AVAILABLE(ios(13.4)) {
return _dataType;
}
- (NSTimeInterval)timestamp API_AVAILABLE(ios(13.4)) {
return _dataTimestamp;
}
@end
@implementation FakeUIKey
- (instancetype)initWithData:(UIKeyboardHIDUsage)keyCode
modifierFlags:(UIKeyModifierFlags)modifierFlags
characters:(NSString*)characters
charactersIgnoringModifiers:(NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)) {
self = [super init];
if (self) {
_dataKeyCode = keyCode;
_dataModifierFlags = modifierFlags;
_dataCharacters = characters;
_dataCharactersIgnoringModifiers = charactersIgnoringModifiers;
}
return self;
}
- (id)copyWithZone:(NSZone*)zone {
FakeUIKey* another = [super copyWithZone:zone];
another.dataKeyCode = _dataKeyCode;
another.dataModifierFlags = _dataModifierFlags;
another.dataCharacters = [_dataCharacters copyWithZone:zone];
another.dataCharactersIgnoringModifiers = [_dataCharactersIgnoringModifiers copyWithZone:zone];
return another;
}
- (UIKeyboardHIDUsage)keyCode API_AVAILABLE(ios(13.4)) {
return _dataKeyCode;
}
- (UIKeyModifierFlags)modifierFlags API_AVAILABLE(ios(13.4)) {
return _dataModifierFlags;
}
- (NSString*)characters API_AVAILABLE(ios(13.4)) {
return _dataCharacters;
}
- (NSString*)charactersIgnoringModifiers API_AVAILABLE(ios(13.4)) {
return _dataCharactersIgnoringModifiers;
}
@end
namespace flutter {
namespace testing {
FlutterUIPressProxy* keyDownEvent(UIKeyboardHIDUsage keyCode,
UIKeyModifierFlags modifierFlags,
NSTimeInterval timestamp,
const char* characters,
const char* charactersIgnoringModifiers)
API_AVAILABLE(ios(13.4)) {
return keyEventWithPhase(UIPressPhaseBegan, keyCode, modifierFlags, timestamp, characters,
charactersIgnoringModifiers);
}
FlutterUIPressProxy* keyUpEvent(UIKeyboardHIDUsage keyCode,
UIKeyModifierFlags modifierFlags,
NSTimeInterval timestamp,
const char* characters,
const char* charactersIgnoringModifiers) API_AVAILABLE(ios(13.4)) {
return keyEventWithPhase(UIPressPhaseEnded, keyCode, modifierFlags, timestamp, characters,
charactersIgnoringModifiers);
}
FlutterUIPressProxy* keyEventWithPhase(UIPressPhase phase,
UIKeyboardHIDUsage keyCode,
UIKeyModifierFlags modifierFlags,
NSTimeInterval timestamp,
const char* characters,
const char* charactersIgnoringModifiers)
API_AVAILABLE(ios(13.4)) {
FML_DCHECK(!(modifierFlags & kModifierFlagSidedMask))
<< "iOS doesn't supply modifier side flags, so don't create events with them.";
UIKey* key =
[[FakeUIKey alloc] initWithData:keyCode
modifierFlags:modifierFlags
characters:[NSString stringWithUTF8String:characters]
charactersIgnoringModifiers:[NSString stringWithUTF8String:charactersIgnoringModifiers]];
return [[FakeUIPressProxy alloc] initWithData:phase
key:key
type:UIEventTypePresses
timestamp:timestamp];
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterFakeKeyEvents.mm",
"repo_id": "engine",
"token_count": 2089
} | 329 |
// 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 <Metal/Metal.h>
#import <UIKit/UIGestureRecognizerSubclass.h>
#include <list>
#include <map>
#include <memory>
#include <string>
#include "flutter/common/graphics/persistent_cache.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterOverlayView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/ios/ios_surface.h"
@implementation UIView (FirstResponder)
- (BOOL)flt_hasFirstResponderInViewHierarchySubtree {
if (self.isFirstResponder) {
return YES;
}
for (UIView* subview in self.subviews) {
if (subview.flt_hasFirstResponderInViewHierarchySubtree) {
return YES;
}
}
return NO;
}
@end
// Determines if the `clip_rect` from a clipRect mutator contains the
// `platformview_boundingrect`.
//
// `clip_rect` is in its own coordinate space. The rect needs to be transformed by
// `transform_matrix` to be in the coordinate space where the PlatformView is displayed.
//
// `platformview_boundingrect` is the final bounding rect of the PlatformView in the coordinate
// space where the PlatformView is displayed.
static bool ClipRectContainsPlatformViewBoundingRect(const SkRect& clip_rect,
const SkRect& platformview_boundingrect,
const SkMatrix& transform_matrix) {
SkRect transformed_rect = transform_matrix.mapRect(clip_rect);
return transformed_rect.contains(platformview_boundingrect);
}
// Determines if the `clipRRect` from a clipRRect mutator contains the
// `platformview_boundingrect`.
//
// `clip_rrect` is in its own coordinate space. The rrect needs to be transformed by
// `transform_matrix` to be in the coordinate space where the PlatformView is displayed.
//
// `platformview_boundingrect` is the final bounding rect of the PlatformView in the coordinate
// space where the PlatformView is displayed.
static bool ClipRRectContainsPlatformViewBoundingRect(const SkRRect& clip_rrect,
const SkRect& platformview_boundingrect,
const SkMatrix& transform_matrix) {
SkVector upper_left = clip_rrect.radii(SkRRect::Corner::kUpperLeft_Corner);
SkVector upper_right = clip_rrect.radii(SkRRect::Corner::kUpperRight_Corner);
SkVector lower_right = clip_rrect.radii(SkRRect::Corner::kLowerRight_Corner);
SkVector lower_left = clip_rrect.radii(SkRRect::Corner::kLowerLeft_Corner);
SkScalar transformed_upper_left_x = transform_matrix.mapRadius(upper_left.x());
SkScalar transformed_upper_left_y = transform_matrix.mapRadius(upper_left.y());
SkScalar transformed_upper_right_x = transform_matrix.mapRadius(upper_right.x());
SkScalar transformed_upper_right_y = transform_matrix.mapRadius(upper_right.y());
SkScalar transformed_lower_right_x = transform_matrix.mapRadius(lower_right.x());
SkScalar transformed_lower_right_y = transform_matrix.mapRadius(lower_right.y());
SkScalar transformed_lower_left_x = transform_matrix.mapRadius(lower_left.x());
SkScalar transformed_lower_left_y = transform_matrix.mapRadius(lower_left.y());
SkRect transformed_clip_rect = transform_matrix.mapRect(clip_rrect.rect());
SkRRect transformed_rrect;
SkVector corners[] = {{transformed_upper_left_x, transformed_upper_left_y},
{transformed_upper_right_x, transformed_upper_right_y},
{transformed_lower_right_x, transformed_lower_right_y},
{transformed_lower_left_x, transformed_lower_left_y}};
transformed_rrect.setRectRadii(transformed_clip_rect, corners);
return transformed_rrect.contains(platformview_boundingrect);
}
namespace flutter {
// Becomes NO if Apple's API changes and blurred backdrop filters cannot be applied.
BOOL canApplyBlurBackdrop = YES;
std::shared_ptr<FlutterPlatformViewLayer> FlutterPlatformViewLayerPool::GetLayer(
GrDirectContext* gr_context,
const std::shared_ptr<IOSContext>& ios_context,
MTLPixelFormat pixel_format) {
if (available_layer_index_ >= layers_.size()) {
std::shared_ptr<FlutterPlatformViewLayer> layer;
fml::scoped_nsobject<UIView> overlay_view;
fml::scoped_nsobject<UIView> overlay_view_wrapper;
bool impeller_enabled = !!ios_context->GetImpellerContext();
if (!gr_context && !impeller_enabled) {
overlay_view.reset([[FlutterOverlayView alloc] init]);
overlay_view_wrapper.reset([[FlutterOverlayView alloc] init]);
auto ca_layer = fml::scoped_nsobject<CALayer>{[[overlay_view.get() layer] retain]};
std::unique_ptr<IOSSurface> ios_surface = IOSSurface::Create(ios_context, ca_layer);
std::unique_ptr<Surface> surface = ios_surface->CreateGPUSurface();
layer = std::make_shared<FlutterPlatformViewLayer>(
std::move(overlay_view), std::move(overlay_view_wrapper), std::move(ios_surface),
std::move(surface));
} else {
CGFloat screenScale = [UIScreen mainScreen].scale;
overlay_view.reset([[FlutterOverlayView alloc] initWithContentsScale:screenScale
pixelFormat:pixel_format]);
overlay_view_wrapper.reset([[FlutterOverlayView alloc] initWithContentsScale:screenScale
pixelFormat:pixel_format]);
auto ca_layer = fml::scoped_nsobject<CALayer>{[[overlay_view.get() layer] retain]};
std::unique_ptr<IOSSurface> ios_surface = IOSSurface::Create(ios_context, ca_layer);
std::unique_ptr<Surface> surface = ios_surface->CreateGPUSurface(gr_context);
layer = std::make_shared<FlutterPlatformViewLayer>(
std::move(overlay_view), std::move(overlay_view_wrapper), std::move(ios_surface),
std::move(surface));
layer->gr_context = gr_context;
}
// The overlay view wrapper masks the overlay view.
// This is required to keep the backing surface size unchanged between frames.
//
// Otherwise, changing the size of the overlay would require a new surface,
// which can be very expensive.
//
// This is the case of an animation in which the overlay size is changing in every frame.
//
// +------------------------+
// | overlay_view |
// | +--------------+ | +--------------+
// | | wrapper | | == mask => | overlay_view |
// | +--------------+ | +--------------+
// +------------------------+
layer->overlay_view_wrapper.get().clipsToBounds = YES;
[layer->overlay_view_wrapper.get() addSubview:layer->overlay_view];
layers_.push_back(layer);
}
std::shared_ptr<FlutterPlatformViewLayer> layer = layers_[available_layer_index_];
if (gr_context != layer->gr_context) {
layer->gr_context = gr_context;
// The overlay already exists, but the GrContext was changed so we need to recreate
// the rendering surface with the new GrContext.
IOSSurface* ios_surface = layer->ios_surface.get();
std::unique_ptr<Surface> surface = ios_surface->CreateGPUSurface(gr_context);
layer->surface = std::move(surface);
}
available_layer_index_++;
return layer;
}
void FlutterPlatformViewLayerPool::RecycleLayers() {
available_layer_index_ = 0;
}
std::vector<std::shared_ptr<FlutterPlatformViewLayer>>
FlutterPlatformViewLayerPool::GetUnusedLayers() {
std::vector<std::shared_ptr<FlutterPlatformViewLayer>> results;
for (size_t i = available_layer_index_; i < layers_.size(); i++) {
results.push_back(layers_[i]);
}
return results;
}
void FlutterPlatformViewsController::SetFlutterView(UIView* flutter_view) {
flutter_view_.reset([flutter_view retain]);
}
void FlutterPlatformViewsController::SetFlutterViewController(
UIViewController* flutter_view_controller) {
flutter_view_controller_.reset([flutter_view_controller retain]);
}
UIViewController* FlutterPlatformViewsController::getFlutterViewController() {
return flutter_view_controller_.get();
}
void FlutterPlatformViewsController::OnMethodCall(FlutterMethodCall* call, FlutterResult result) {
if ([[call method] isEqualToString:@"create"]) {
OnCreate(call, result);
} else if ([[call method] isEqualToString:@"dispose"]) {
OnDispose(call, result);
} else if ([[call method] isEqualToString:@"acceptGesture"]) {
OnAcceptGesture(call, result);
} else if ([[call method] isEqualToString:@"rejectGesture"]) {
OnRejectGesture(call, result);
} else {
result(FlutterMethodNotImplemented);
}
}
void FlutterPlatformViewsController::OnCreate(FlutterMethodCall* call, FlutterResult result) {
NSDictionary<NSString*, id>* args = [call arguments];
int64_t viewId = [args[@"id"] longLongValue];
NSString* viewTypeString = args[@"viewType"];
std::string viewType(viewTypeString.UTF8String);
if (views_.count(viewId) != 0) {
result([FlutterError errorWithCode:@"recreating_view"
message:@"trying to create an already created view"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
}
NSObject<FlutterPlatformViewFactory>* factory = factories_[viewType].get();
if (factory == nil) {
result([FlutterError
errorWithCode:@"unregistered_view_type"
message:[NSString stringWithFormat:@"A UIKitView widget is trying to create a "
@"PlatformView with an unregistered type: < %@ >",
viewTypeString]
details:@"If you are the author of the PlatformView, make sure `registerViewFactory` "
@"is invoked.\n"
@"See: "
@"https://docs.flutter.dev/development/platform-integration/"
@"platform-views#on-the-platform-side-1 for more details.\n"
@"If you are not the author of the PlatformView, make sure to call "
@"`GeneratedPluginRegistrant.register`."]);
return;
}
id params = nil;
if ([factory respondsToSelector:@selector(createArgsCodec)]) {
NSObject<FlutterMessageCodec>* codec = [factory createArgsCodec];
if (codec != nil && args[@"params"] != nil) {
FlutterStandardTypedData* paramsData = args[@"params"];
params = [codec decode:paramsData.data];
}
}
NSObject<FlutterPlatformView>* embedded_view = [factory createWithFrame:CGRectZero
viewIdentifier:viewId
arguments:params];
UIView* platform_view = [embedded_view view];
// Set a unique view identifier, so the platform view can be identified in unit tests.
platform_view.accessibilityIdentifier =
[NSString stringWithFormat:@"platform_view[%lld]", viewId];
views_[viewId] = fml::scoped_nsobject<NSObject<FlutterPlatformView>>([embedded_view retain]);
FlutterTouchInterceptingView* touch_interceptor = [[[FlutterTouchInterceptingView alloc]
initWithEmbeddedView:platform_view
platformViewsController:GetWeakPtr()
gestureRecognizersBlockingPolicy:gesture_recognizers_blocking_policies_[viewType]]
autorelease];
touch_interceptors_[viewId] =
fml::scoped_nsobject<FlutterTouchInterceptingView>([touch_interceptor retain]);
ChildClippingView* clipping_view =
[[[ChildClippingView alloc] initWithFrame:CGRectZero] autorelease];
[clipping_view addSubview:touch_interceptor];
root_views_[viewId] = fml::scoped_nsobject<UIView>([clipping_view retain]);
result(nil);
}
void FlutterPlatformViewsController::OnDispose(FlutterMethodCall* call, FlutterResult result) {
NSNumber* arg = [call arguments];
int64_t viewId = [arg longLongValue];
if (views_.count(viewId) == 0) {
result([FlutterError errorWithCode:@"unknown_view"
message:@"trying to dispose an unknown"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
// We wait for next submitFrame to dispose views.
views_to_dispose_.insert(viewId);
result(nil);
}
void FlutterPlatformViewsController::OnAcceptGesture(FlutterMethodCall* call,
FlutterResult result) {
NSDictionary<NSString*, id>* args = [call arguments];
int64_t viewId = [args[@"id"] longLongValue];
if (views_.count(viewId) == 0) {
result([FlutterError errorWithCode:@"unknown_view"
message:@"trying to set gesture state for an unknown view"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
FlutterTouchInterceptingView* view = touch_interceptors_[viewId].get();
[view releaseGesture];
result(nil);
}
void FlutterPlatformViewsController::OnRejectGesture(FlutterMethodCall* call,
FlutterResult result) {
NSDictionary<NSString*, id>* args = [call arguments];
int64_t viewId = [args[@"id"] longLongValue];
if (views_.count(viewId) == 0) {
result([FlutterError errorWithCode:@"unknown_view"
message:@"trying to set gesture state for an unknown view"
details:[NSString stringWithFormat:@"view id: '%lld'", viewId]]);
return;
}
FlutterTouchInterceptingView* view = touch_interceptors_[viewId].get();
[view blockGesture];
result(nil);
}
void FlutterPlatformViewsController::RegisterViewFactory(
NSObject<FlutterPlatformViewFactory>* factory,
NSString* factoryId,
FlutterPlatformViewGestureRecognizersBlockingPolicy gestureRecognizerBlockingPolicy) {
std::string idString([factoryId UTF8String]);
FML_CHECK(factories_.count(idString) == 0);
factories_[idString] =
fml::scoped_nsobject<NSObject<FlutterPlatformViewFactory>>([factory retain]);
gesture_recognizers_blocking_policies_[idString] = gestureRecognizerBlockingPolicy;
}
void FlutterPlatformViewsController::BeginFrame(SkISize frame_size) {
ResetFrameState();
frame_size_ = frame_size;
}
void FlutterPlatformViewsController::CancelFrame() {
ResetFrameState();
}
// TODO(cyanglaz): https://github.com/flutter/flutter/issues/56474
// Make this method check if there are pending view operations instead.
// Also rename it to `HasPendingViewOperations`.
bool FlutterPlatformViewsController::HasPlatformViewThisOrNextFrame() {
return !composition_order_.empty() || !active_composition_order_.empty();
}
const int FlutterPlatformViewsController::kDefaultMergedLeaseDuration;
PostPrerollResult FlutterPlatformViewsController::PostPrerollAction(
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
// TODO(cyanglaz): https://github.com/flutter/flutter/issues/56474
// Rename `has_platform_view` to `view_mutated` when the above issue is resolved.
if (!HasPlatformViewThisOrNextFrame()) {
return PostPrerollResult::kSuccess;
}
if (!raster_thread_merger->IsMerged()) {
// The raster thread merger may be disabled if the rasterizer is being
// created or teared down.
//
// In such cases, the current frame is dropped, and a new frame is attempted
// with the same layer tree.
//
// Eventually, the frame is submitted once this method returns `kSuccess`.
// At that point, the raster tasks are handled on the platform thread.
CancelFrame();
return PostPrerollResult::kSkipAndRetryFrame;
}
// If the post preroll action is successful, we will display platform views in the current frame.
// In order to sync the rendering of the platform views (quartz) with skia's rendering,
// We need to begin an explicit CATransaction. This transaction needs to be submitted
// after the current frame is submitted.
BeginCATransaction();
raster_thread_merger->ExtendLeaseTo(kDefaultMergedLeaseDuration);
return PostPrerollResult::kSuccess;
}
void FlutterPlatformViewsController::EndFrame(
bool should_resubmit_frame,
const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) {
if (should_resubmit_frame) {
raster_thread_merger->MergeWithLease(kDefaultMergedLeaseDuration);
}
}
void FlutterPlatformViewsController::PushFilterToVisitedPlatformViews(
const std::shared_ptr<const DlImageFilter>& filter,
const SkRect& filter_rect) {
for (int64_t id : visited_platform_views_) {
EmbeddedViewParams params = current_composition_params_[id];
params.PushImageFilter(filter, filter_rect);
current_composition_params_[id] = params;
}
}
void FlutterPlatformViewsController::PrerollCompositeEmbeddedView(
int64_t view_id,
std::unique_ptr<EmbeddedViewParams> params) {
// All the CATransactions should be committed by the end of the last frame,
// so catransaction_added_ must be false.
FML_DCHECK(!catransaction_added_);
SkRect view_bounds = SkRect::Make(frame_size_);
std::unique_ptr<EmbedderViewSlice> view;
view = std::make_unique<DisplayListEmbedderViewSlice>(view_bounds);
slices_.insert_or_assign(view_id, std::move(view));
composition_order_.push_back(view_id);
if (current_composition_params_.count(view_id) == 1 &&
current_composition_params_[view_id] == *params.get()) {
// Do nothing if the params didn't change.
return;
}
current_composition_params_[view_id] = EmbeddedViewParams(*params.get());
views_to_recomposite_.insert(view_id);
}
size_t FlutterPlatformViewsController::EmbeddedViewCount() {
return composition_order_.size();
}
UIView* FlutterPlatformViewsController::GetPlatformViewByID(int64_t view_id) {
return [GetFlutterTouchInterceptingViewByID(view_id) embeddedView];
}
FlutterTouchInterceptingView* FlutterPlatformViewsController::GetFlutterTouchInterceptingViewByID(
int64_t view_id) {
if (views_.empty()) {
return nil;
}
return touch_interceptors_[view_id].get();
}
long FlutterPlatformViewsController::FindFirstResponderPlatformViewId() {
for (auto const& [id, root_view] : root_views_) {
if ((UIView*)(root_view.get()).flt_hasFirstResponderInViewHierarchySubtree) {
return id;
}
}
return -1;
}
int FlutterPlatformViewsController::CountClips(const MutatorsStack& mutators_stack) {
std::vector<std::shared_ptr<Mutator>>::const_reverse_iterator iter = mutators_stack.Bottom();
int clipCount = 0;
while (iter != mutators_stack.Top()) {
if ((*iter)->IsClipType()) {
clipCount++;
}
++iter;
}
return clipCount;
}
void FlutterPlatformViewsController::ClipViewSetMaskView(UIView* clipView) {
if (clipView.maskView) {
return;
}
UIView* flutterView = flutter_view_.get();
CGRect frame =
CGRectMake(-clipView.frame.origin.x, -clipView.frame.origin.y,
CGRectGetWidth(flutterView.bounds), CGRectGetHeight(flutterView.bounds));
clipView.maskView = [mask_view_pool_.get() getMaskViewWithFrame:frame];
}
// This method is only called when the `embedded_view` needs to be re-composited at the current
// frame. See: `CompositeWithParams` for details.
void FlutterPlatformViewsController::ApplyMutators(const MutatorsStack& mutators_stack,
UIView* embedded_view,
const SkRect& bounding_rect) {
if (flutter_view_ == nullptr) {
return;
}
FML_DCHECK(CATransform3DEqualToTransform(embedded_view.layer.transform, CATransform3DIdentity));
ResetAnchor(embedded_view.layer);
ChildClippingView* clipView = (ChildClippingView*)embedded_view.superview;
SkMatrix transformMatrix;
NSMutableArray* blurFilters = [[[NSMutableArray alloc] init] autorelease];
FML_DCHECK(!clipView.maskView ||
[clipView.maskView isKindOfClass:[FlutterClippingMaskView class]]);
if (clipView.maskView) {
[mask_view_pool_.get() insertViewToPoolIfNeeded:(FlutterClippingMaskView*)(clipView.maskView)];
clipView.maskView = nil;
}
CGFloat screenScale = [UIScreen mainScreen].scale;
auto iter = mutators_stack.Begin();
while (iter != mutators_stack.End()) {
switch ((*iter)->GetType()) {
case kTransform: {
transformMatrix.preConcat((*iter)->GetMatrix());
break;
}
case kClipRect: {
if (ClipRectContainsPlatformViewBoundingRect((*iter)->GetRect(), bounding_rect,
transformMatrix)) {
break;
}
ClipViewSetMaskView(clipView);
[(FlutterClippingMaskView*)clipView.maskView clipRect:(*iter)->GetRect()
matrix:transformMatrix];
break;
}
case kClipRRect: {
if (ClipRRectContainsPlatformViewBoundingRect((*iter)->GetRRect(), bounding_rect,
transformMatrix)) {
break;
}
ClipViewSetMaskView(clipView);
[(FlutterClippingMaskView*)clipView.maskView clipRRect:(*iter)->GetRRect()
matrix:transformMatrix];
break;
}
case kClipPath: {
// TODO(cyanglaz): Find a way to pre-determine if path contains the PlatformView boudning
// rect. See `ClipRRectContainsPlatformViewBoundingRect`.
// https://github.com/flutter/flutter/issues/118650
ClipViewSetMaskView(clipView);
[(FlutterClippingMaskView*)clipView.maskView clipPath:(*iter)->GetPath()
matrix:transformMatrix];
break;
}
case kOpacity:
embedded_view.alpha = (*iter)->GetAlphaFloat() * embedded_view.alpha;
break;
case kBackdropFilter: {
// Only support DlBlurImageFilter for BackdropFilter.
if (!canApplyBlurBackdrop || !(*iter)->GetFilterMutation().GetFilter().asBlur()) {
break;
}
CGRect filterRect =
flutter::GetCGRectFromSkRect((*iter)->GetFilterMutation().GetFilterRect());
// `filterRect` is in global coordinates. We need to convert to local space.
filterRect = CGRectApplyAffineTransform(
filterRect, CGAffineTransformMakeScale(1 / screenScale, 1 / screenScale));
// `filterRect` reprents the rect that should be filtered inside the `flutter_view_`.
// The `PlatformViewFilter` needs the frame inside the `clipView` that needs to be
// filtered.
if (CGRectIsNull(CGRectIntersection(filterRect, clipView.frame))) {
break;
}
CGRect intersection = CGRectIntersection(filterRect, clipView.frame);
CGRect frameInClipView = [flutter_view_.get() convertRect:intersection toView:clipView];
// sigma_x is arbitrarily chosen as the radius value because Quartz sets
// sigma_x and sigma_y equal to each other. DlBlurImageFilter's Tile Mode
// is not supported in Quartz's gaussianBlur CAFilter, so it is not used
// to blur the PlatformView.
CGFloat blurRadius = (*iter)->GetFilterMutation().GetFilter().asBlur()->sigma_x();
UIVisualEffectView* visualEffectView = [[[UIVisualEffectView alloc]
initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]] autorelease];
PlatformViewFilter* filter =
[[[PlatformViewFilter alloc] initWithFrame:frameInClipView
blurRadius:blurRadius
visualEffectView:visualEffectView] autorelease];
if (!filter) {
canApplyBlurBackdrop = NO;
} else {
[blurFilters addObject:filter];
}
break;
}
}
++iter;
}
if (canApplyBlurBackdrop) {
[clipView applyBlurBackdropFilters:blurFilters];
}
// The UIKit frame is set based on the logical resolution (points) instead of physical.
// (https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html).
// However, flow is based on the physical resolution. For example, 1000 pixels in flow equals
// 500 points in UIKit for devices that has screenScale of 2. We need to scale the transformMatrix
// down to the logical resoltion before applying it to the layer of PlatformView.
transformMatrix.postScale(1 / screenScale, 1 / screenScale);
// Reverse the offset of the clipView.
// The clipView's frame includes the final translate of the final transform matrix.
// Thus, this translate needs to be reversed so the platform view can layout at the correct
// offset.
//
// Note that the transforms are not applied to the clipping paths because clipping paths happen on
// the mask view, whose origin is always (0,0) to the flutter_view.
transformMatrix.postTranslate(-clipView.frame.origin.x, -clipView.frame.origin.y);
embedded_view.layer.transform = flutter::GetCATransform3DFromSkMatrix(transformMatrix);
}
// Composite the PlatformView with `view_id`.
//
// Every frame, during the paint traversal of the layer tree, this method is called for all
// the PlatformViews in `views_to_recomposite_`.
//
// Note that `views_to_recomposite_` does not represent all the views in the view hierarchy,
// if a PlatformView does not change its composition parameter from last frame, it is not
// included in the `views_to_recomposite_`.
void FlutterPlatformViewsController::CompositeWithParams(int64_t view_id,
const EmbeddedViewParams& params) {
CGRect frame = CGRectMake(0, 0, params.sizePoints().width(), params.sizePoints().height());
FlutterTouchInterceptingView* touchInterceptor = touch_interceptors_[view_id].get();
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
FML_DCHECK(CGPointEqualToPoint([touchInterceptor embeddedView].frame.origin, CGPointZero));
if (non_zero_origin_views_.find(view_id) == non_zero_origin_views_.end() &&
!CGPointEqualToPoint([touchInterceptor embeddedView].frame.origin, CGPointZero)) {
non_zero_origin_views_.insert(view_id);
NSLog(
@"A Embedded PlatformView's origin is not CGPointZero.\n"
" View id: %@\n"
" View info: \n %@ \n"
"A non-zero origin might cause undefined behavior.\n"
"See https://github.com/flutter/flutter/issues/109700 for more details.\n"
"If you are the author of the PlatformView, please update the implementation of the "
"PlatformView to have a (0, 0) origin.\n"
"If you have a valid case of using a non-zero origin, "
"please leave a comment at https://github.com/flutter/flutter/issues/109700 with details.",
@(view_id), [touchInterceptor embeddedView]);
}
#endif
touchInterceptor.layer.transform = CATransform3DIdentity;
touchInterceptor.frame = frame;
touchInterceptor.alpha = 1;
const MutatorsStack& mutatorStack = params.mutatorsStack();
UIView* clippingView = root_views_[view_id].get();
// The frame of the clipping view should be the final bounding rect.
// Because the translate matrix in the Mutator Stack also includes the offset,
// when we apply the transforms matrix in |ApplyMutators|, we need
// to remember to do a reverse translate.
const SkRect& rect = params.finalBoundingRect();
CGFloat screenScale = [UIScreen mainScreen].scale;
clippingView.frame = CGRectMake(rect.x() / screenScale, rect.y() / screenScale,
rect.width() / screenScale, rect.height() / screenScale);
ApplyMutators(mutatorStack, touchInterceptor, rect);
}
DlCanvas* FlutterPlatformViewsController::CompositeEmbeddedView(int64_t view_id) {
// Any UIKit related code has to run on main thread.
FML_DCHECK([[NSThread currentThread] isMainThread]);
// Do nothing if the view doesn't need to be composited.
if (views_to_recomposite_.count(view_id) == 0) {
return slices_[view_id]->canvas();
}
CompositeWithParams(view_id, current_composition_params_[view_id]);
views_to_recomposite_.erase(view_id);
return slices_[view_id]->canvas();
}
void FlutterPlatformViewsController::Reset() {
for (int64_t view_id : active_composition_order_) {
UIView* sub_view = root_views_[view_id].get();
[sub_view removeFromSuperview];
}
root_views_.clear();
touch_interceptors_.clear();
views_.clear();
composition_order_.clear();
active_composition_order_.clear();
slices_.clear();
current_composition_params_.clear();
clip_count_.clear();
views_to_recomposite_.clear();
layer_pool_->RecycleLayers();
visited_platform_views_.clear();
}
SkRect FlutterPlatformViewsController::GetPlatformViewRect(int64_t view_id) {
UIView* platform_view = GetPlatformViewByID(view_id);
UIScreen* screen = [UIScreen mainScreen];
CGRect platform_view_cgrect = [platform_view convertRect:platform_view.bounds
toView:flutter_view_];
return SkRect::MakeXYWH(platform_view_cgrect.origin.x * screen.scale, //
platform_view_cgrect.origin.y * screen.scale, //
platform_view_cgrect.size.width * screen.scale, //
platform_view_cgrect.size.height * screen.scale //
);
}
bool FlutterPlatformViewsController::SubmitFrame(GrDirectContext* gr_context,
const std::shared_ptr<IOSContext>& ios_context,
std::unique_ptr<SurfaceFrame> frame) {
TRACE_EVENT0("flutter", "FlutterPlatformViewsController::SubmitFrame");
// Any UIKit related code has to run on main thread.
FML_DCHECK([[NSThread currentThread] isMainThread]);
if (flutter_view_ == nullptr) {
return frame->Submit();
}
DisposeViews();
DlCanvas* background_canvas = frame->Canvas();
// Resolve all pending GPU operations before allocating a new surface.
background_canvas->Flush();
// Clipping the background canvas before drawing the picture recorders requires
// saving and restoring the clip context.
DlAutoCanvasRestore save(background_canvas, /*do_save=*/true);
// Maps a platform view id to a vector of `FlutterPlatformViewLayer`.
LayersMap platform_view_layers;
auto did_submit = true;
auto num_platform_views = composition_order_.size();
for (size_t i = 0; i < num_platform_views; i++) {
int64_t platform_view_id = composition_order_[i];
EmbedderViewSlice* slice = slices_[platform_view_id].get();
slice->end_recording();
// Check if the current picture contains overlays that intersect with the
// current platform view or any of the previous platform views.
for (size_t j = i + 1; j > 0; j--) {
int64_t current_platform_view_id = composition_order_[j - 1];
SkRect platform_view_rect = GetPlatformViewRect(current_platform_view_id);
std::vector<SkIRect> intersection_rects = slice->region(platform_view_rect).getRects();
auto allocation_size = intersection_rects.size();
// For testing purposes, the overlay id is used to find the overlay view.
// This is the index of the layer for the current platform view.
auto overlay_id = platform_view_layers[current_platform_view_id].size();
// If the max number of allocations per platform view is exceeded,
// then join all the rects into a single one.
//
// TODO(egarciad): Consider making this configurable.
// https://github.com/flutter/flutter/issues/52510
if (allocation_size > kMaxLayerAllocations) {
SkIRect joined_rect = SkIRect::MakeEmpty();
for (const SkIRect& rect : intersection_rects) {
joined_rect.join(rect);
}
// Replace the rects in the intersection rects list for a single rect that is
// the union of all the rects in the list.
intersection_rects.clear();
intersection_rects.push_back(joined_rect);
}
for (SkIRect& joined_rect : intersection_rects) {
// Get the intersection rect between the current rect
// and the platform view rect.
joined_rect.intersect(platform_view_rect.roundOut());
// Clip the background canvas, so it doesn't contain any of the pixels drawn
// on the overlay layer.
background_canvas->ClipRect(SkRect::Make(joined_rect), DlCanvas::ClipOp::kDifference);
// Get a new host layer.
std::shared_ptr<FlutterPlatformViewLayer> layer =
GetLayer(gr_context, //
ios_context, //
slice, //
joined_rect, //
current_platform_view_id, //
overlay_id, //
((FlutterView*)flutter_view_.get()).pixelFormat //
);
did_submit &= layer->did_submit_last_frame;
platform_view_layers[current_platform_view_id].push_back(layer);
overlay_id++;
}
}
slice->render_into(background_canvas);
}
// Manually trigger the SkAutoCanvasRestore before we submit the frame
save.Restore();
// If a layer was allocated in the previous frame, but it's not used in the current frame,
// then it can be removed from the scene.
RemoveUnusedLayers();
// Organize the layers by their z indexes.
BringLayersIntoView(platform_view_layers);
// Mark all layers as available, so they can be used in the next frame.
layer_pool_->RecycleLayers();
did_submit &= frame->Submit();
// If the frame is submitted with embedded platform views,
// there should be a |[CATransaction begin]| call in this frame prior to all the drawing.
// If that case, we need to commit the transaction.
CommitCATransactionIfNeeded();
return did_submit;
}
void FlutterPlatformViewsController::BringLayersIntoView(LayersMap layer_map) {
FML_DCHECK(flutter_view_);
UIView* flutter_view = flutter_view_.get();
// Clear the `active_composition_order_`, which will be populated down below.
active_composition_order_.clear();
NSMutableArray* desired_platform_subviews = [NSMutableArray array];
for (size_t i = 0; i < composition_order_.size(); i++) {
int64_t platform_view_id = composition_order_[i];
std::vector<std::shared_ptr<FlutterPlatformViewLayer>> layers = layer_map[platform_view_id];
UIView* platform_view_root = root_views_[platform_view_id].get();
[desired_platform_subviews addObject:platform_view_root];
for (const std::shared_ptr<FlutterPlatformViewLayer>& layer : layers) {
[desired_platform_subviews addObject:layer->overlay_view_wrapper];
}
active_composition_order_.push_back(platform_view_id);
}
NSSet* desired_platform_subviews_set = [NSSet setWithArray:desired_platform_subviews];
NSArray* existing_platform_subviews = [flutter_view.subviews
filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object,
NSDictionary* bindings) {
return [desired_platform_subviews_set containsObject:object];
}]];
// Manipulate view hierarchy only if needed, to address a performance issue where
// `BringLayersIntoView` is called even when view hierarchy stays the same.
// See: https://github.com/flutter/flutter/issues/121833
// TODO(hellohuanlin): investigate if it is possible to skip unnecessary BringLayersIntoView.
if (![desired_platform_subviews isEqualToArray:existing_platform_subviews]) {
for (UIView* subview in desired_platform_subviews) {
// `addSubview` will automatically reorder subview if it is already added.
[flutter_view addSubview:subview];
}
}
}
std::shared_ptr<FlutterPlatformViewLayer> FlutterPlatformViewsController::GetLayer(
GrDirectContext* gr_context,
const std::shared_ptr<IOSContext>& ios_context,
EmbedderViewSlice* slice,
SkIRect rect,
int64_t view_id,
int64_t overlay_id,
MTLPixelFormat pixel_format) {
FML_DCHECK(flutter_view_);
std::shared_ptr<FlutterPlatformViewLayer> layer =
layer_pool_->GetLayer(gr_context, ios_context, pixel_format);
UIView* overlay_view_wrapper = layer->overlay_view_wrapper.get();
auto screenScale = [UIScreen mainScreen].scale;
// Set the size of the overlay view wrapper.
// This wrapper view masks the overlay view.
overlay_view_wrapper.frame = CGRectMake(rect.x() / screenScale, rect.y() / screenScale,
rect.width() / screenScale, rect.height() / screenScale);
// Set a unique view identifier, so the overlay_view_wrapper can be identified in XCUITests.
overlay_view_wrapper.accessibilityIdentifier =
[NSString stringWithFormat:@"platform_view[%lld].overlay[%lld]", view_id, overlay_id];
UIView* overlay_view = layer->overlay_view.get();
// Set the size of the overlay view.
// This size is equal to the device screen size.
overlay_view.frame = [flutter_view_.get() convertRect:flutter_view_.get().bounds
toView:overlay_view_wrapper];
// Set a unique view identifier, so the overlay_view can be identified in XCUITests.
overlay_view.accessibilityIdentifier =
[NSString stringWithFormat:@"platform_view[%lld].overlay_view[%lld]", view_id, overlay_id];
std::unique_ptr<SurfaceFrame> frame = layer->surface->AcquireFrame(frame_size_);
// If frame is null, AcquireFrame already printed out an error message.
if (!frame) {
return layer;
}
DlCanvas* overlay_canvas = frame->Canvas();
int restore_count = overlay_canvas->GetSaveCount();
overlay_canvas->Save();
overlay_canvas->ClipRect(SkRect::Make(rect));
overlay_canvas->Clear(DlColor::kTransparent());
slice->render_into(overlay_canvas);
overlay_canvas->RestoreToCount(restore_count);
layer->did_submit_last_frame = frame->Submit();
return layer;
}
void FlutterPlatformViewsController::RemoveUnusedLayers() {
std::vector<std::shared_ptr<FlutterPlatformViewLayer>> layers = layer_pool_->GetUnusedLayers();
for (const std::shared_ptr<FlutterPlatformViewLayer>& layer : layers) {
[layer->overlay_view_wrapper removeFromSuperview];
}
std::unordered_set<int64_t> composition_order_set;
for (int64_t view_id : composition_order_) {
composition_order_set.insert(view_id);
}
// Remove unused platform views.
for (int64_t view_id : active_composition_order_) {
if (composition_order_set.find(view_id) == composition_order_set.end()) {
UIView* platform_view_root = root_views_[view_id].get();
[platform_view_root removeFromSuperview];
}
}
}
void FlutterPlatformViewsController::DisposeViews() {
if (views_to_dispose_.empty()) {
return;
}
FML_DCHECK([[NSThread currentThread] isMainThread]);
std::unordered_set<int64_t> views_to_composite(composition_order_.begin(),
composition_order_.end());
std::unordered_set<int64_t> views_to_delay_dispose;
for (int64_t viewId : views_to_dispose_) {
if (views_to_composite.count(viewId)) {
views_to_delay_dispose.insert(viewId);
continue;
}
UIView* root_view = root_views_[viewId].get();
[root_view removeFromSuperview];
views_.erase(viewId);
touch_interceptors_.erase(viewId);
root_views_.erase(viewId);
current_composition_params_.erase(viewId);
clip_count_.erase(viewId);
views_to_recomposite_.erase(viewId);
}
views_to_dispose_ = std::move(views_to_delay_dispose);
}
void FlutterPlatformViewsController::BeginCATransaction() {
FML_DCHECK([[NSThread currentThread] isMainThread]);
FML_DCHECK(!catransaction_added_);
[CATransaction begin];
catransaction_added_ = true;
}
void FlutterPlatformViewsController::CommitCATransactionIfNeeded() {
if (catransaction_added_) {
FML_DCHECK([[NSThread currentThread] isMainThread]);
[CATransaction commit];
catransaction_added_ = false;
}
}
void FlutterPlatformViewsController::ResetFrameState() {
slices_.clear();
composition_order_.clear();
visited_platform_views_.clear();
}
} // namespace flutter
// This recognizers delays touch events from being dispatched to the responder chain until it failed
// recognizing a gesture.
//
// We only fail this recognizer when asked to do so by the Flutter framework (which does so by
// invoking an acceptGesture method on the platform_views channel). And this is how we allow the
// Flutter framework to delay or prevent the embedded view from getting a touch sequence.
@interface DelayingGestureRecognizer : UIGestureRecognizer <UIGestureRecognizerDelegate>
// Indicates that if the `DelayingGestureRecognizer`'s state should be set to
// `UIGestureRecognizerStateEnded` during next `touchesEnded` call.
@property(nonatomic) bool shouldEndInNextTouchesEnded;
// Indicates that the `DelayingGestureRecognizer`'s `touchesEnded` has been invoked without
// setting the state to `UIGestureRecognizerStateEnded`.
@property(nonatomic) bool touchedEndedWithoutBlocking;
- (instancetype)initWithTarget:(id)target
action:(SEL)action
forwardingRecognizer:(UIGestureRecognizer*)forwardingRecognizer;
@end
// While the DelayingGestureRecognizer is preventing touches from hitting the responder chain
// the touch events are not arriving to the FlutterView (and thus not arriving to the Flutter
// framework). We use this gesture recognizer to dispatch the events directly to the FlutterView
// while during this phase.
//
// If the Flutter framework decides to dispatch events to the embedded view, we fail the
// DelayingGestureRecognizer which sends the events up the responder chain. But since the events
// are handled by the embedded view they are not delivered to the Flutter framework in this phase
// as well. So during this phase as well the ForwardingGestureRecognizer dispatched the events
// directly to the FlutterView.
@interface ForwardingGestureRecognizer : UIGestureRecognizer <UIGestureRecognizerDelegate>
- (instancetype)initWithTarget:(id)target
platformViewsController:
(fml::WeakPtr<flutter::FlutterPlatformViewsController>)platformViewsController;
@end
@implementation FlutterTouchInterceptingView {
fml::scoped_nsobject<DelayingGestureRecognizer> _delayingRecognizer;
FlutterPlatformViewGestureRecognizersBlockingPolicy _blockingPolicy;
UIView* _embeddedView;
// The used as the accessiblityContainer.
// The `accessiblityContainer` is used in UIKit to determine the parent of this accessibility
// node.
NSObject* _flutterAccessibilityContainer;
}
- (instancetype)initWithEmbeddedView:(UIView*)embeddedView
platformViewsController:
(fml::WeakPtr<flutter::FlutterPlatformViewsController>)platformViewsController
gestureRecognizersBlockingPolicy:
(FlutterPlatformViewGestureRecognizersBlockingPolicy)blockingPolicy {
self = [super initWithFrame:embeddedView.frame];
if (self) {
self.multipleTouchEnabled = YES;
_embeddedView = embeddedView;
embeddedView.autoresizingMask =
(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[self addSubview:embeddedView];
ForwardingGestureRecognizer* forwardingRecognizer = [[[ForwardingGestureRecognizer alloc]
initWithTarget:self
platformViewsController:std::move(platformViewsController)] autorelease];
_delayingRecognizer.reset([[DelayingGestureRecognizer alloc]
initWithTarget:self
action:nil
forwardingRecognizer:forwardingRecognizer]);
_blockingPolicy = blockingPolicy;
[self addGestureRecognizer:_delayingRecognizer.get()];
[self addGestureRecognizer:forwardingRecognizer];
}
return self;
}
- (UIView*)embeddedView {
return [[_embeddedView retain] autorelease];
}
- (void)releaseGesture {
_delayingRecognizer.get().state = UIGestureRecognizerStateFailed;
}
- (void)blockGesture {
switch (_blockingPolicy) {
case FlutterPlatformViewGestureRecognizersBlockingPolicyEager:
// We block all other gesture recognizers immediately in this policy.
_delayingRecognizer.get().state = UIGestureRecognizerStateEnded;
break;
case FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded:
if (_delayingRecognizer.get().touchedEndedWithoutBlocking) {
// If touchesEnded of the `DelayingGesureRecognizer` has been already invoked,
// we want to set the state of the `DelayingGesureRecognizer` to
// `UIGestureRecognizerStateEnded` as soon as possible.
_delayingRecognizer.get().state = UIGestureRecognizerStateEnded;
} else {
// If touchesEnded of the `DelayingGesureRecognizer` has not been invoked,
// We will set a flag to notify the `DelayingGesureRecognizer` to set the state to
// `UIGestureRecognizerStateEnded` when touchesEnded is called.
_delayingRecognizer.get().shouldEndInNextTouchesEnded = YES;
}
break;
default:
break;
}
}
// We want the intercepting view to consume the touches and not pass the touches up to the parent
// view. Make the touch event method not call super will not pass the touches up to the parent view.
// Hence we overide the touch event methods and do nothing.
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
}
- (void)touchesMoved:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
}
- (void)touchesCancelled:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
}
- (void)setFlutterAccessibilityContainer:(NSObject*)flutterAccessibilityContainer {
_flutterAccessibilityContainer = flutterAccessibilityContainer;
}
- (id)accessibilityContainer {
return _flutterAccessibilityContainer;
}
@end
@implementation DelayingGestureRecognizer {
fml::scoped_nsobject<UIGestureRecognizer> _forwardingRecognizer;
}
- (instancetype)initWithTarget:(id)target
action:(SEL)action
forwardingRecognizer:(UIGestureRecognizer*)forwardingRecognizer {
self = [super initWithTarget:target action:action];
if (self) {
self.delaysTouchesBegan = YES;
self.delaysTouchesEnded = YES;
self.delegate = self;
self.shouldEndInNextTouchesEnded = NO;
self.touchedEndedWithoutBlocking = NO;
_forwardingRecognizer.reset([forwardingRecognizer retain]);
}
return self;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer {
// The forwarding gesture recognizer should always get all touch events, so it should not be
// required to fail by any other gesture recognizer.
return otherGestureRecognizer != _forwardingRecognizer.get() && otherGestureRecognizer != self;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
shouldRequireFailureOfGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer {
return otherGestureRecognizer == self;
}
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
self.touchedEndedWithoutBlocking = NO;
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
if (self.shouldEndInNextTouchesEnded) {
self.state = UIGestureRecognizerStateEnded;
self.shouldEndInNextTouchesEnded = NO;
} else {
self.touchedEndedWithoutBlocking = YES;
}
[super touchesEnded:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
self.state = UIGestureRecognizerStateFailed;
}
@end
@implementation ForwardingGestureRecognizer {
// Weak reference to FlutterPlatformViewsController. The FlutterPlatformViewsController has
// a reference to the FlutterViewController, where we can dispatch pointer events to.
//
// The lifecycle of FlutterPlatformViewsController is bind to FlutterEngine, which should always
// outlives the FlutterViewController. And ForwardingGestureRecognizer is owned by a subview of
// FlutterView, so the ForwardingGestureRecognizer never out lives FlutterViewController.
// Therefore, `_platformViewsController` should never be nullptr.
fml::WeakPtr<flutter::FlutterPlatformViewsController> _platformViewsController;
// Counting the pointers that has started in one touch sequence.
NSInteger _currentTouchPointersCount;
// We can't dispatch events to the framework without this back pointer.
// This gesture recognizer retains the `FlutterViewController` until the
// end of a gesture sequence, that is all the touches in touchesBegan are concluded
// with |touchesCancelled| or |touchesEnded|.
fml::scoped_nsobject<UIViewController> _flutterViewController;
}
- (instancetype)initWithTarget:(id)target
platformViewsController:
(fml::WeakPtr<flutter::FlutterPlatformViewsController>)platformViewsController {
self = [super initWithTarget:target action:nil];
if (self) {
self.delegate = self;
FML_DCHECK(platformViewsController.get() != nullptr);
_platformViewsController = std::move(platformViewsController);
_currentTouchPointersCount = 0;
}
return self;
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
FML_DCHECK(_currentTouchPointersCount >= 0);
if (_currentTouchPointersCount == 0) {
// At the start of each gesture sequence, we reset the `_flutterViewController`,
// so that all the touch events in the same sequence are forwarded to the same
// `_flutterViewController`.
_flutterViewController.reset([_platformViewsController->getFlutterViewController() retain]);
}
[_flutterViewController.get() touchesBegan:touches withEvent:event];
_currentTouchPointersCount += touches.count;
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
[_flutterViewController.get() touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
[_flutterViewController.get() touchesEnded:touches withEvent:event];
_currentTouchPointersCount -= touches.count;
// Touches in one touch sequence are sent to the touchesEnded method separately if different
// fingers stop touching the screen at different time. So one touchesEnded method triggering does
// not necessarially mean the touch sequence has ended. We Only set the state to
// UIGestureRecognizerStateFailed when all the touches in the current touch sequence is ended.
if (_currentTouchPointersCount == 0) {
self.state = UIGestureRecognizerStateFailed;
_flutterViewController.reset(nil);
}
}
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
// In the event of platform view is removed, iOS generates a "stationary" change type instead of
// "cancelled" change type.
// Flutter needs all the cancelled touches to be "cancelled" change types in order to correctly
// handle gesture sequence.
// We always override the change type to "cancelled".
[((FlutterViewController*)_flutterViewController.get()) forceTouchesCancelled:touches];
_currentTouchPointersCount -= touches.count;
if (_currentTouchPointersCount == 0) {
self.state = UIGestureRecognizerStateFailed;
_flutterViewController.reset(nil);
}
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:
(UIGestureRecognizer*)otherGestureRecognizer {
return YES;
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews.mm",
"repo_id": "engine",
"token_count": 19495
} | 330 |
// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_
#import <UIKit/UIKit.h>
#import "flutter/shell/platform/common/text_editing_delta.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterIndirectScribbleDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeySecondaryResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewResponder.h"
typedef NS_ENUM(NSInteger, FlutterScribbleFocusStatus) {
// NOLINTBEGIN(readability-identifier-naming)
FlutterScribbleFocusStatusUnfocused,
FlutterScribbleFocusStatusFocusing,
FlutterScribbleFocusStatusFocused,
// NOLINTEND(readability-identifier-naming)
};
typedef NS_ENUM(NSInteger, FlutterScribbleInteractionStatus) {
// NOLINTBEGIN(readability-identifier-naming)
FlutterScribbleInteractionStatusNone,
FlutterScribbleInteractionStatusStarted,
FlutterScribbleInteractionStatusEnding,
// NOLINTEND(readability-identifier-naming)
};
@interface FlutterTextInputPlugin
: NSObject <FlutterKeySecondaryResponder, UIIndirectScribbleInteractionDelegate>
@property(nonatomic, weak) UIViewController* viewController;
@property(nonatomic, weak) id<FlutterIndirectScribbleDelegate> indirectScribbleDelegate;
@property(nonatomic, strong)
NSMutableDictionary<UIScribbleElementIdentifier, NSValue*>* scribbleElements;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithDelegate:(id<FlutterTextInputDelegate>)textInputDelegate
NS_DESIGNATED_INITIALIZER;
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result;
/**
* The `UITextInput` implementation used to control text entry.
*
* This is used by `AccessibilityBridge` to forward interactions with iOS'
* accessibility system.
*/
- (UIView<UITextInput>*)textInputView;
/**
* These are used by the UIIndirectScribbleInteractionDelegate methods to handle focusing on the
* correct element.
*/
- (void)setUpIndirectScribbleInteraction:(id<FlutterViewResponder>)viewResponder;
- (void)resetViewResponder;
@end
/** An indexed position in the buffer of a Flutter text editing widget. */
@interface FlutterTextPosition : UITextPosition
@property(nonatomic, readonly) NSUInteger index;
@property(nonatomic, readonly) UITextStorageDirection affinity;
+ (instancetype)positionWithIndex:(NSUInteger)index;
+ (instancetype)positionWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity;
- (instancetype)initWithIndex:(NSUInteger)index affinity:(UITextStorageDirection)affinity;
@end
/** A range of text in the buffer of a Flutter text editing widget. */
@interface FlutterTextRange : UITextRange <NSCopying>
@property(nonatomic, readonly) NSRange range;
+ (instancetype)rangeWithNSRange:(NSRange)range;
@end
/** A tokenizer used by `FlutterTextInputView` to customize string parsing. */
@interface FlutterTokenizer : UITextInputStringTokenizer
@end
@interface FlutterTextSelectionRect : UITextSelectionRect
@property(nonatomic, assign) CGRect rect;
@property(nonatomic) NSUInteger position;
@property(nonatomic, assign) NSWritingDirection writingDirection;
@property(nonatomic) BOOL containsStart;
@property(nonatomic) BOOL containsEnd;
@property(nonatomic) BOOL isVertical;
+ (instancetype)selectionRectWithRectAndInfo:(CGRect)rect
position:(NSUInteger)position
writingDirection:(NSWritingDirection)writingDirection
containsStart:(BOOL)containsStart
containsEnd:(BOOL)containsEnd
isVertical:(BOOL)isVertical;
+ (instancetype)selectionRectWithRect:(CGRect)rect position:(NSUInteger)position;
+ (instancetype)selectionRectWithRect:(CGRect)rect
position:(NSUInteger)position
writingDirection:(NSWritingDirection)writingDirection;
- (instancetype)initWithRectAndInfo:(CGRect)rect
position:(NSUInteger)position
writingDirection:(NSWritingDirection)writingDirection
containsStart:(BOOL)containsStart
containsEnd:(BOOL)containsEnd
isVertical:(BOOL)isVertical;
- (instancetype)init NS_UNAVAILABLE;
- (BOOL)isRTL;
@end
API_AVAILABLE(ios(13.0)) @interface FlutterTextPlaceholder : UITextPlaceholder
@end
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
FLUTTER_DARWIN_EXPORT
#endif
@interface FlutterTextInputView : UIView <UITextInput, UIScribbleInteractionDelegate>
// UITextInput
@property(nonatomic, readonly) NSMutableString* text;
@property(readwrite, copy) UITextRange* selectedTextRange;
@property(nonatomic, strong) UITextRange* markedTextRange;
@property(nonatomic, copy) NSDictionary* markedTextStyle;
@property(nonatomic, weak) id<UITextInputDelegate> inputDelegate;
@property(nonatomic, strong) NSMutableArray* pendingDeltas;
// UITextInputTraits
@property(nonatomic) UITextAutocapitalizationType autocapitalizationType;
@property(nonatomic) UITextAutocorrectionType autocorrectionType;
@property(nonatomic) UITextSpellCheckingType spellCheckingType;
@property(nonatomic) BOOL enablesReturnKeyAutomatically;
@property(nonatomic) UIKeyboardAppearance keyboardAppearance;
@property(nonatomic) UIKeyboardType keyboardType;
@property(nonatomic) UIReturnKeyType returnKeyType;
@property(nonatomic, getter=isSecureTextEntry) BOOL secureTextEntry;
@property(nonatomic, getter=isEnableDeltaModel) BOOL enableDeltaModel;
@property(nonatomic) UITextSmartQuotesType smartQuotesType API_AVAILABLE(ios(11.0));
@property(nonatomic) UITextSmartDashesType smartDashesType API_AVAILABLE(ios(11.0));
@property(nonatomic, copy) UITextContentType textContentType API_AVAILABLE(ios(10.0));
@property(nonatomic, weak) UIAccessibilityElement* backingTextInputAccessibilityObject;
// Scribble Support
@property(nonatomic, weak) id<FlutterViewResponder> viewResponder;
@property(nonatomic) FlutterScribbleFocusStatus scribbleFocusStatus;
@property(nonatomic, strong) NSArray<FlutterTextSelectionRect*>* selectionRects;
- (void)resetScribbleInteractionStatusIfEnding;
- (BOOL)isScribbleAvailable;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)initWithCoder:(NSCoder*)aDecoder NS_UNAVAILABLE;
- (instancetype)initWithFrame:(CGRect)frame NS_UNAVAILABLE;
- (instancetype)initWithOwner:(FlutterTextInputPlugin*)textInputPlugin NS_DESIGNATED_INITIALIZER;
// TODO(louisehsu): These are being exposed to support Share in FlutterPlatformPlugin
// Consider moving that feature into FlutterTextInputPlugin to avoid exposing extra methods
- (CGRect)localRectFromFrameworkTransform:(CGRect)incomingRect;
- (CGRect)caretRectForPosition:(UITextPosition*)position;
@end
@interface UIView (FindFirstResponder)
@property(nonatomic, readonly) id flutterFirstResponder;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERTEXTINPUTPLUGIN_H_
| engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h",
"repo_id": "engine",
"token_count": 2667
} | 331 |
// 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.
#define FML_USED_ON_EMBEDDER
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import <os/log.h>
#include <memory>
#include "flutter/common/constants.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/platform/darwin/platform_version.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/runtime/ptrace_check.h"
#include "flutter/shell/common/thread_host.h"
#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterChannelKeyResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyPrimaryResponder.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterPlatformViews_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputDelegate.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/UIViewController+FlutterScreenAndSceneIfLoaded.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/platform_message_response_darwin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/vsync_waiter_ios.h"
#import "flutter/shell/platform/darwin/ios/platform_view_ios.h"
#import "flutter/shell/platform/embedder/embedder.h"
#import "flutter/third_party/spring_animation/spring_animation.h"
static constexpr int kMicrosecondsPerSecond = 1000 * 1000;
static constexpr CGFloat kScrollViewContentSize = 2.0;
static NSString* const kFlutterRestorationStateAppData = @"FlutterRestorationStateAppData";
NSNotificationName const FlutterSemanticsUpdateNotification = @"FlutterSemanticsUpdate";
NSNotificationName const FlutterViewControllerWillDealloc = @"FlutterViewControllerWillDealloc";
NSNotificationName const FlutterViewControllerHideHomeIndicator =
@"FlutterViewControllerHideHomeIndicator";
NSNotificationName const FlutterViewControllerShowHomeIndicator =
@"FlutterViewControllerShowHomeIndicator";
// Struct holding data to help adapt system mouse/trackpad events to embedder events.
typedef struct MouseState {
// Current coordinate of the mouse cursor in physical device pixels.
CGPoint location = CGPointZero;
// Last reported translation for an in-flight pan gesture in physical device pixels.
CGPoint last_translation = CGPointZero;
} MouseState;
// This is left a FlutterBinaryMessenger privately for now to give people a chance to notice the
// change. Unfortunately unless you have Werror turned on, incompatible pointers as arguments are
// just a warning.
@interface FlutterViewController () <FlutterBinaryMessenger, UIScrollViewDelegate>
// TODO(dkwingsmt): Make the view ID property public once the iOS shell
// supports multiple views.
// https://github.com/flutter/flutter/issues/138168
@property(nonatomic, readonly) int64_t viewIdentifier;
@property(nonatomic, readwrite, getter=isDisplayingFlutterUI) BOOL displayingFlutterUI;
@property(nonatomic, assign) BOOL isHomeIndicatorHidden;
@property(nonatomic, assign) BOOL isPresentingViewControllerAnimating;
/**
* Whether we should ignore viewport metrics updates during rotation transition.
*/
@property(nonatomic, assign) BOOL shouldIgnoreViewportMetricsUpdatesDuringRotation;
/**
* Keyboard animation properties
*/
@property(nonatomic, assign) CGFloat targetViewInsetBottom;
@property(nonatomic, assign) CGFloat originalViewInsetBottom;
@property(nonatomic, retain) VSyncClient* keyboardAnimationVSyncClient;
@property(nonatomic, assign) BOOL keyboardAnimationIsShowing;
@property(nonatomic, assign) fml::TimePoint keyboardAnimationStartTime;
@property(nonatomic, assign) BOOL isKeyboardInOrTransitioningFromBackground;
/// VSyncClient for touch events delivery frame rate correction.
///
/// On promotion devices(eg: iPhone13 Pro), the delivery frame rate of touch events is 60HZ
/// but the frame rate of rendering is 120HZ, which is different and will leads jitter and laggy.
/// With this VSyncClient, it can correct the delivery frame rate of touch events to let it keep
/// the same with frame rate of rendering.
@property(nonatomic, retain) VSyncClient* touchRateCorrectionVSyncClient;
/*
* Mouse and trackpad gesture recognizers
*/
// Mouse and trackpad hover
@property(nonatomic, retain)
UIHoverGestureRecognizer* hoverGestureRecognizer API_AVAILABLE(ios(13.4));
// Mouse wheel scrolling
@property(nonatomic, retain)
UIPanGestureRecognizer* discreteScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4));
// Trackpad and Magic Mouse scrolling
@property(nonatomic, retain)
UIPanGestureRecognizer* continuousScrollingPanGestureRecognizer API_AVAILABLE(ios(13.4));
// Trackpad pinching
@property(nonatomic, retain)
UIPinchGestureRecognizer* pinchGestureRecognizer API_AVAILABLE(ios(13.4));
// Trackpad rotating
@property(nonatomic, retain)
UIRotationGestureRecognizer* rotationGestureRecognizer API_AVAILABLE(ios(13.4));
/**
* Creates and registers plugins used by this view controller.
*/
- (void)addInternalPlugins;
- (void)deregisterNotifications;
@end
@implementation FlutterViewController {
std::unique_ptr<fml::WeakNSObjectFactory<FlutterViewController>> _weakFactory;
fml::scoped_nsobject<FlutterEngine> _engine;
// We keep a separate reference to this and create it ahead of time because we want to be able to
// set up a shell along with its platform view before the view has to appear.
fml::scoped_nsobject<FlutterView> _flutterView;
fml::scoped_nsobject<UIView> _splashScreenView;
fml::ScopedBlock<void (^)(void)> _flutterViewRenderedCallback;
UIInterfaceOrientationMask _orientationPreferences;
UIStatusBarStyle _statusBarStyle;
flutter::ViewportMetrics _viewportMetrics;
BOOL _initialized;
BOOL _viewOpaque;
BOOL _engineNeedsLaunch;
fml::scoped_nsobject<NSMutableSet<NSNumber*>> _ongoingTouches;
// This scroll view is a workaround to accommodate iOS 13 and higher. There isn't a way to get
// touches on the status bar to trigger scrolling to the top of a scroll view. We place a
// UIScrollView with height zero and a content offset so we can get those events. See also:
// https://github.com/flutter/flutter/issues/35050
fml::scoped_nsobject<UIScrollView> _scrollView;
fml::scoped_nsobject<UIView> _keyboardAnimationView;
fml::scoped_nsobject<SpringAnimation> _keyboardSpringAnimation;
MouseState _mouseState;
// Timestamp after which a scroll inertia cancel event should be inferred.
NSTimeInterval _scrollInertiaEventStartline;
// When an iOS app is running in emulation on an Apple Silicon Mac, trackpad input goes through
// a translation layer, and events are not received with precise deltas. Due to this, we can't
// rely on checking for a stationary trackpad event. Fortunately, AppKit will send an event of
// type UIEventTypeScroll following a scroll when inertia should stop. This field is needed to
// estimate if such an event represents the natural end of scrolling inertia or a user-initiated
// cancellation.
NSTimeInterval _scrollInertiaEventAppKitDeadline;
}
@synthesize displayingFlutterUI = _displayingFlutterUI;
@synthesize prefersStatusBarHidden = _flutterPrefersStatusBarHidden;
@dynamic viewIdentifier;
#pragma mark - Manage and override all designated initializers
- (instancetype)initWithEngine:(FlutterEngine*)engine
nibName:(nullable NSString*)nibName
bundle:(nullable NSBundle*)nibBundle {
NSAssert(engine != nil, @"Engine is required");
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
_viewOpaque = YES;
if (engine.viewController) {
FML_LOG(ERROR) << "The supplied FlutterEngine " << [[engine description] UTF8String]
<< " is already used with FlutterViewController instance "
<< [[engine.viewController description] UTF8String]
<< ". One instance of the FlutterEngine can only be attached to one "
"FlutterViewController at a time. Set FlutterEngine.viewController "
"to nil before attaching it to another FlutterViewController.";
}
_engine.reset([engine retain]);
_engineNeedsLaunch = NO;
_flutterView.reset([[FlutterView alloc] initWithDelegate:_engine
opaque:self.isViewOpaque
enableWideGamut:engine.project.isWideGamutEnabled]);
_weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>(self);
_ongoingTouches.reset([[NSMutableSet alloc] init]);
[self performCommonViewControllerInitialization];
[engine setViewController:self];
}
return self;
}
- (instancetype)initWithProject:(FlutterDartProject*)project
nibName:(NSString*)nibName
bundle:(NSBundle*)nibBundle {
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
[self sharedSetupWithProject:project initialRoute:nil];
}
return self;
}
- (instancetype)initWithProject:(FlutterDartProject*)project
initialRoute:(NSString*)initialRoute
nibName:(NSString*)nibName
bundle:(NSBundle*)nibBundle {
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
[self sharedSetupWithProject:project initialRoute:initialRoute];
}
return self;
}
- (instancetype)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
return [self initWithProject:nil nibName:nil bundle:nil];
}
- (instancetype)initWithCoder:(NSCoder*)aDecoder {
self = [super initWithCoder:aDecoder];
return self;
}
- (void)awakeFromNib {
[super awakeFromNib];
if (!_engine) {
[self sharedSetupWithProject:nil initialRoute:nil];
}
}
- (instancetype)init {
return [self initWithProject:nil nibName:nil bundle:nil];
}
- (void)sharedSetupWithProject:(nullable FlutterDartProject*)project
initialRoute:(nullable NSString*)initialRoute {
// Need the project to get settings for the view. Initializing it here means
// the Engine class won't initialize it later.
if (!project) {
project = [[[FlutterDartProject alloc] init] autorelease];
}
FlutterView.forceSoftwareRendering = project.settings.enable_software_rendering;
_weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterViewController>>(self);
auto engine = fml::scoped_nsobject<FlutterEngine>{[[FlutterEngine alloc]
initWithName:@"io.flutter"
project:project
allowHeadlessExecution:self.engineAllowHeadlessExecution
restorationEnabled:[self restorationIdentifier] != nil]};
if (!engine) {
return;
}
_viewOpaque = YES;
_engine = engine;
_flutterView.reset([[FlutterView alloc] initWithDelegate:_engine
opaque:self.isViewOpaque
enableWideGamut:project.isWideGamutEnabled]);
[_engine.get() createShell:nil libraryURI:nil initialRoute:initialRoute];
_engineNeedsLaunch = YES;
_ongoingTouches.reset([[NSMutableSet alloc] init]);
[self loadDefaultSplashScreenView];
[self performCommonViewControllerInitialization];
}
- (BOOL)isViewOpaque {
return _viewOpaque;
}
- (void)setViewOpaque:(BOOL)value {
_viewOpaque = value;
if (_flutterView.get().layer.opaque != value) {
_flutterView.get().layer.opaque = value;
[_flutterView.get().layer setNeedsLayout];
}
}
#pragma mark - Common view controller initialization tasks
- (void)performCommonViewControllerInitialization {
if (_initialized) {
return;
}
_initialized = YES;
_orientationPreferences = UIInterfaceOrientationMaskAll;
_statusBarStyle = UIStatusBarStyleDefault;
[self setUpNotificationCenterObservers];
}
- (FlutterEngine*)engine {
return _engine.get();
}
- (fml::WeakNSObject<FlutterViewController>)getWeakNSObject {
return _weakFactory->GetWeakNSObject();
}
- (void)setUpNotificationCenterObservers {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
[center addObserver:self
selector:@selector(onOrientationPreferencesUpdated:)
name:@(flutter::kOrientationUpdateNotificationName)
object:nil];
[center addObserver:self
selector:@selector(onPreferredStatusBarStyleUpdated:)
name:@(flutter::kOverlayStyleUpdateNotificationName)
object:nil];
#if APPLICATION_EXTENSION_API_ONLY
if (@available(iOS 13.0, *)) {
[self setUpSceneLifecycleNotifications:center];
} else {
[self setUpApplicationLifecycleNotifications:center];
}
#else
[self setUpApplicationLifecycleNotifications:center];
#endif
[center addObserver:self
selector:@selector(keyboardWillChangeFrame:)
name:UIKeyboardWillChangeFrameNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardWillShowNotification:)
name:UIKeyboardWillShowNotification
object:nil];
[center addObserver:self
selector:@selector(keyboardWillBeHidden:)
name:UIKeyboardWillHideNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityVoiceOverStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilitySwitchControlStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilitySpeakScreenStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityInvertColorsStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityReduceMotionStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityBoldTextStatusDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityDarkerSystemColorsStatusDidChangeNotification
object:nil];
if (@available(iOS 13.0, *)) {
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:UIAccessibilityOnOffSwitchLabelsDidChangeNotification
object:nil];
}
[center addObserver:self
selector:@selector(onUserSettingsChanged:)
name:UIContentSizeCategoryDidChangeNotification
object:nil];
[center addObserver:self
selector:@selector(onHideHomeIndicatorNotification:)
name:FlutterViewControllerHideHomeIndicator
object:nil];
[center addObserver:self
selector:@selector(onShowHomeIndicatorNotification:)
name:FlutterViewControllerShowHomeIndicator
object:nil];
}
- (void)setUpSceneLifecycleNotifications:(NSNotificationCenter*)center API_AVAILABLE(ios(13.0)) {
[center addObserver:self
selector:@selector(sceneBecameActive:)
name:UISceneDidActivateNotification
object:nil];
[center addObserver:self
selector:@selector(sceneWillResignActive:)
name:UISceneWillDeactivateNotification
object:nil];
[center addObserver:self
selector:@selector(sceneWillDisconnect:)
name:UISceneDidDisconnectNotification
object:nil];
[center addObserver:self
selector:@selector(sceneDidEnterBackground:)
name:UISceneDidEnterBackgroundNotification
object:nil];
[center addObserver:self
selector:@selector(sceneWillEnterForeground:)
name:UISceneWillEnterForegroundNotification
object:nil];
}
- (void)setUpApplicationLifecycleNotifications:(NSNotificationCenter*)center {
[center addObserver:self
selector:@selector(applicationBecameActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:nil];
[center addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
- (void)setInitialRoute:(NSString*)route {
[[_engine.get() navigationChannel] invokeMethod:@"setInitialRoute" arguments:route];
}
- (void)popRoute {
[[_engine.get() navigationChannel] invokeMethod:@"popRoute" arguments:nil];
}
- (void)pushRoute:(NSString*)route {
[[_engine.get() navigationChannel] invokeMethod:@"pushRoute" arguments:route];
}
#pragma mark - Loading the view
static UIView* GetViewOrPlaceholder(UIView* existing_view) {
if (existing_view) {
return existing_view;
}
auto placeholder = [[[UIView alloc] init] autorelease];
placeholder.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
if (@available(iOS 13.0, *)) {
placeholder.backgroundColor = UIColor.systemBackgroundColor;
} else {
placeholder.backgroundColor = UIColor.whiteColor;
}
placeholder.autoresizesSubviews = YES;
// Only add the label when we know we have failed to enable tracing (and it was necessary).
// Otherwise, a spurious warning will be shown in cases where an engine cannot be initialized for
// other reasons.
if (flutter::GetTracingResult() == flutter::TracingResult::kDisabled) {
auto messageLabel = [[[UILabel alloc] init] autorelease];
messageLabel.numberOfLines = 0u;
messageLabel.textAlignment = NSTextAlignmentCenter;
messageLabel.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
messageLabel.text =
@"In iOS 14+, debug mode Flutter apps can only be launched from Flutter tooling, "
@"IDEs with Flutter plugins or from Xcode.\n\nAlternatively, build in profile or release "
@"modes to enable launching from the home screen.";
[placeholder addSubview:messageLabel];
}
return placeholder;
}
- (void)loadView {
self.view = GetViewOrPlaceholder(_flutterView.get());
self.view.multipleTouchEnabled = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self installSplashScreenViewIfNecessary];
UIScrollView* scrollView = [[UIScrollView alloc] init];
scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
// The color shouldn't matter since it is offscreen.
scrollView.backgroundColor = UIColor.whiteColor;
scrollView.delegate = self;
// This is an arbitrary small size.
scrollView.contentSize = CGSizeMake(kScrollViewContentSize, kScrollViewContentSize);
// This is an arbitrary offset that is not CGPointZero.
scrollView.contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize);
[self.view addSubview:scrollView];
_scrollView.reset(scrollView);
}
- (flutter::PointerData)generatePointerDataForFake {
flutter::PointerData pointer_data;
pointer_data.Clear();
pointer_data.kind = flutter::PointerData::DeviceKind::kTouch;
// `UITouch.timestamp` is defined as seconds since system startup. Synthesized events can get this
// time with `NSProcessInfo.systemUptime`. See
// https://developer.apple.com/documentation/uikit/uitouch/1618144-timestamp?language=objc
pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond;
return pointer_data;
}
static void SendFakeTouchEvent(UIScreen* screen,
FlutterEngine* engine,
CGPoint location,
flutter::PointerData::Change change) {
const CGFloat scale = screen.scale;
flutter::PointerData pointer_data = [[engine viewController] generatePointerDataForFake];
pointer_data.physical_x = location.x * scale;
pointer_data.physical_y = location.y * scale;
auto packet = std::make_unique<flutter::PointerDataPacket>(/*count=*/1);
pointer_data.change = change;
packet->SetPointerData(0, pointer_data);
[engine dispatchPointerDataPacket:std::move(packet)];
}
- (BOOL)scrollViewShouldScrollToTop:(UIScrollView*)scrollView {
if (!_engine) {
return NO;
}
CGPoint statusBarPoint = CGPointZero;
UIScreen* screen = [self flutterScreenIfViewLoaded];
if (screen) {
SendFakeTouchEvent(screen, _engine.get(), statusBarPoint, flutter::PointerData::Change::kDown);
SendFakeTouchEvent(screen, _engine.get(), statusBarPoint, flutter::PointerData::Change::kUp);
}
return NO;
}
#pragma mark - Managing launch views
- (void)installSplashScreenViewIfNecessary {
// Show the launch screen view again on top of the FlutterView if available.
// This launch screen view will be removed once the first Flutter frame is rendered.
if (_splashScreenView && (self.isBeingPresented || self.isMovingToParentViewController)) {
[_splashScreenView.get() removeFromSuperview];
_splashScreenView.reset();
return;
}
// Use the property getter to initialize the default value.
UIView* splashScreenView = self.splashScreenView;
if (splashScreenView == nil) {
return;
}
splashScreenView.frame = self.view.bounds;
[self.view addSubview:splashScreenView];
}
+ (BOOL)automaticallyNotifiesObserversOfDisplayingFlutterUI {
return NO;
}
- (void)setDisplayingFlutterUI:(BOOL)displayingFlutterUI {
if (_displayingFlutterUI != displayingFlutterUI) {
if (displayingFlutterUI == YES) {
if (!self.viewIfLoaded.window) {
return;
}
}
[self willChangeValueForKey:@"displayingFlutterUI"];
_displayingFlutterUI = displayingFlutterUI;
[self didChangeValueForKey:@"displayingFlutterUI"];
}
}
- (void)callViewRenderedCallback {
self.displayingFlutterUI = YES;
if (_flutterViewRenderedCallback != nil) {
_flutterViewRenderedCallback.get()();
_flutterViewRenderedCallback.reset();
}
}
- (void)removeSplashScreenView:(dispatch_block_t _Nullable)onComplete {
NSAssert(_splashScreenView, @"The splash screen view must not be null");
UIView* splashScreen = [_splashScreenView.get() retain];
_splashScreenView.reset();
[UIView animateWithDuration:0.2
animations:^{
splashScreen.alpha = 0;
}
completion:^(BOOL finished) {
[splashScreen removeFromSuperview];
[splashScreen release];
if (onComplete) {
onComplete();
}
}];
}
- (void)installFirstFrameCallback {
if (!_engine) {
return;
}
fml::WeakPtr<flutter::PlatformViewIOS> weakPlatformView = [_engine.get() platformView];
if (!weakPlatformView) {
return;
}
// Start on the platform thread.
weakPlatformView->SetNextFrameCallback([weakSelf = [self getWeakNSObject],
platformTaskRunner = [_engine.get() platformTaskRunner],
rasterTaskRunner = [_engine.get() rasterTaskRunner]]() {
FML_DCHECK(rasterTaskRunner->RunsTasksOnCurrentThread());
// Get callback on raster thread and jump back to platform thread.
platformTaskRunner->PostTask([weakSelf]() {
if (weakSelf) {
fml::scoped_nsobject<FlutterViewController> flutterViewController(
[(FlutterViewController*)weakSelf.get() retain]);
if (flutterViewController) {
if (flutterViewController.get()->_splashScreenView) {
[flutterViewController removeSplashScreenView:^{
[flutterViewController callViewRenderedCallback];
}];
} else {
[flutterViewController callViewRenderedCallback];
}
}
}
});
});
}
#pragma mark - Properties
- (int64_t)viewIdentifier {
// TODO(dkwingsmt): Fill the view ID property with the correct value once the
// iOS shell supports multiple views.
return flutter::kFlutterImplicitViewId;
}
- (UIView*)splashScreenView {
if (!_splashScreenView) {
return nil;
}
return _splashScreenView.get();
}
- (UIView*)keyboardAnimationView {
return _keyboardAnimationView.get();
}
- (SpringAnimation*)keyboardSpringAnimation {
return _keyboardSpringAnimation.get();
}
- (BOOL)loadDefaultSplashScreenView {
NSString* launchscreenName =
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"UILaunchStoryboardName"];
if (launchscreenName == nil) {
return NO;
}
UIView* splashView = [self splashScreenFromStoryboard:launchscreenName];
if (!splashView) {
splashView = [self splashScreenFromXib:launchscreenName];
}
if (!splashView) {
return NO;
}
self.splashScreenView = splashView;
return YES;
}
- (UIView*)splashScreenFromStoryboard:(NSString*)name {
UIStoryboard* storyboard = nil;
@try {
storyboard = [UIStoryboard storyboardWithName:name bundle:nil];
} @catch (NSException* exception) {
return nil;
}
if (storyboard) {
UIViewController* splashScreenViewController = [storyboard instantiateInitialViewController];
return splashScreenViewController.view;
}
return nil;
}
- (UIView*)splashScreenFromXib:(NSString*)name {
NSArray* objects = nil;
@try {
objects = [[NSBundle mainBundle] loadNibNamed:name owner:self options:nil];
} @catch (NSException* exception) {
return nil;
}
if ([objects count] != 0) {
UIView* view = [objects objectAtIndex:0];
return view;
}
return nil;
}
- (void)setSplashScreenView:(UIView*)view {
if (!view) {
// Special case: user wants to remove the splash screen view.
if (_splashScreenView) {
[self removeSplashScreenView:nil];
}
return;
}
_splashScreenView.reset([view retain]);
_splashScreenView.get().autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
}
- (void)setFlutterViewDidRenderCallback:(void (^)(void))callback {
_flutterViewRenderedCallback.reset(callback, fml::scoped_policy::OwnershipPolicy::kRetain);
}
#pragma mark - Surface creation and teardown updates
- (void)surfaceUpdated:(BOOL)appeared {
if (!_engine) {
return;
}
// NotifyCreated/NotifyDestroyed are synchronous and require hops between the UI and raster
// thread.
if (appeared) {
[self installFirstFrameCallback];
[_engine.get() platformViewsController]->SetFlutterView(_flutterView.get());
[_engine.get() platformViewsController]->SetFlutterViewController(self);
[_engine.get() iosPlatformView]->NotifyCreated();
} else {
self.displayingFlutterUI = NO;
[_engine.get() iosPlatformView]->NotifyDestroyed();
[_engine.get() platformViewsController]->SetFlutterView(nullptr);
[_engine.get() platformViewsController]->SetFlutterViewController(nullptr);
}
}
#pragma mark - UIViewController lifecycle notifications
- (void)viewDidLoad {
TRACE_EVENT0("flutter", "viewDidLoad");
if (_engine && _engineNeedsLaunch) {
[_engine.get() launchEngine:nil libraryURI:nil entrypointArgs:nil];
[_engine.get() setViewController:self];
_engineNeedsLaunch = NO;
} else if ([_engine.get() viewController] == self) {
[_engine.get() attachView];
}
// Register internal plugins.
[self addInternalPlugins];
// Create a vsync client to correct delivery frame rate of touch events if needed.
[self createTouchRateCorrectionVSyncClientIfNeeded];
if (@available(iOS 13.4, *)) {
_hoverGestureRecognizer =
[[UIHoverGestureRecognizer alloc] initWithTarget:self action:@selector(hoverEvent:)];
_hoverGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_hoverGestureRecognizer];
_discreteScrollingPanGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(discreteScrollEvent:)];
_discreteScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskDiscrete;
// Disallowing all touch types. If touch events are allowed here, touches to the screen will be
// consumed by the UIGestureRecognizer instead of being passed through to flutter via
// touchesBegan. Trackpad and mouse scrolls are sent by the platform as scroll events rather
// than touch events, so they will still be received.
_discreteScrollingPanGestureRecognizer.allowedTouchTypes = @[];
_discreteScrollingPanGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_discreteScrollingPanGestureRecognizer];
_continuousScrollingPanGestureRecognizer =
[[UIPanGestureRecognizer alloc] initWithTarget:self
action:@selector(continuousScrollEvent:)];
_continuousScrollingPanGestureRecognizer.allowedScrollTypesMask = UIScrollTypeMaskContinuous;
_continuousScrollingPanGestureRecognizer.allowedTouchTypes = @[];
_continuousScrollingPanGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_continuousScrollingPanGestureRecognizer];
_pinchGestureRecognizer =
[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchEvent:)];
_pinchGestureRecognizer.allowedTouchTypes = @[];
_pinchGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_pinchGestureRecognizer];
_rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] init];
_rotationGestureRecognizer.allowedTouchTypes = @[];
_rotationGestureRecognizer.delegate = self;
[_flutterView.get() addGestureRecognizer:_rotationGestureRecognizer];
}
[super viewDidLoad];
}
- (void)addInternalPlugins {
self.keyboardManager = [[[FlutterKeyboardManager alloc] init] autorelease];
fml::WeakNSObject<FlutterViewController> weakSelf = [self getWeakNSObject];
FlutterSendKeyEvent sendEvent =
^(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* userData) {
if (weakSelf) {
[weakSelf.get()->_engine.get() sendKeyEvent:event callback:callback userData:userData];
}
};
[self.keyboardManager addPrimaryResponder:[[[FlutterEmbedderKeyResponder alloc]
initWithSendEvent:sendEvent] autorelease]];
FlutterChannelKeyResponder* responder = [[[FlutterChannelKeyResponder alloc]
initWithChannel:self.engine.keyEventChannel] autorelease];
[self.keyboardManager addPrimaryResponder:responder];
FlutterTextInputPlugin* textInputPlugin = self.engine.textInputPlugin;
if (textInputPlugin != nil) {
[self.keyboardManager addSecondaryResponder:textInputPlugin];
}
if ([_engine.get() viewController] == self) {
[textInputPlugin setUpIndirectScribbleInteraction:self];
}
}
- (void)removeInternalPlugins {
self.keyboardManager = nil;
}
- (void)viewWillAppear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewWillAppear");
if ([_engine.get() viewController] == self) {
// Send platform settings to Flutter, e.g., platform brightness.
[self onUserSettingsChanged:nil];
// Only recreate surface on subsequent appearances when viewport metrics are known.
// First time surface creation is done on viewDidLayoutSubviews.
if (_viewportMetrics.physical_width) {
[self surfaceUpdated:YES];
}
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.inactive"];
[[_engine.get() restorationPlugin] markRestorationComplete];
}
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewDidAppear");
if ([_engine.get() viewController] == self) {
[self onUserSettingsChanged:nil];
[self onAccessibilityStatusChanged:nil];
BOOL stateIsActive = YES;
#if APPLICATION_EXTENSION_API_ONLY
if (@available(iOS 13.0, *)) {
stateIsActive = self.flutterWindowSceneIfViewLoaded.activationState ==
UISceneActivationStateForegroundActive;
}
#else
stateIsActive = UIApplication.sharedApplication.applicationState == UIApplicationStateActive;
#endif
if (stateIsActive) {
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.resumed"];
}
}
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewWillDisappear");
if ([_engine.get() viewController] == self) {
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.inactive"];
}
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
TRACE_EVENT0("flutter", "viewDidDisappear");
if ([_engine.get() viewController] == self) {
[self invalidateKeyboardAnimationVSyncClient];
[self ensureViewportMetricsIsCorrect];
[self surfaceUpdated:NO];
[[_engine.get() lifecycleChannel] sendMessage:@"AppLifecycleState.paused"];
[self flushOngoingTouches];
[_engine.get() notifyLowMemory];
}
[super viewDidDisappear:animated];
}
- (void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// We delay the viewport metrics update for half of rotation transition duration, to address
// a bug with distorted aspect ratio.
// See: https://github.com/flutter/flutter/issues/16322
//
// This approach does not fully resolve all distortion problem. But instead, it reduces the
// rotation distortion roughly from 4x to 2x. The most distorted frames occur in the middle
// of the transition when it is rotating the fastest, making it hard to notice.
NSTimeInterval transitionDuration = coordinator.transitionDuration;
// Do not delay viewport metrics update if zero transition duration.
if (transitionDuration == 0) {
return;
}
_shouldIgnoreViewportMetricsUpdatesDuringRotation = YES;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
static_cast<int64_t>(transitionDuration / 2.0 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
// `viewWillTransitionToSize` is only called after the previous rotation is
// complete. So there won't be race condition for this flag.
_shouldIgnoreViewportMetricsUpdatesDuringRotation = NO;
[self updateViewportMetricsIfNeeded];
});
}
- (void)flushOngoingTouches {
if (_engine && _ongoingTouches.get().count > 0) {
auto packet = std::make_unique<flutter::PointerDataPacket>(_ongoingTouches.get().count);
size_t pointer_index = 0;
// If the view controller is going away, we want to flush cancel all the ongoing
// touches to the framework so nothing gets orphaned.
for (NSNumber* device in _ongoingTouches.get()) {
// Create fake PointerData to balance out each previously started one for the framework.
flutter::PointerData pointer_data = [self generatePointerDataForFake];
pointer_data.change = flutter::PointerData::Change::kCancel;
pointer_data.device = device.longLongValue;
pointer_data.pointer_identifier = 0;
pointer_data.view_id = self.viewIdentifier;
// Anything we put here will be arbitrary since there are no touches.
pointer_data.physical_x = 0;
pointer_data.physical_y = 0;
pointer_data.physical_delta_x = 0.0;
pointer_data.physical_delta_y = 0.0;
pointer_data.pressure = 1.0;
pointer_data.pressure_max = 1.0;
packet->SetPointerData(pointer_index++, pointer_data);
}
[_ongoingTouches removeAllObjects];
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
}
- (void)deregisterNotifications {
[[NSNotificationCenter defaultCenter] postNotificationName:FlutterViewControllerWillDealloc
object:self
userInfo:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dealloc {
// It will be destroyed and invalidate its weak pointers
// before any other members are destroyed.
_weakFactory.reset();
[self removeInternalPlugins];
[self deregisterNotifications];
[self invalidateKeyboardAnimationVSyncClient];
[self invalidateTouchRateCorrectionVSyncClient];
_scrollView.get().delegate = nil;
_hoverGestureRecognizer.delegate = nil;
[_hoverGestureRecognizer release];
_discreteScrollingPanGestureRecognizer.delegate = nil;
[_discreteScrollingPanGestureRecognizer release];
_continuousScrollingPanGestureRecognizer.delegate = nil;
[_continuousScrollingPanGestureRecognizer release];
_pinchGestureRecognizer.delegate = nil;
[_pinchGestureRecognizer release];
_rotationGestureRecognizer.delegate = nil;
[_rotationGestureRecognizer release];
[super dealloc];
}
#pragma mark - Application lifecycle notifications
- (void)applicationBecameActive:(NSNotification*)notification {
TRACE_EVENT0("flutter", "applicationBecameActive");
[self appOrSceneBecameActive];
}
- (void)applicationWillResignActive:(NSNotification*)notification {
TRACE_EVENT0("flutter", "applicationWillResignActive");
[self appOrSceneWillResignActive];
}
- (void)applicationWillTerminate:(NSNotification*)notification {
[self appOrSceneWillTerminate];
}
- (void)applicationDidEnterBackground:(NSNotification*)notification {
TRACE_EVENT0("flutter", "applicationDidEnterBackground");
[self appOrSceneDidEnterBackground];
}
- (void)applicationWillEnterForeground:(NSNotification*)notification {
TRACE_EVENT0("flutter", "applicationWillEnterForeground");
[self appOrSceneWillEnterForeground];
}
#pragma mark - Scene lifecycle notifications
- (void)sceneBecameActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
TRACE_EVENT0("flutter", "sceneBecameActive");
[self appOrSceneBecameActive];
}
- (void)sceneWillResignActive:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
TRACE_EVENT0("flutter", "sceneWillResignActive");
[self appOrSceneWillResignActive];
}
- (void)sceneWillDisconnect:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
[self appOrSceneWillTerminate];
}
- (void)sceneDidEnterBackground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
TRACE_EVENT0("flutter", "sceneDidEnterBackground");
[self appOrSceneDidEnterBackground];
}
- (void)sceneWillEnterForeground:(NSNotification*)notification API_AVAILABLE(ios(13.0)) {
TRACE_EVENT0("flutter", "sceneWillEnterForeground");
[self appOrSceneWillEnterForeground];
}
#pragma mark - Lifecycle shared
- (void)appOrSceneBecameActive {
self.isKeyboardInOrTransitioningFromBackground = NO;
if (_viewportMetrics.physical_width) {
[self surfaceUpdated:YES];
}
[self performSelector:@selector(goToApplicationLifecycle:)
withObject:@"AppLifecycleState.resumed"
afterDelay:0.0f];
}
- (void)appOrSceneWillResignActive {
[NSObject cancelPreviousPerformRequestsWithTarget:self
selector:@selector(goToApplicationLifecycle:)
object:@"AppLifecycleState.resumed"];
[self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
}
- (void)appOrSceneWillTerminate {
[self goToApplicationLifecycle:@"AppLifecycleState.detached"];
[self.engine destroyContext];
}
- (void)appOrSceneDidEnterBackground {
self.isKeyboardInOrTransitioningFromBackground = YES;
[self surfaceUpdated:NO];
[self goToApplicationLifecycle:@"AppLifecycleState.paused"];
}
- (void)appOrSceneWillEnterForeground {
[self goToApplicationLifecycle:@"AppLifecycleState.inactive"];
}
// Make this transition only while this current view controller is visible.
- (void)goToApplicationLifecycle:(nonnull NSString*)state {
// Accessing self.view will create the view. Instead use viewIfLoaded
// to check whether the view is attached to window.
if (self.viewIfLoaded.window) {
[[_engine.get() lifecycleChannel] sendMessage:state];
}
}
#pragma mark - Touch event handling
static flutter::PointerData::Change PointerDataChangeFromUITouchPhase(UITouchPhase phase) {
switch (phase) {
case UITouchPhaseBegan:
return flutter::PointerData::Change::kDown;
case UITouchPhaseMoved:
case UITouchPhaseStationary:
// There is no EVENT_TYPE_POINTER_STATIONARY. So we just pass a move type
// with the same coordinates
return flutter::PointerData::Change::kMove;
case UITouchPhaseEnded:
return flutter::PointerData::Change::kUp;
case UITouchPhaseCancelled:
return flutter::PointerData::Change::kCancel;
default:
// TODO(53695): Handle the `UITouchPhaseRegion`... enum values.
FML_DLOG(INFO) << "Unhandled touch phase: " << phase;
break;
}
return flutter::PointerData::Change::kCancel;
}
static flutter::PointerData::DeviceKind DeviceKindFromTouchType(UITouch* touch) {
switch (touch.type) {
case UITouchTypeDirect:
case UITouchTypeIndirect:
return flutter::PointerData::DeviceKind::kTouch;
case UITouchTypeStylus:
return flutter::PointerData::DeviceKind::kStylus;
case UITouchTypeIndirectPointer:
return flutter::PointerData::DeviceKind::kMouse;
default:
FML_DLOG(INFO) << "Unhandled touch type: " << touch.type;
break;
}
return flutter::PointerData::DeviceKind::kTouch;
}
// Dispatches the UITouches to the engine. Usually, the type of change of the touch is determined
// from the UITouch's phase. However, FlutterAppDelegate fakes touches to ensure that touch events
// in the status bar area are available to framework code. The change type (optional) of the faked
// touch is specified in the second argument.
- (void)dispatchTouches:(NSSet*)touches
pointerDataChangeOverride:(flutter::PointerData::Change*)overridden_change
event:(UIEvent*)event {
if (!_engine) {
return;
}
// If the UIApplicationSupportsIndirectInputEvents in Info.plist returns YES, then the platform
// dispatches indirect pointer touches (trackpad clicks) as UITouch with a type of
// UITouchTypeIndirectPointer and different identifiers for each click. They are translated into
// Flutter pointer events with type of kMouse and different device IDs. These devices must be
// terminated with kRemove events when the touches end, otherwise they will keep triggering hover
// events.
//
// If the UIApplicationSupportsIndirectInputEvents in Info.plist returns NO, then the platform
// dispatches indirect pointer touches (trackpad clicks) as UITouch with a type of
// UITouchTypeIndirectPointer and different identifiers for each click. They are translated into
// Flutter pointer events with type of kTouch and different device IDs. Removing these devices is
// neither necessary nor harmful.
//
// Therefore Flutter always removes these devices. The touches_to_remove_count tracks how many
// remove events are needed in this group of touches to properly allocate space for the packet.
// The remove event of a touch is synthesized immediately after its normal event.
//
// See also:
// https://developer.apple.com/documentation/uikit/pointer_interactions?language=objc
// https://developer.apple.com/documentation/bundleresources/information_property_list/uiapplicationsupportsindirectinputevents?language=objc
NSUInteger touches_to_remove_count = 0;
for (UITouch* touch in touches) {
if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
touches_to_remove_count++;
}
}
// Activate or pause the correction of delivery frame rate of touch events.
[self triggerTouchRateCorrectionIfNeeded:touches];
const CGFloat scale = [self flutterScreenIfViewLoaded].scale;
auto packet =
std::make_unique<flutter::PointerDataPacket>(touches.count + touches_to_remove_count);
size_t pointer_index = 0;
for (UITouch* touch in touches) {
CGPoint windowCoordinates = [touch locationInView:self.view];
flutter::PointerData pointer_data;
pointer_data.Clear();
constexpr int kMicrosecondsPerSecond = 1000 * 1000;
pointer_data.time_stamp = touch.timestamp * kMicrosecondsPerSecond;
pointer_data.change = overridden_change != nullptr
? *overridden_change
: PointerDataChangeFromUITouchPhase(touch.phase);
pointer_data.kind = DeviceKindFromTouchType(touch);
pointer_data.device = reinterpret_cast<int64_t>(touch);
pointer_data.view_id = self.viewIdentifier;
// Pointer will be generated in pointer_data_packet_converter.cc.
pointer_data.pointer_identifier = 0;
pointer_data.physical_x = windowCoordinates.x * scale;
pointer_data.physical_y = windowCoordinates.y * scale;
// Delta will be generated in pointer_data_packet_converter.cc.
pointer_data.physical_delta_x = 0.0;
pointer_data.physical_delta_y = 0.0;
NSNumber* deviceKey = [NSNumber numberWithLongLong:pointer_data.device];
// Track touches that began and not yet stopped so we can flush them
// if the view controller goes away.
switch (pointer_data.change) {
case flutter::PointerData::Change::kDown:
[_ongoingTouches addObject:deviceKey];
break;
case flutter::PointerData::Change::kCancel:
case flutter::PointerData::Change::kUp:
[_ongoingTouches removeObject:deviceKey];
break;
case flutter::PointerData::Change::kHover:
case flutter::PointerData::Change::kMove:
// We're only tracking starts and stops.
break;
case flutter::PointerData::Change::kAdd:
case flutter::PointerData::Change::kRemove:
// We don't use kAdd/kRemove.
break;
case flutter::PointerData::Change::kPanZoomStart:
case flutter::PointerData::Change::kPanZoomUpdate:
case flutter::PointerData::Change::kPanZoomEnd:
// We don't send pan/zoom events here
break;
}
// pressure_min is always 0.0
pointer_data.pressure = touch.force;
pointer_data.pressure_max = touch.maximumPossibleForce;
pointer_data.radius_major = touch.majorRadius;
pointer_data.radius_min = touch.majorRadius - touch.majorRadiusTolerance;
pointer_data.radius_max = touch.majorRadius + touch.majorRadiusTolerance;
// iOS Documentation: altitudeAngle
// A value of 0 radians indicates that the stylus is parallel to the surface. The value of
// this property is Pi/2 when the stylus is perpendicular to the surface.
//
// PointerData Documentation: tilt
// The angle of the stylus, in radians in the range:
// 0 <= tilt <= pi/2
// giving the angle of the axis of the stylus, relative to the axis perpendicular to the input
// surface (thus 0.0 indicates the stylus is orthogonal to the plane of the input surface,
// while pi/2 indicates that the stylus is flat on that surface).
//
// Discussion:
// The ranges are the same. Origins are swapped.
pointer_data.tilt = M_PI_2 - touch.altitudeAngle;
// iOS Documentation: azimuthAngleInView:
// With the tip of the stylus touching the screen, the value of this property is 0 radians
// when the cap end of the stylus (that is, the end opposite of the tip) points along the
// positive x axis of the device's screen. The azimuth angle increases as the user swings the
// cap end of the stylus in a clockwise direction around the tip.
//
// PointerData Documentation: orientation
// The angle of the stylus, in radians in the range:
// -pi < orientation <= pi
// giving the angle of the axis of the stylus projected onto the input surface, relative to
// the positive y-axis of that surface (thus 0.0 indicates the stylus, if projected onto that
// surface, would go from the contact point vertically up in the positive y-axis direction, pi
// would indicate that the stylus would go down in the negative y-axis direction; pi/4 would
// indicate that the stylus goes up and to the right, -pi/2 would indicate that the stylus
// goes to the left, etc).
//
// Discussion:
// Sweep direction is the same. Phase of M_PI_2.
pointer_data.orientation = [touch azimuthAngleInView:nil] - M_PI_2;
if (@available(iOS 13.4, *)) {
if (event != nullptr) {
pointer_data.buttons = (((event.buttonMask & UIEventButtonMaskPrimary) > 0)
? flutter::PointerButtonMouse::kPointerButtonMousePrimary
: 0) |
(((event.buttonMask & UIEventButtonMaskSecondary) > 0)
? flutter::PointerButtonMouse::kPointerButtonMouseSecondary
: 0);
}
}
packet->SetPointerData(pointer_index++, pointer_data);
if (touch.phase == UITouchPhaseEnded || touch.phase == UITouchPhaseCancelled) {
flutter::PointerData remove_pointer_data = pointer_data;
remove_pointer_data.change = flutter::PointerData::Change::kRemove;
packet->SetPointerData(pointer_index++, remove_pointer_data);
}
}
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
}
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
[self dispatchTouches:touches pointerDataChangeOverride:nullptr event:event];
}
- (void)forceTouchesCancelled:(NSSet*)touches {
flutter::PointerData::Change cancel = flutter::PointerData::Change::kCancel;
[self dispatchTouches:touches pointerDataChangeOverride:&cancel event:nullptr];
}
#pragma mark - Touch events rate correction
- (void)createTouchRateCorrectionVSyncClientIfNeeded {
if (_touchRateCorrectionVSyncClient != nil) {
return;
}
double displayRefreshRate = [DisplayLinkManager displayRefreshRate];
const double epsilon = 0.1;
if (displayRefreshRate < 60.0 + epsilon) { // displayRefreshRate <= 60.0
// If current device's max frame rate is not larger than 60HZ, the delivery rate of touch events
// is the same with render vsync rate. So it is unnecessary to create
// _touchRateCorrectionVSyncClient to correct touch callback's rate.
return;
}
flutter::Shell& shell = [_engine.get() shell];
auto callback = [](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
// Do nothing in this block. Just trigger system to callback touch events with correct rate.
};
_touchRateCorrectionVSyncClient =
[[VSyncClient alloc] initWithTaskRunner:shell.GetTaskRunners().GetPlatformTaskRunner()
callback:callback];
_touchRateCorrectionVSyncClient.allowPauseAfterVsync = NO;
}
- (void)triggerTouchRateCorrectionIfNeeded:(NSSet*)touches {
if (_touchRateCorrectionVSyncClient == nil) {
// If the _touchRateCorrectionVSyncClient is not created, means current devices doesn't
// need to correct the touch rate. So just return.
return;
}
// As long as there is a touch's phase is UITouchPhaseBegan or UITouchPhaseMoved,
// activate the correction. Otherwise pause the correction.
BOOL isUserInteracting = NO;
for (UITouch* touch in touches) {
if (touch.phase == UITouchPhaseBegan || touch.phase == UITouchPhaseMoved) {
isUserInteracting = YES;
break;
}
}
if (isUserInteracting && [_engine.get() viewController] == self) {
[_touchRateCorrectionVSyncClient await];
} else {
[_touchRateCorrectionVSyncClient pause];
}
}
- (void)invalidateTouchRateCorrectionVSyncClient {
[_touchRateCorrectionVSyncClient invalidate];
[_touchRateCorrectionVSyncClient release];
_touchRateCorrectionVSyncClient = nil;
}
#pragma mark - Handle view resizing
- (void)updateViewportMetricsIfNeeded {
if (_shouldIgnoreViewportMetricsUpdatesDuringRotation) {
return;
}
if ([_engine.get() viewController] == self) {
[_engine.get() updateViewportMetrics:_viewportMetrics];
}
}
- (void)viewDidLayoutSubviews {
CGRect viewBounds = self.view.bounds;
CGFloat scale = [self flutterScreenIfViewLoaded].scale;
// Purposefully place this not visible.
_scrollView.get().frame = CGRectMake(0.0, 0.0, viewBounds.size.width, 0.0);
_scrollView.get().contentOffset = CGPointMake(kScrollViewContentSize, kScrollViewContentSize);
// First time since creation that the dimensions of its view is known.
bool firstViewBoundsUpdate = !_viewportMetrics.physical_width;
_viewportMetrics.device_pixel_ratio = scale;
[self setViewportMetricsSize];
[self setViewportMetricsPaddings];
[self updateViewportMetricsIfNeeded];
// There is no guarantee that UIKit will layout subviews when the application/scene is active.
// Creating the surface when inactive will cause GPU accesses from the background. Only wait for
// the first frame to render when the application/scene is actually active.
bool applicationOrSceneIsActive = YES;
#if APPLICATION_EXTENSION_API_ONLY
if (@available(iOS 13.0, *)) {
applicationOrSceneIsActive = self.flutterWindowSceneIfViewLoaded.activationState ==
UISceneActivationStateForegroundActive;
}
#else
applicationOrSceneIsActive =
[UIApplication sharedApplication].applicationState == UIApplicationStateActive;
#endif
// This must run after updateViewportMetrics so that the surface creation tasks are queued after
// the viewport metrics update tasks.
if (firstViewBoundsUpdate && applicationOrSceneIsActive && _engine) {
[self surfaceUpdated:YES];
flutter::Shell& shell = [_engine.get() shell];
fml::TimeDelta waitTime =
#if FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_DEBUG
fml::TimeDelta::FromMilliseconds(200);
#else
fml::TimeDelta::FromMilliseconds(100);
#endif
if (shell.WaitForFirstFrame(waitTime).code() == fml::StatusCode::kDeadlineExceeded) {
FML_LOG(INFO) << "Timeout waiting for the first frame to render. This may happen in "
<< "unoptimized builds. If this is a release build, you should load a less "
<< "complex frame to avoid the timeout.";
}
}
}
- (void)viewSafeAreaInsetsDidChange {
[self setViewportMetricsPaddings];
[self updateViewportMetricsIfNeeded];
[super viewSafeAreaInsetsDidChange];
}
// Set _viewportMetrics physical size.
- (void)setViewportMetricsSize {
UIScreen* screen = [self flutterScreenIfViewLoaded];
if (!screen) {
return;
}
CGFloat scale = screen.scale;
_viewportMetrics.physical_width = self.view.bounds.size.width * scale;
_viewportMetrics.physical_height = self.view.bounds.size.height * scale;
}
// Set _viewportMetrics physical paddings.
//
// Viewport paddings represent the iOS safe area insets.
- (void)setViewportMetricsPaddings {
UIScreen* screen = [self flutterScreenIfViewLoaded];
if (!screen) {
return;
}
CGFloat scale = screen.scale;
_viewportMetrics.physical_padding_top = self.view.safeAreaInsets.top * scale;
_viewportMetrics.physical_padding_left = self.view.safeAreaInsets.left * scale;
_viewportMetrics.physical_padding_right = self.view.safeAreaInsets.right * scale;
_viewportMetrics.physical_padding_bottom = self.view.safeAreaInsets.bottom * scale;
}
#pragma mark - Keyboard events
- (void)keyboardWillShowNotification:(NSNotification*)notification {
// Immediately prior to a docked keyboard being shown or when a keyboard goes from
// undocked/floating to docked, this notification is triggered. This notification also happens
// when Minimized/Expanded Shortcuts bar is dropped after dragging (the keyboard's end frame will
// be CGRectZero).
[self handleKeyboardNotification:notification];
}
- (void)keyboardWillChangeFrame:(NSNotification*)notification {
// Immediately prior to a change in keyboard frame, this notification is triggered.
// Sometimes when the keyboard is being hidden or undocked, this notification's keyboard's end
// frame is not yet entirely out of screen, which is why we also use
// UIKeyboardWillHideNotification.
[self handleKeyboardNotification:notification];
}
- (void)keyboardWillBeHidden:(NSNotification*)notification {
// When keyboard is hidden or undocked, this notification will be triggered.
// This notification might not occur when the keyboard is changed from docked to floating, which
// is why we also use UIKeyboardWillChangeFrameNotification.
[self handleKeyboardNotification:notification];
}
- (void)handleKeyboardNotification:(NSNotification*)notification {
// See https://flutter.dev/go/ios-keyboard-calculating-inset for more details
// on why notifications are used and how things are calculated.
if ([self shouldIgnoreKeyboardNotification:notification]) {
return;
}
NSDictionary* info = notification.userInfo;
CGRect beginKeyboardFrame = [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
FlutterKeyboardMode keyboardMode = [self calculateKeyboardAttachMode:notification];
CGFloat calculatedInset = [self calculateKeyboardInset:keyboardFrame keyboardMode:keyboardMode];
// Avoid double triggering startKeyBoardAnimation.
if (self.targetViewInsetBottom == calculatedInset) {
return;
}
self.targetViewInsetBottom = calculatedInset;
NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Flag for simultaneous compounding animation calls.
// This captures animation calls made while the keyboard animation is currently animating. If the
// new animation is in the same direction as the current animation, this flag lets the current
// animation continue with an updated targetViewInsetBottom instead of starting a new keyboard
// animation. This allows for smoother keyboard animation interpolation.
BOOL keyboardWillShow = beginKeyboardFrame.origin.y > keyboardFrame.origin.y;
BOOL keyboardAnimationIsCompounding =
self.keyboardAnimationIsShowing == keyboardWillShow && _keyboardAnimationVSyncClient != nil;
// Mark keyboard as showing or hiding.
self.keyboardAnimationIsShowing = keyboardWillShow;
if (!keyboardAnimationIsCompounding) {
[self startKeyBoardAnimation:duration];
} else if ([self keyboardSpringAnimation]) {
[self keyboardSpringAnimation].toValue = self.targetViewInsetBottom;
}
}
- (BOOL)shouldIgnoreKeyboardNotification:(NSNotification*)notification {
// Don't ignore UIKeyboardWillHideNotification notifications.
// Even if the notification is triggered in the background or by a different app/view controller,
// we want to always handle this notification to avoid inaccurate inset when in a mulitasking mode
// or when switching between apps.
if (notification.name == UIKeyboardWillHideNotification) {
return NO;
}
// Ignore notification when keyboard's dimensions and position are all zeroes for
// UIKeyboardWillChangeFrameNotification. This happens when keyboard is dragged. Do not ignore if
// the notification is UIKeyboardWillShowNotification, as CGRectZero for that notfication only
// occurs when Minimized/Expanded Shortcuts Bar is dropped after dragging, which we later use to
// categorize it as floating.
NSDictionary* info = notification.userInfo;
CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (notification.name == UIKeyboardWillChangeFrameNotification &&
CGRectEqualToRect(keyboardFrame, CGRectZero)) {
return YES;
}
// When keyboard's height or width is set to 0, don't ignore. This does not happen
// often but can happen sometimes when switching between multitasking modes.
if (CGRectIsEmpty(keyboardFrame)) {
return NO;
}
// Ignore keyboard notifications related to other apps or view controllers.
if ([self isKeyboardNotificationForDifferentView:notification]) {
return YES;
}
if (@available(iOS 13.0, *)) {
// noop
} else {
// If OS version is less than 13, ignore notification if the app is in the background
// or is transitioning from the background. In older versions, when switching between
// apps with the keyboard open in the secondary app, notifications are sent when
// the app is in the background/transitioning from background as if they belong
// to the app and as if the keyboard is showing even though it is not.
if (self.isKeyboardInOrTransitioningFromBackground) {
return YES;
}
}
return NO;
}
- (BOOL)isKeyboardNotificationForDifferentView:(NSNotification*)notification {
NSDictionary* info = notification.userInfo;
// Keyboard notifications related to other apps.
// If the UIKeyboardIsLocalUserInfoKey key doesn't exist (this should not happen after iOS 8),
// proceed as if it was local so that the notification is not ignored.
id isLocal = info[UIKeyboardIsLocalUserInfoKey];
if (isLocal && ![isLocal boolValue]) {
return YES;
}
// Engine’s viewController is not current viewController.
if ([_engine.get() viewController] != self) {
return YES;
}
return NO;
}
- (FlutterKeyboardMode)calculateKeyboardAttachMode:(NSNotification*)notification {
// There are multiple types of keyboard: docked, undocked, split, split docked,
// floating, expanded shortcuts bar, minimized shortcuts bar. This function will categorize
// the keyboard as one of the following modes: docked, floating, or hidden.
// Docked mode includes docked, split docked, expanded shortcuts bar (when opening via click),
// and minimized shortcuts bar (when opened via click).
// Floating includes undocked, split, floating, expanded shortcuts bar (when dragged and dropped),
// and minimized shortcuts bar (when dragged and dropped).
NSDictionary* info = notification.userInfo;
CGRect keyboardFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
if (notification.name == UIKeyboardWillHideNotification) {
return FlutterKeyboardModeHidden;
}
// If keyboard's dimensions and position are all zeroes, that means it's a Minimized/Expanded
// Shortcuts Bar that has been dropped after dragging, which we categorize as floating.
if (CGRectEqualToRect(keyboardFrame, CGRectZero)) {
return FlutterKeyboardModeFloating;
}
// If keyboard's width or height are 0, it's hidden.
if (CGRectIsEmpty(keyboardFrame)) {
return FlutterKeyboardModeHidden;
}
CGRect screenRect = [self flutterScreenIfViewLoaded].bounds;
CGRect adjustedKeyboardFrame = keyboardFrame;
adjustedKeyboardFrame.origin.y += [self calculateMultitaskingAdjustment:screenRect
keyboardFrame:keyboardFrame];
// If the keyboard is partially or fully showing within the screen, it's either docked or
// floating. Sometimes with custom keyboard extensions, the keyboard's position may be off by a
// small decimal amount (which is why CGRectIntersectRect can't be used). Round to compare.
CGRect intersection = CGRectIntersection(adjustedKeyboardFrame, screenRect);
CGFloat intersectionHeight = CGRectGetHeight(intersection);
CGFloat intersectionWidth = CGRectGetWidth(intersection);
if (round(intersectionHeight) > 0 && intersectionWidth > 0) {
// If the keyboard is above the bottom of the screen, it's floating.
CGFloat screenHeight = CGRectGetHeight(screenRect);
CGFloat adjustedKeyboardBottom = CGRectGetMaxY(adjustedKeyboardFrame);
if (round(adjustedKeyboardBottom) < screenHeight) {
return FlutterKeyboardModeFloating;
}
return FlutterKeyboardModeDocked;
}
return FlutterKeyboardModeHidden;
}
- (CGFloat)calculateMultitaskingAdjustment:(CGRect)screenRect keyboardFrame:(CGRect)keyboardFrame {
// In Slide Over mode, the keyboard's frame does not include the space
// below the app, even though the keyboard may be at the bottom of the screen.
// To handle, shift the Y origin by the amount of space below the app.
if (self.viewIfLoaded.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiomPad &&
self.viewIfLoaded.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact &&
self.viewIfLoaded.traitCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
CGFloat screenHeight = CGRectGetHeight(screenRect);
CGFloat keyboardBottom = CGRectGetMaxY(keyboardFrame);
// Stage Manager mode will also meet the above parameters, but it does not handle
// the keyboard positioning the same way, so skip if keyboard is at bottom of page.
if (screenHeight == keyboardBottom) {
return 0;
}
CGRect viewRectRelativeToScreen =
[self.viewIfLoaded convertRect:self.viewIfLoaded.frame
toCoordinateSpace:[self flutterScreenIfViewLoaded].coordinateSpace];
CGFloat viewBottom = CGRectGetMaxY(viewRectRelativeToScreen);
CGFloat offset = screenHeight - viewBottom;
if (offset > 0) {
return offset;
}
}
return 0;
}
- (CGFloat)calculateKeyboardInset:(CGRect)keyboardFrame keyboardMode:(NSInteger)keyboardMode {
// Only docked keyboards will have an inset.
if (keyboardMode == FlutterKeyboardModeDocked) {
// Calculate how much of the keyboard intersects with the view.
CGRect viewRectRelativeToScreen =
[self.viewIfLoaded convertRect:self.viewIfLoaded.frame
toCoordinateSpace:[self flutterScreenIfViewLoaded].coordinateSpace];
CGRect intersection = CGRectIntersection(keyboardFrame, viewRectRelativeToScreen);
CGFloat portionOfKeyboardInView = CGRectGetHeight(intersection);
// The keyboard is treated as an inset since we want to effectively reduce the window size by
// the keyboard height. The Dart side will compute a value accounting for the keyboard-consuming
// bottom padding.
CGFloat scale = [self flutterScreenIfViewLoaded].scale;
return portionOfKeyboardInView * scale;
}
return 0;
}
- (void)startKeyBoardAnimation:(NSTimeInterval)duration {
// If current physical_view_inset_bottom == targetViewInsetBottom, do nothing.
if (_viewportMetrics.physical_view_inset_bottom == self.targetViewInsetBottom) {
return;
}
// When this method is called for the first time,
// initialize the keyboardAnimationView to get animation interpolation during animation.
if ([self keyboardAnimationView] == nil) {
UIView* keyboardAnimationView = [[UIView alloc] init];
[keyboardAnimationView setHidden:YES];
_keyboardAnimationView.reset(keyboardAnimationView);
}
if ([self keyboardAnimationView].superview == nil) {
[self.view addSubview:[self keyboardAnimationView]];
}
// Remove running animation when start another animation.
[[self keyboardAnimationView].layer removeAllAnimations];
// Set animation begin value and DisplayLink tracking values.
[self keyboardAnimationView].frame =
CGRectMake(0, _viewportMetrics.physical_view_inset_bottom, 0, 0);
self.keyboardAnimationStartTime = fml::TimePoint().Now();
self.originalViewInsetBottom = _viewportMetrics.physical_view_inset_bottom;
// Invalidate old vsync client if old animation is not completed.
[self invalidateKeyboardAnimationVSyncClient];
fml::WeakNSObject<FlutterViewController> weakSelf = [self getWeakNSObject];
FlutterKeyboardAnimationCallback keyboardAnimationCallback = ^(
fml::TimePoint keyboardAnimationTargetTime) {
if (!weakSelf) {
return;
}
fml::scoped_nsobject<FlutterViewController> flutterViewController(
[(FlutterViewController*)weakSelf.get() retain]);
if (!flutterViewController) {
return;
}
// If the view controller's view is not loaded, bail out.
if (!flutterViewController.get().isViewLoaded) {
return;
}
// If the view for tracking keyboard animation is nil, means it is not
// created, bail out.
if ([flutterViewController keyboardAnimationView] == nil) {
return;
}
// If keyboardAnimationVSyncClient is nil, means the animation ends.
// And should bail out.
if (flutterViewController.get().keyboardAnimationVSyncClient == nil) {
return;
}
if ([flutterViewController keyboardAnimationView].superview == nil) {
// Ensure the keyboardAnimationView is in view hierarchy when animation running.
[flutterViewController.get().view addSubview:[flutterViewController keyboardAnimationView]];
}
if ([flutterViewController keyboardSpringAnimation] == nil) {
if (flutterViewController.get().keyboardAnimationView.layer.presentationLayer) {
flutterViewController.get()->_viewportMetrics.physical_view_inset_bottom =
flutterViewController.get()
.keyboardAnimationView.layer.presentationLayer.frame.origin.y;
[flutterViewController updateViewportMetricsIfNeeded];
}
} else {
fml::TimeDelta timeElapsed =
keyboardAnimationTargetTime - flutterViewController.get().keyboardAnimationStartTime;
flutterViewController.get()->_viewportMetrics.physical_view_inset_bottom =
[[flutterViewController keyboardSpringAnimation] curveFunction:timeElapsed.ToSecondsF()];
[flutterViewController updateViewportMetricsIfNeeded];
}
};
[self setUpKeyboardAnimationVsyncClient:keyboardAnimationCallback];
VSyncClient* currentVsyncClient = _keyboardAnimationVSyncClient;
[UIView animateWithDuration:duration
animations:^{
// Set end value.
[self keyboardAnimationView].frame = CGRectMake(0, self.targetViewInsetBottom, 0, 0);
// Setup keyboard animation interpolation.
CAAnimation* keyboardAnimation =
[[self keyboardAnimationView].layer animationForKey:@"position"];
[self setUpKeyboardSpringAnimationIfNeeded:keyboardAnimation];
}
completion:^(BOOL finished) {
if (_keyboardAnimationVSyncClient == currentVsyncClient) {
// Indicates the vsync client captured by this block is the original one, which also
// indicates the animation has not been interrupted from its beginning. Moreover,
// indicates the animation is over and there is no more to execute.
[self invalidateKeyboardAnimationVSyncClient];
[self removeKeyboardAnimationView];
[self ensureViewportMetricsIsCorrect];
}
}];
}
- (void)setUpKeyboardSpringAnimationIfNeeded:(CAAnimation*)keyboardAnimation {
// If keyboard animation is null or not a spring animation, fallback to DisplayLink tracking.
if (keyboardAnimation == nil || ![keyboardAnimation isKindOfClass:[CASpringAnimation class]]) {
_keyboardSpringAnimation.reset();
return;
}
// Setup keyboard spring animation details for spring curve animation calculation.
CASpringAnimation* keyboardCASpringAnimation = (CASpringAnimation*)keyboardAnimation;
_keyboardSpringAnimation.reset([[SpringAnimation alloc]
initWithStiffness:keyboardCASpringAnimation.stiffness
damping:keyboardCASpringAnimation.damping
mass:keyboardCASpringAnimation.mass
initialVelocity:keyboardCASpringAnimation.initialVelocity
fromValue:self.originalViewInsetBottom
toValue:self.targetViewInsetBottom]);
}
- (void)setUpKeyboardAnimationVsyncClient:
(FlutterKeyboardAnimationCallback)keyboardAnimationCallback {
if (!keyboardAnimationCallback) {
return;
}
NSAssert(_keyboardAnimationVSyncClient == nil,
@"_keyboardAnimationVSyncClient must be nil when setting up.");
// Make sure the new viewport metrics get sent after the begin frame event has processed.
fml::scoped_nsprotocol<FlutterKeyboardAnimationCallback> animationCallback(
[keyboardAnimationCallback copy]);
auto uiCallback = [animationCallback](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
fml::TimeDelta frameInterval = recorder->GetVsyncTargetTime() - recorder->GetVsyncStartTime();
fml::TimePoint keyboardAnimationTargetTime = recorder->GetVsyncTargetTime() + frameInterval;
dispatch_async(dispatch_get_main_queue(), ^(void) {
animationCallback.get()(keyboardAnimationTargetTime);
});
};
_keyboardAnimationVSyncClient = [[VSyncClient alloc] initWithTaskRunner:[_engine uiTaskRunner]
callback:uiCallback];
_keyboardAnimationVSyncClient.allowPauseAfterVsync = NO;
[_keyboardAnimationVSyncClient await];
}
- (void)invalidateKeyboardAnimationVSyncClient {
[_keyboardAnimationVSyncClient invalidate];
[_keyboardAnimationVSyncClient release];
_keyboardAnimationVSyncClient = nil;
}
- (void)removeKeyboardAnimationView {
if ([self keyboardAnimationView].superview != nil) {
[[self keyboardAnimationView] removeFromSuperview];
}
}
- (void)ensureViewportMetricsIsCorrect {
if (_viewportMetrics.physical_view_inset_bottom != self.targetViewInsetBottom) {
// Make sure the `physical_view_inset_bottom` is the target value.
_viewportMetrics.physical_view_inset_bottom = self.targetViewInsetBottom;
[self updateViewportMetricsIfNeeded];
}
}
- (void)handlePressEvent:(FlutterUIPressProxy*)press
nextAction:(void (^)())next API_AVAILABLE(ios(13.4)) {
if (@available(iOS 13.4, *)) {
} else {
next();
return;
}
[self.keyboardManager handlePress:press nextAction:next];
}
// The documentation for presses* handlers (implemented below) is entirely
// unclear about how to handle the case where some, but not all, of the presses
// are handled here. I've elected to call super separately for each of the
// presses that aren't handled, but it's not clear if this is correct. It may be
// that iOS intends for us to either handle all or none of the presses, and pass
// the original set to super. I have not yet seen multiple presses in the set in
// the wild, however, so I suspect that the API is built for a tvOS remote or
// something, and perhaps only one ever appears in the set on iOS from a
// keyboard.
// If you substantially change these presses overrides, consider also changing
// the similar ones in FlutterTextInputPlugin. They need to be overridden in
// both places to capture keys both inside and outside of a text field, but have
// slightly different implmentations.
- (void)pressesBegan:(NSSet<UIPress*>*)presses
withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
if (@available(iOS 13.4, *)) {
for (UIPress* press in presses) {
[self handlePressEvent:[[[FlutterUIPressProxy alloc] initWithPress:press
withEvent:event] autorelease]
nextAction:^() {
[super pressesBegan:[NSSet setWithObject:press] withEvent:event];
}];
}
} else {
[super pressesBegan:presses withEvent:event];
}
}
- (void)pressesChanged:(NSSet<UIPress*>*)presses
withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
if (@available(iOS 13.4, *)) {
for (UIPress* press in presses) {
[self handlePressEvent:[[[FlutterUIPressProxy alloc] initWithPress:press
withEvent:event] autorelease]
nextAction:^() {
[super pressesChanged:[NSSet setWithObject:press] withEvent:event];
}];
}
} else {
[super pressesChanged:presses withEvent:event];
}
}
- (void)pressesEnded:(NSSet<UIPress*>*)presses
withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
if (@available(iOS 13.4, *)) {
for (UIPress* press in presses) {
[self handlePressEvent:[[[FlutterUIPressProxy alloc] initWithPress:press
withEvent:event] autorelease]
nextAction:^() {
[super pressesEnded:[NSSet setWithObject:press] withEvent:event];
}];
}
} else {
[super pressesEnded:presses withEvent:event];
}
}
- (void)pressesCancelled:(NSSet<UIPress*>*)presses
withEvent:(UIPressesEvent*)event API_AVAILABLE(ios(9.0)) {
if (@available(iOS 13.4, *)) {
for (UIPress* press in presses) {
[self handlePressEvent:[[[FlutterUIPressProxy alloc] initWithPress:press
withEvent:event] autorelease]
nextAction:^() {
[super pressesCancelled:[NSSet setWithObject:press] withEvent:event];
}];
}
} else {
[super pressesCancelled:presses withEvent:event];
}
}
#pragma mark - Orientation updates
- (void)onOrientationPreferencesUpdated:(NSNotification*)notification {
// Notifications may not be on the iOS UI thread
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary* info = notification.userInfo;
NSNumber* update = info[@(flutter::kOrientationUpdateNotificationKey)];
if (update == nil) {
return;
}
[self performOrientationUpdate:update.unsignedIntegerValue];
});
}
- (void)requestGeometryUpdateForWindowScenes:(NSSet<UIScene*>*)windowScenes
API_AVAILABLE(ios(16.0)) {
for (UIScene* windowScene in windowScenes) {
FML_DCHECK([windowScene isKindOfClass:[UIWindowScene class]]);
UIWindowSceneGeometryPreferencesIOS* preference = [[[UIWindowSceneGeometryPreferencesIOS alloc]
initWithInterfaceOrientations:_orientationPreferences] autorelease];
[(UIWindowScene*)windowScene
requestGeometryUpdateWithPreferences:preference
errorHandler:^(NSError* error) {
os_log_error(OS_LOG_DEFAULT,
"Failed to change device orientation: %@", error);
}];
[self setNeedsUpdateOfSupportedInterfaceOrientations];
}
}
- (void)performOrientationUpdate:(UIInterfaceOrientationMask)new_preferences {
if (new_preferences != _orientationPreferences) {
_orientationPreferences = new_preferences;
if (@available(iOS 16.0, *)) {
NSSet<UIScene*>* scenes =
#if APPLICATION_EXTENSION_API_ONLY
self.flutterWindowSceneIfViewLoaded
? [NSSet setWithObject:self.flutterWindowSceneIfViewLoaded]
: [NSSet set];
#else
[UIApplication.sharedApplication.connectedScenes
filteredSetUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(
id scene, NSDictionary* bindings) {
return [scene isKindOfClass:[UIWindowScene class]];
}]];
#endif
[self requestGeometryUpdateForWindowScenes:scenes];
} else {
UIInterfaceOrientationMask currentInterfaceOrientation = 0;
if (@available(iOS 13.0, *)) {
UIWindowScene* windowScene = [self flutterWindowSceneIfViewLoaded];
if (!windowScene) {
FML_LOG(WARNING)
<< "Accessing the interface orientation when the window scene is unavailable.";
return;
}
currentInterfaceOrientation = 1 << windowScene.interfaceOrientation;
} else {
#if APPLICATION_EXTENSION_API_ONLY
FML_LOG(ERROR) << "Application based status bar orentiation update is not supported in "
"app extension. Orientation: "
<< currentInterfaceOrientation;
#else
currentInterfaceOrientation = 1 << [[UIApplication sharedApplication] statusBarOrientation];
#endif
}
if (!(_orientationPreferences & currentInterfaceOrientation)) {
[UIViewController attemptRotationToDeviceOrientation];
// Force orientation switch if the current orientation is not allowed
if (_orientationPreferences & UIInterfaceOrientationMaskPortrait) {
// This is no official API but more like a workaround / hack (using
// key-value coding on a read-only property). This might break in
// the future, but currently it´s the only way to force an orientation change
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait)
forKey:@"orientation"];
} else if (_orientationPreferences & UIInterfaceOrientationMaskPortraitUpsideDown) {
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortraitUpsideDown)
forKey:@"orientation"];
} else if (_orientationPreferences & UIInterfaceOrientationMaskLandscapeLeft) {
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft)
forKey:@"orientation"];
} else if (_orientationPreferences & UIInterfaceOrientationMaskLandscapeRight) {
[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight)
forKey:@"orientation"];
}
}
}
}
}
- (void)onHideHomeIndicatorNotification:(NSNotification*)notification {
self.isHomeIndicatorHidden = YES;
}
- (void)onShowHomeIndicatorNotification:(NSNotification*)notification {
self.isHomeIndicatorHidden = NO;
}
- (void)setIsHomeIndicatorHidden:(BOOL)hideHomeIndicator {
if (hideHomeIndicator != _isHomeIndicatorHidden) {
_isHomeIndicatorHidden = hideHomeIndicator;
[self setNeedsUpdateOfHomeIndicatorAutoHidden];
}
}
- (BOOL)prefersHomeIndicatorAutoHidden {
return self.isHomeIndicatorHidden;
}
- (BOOL)shouldAutorotate {
return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
return _orientationPreferences;
}
#pragma mark - Accessibility
- (void)onAccessibilityStatusChanged:(NSNotification*)notification {
if (!_engine) {
return;
}
auto platformView = [_engine.get() platformView];
int32_t flags = [self accessibilityFlags];
#if TARGET_OS_SIMULATOR
// There doesn't appear to be any way to determine whether the accessibility
// inspector is enabled on the simulator. We conservatively always turn on the
// accessibility bridge in the simulator, but never assistive technology.
platformView->SetSemanticsEnabled(true);
platformView->SetAccessibilityFeatures(flags);
#else
_isVoiceOverRunning = UIAccessibilityIsVoiceOverRunning();
bool enabled = _isVoiceOverRunning || UIAccessibilityIsSwitchControlRunning();
if (enabled) {
flags |= static_cast<int32_t>(flutter::AccessibilityFeatureFlag::kAccessibleNavigation);
}
platformView->SetSemanticsEnabled(enabled || UIAccessibilityIsSpeakScreenEnabled());
platformView->SetAccessibilityFeatures(flags);
#endif
}
- (int32_t)accessibilityFlags {
int32_t flags = 0;
if (UIAccessibilityIsInvertColorsEnabled()) {
flags |= static_cast<int32_t>(flutter::AccessibilityFeatureFlag::kInvertColors);
}
if (UIAccessibilityIsReduceMotionEnabled()) {
flags |= static_cast<int32_t>(flutter::AccessibilityFeatureFlag::kReduceMotion);
}
if (UIAccessibilityIsBoldTextEnabled()) {
flags |= static_cast<int32_t>(flutter::AccessibilityFeatureFlag::kBoldText);
}
if (UIAccessibilityDarkerSystemColorsEnabled()) {
flags |= static_cast<int32_t>(flutter::AccessibilityFeatureFlag::kHighContrast);
}
if ([FlutterViewController accessibilityIsOnOffSwitchLabelsEnabled]) {
flags |= static_cast<int32_t>(flutter::AccessibilityFeatureFlag::kOnOffSwitchLabels);
}
return flags;
}
- (BOOL)accessibilityPerformEscape {
FlutterMethodChannel* navigationChannel = [_engine.get() navigationChannel];
if (navigationChannel) {
[self popRoute];
return YES;
}
return NO;
}
+ (BOOL)accessibilityIsOnOffSwitchLabelsEnabled {
if (@available(iOS 13, *)) {
return UIAccessibilityIsOnOffSwitchLabelsEnabled();
} else {
return NO;
}
}
#pragma mark - Set user settings
- (void)traitCollectionDidChange:(UITraitCollection*)previousTraitCollection {
[super traitCollectionDidChange:previousTraitCollection];
[self onUserSettingsChanged:nil];
}
- (void)onUserSettingsChanged:(NSNotification*)notification {
[[_engine.get() settingsChannel] sendMessage:@{
@"textScaleFactor" : @([self textScaleFactor]),
@"alwaysUse24HourFormat" : @([self isAlwaysUse24HourFormat]),
@"platformBrightness" : [self brightnessMode],
@"platformContrast" : [self contrastMode],
@"nativeSpellCheckServiceDefined" : @true
}];
}
- (CGFloat)textScaleFactor {
#if APPLICATION_EXTENSION_API_ONLY
FML_LOG(WARNING) << "Dynamic content size update is not supported in app extension.";
return 1.0;
#else
UIContentSizeCategory category = [UIApplication sharedApplication].preferredContentSizeCategory;
// The delta is computed by approximating Apple's typography guidelines:
// https://developer.apple.com/ios/human-interface-guidelines/visual-design/typography/
//
// Specifically:
// Non-accessibility sizes for "body" text are:
const CGFloat xs = 14;
const CGFloat s = 15;
const CGFloat m = 16;
const CGFloat l = 17;
const CGFloat xl = 19;
const CGFloat xxl = 21;
const CGFloat xxxl = 23;
// Accessibility sizes for "body" text are:
const CGFloat ax1 = 28;
const CGFloat ax2 = 33;
const CGFloat ax3 = 40;
const CGFloat ax4 = 47;
const CGFloat ax5 = 53;
// We compute the scale as relative difference from size L (large, the default size), where
// L is assumed to have scale 1.0.
if ([category isEqualToString:UIContentSizeCategoryExtraSmall]) {
return xs / l;
} else if ([category isEqualToString:UIContentSizeCategorySmall]) {
return s / l;
} else if ([category isEqualToString:UIContentSizeCategoryMedium]) {
return m / l;
} else if ([category isEqualToString:UIContentSizeCategoryLarge]) {
return 1.0;
} else if ([category isEqualToString:UIContentSizeCategoryExtraLarge]) {
return xl / l;
} else if ([category isEqualToString:UIContentSizeCategoryExtraExtraLarge]) {
return xxl / l;
} else if ([category isEqualToString:UIContentSizeCategoryExtraExtraExtraLarge]) {
return xxxl / l;
} else if ([category isEqualToString:UIContentSizeCategoryAccessibilityMedium]) {
return ax1 / l;
} else if ([category isEqualToString:UIContentSizeCategoryAccessibilityLarge]) {
return ax2 / l;
} else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraLarge]) {
return ax3 / l;
} else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraLarge]) {
return ax4 / l;
} else if ([category isEqualToString:UIContentSizeCategoryAccessibilityExtraExtraExtraLarge]) {
return ax5 / l;
} else {
return 1.0;
}
#endif
}
- (BOOL)isAlwaysUse24HourFormat {
// iOS does not report its "24-Hour Time" user setting in the API. Instead, it applies
// it automatically to NSDateFormatter when used with [NSLocale currentLocale]. It is
// essential that [NSLocale currentLocale] is used. Any custom locale, even the one
// that's the same as [NSLocale currentLocale] will ignore the 24-hour option (there
// must be some internal field that's not exposed to developers).
//
// Therefore this option behaves differently across Android and iOS. On Android this
// setting is exposed standalone, and can therefore be applied to all locales, whether
// the "current system locale" or a custom one. On iOS it only applies to the current
// system locale. Widget implementors must take this into account in order to provide
// platform-idiomatic behavior in their widgets.
NSString* dateFormat = [NSDateFormatter dateFormatFromTemplate:@"j"
options:0
locale:[NSLocale currentLocale]];
return [dateFormat rangeOfString:@"a"].location == NSNotFound;
}
// The brightness mode of the platform, e.g., light or dark, expressed as a string that
// is understood by the Flutter framework. See the settings
// system channel for more information.
- (NSString*)brightnessMode {
if (@available(iOS 13, *)) {
UIUserInterfaceStyle style = self.traitCollection.userInterfaceStyle;
if (style == UIUserInterfaceStyleDark) {
return @"dark";
} else {
return @"light";
}
} else {
return @"light";
}
}
// The contrast mode of the platform, e.g., normal or high, expressed as a string that is
// understood by the Flutter framework. See the settings system channel for more
// information.
- (NSString*)contrastMode {
if (@available(iOS 13, *)) {
UIAccessibilityContrast contrast = self.traitCollection.accessibilityContrast;
if (contrast == UIAccessibilityContrastHigh) {
return @"high";
} else {
return @"normal";
}
} else {
return @"normal";
}
}
#pragma mark - Status bar style
- (UIStatusBarStyle)preferredStatusBarStyle {
return _statusBarStyle;
}
- (void)onPreferredStatusBarStyleUpdated:(NSNotification*)notification {
// Notifications may not be on the iOS UI thread
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary* info = notification.userInfo;
NSNumber* update = info[@(flutter::kOverlayStyleUpdateNotificationKey)];
if (update == nil) {
return;
}
NSInteger style = update.integerValue;
if (style != _statusBarStyle) {
_statusBarStyle = static_cast<UIStatusBarStyle>(style);
[self setNeedsStatusBarAppearanceUpdate];
}
});
}
- (void)setPrefersStatusBarHidden:(BOOL)hidden {
if (hidden != _flutterPrefersStatusBarHidden) {
_flutterPrefersStatusBarHidden = hidden;
[self setNeedsStatusBarAppearanceUpdate];
}
}
- (BOOL)prefersStatusBarHidden {
return _flutterPrefersStatusBarHidden;
}
#pragma mark - Platform views
- (std::shared_ptr<flutter::FlutterPlatformViewsController>&)platformViewsController {
return [_engine.get() platformViewsController];
}
- (NSObject<FlutterBinaryMessenger>*)binaryMessenger {
return _engine.get().binaryMessenger;
}
#pragma mark - FlutterBinaryMessenger
- (void)sendOnChannel:(NSString*)channel message:(NSData*)message {
[_engine.get().binaryMessenger sendOnChannel:channel message:message];
}
- (void)sendOnChannel:(NSString*)channel
message:(NSData*)message
binaryReply:(FlutterBinaryReply)callback {
NSAssert(channel, @"The channel must not be null");
[_engine.get().binaryMessenger sendOnChannel:channel message:message binaryReply:callback];
}
- (NSObject<FlutterTaskQueue>*)makeBackgroundTaskQueue {
return [_engine.get().binaryMessenger makeBackgroundTaskQueue];
}
- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(NSString*)channel
binaryMessageHandler:
(FlutterBinaryMessageHandler)handler {
return [self setMessageHandlerOnChannel:channel binaryMessageHandler:handler taskQueue:nil];
}
- (FlutterBinaryMessengerConnection)
setMessageHandlerOnChannel:(NSString*)channel
binaryMessageHandler:(FlutterBinaryMessageHandler _Nullable)handler
taskQueue:(NSObject<FlutterTaskQueue>* _Nullable)taskQueue {
NSAssert(channel, @"The channel must not be null");
return [_engine.get().binaryMessenger setMessageHandlerOnChannel:channel
binaryMessageHandler:handler
taskQueue:taskQueue];
}
- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection {
[_engine.get().binaryMessenger cleanUpConnection:connection];
}
#pragma mark - FlutterTextureRegistry
- (int64_t)registerTexture:(NSObject<FlutterTexture>*)texture {
return [_engine.get().textureRegistry registerTexture:texture];
}
- (void)unregisterTexture:(int64_t)textureId {
[_engine.get().textureRegistry unregisterTexture:textureId];
}
- (void)textureFrameAvailable:(int64_t)textureId {
[_engine.get().textureRegistry textureFrameAvailable:textureId];
}
- (NSString*)lookupKeyForAsset:(NSString*)asset {
return [FlutterDartProject lookupKeyForAsset:asset];
}
- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package];
}
- (id<FlutterPluginRegistry>)pluginRegistry {
return _engine;
}
+ (BOOL)isUIAccessibilityIsVoiceOverRunning {
return UIAccessibilityIsVoiceOverRunning();
}
#pragma mark - FlutterPluginRegistry
- (NSObject<FlutterPluginRegistrar>*)registrarForPlugin:(NSString*)pluginKey {
return [_engine.get() registrarForPlugin:pluginKey];
}
- (BOOL)hasPlugin:(NSString*)pluginKey {
return [_engine.get() hasPlugin:pluginKey];
}
- (NSObject*)valuePublishedByPlugin:(NSString*)pluginKey {
return [_engine.get() valuePublishedByPlugin:pluginKey];
}
- (void)presentViewController:(UIViewController*)viewControllerToPresent
animated:(BOOL)flag
completion:(void (^)(void))completion {
self.isPresentingViewControllerAnimating = YES;
[super presentViewController:viewControllerToPresent
animated:flag
completion:^{
self.isPresentingViewControllerAnimating = NO;
if (completion) {
completion();
}
}];
}
- (BOOL)isPresentingViewController {
return self.presentedViewController != nil || self.isPresentingViewControllerAnimating;
}
- (flutter::PointerData)generatePointerDataAtLastMouseLocation API_AVAILABLE(ios(13.4)) {
flutter::PointerData pointer_data;
pointer_data.Clear();
pointer_data.time_stamp = [[NSProcessInfo processInfo] systemUptime] * kMicrosecondsPerSecond;
pointer_data.physical_x = _mouseState.location.x;
pointer_data.physical_y = _mouseState.location.y;
return pointer_data;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer*)otherGestureRecognizer
API_AVAILABLE(ios(13.4)) {
return YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer
shouldReceiveEvent:(UIEvent*)event API_AVAILABLE(ios(13.4)) {
if (gestureRecognizer == _continuousScrollingPanGestureRecognizer &&
event.type == UIEventTypeScroll) {
// Events with type UIEventTypeScroll are only received when running on macOS under emulation.
flutter::PointerData pointer_data = [self generatePointerDataAtLastMouseLocation];
pointer_data.device = reinterpret_cast<int64_t>(_continuousScrollingPanGestureRecognizer);
pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
pointer_data.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
pointer_data.view_id = self.viewIdentifier;
if (event.timestamp < _scrollInertiaEventAppKitDeadline) {
// Only send the event if it occured before the expected natural end of gesture momentum.
// If received after the deadline, it's not likely the event is from a user-initiated cancel.
auto packet = std::make_unique<flutter::PointerDataPacket>(1);
packet->SetPointerData(/*i=*/0, pointer_data);
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
_scrollInertiaEventAppKitDeadline = 0;
}
}
// This method is also called for UITouches, should return YES to process all touches.
return YES;
}
- (void)hoverEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
CGPoint location = [recognizer locationInView:self.view];
CGFloat scale = [self flutterScreenIfViewLoaded].scale;
CGPoint oldLocation = _mouseState.location;
_mouseState.location = {location.x * scale, location.y * scale};
flutter::PointerData pointer_data = [self generatePointerDataAtLastMouseLocation];
pointer_data.device = reinterpret_cast<int64_t>(recognizer);
pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
pointer_data.view_id = self.viewIdentifier;
switch (_hoverGestureRecognizer.state) {
case UIGestureRecognizerStateBegan:
pointer_data.change = flutter::PointerData::Change::kAdd;
break;
case UIGestureRecognizerStateChanged:
pointer_data.change = flutter::PointerData::Change::kHover;
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
pointer_data.change = flutter::PointerData::Change::kRemove;
break;
default:
// Sending kHover is the least harmful thing to do here
// But this state is not expected to ever be reached.
pointer_data.change = flutter::PointerData::Change::kHover;
break;
}
NSTimeInterval time = [NSProcessInfo processInfo].systemUptime;
BOOL isRunningOnMac = NO;
if (@available(iOS 14.0, *)) {
// This "stationary pointer" heuristic is not reliable when running within macOS.
// We instead receive a scroll cancel event directly from AppKit.
// See gestureRecognizer:shouldReceiveEvent:
isRunningOnMac = [NSProcessInfo processInfo].iOSAppOnMac;
}
if (!isRunningOnMac && CGPointEqualToPoint(oldLocation, _mouseState.location) &&
time > _scrollInertiaEventStartline) {
// iPadOS reports trackpad movements events with high (sub-pixel) precision. When an event
// is received with the same position as the previous one, it can only be from a finger
// making or breaking contact with the trackpad surface.
auto packet = std::make_unique<flutter::PointerDataPacket>(2);
packet->SetPointerData(/*i=*/0, pointer_data);
flutter::PointerData inertia_cancel = pointer_data;
inertia_cancel.device = reinterpret_cast<int64_t>(_continuousScrollingPanGestureRecognizer);
inertia_cancel.kind = flutter::PointerData::DeviceKind::kTrackpad;
inertia_cancel.signal_kind = flutter::PointerData::SignalKind::kScrollInertiaCancel;
inertia_cancel.view_id = self.viewIdentifier;
packet->SetPointerData(/*i=*/1, inertia_cancel);
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
_scrollInertiaEventStartline = DBL_MAX;
} else {
auto packet = std::make_unique<flutter::PointerDataPacket>(1);
packet->SetPointerData(/*i=*/0, pointer_data);
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
}
- (void)discreteScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
CGPoint translation = [recognizer translationInView:self.view];
const CGFloat scale = [self flutterScreenIfViewLoaded].scale;
translation.x *= scale;
translation.y *= scale;
flutter::PointerData pointer_data = [self generatePointerDataAtLastMouseLocation];
pointer_data.device = reinterpret_cast<int64_t>(recognizer);
pointer_data.kind = flutter::PointerData::DeviceKind::kMouse;
pointer_data.signal_kind = flutter::PointerData::SignalKind::kScroll;
pointer_data.scroll_delta_x = (translation.x - _mouseState.last_translation.x);
pointer_data.scroll_delta_y = -(translation.y - _mouseState.last_translation.y);
pointer_data.view_id = self.viewIdentifier;
// The translation reported by UIPanGestureRecognizer is the total translation
// generated by the pan gesture since the gesture began. We need to be able
// to keep track of the last translation value in order to generate the deltaX
// and deltaY coordinates for each subsequent scroll event.
if (recognizer.state != UIGestureRecognizerStateEnded) {
_mouseState.last_translation = translation;
} else {
_mouseState.last_translation = CGPointZero;
}
auto packet = std::make_unique<flutter::PointerDataPacket>(1);
packet->SetPointerData(/*i=*/0, pointer_data);
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
- (void)continuousScrollEvent:(UIPanGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
CGPoint translation = [recognizer translationInView:self.view];
const CGFloat scale = [self flutterScreenIfViewLoaded].scale;
flutter::PointerData pointer_data = [self generatePointerDataAtLastMouseLocation];
pointer_data.device = reinterpret_cast<int64_t>(recognizer);
pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
pointer_data.view_id = self.viewIdentifier;
switch (recognizer.state) {
case UIGestureRecognizerStateBegan:
pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
break;
case UIGestureRecognizerStateChanged:
pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
pointer_data.pan_x = translation.x * scale;
pointer_data.pan_y = translation.y * scale;
pointer_data.pan_delta_x = 0; // Delta will be generated in pointer_data_packet_converter.cc.
pointer_data.pan_delta_y = 0; // Delta will be generated in pointer_data_packet_converter.cc.
pointer_data.scale = 1;
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
_scrollInertiaEventStartline =
[[NSProcessInfo processInfo] systemUptime] +
0.1; // Time to lift fingers off trackpad (experimentally determined)
// When running an iOS app on an Apple Silicon Mac, AppKit will send an event
// of type UIEventTypeScroll when trackpad scroll momentum has ended. This event
// is sent whether the momentum ended normally or was cancelled by a trackpad touch.
// Since Flutter scrolling inertia will likely not match the system inertia, we should
// only send a PointerScrollInertiaCancel event for user-initiated cancellations.
// The following (curve-fitted) calculation provides a cutoff point after which any
// UIEventTypeScroll event will likely be from the system instead of the user.
// See https://github.com/flutter/engine/pull/34929.
_scrollInertiaEventAppKitDeadline =
[[NSProcessInfo processInfo] systemUptime] +
(0.1821 * log(fmax([recognizer velocityInView:self.view].x,
[recognizer velocityInView:self.view].y))) -
0.4825;
pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
break;
default:
// continuousScrollEvent: should only ever be triggered with the above phases
NSAssert(false, @"Trackpad pan event occured with unexpected phase 0x%lx",
(long)recognizer.state);
break;
}
auto packet = std::make_unique<flutter::PointerDataPacket>(1);
packet->SetPointerData(/*i=*/0, pointer_data);
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
- (void)pinchEvent:(UIPinchGestureRecognizer*)recognizer API_AVAILABLE(ios(13.4)) {
flutter::PointerData pointer_data = [self generatePointerDataAtLastMouseLocation];
pointer_data.device = reinterpret_cast<int64_t>(recognizer);
pointer_data.kind = flutter::PointerData::DeviceKind::kTrackpad;
pointer_data.view_id = self.viewIdentifier;
switch (recognizer.state) {
case UIGestureRecognizerStateBegan:
pointer_data.change = flutter::PointerData::Change::kPanZoomStart;
break;
case UIGestureRecognizerStateChanged:
pointer_data.change = flutter::PointerData::Change::kPanZoomUpdate;
pointer_data.scale = recognizer.scale;
pointer_data.rotation = _rotationGestureRecognizer.rotation;
break;
case UIGestureRecognizerStateEnded:
case UIGestureRecognizerStateCancelled:
pointer_data.change = flutter::PointerData::Change::kPanZoomEnd;
break;
default:
// pinchEvent: should only ever be triggered with the above phases
NSAssert(false, @"Trackpad pinch event occured with unexpected phase 0x%lx",
(long)recognizer.state);
break;
}
auto packet = std::make_unique<flutter::PointerDataPacket>(1);
packet->SetPointerData(/*i=*/0, pointer_data);
[_engine.get() dispatchPointerDataPacket:std::move(packet)];
}
#pragma mark - State Restoration
- (void)encodeRestorableStateWithCoder:(NSCoder*)coder {
NSData* restorationData = [[_engine.get() restorationPlugin] restorationData];
[coder encodeBytes:(const unsigned char*)restorationData.bytes
length:restorationData.length
forKey:kFlutterRestorationStateAppData];
[super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder*)coder {
NSUInteger restorationDataLength;
const unsigned char* restorationBytes = [coder decodeBytesForKey:kFlutterRestorationStateAppData
returnedLength:&restorationDataLength];
NSData* restorationData = [NSData dataWithBytes:restorationBytes length:restorationDataLength];
[[_engine.get() restorationPlugin] setRestorationData:restorationData];
}
- (FlutterRestorationPlugin*)restorationPlugin {
return [_engine.get() restorationPlugin];
}
@end
| engine/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterViewController.mm",
"repo_id": "engine",
"token_count": 37528
} | 332 |
// 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_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
#import <UIKit/UIKit.h>
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/lib/ui/semantics/custom_accessibility_action.h"
#include "flutter/lib/ui/semantics/semantics_node.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterView.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/SemanticsObject.h"
#import "flutter/shell/platform/darwin/ios/framework/Source/accessibility_bridge_ios.h"
#include "third_party/skia/include/core/SkRect.h"
namespace flutter {
class PlatformViewIOS;
/**
* An accessibility instance is bound to one `FlutterViewController` and
* `FlutterView` instance.
*
* It helps populate the UIView's accessibilityElements property from Flutter's
* semantics nodes.
*/
class AccessibilityBridge final : public AccessibilityBridgeIos {
public:
/** Delegate for handling iOS operations. */
class IosDelegate {
public:
virtual ~IosDelegate() = default;
/// Returns true when the FlutterViewController associated with the `view`
/// is presenting a modal view controller.
virtual bool IsFlutterViewControllerPresentingModalViewController(
FlutterViewController* view_controller) = 0;
virtual void PostAccessibilityNotification(UIAccessibilityNotifications notification,
id argument) = 0;
};
AccessibilityBridge(FlutterViewController* view_controller,
PlatformViewIOS* platform_view,
std::shared_ptr<FlutterPlatformViewsController> platform_views_controller,
std::unique_ptr<IosDelegate> ios_delegate = nullptr);
~AccessibilityBridge();
void UpdateSemantics(flutter::SemanticsNodeUpdates nodes,
const flutter::CustomAccessibilityActionUpdates& actions);
void HandleEvent(NSDictionary<NSString*, id>* annotatedEvent);
void DispatchSemanticsAction(int32_t id, flutter::SemanticsAction action) override;
void DispatchSemanticsAction(int32_t id,
flutter::SemanticsAction action,
fml::MallocMapping args) override;
void AccessibilityObjectDidBecomeFocused(int32_t id) override;
void AccessibilityObjectDidLoseFocus(int32_t id) override;
UIView<UITextInput>* textInputView() override;
UIView* view() const override { return view_controller_.view; }
bool isVoiceOverRunning() const override { return view_controller_.isVoiceOverRunning; }
fml::WeakPtr<AccessibilityBridge> GetWeakPtr();
std::shared_ptr<FlutterPlatformViewsController> GetPlatformViewsController() const override {
return platform_views_controller_;
};
void clearState();
private:
SemanticsObject* GetOrCreateObject(int32_t id, flutter::SemanticsNodeUpdates& updates);
SemanticsObject* FindNextFocusableIfNecessary();
// Finds the first focusable SemanticsObject rooted at the parent. This includes the parent itself
// if it is a focusable SemanticsObject.
//
// If the parent is nil, this function use the root SemanticsObject as the parent.
SemanticsObject* FindFirstFocusable(SemanticsObject* parent);
void VisitObjectsRecursivelyAndRemove(SemanticsObject* object,
NSMutableArray<NSNumber*>* doomed_uids);
FlutterViewController* view_controller_;
PlatformViewIOS* platform_view_;
const std::shared_ptr<FlutterPlatformViewsController> platform_views_controller_;
// If the this id is kSemanticObjectIdInvalid, it means either nothing has
// been focused or the focus is currently outside of the flutter application
// (i.e. the status bar or keyboard)
int32_t last_focused_semantics_object_id_;
fml::scoped_nsobject<NSMutableDictionary<NSNumber*, SemanticsObject*>> objects_;
fml::scoped_nsprotocol<FlutterBasicMessageChannel*> accessibility_channel_;
int32_t previous_route_id_ = 0;
std::unordered_map<int32_t, flutter::CustomAccessibilityAction> actions_;
std::vector<int32_t> previous_routes_;
std::unique_ptr<IosDelegate> ios_delegate_;
fml::WeakPtrFactory<AccessibilityBridge> weak_factory_; // Must be the last member.
FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityBridge);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_ACCESSIBILITY_BRIDGE_H_
| engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/Source/accessibility_bridge.h",
"repo_id": "engine",
"token_count": 1752
} | 333 |
framework module Flutter {
umbrella header "Flutter.h"
export *
module * { export * }
}
| engine/shell/platform/darwin/ios/framework/module.modulemap/0 | {
"file_path": "engine/shell/platform/darwin/ios/framework/module.modulemap",
"repo_id": "engine",
"token_count": 30
} | 334 |
// 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.
#import "flutter/shell/platform/darwin/ios/ios_surface_metal_impeller.h"
#include "flutter/impeller/renderer/backend/metal/formats_mtl.h"
#include "flutter/impeller/renderer/context.h"
#include "flutter/shell/gpu/gpu_surface_metal_impeller.h"
namespace flutter {
IOSSurfaceMetalImpeller::IOSSurfaceMetalImpeller(const fml::scoped_nsobject<CAMetalLayer>& layer,
const std::shared_ptr<IOSContext>& context)
: IOSSurface(context),
GPUSurfaceMetalDelegate(MTLRenderTargetType::kCAMetalLayer),
layer_(layer),
impeller_context_(context ? context->GetImpellerContext() : nullptr) {
if (!impeller_context_) {
return;
}
is_valid_ = true;
}
// |IOSSurface|
IOSSurfaceMetalImpeller::~IOSSurfaceMetalImpeller() = default;
// |IOSSurface|
bool IOSSurfaceMetalImpeller::IsValid() const {
return is_valid_;
}
// |IOSSurface|
void IOSSurfaceMetalImpeller::UpdateStorageSizeIfNecessary() {
// Nothing to do.
}
// |IOSSurface|
std::unique_ptr<Surface> IOSSurfaceMetalImpeller::CreateGPUSurface(GrDirectContext*) {
impeller_context_->UpdateOffscreenLayerPixelFormat(
impeller::FromMTLPixelFormat(layer_.get().pixelFormat));
return std::make_unique<GPUSurfaceMetalImpeller>(this, //
impeller_context_ //
);
}
// |GPUSurfaceMetalDelegate|
GPUCAMetalLayerHandle IOSSurfaceMetalImpeller::GetCAMetalLayer(const SkISize& frame_info) const {
CAMetalLayer* layer = layer_.get();
const auto drawable_size = CGSizeMake(frame_info.width(), frame_info.height());
if (!CGSizeEqualToSize(drawable_size, layer.drawableSize)) {
layer.drawableSize = drawable_size;
}
// Flutter needs to read from the color attachment in cases where there are effects such as
// backdrop filters. Flutter plugins that create platform views may also read from the layer.
layer.framebufferOnly = NO;
// When there are platform views in the scene, the drawable needs to be presented in the same
// transaction as the one created for platform views. When the drawable are being presented from
// the raster thread, we may not be able to use a transaction as it will dirty the UIViews being
// presented. If there is a non-Flutter UIView active, such as in add2app or a
// presentViewController page transition, then this will cause CoreAnimation assertion errors and
// exit the app.
layer.presentsWithTransaction = [[NSThread currentThread] isMainThread];
return layer;
}
// |GPUSurfaceMetalDelegate|
bool IOSSurfaceMetalImpeller::PresentDrawable(GrMTLHandle drawable) const {
FML_DCHECK(false);
return false;
}
// |GPUSurfaceMetalDelegate|
GPUMTLTextureInfo IOSSurfaceMetalImpeller::GetMTLTexture(const SkISize& frame_info) const {
FML_CHECK(false);
return GPUMTLTextureInfo{
.texture_id = -1, //
.texture = nullptr //
};
}
// |GPUSurfaceMetalDelegate|
bool IOSSurfaceMetalImpeller::PresentTexture(GPUMTLTextureInfo texture) const {
FML_CHECK(false);
return false;
}
// |GPUSurfaceMetalDelegate|
bool IOSSurfaceMetalImpeller::AllowsDrawingWhenGpuDisabled() const {
return false;
}
} // namespace flutter
| engine/shell/platform/darwin/ios/ios_surface_metal_impeller.mm/0 | {
"file_path": "engine/shell/platform/darwin/ios/ios_surface_metal_impeller.mm",
"repo_id": "engine",
"token_count": 1204
} | 335 |
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_
#import <Foundation/Foundation.h>
#include <stdint.h>
#import "FlutterAppLifecycleDelegate.h"
#import "FlutterBinaryMessenger.h"
#import "FlutterDartProject.h"
#import "FlutterMacros.h"
#import "FlutterPluginRegistrarMacOS.h"
#import "FlutterTexture.h"
// TODO(stuartmorgan): Merge this file with the iOS FlutterEngine.h.
@class FlutterViewController;
/**
* Coordinates a single instance of execution of a Flutter engine.
*
* A FlutterEngine can only be attached with one controller from the native
* code.
*/
FLUTTER_DARWIN_EXPORT
@interface FlutterEngine
: NSObject <FlutterTextureRegistry, FlutterPluginRegistry, FlutterAppLifecycleDelegate>
/**
* Initializes an engine with the given project.
*
* @param labelPrefix Currently unused; in the future, may be used for labelling threads
* as with the iOS FlutterEngine.
* @param project The project configuration. If nil, a default FlutterDartProject will be used.
*/
- (nonnull instancetype)initWithName:(nonnull NSString*)labelPrefix
project:(nullable FlutterDartProject*)project;
/**
* Initializes an engine that can run headlessly with the given project.
*
* @param labelPrefix Currently unused; in the future, may be used for labelling threads
* as with the iOS FlutterEngine.
* @param project The project configuration. If nil, a default FlutterDartProject will be used.
*/
- (nonnull instancetype)initWithName:(nonnull NSString*)labelPrefix
project:(nullable FlutterDartProject*)project
allowHeadlessExecution:(BOOL)allowHeadlessExecution NS_DESIGNATED_INITIALIZER;
- (nonnull instancetype)init NS_UNAVAILABLE;
/**
* Runs a Dart program on an Isolate from the main Dart library (i.e. the library that
* contains `main()`).
*
* The first call to this method will create a new Isolate. Subsequent calls will return
* immediately.
*
* @param entrypoint The name of a top-level function from the same Dart
* library that contains the app's main() function. If this is nil, it will
* default to `main()`. If it is not the app's main() function, that function
* must be decorated with `@pragma(vm:entry-point)` to ensure the method is not
* tree-shaken by the Dart compiler.
* @return YES if the call succeeds in creating and running a Flutter Engine instance; NO otherwise.
*/
- (BOOL)runWithEntrypoint:(nullable NSString*)entrypoint;
/**
* The `FlutterViewController` of this engine, if any.
*
* This view is used by legacy APIs that assume a single view.
*
* Setting this field from nil to a non-nil view controller also updates
* the view controller's engine and ID.
*
* Setting this field from non-nil to nil will terminate the engine if
* allowHeadlessExecution is NO.
*
* Setting this field from non-nil to a different non-nil FlutterViewController
* is prohibited and will throw an assertion error.
*/
@property(nonatomic, nullable, weak) FlutterViewController* viewController;
/**
* The `FlutterBinaryMessenger` for communicating with this engine.
*/
@property(nonatomic, nonnull, readonly) id<FlutterBinaryMessenger> binaryMessenger;
/**
* Shuts the Flutter engine if it is running. The FlutterEngine instance must always be shutdown
* before it may be collected. Not shutting down the FlutterEngine instance before releasing it will
* result in the leak of that engine instance.
*/
- (void)shutDownEngine;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_HEADERS_FLUTTERENGINE_H_
| engine/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h",
"repo_id": "engine",
"token_count": 1224
} | 336 |
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERBACKINGSTORE_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERBACKINGSTORE_H_
#import <Cocoa/Cocoa.h>
#import <Metal/Metal.h>
/**
* Interface for backing store handles. Typically contain references to the buffers that
* are handed by the `FlutterView` to the `FlutterRenderer`.
*/
@interface FlutterRenderBackingStore : NSObject
/**
* MTLTexture referenced by this backing store instance.
*/
@property(nonnull, nonatomic, readonly) id<MTLTexture> texture;
/**
* Initializes a backing store with the specified MTLTexture.
*/
- (nonnull instancetype)initWithTexture:(nonnull id<MTLTexture>)texture;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERBACKINGSTORE_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterBackingStore.h",
"repo_id": "engine",
"token_count": 323
} | 337 |
// 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.
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#include <algorithm>
#include <iostream>
#include <vector>
#include "flutter/shell/platform/common/app_lifecycle_state.h"
#include "flutter/shell/platform/common/engine_switches.h"
#include "flutter/shell/platform/embedder/embedder.h"
#import "flutter/shell/platform/darwin/common/framework/Source/FlutterBinaryMessengerRelay.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterAppDelegate_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDisplayLink.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterPlatformViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h"
@class FlutterEngineRegistrar;
NSString* const kFlutterPlatformChannel = @"flutter/platform";
NSString* const kFlutterSettingsChannel = @"flutter/settings";
NSString* const kFlutterLifecycleChannel = @"flutter/lifecycle";
/**
* Constructs and returns a FlutterLocale struct corresponding to |locale|, which must outlive
* the returned struct.
*/
static FlutterLocale FlutterLocaleFromNSLocale(NSLocale* locale) {
FlutterLocale flutterLocale = {};
flutterLocale.struct_size = sizeof(FlutterLocale);
flutterLocale.language_code = [[locale objectForKey:NSLocaleLanguageCode] UTF8String];
flutterLocale.country_code = [[locale objectForKey:NSLocaleCountryCode] UTF8String];
flutterLocale.script_code = [[locale objectForKey:NSLocaleScriptCode] UTF8String];
flutterLocale.variant_code = [[locale objectForKey:NSLocaleVariantCode] UTF8String];
return flutterLocale;
}
/// The private notification for voice over.
static NSString* const kEnhancedUserInterfaceNotification =
@"NSApplicationDidChangeAccessibilityEnhancedUserInterfaceNotification";
static NSString* const kEnhancedUserInterfaceKey = @"AXEnhancedUserInterface";
/// Clipboard plain text format.
constexpr char kTextPlainFormat[] = "text/plain";
#pragma mark -
// Records an active handler of the messenger (FlutterEngine) that listens to
// platform messages on a given channel.
@interface FlutterEngineHandlerInfo : NSObject
- (instancetype)initWithConnection:(NSNumber*)connection
handler:(FlutterBinaryMessageHandler)handler;
@property(nonatomic, readonly) FlutterBinaryMessageHandler handler;
@property(nonatomic, readonly) NSNumber* connection;
@end
@implementation FlutterEngineHandlerInfo
- (instancetype)initWithConnection:(NSNumber*)connection
handler:(FlutterBinaryMessageHandler)handler {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_connection = connection;
_handler = handler;
return self;
}
@end
#pragma mark -
/**
* Private interface declaration for FlutterEngine.
*/
@interface FlutterEngine () <FlutterBinaryMessenger>
/**
* A mutable array that holds one bool value that determines if responses to platform messages are
* clear to execute. This value should be read or written only inside of a synchronized block and
* will return `NO` after the FlutterEngine has been dealloc'd.
*/
@property(nonatomic, strong) NSMutableArray<NSNumber*>* isResponseValid;
/**
* All delegates added via plugin calls to addApplicationDelegate.
*/
@property(nonatomic, strong) NSPointerArray* pluginAppDelegates;
/**
* All registrars returned from registrarForPlugin:
*/
@property(nonatomic, readonly)
NSMutableDictionary<NSString*, FlutterEngineRegistrar*>* pluginRegistrars;
- (nullable FlutterViewController*)viewControllerForId:(FlutterViewId)viewId;
/**
* An internal method that adds the view controller with the given ID.
*
* This method assigns the controller with the ID, puts the controller into the
* map, and does assertions related to the implicit view ID.
*/
- (void)registerViewController:(FlutterViewController*)controller forId:(FlutterViewId)viewId;
/**
* An internal method that removes the view controller with the given ID.
*
* This method clears the ID of the controller, removes the controller from the
* map. This is an no-op if the view ID is not associated with any view
* controllers.
*/
- (void)deregisterViewControllerForId:(FlutterViewId)viewId;
/**
* Shuts down the engine if view requirement is not met, and headless execution
* is not allowed.
*/
- (void)shutDownIfNeeded;
/**
* Sends the list of user-preferred locales to the Flutter engine.
*/
- (void)sendUserLocales;
/**
* Handles a platform message from the engine.
*/
- (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message;
/**
* Invoked right before the engine is restarted.
*
* This should reset states to as if the application has just started. It
* usually indicates a hot restart (Shift-R in Flutter CLI.)
*/
- (void)engineCallbackOnPreEngineRestart;
/**
* Requests that the task be posted back the to the Flutter engine at the target time. The target
* time is in the clock used by the Flutter engine.
*/
- (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime;
/**
* Loads the AOT snapshots and instructions from the elf bundle (app_elf_snapshot.so) into _aotData,
* if it is present in the assets directory.
*/
- (void)loadAOTData:(NSString*)assetsDir;
/**
* Creates a platform view channel and sets up the method handler.
*/
- (void)setUpPlatformViewChannel;
/**
* Creates an accessibility channel and sets up the message handler.
*/
- (void)setUpAccessibilityChannel;
/**
* Handles messages received from the Flutter engine on the _*Channel channels.
*/
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result;
@end
#pragma mark -
@implementation FlutterEngineTerminationHandler {
__weak FlutterEngine* _engine;
FlutterTerminationCallback _terminator;
}
- (instancetype)initWithEngine:(FlutterEngine*)engine
terminator:(FlutterTerminationCallback)terminator {
self = [super init];
_acceptingRequests = NO;
_engine = engine;
_terminator = terminator ? terminator : ^(id sender) {
// Default to actually terminating the application. The terminator exists to
// allow tests to override it so that an actual exit doesn't occur.
[[NSApplication sharedApplication] terminate:sender];
};
id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
if ([appDelegate respondsToSelector:@selector(setTerminationHandler:)]) {
FlutterAppDelegate* flutterAppDelegate = reinterpret_cast<FlutterAppDelegate*>(appDelegate);
flutterAppDelegate.terminationHandler = self;
}
return self;
}
// This is called by the method call handler in the engine when the application
// requests termination itself.
- (void)handleRequestAppExitMethodCall:(NSDictionary<NSString*, id>*)arguments
result:(FlutterResult)result {
NSString* type = arguments[@"type"];
// Ignore the "exitCode" value in the arguments because AppKit doesn't have
// any good way to set the process exit code other than calling exit(), and
// that bypasses all of the native applicationShouldExit shutdown events,
// etc., which we don't want to skip.
FlutterAppExitType exitType =
[type isEqualTo:@"cancelable"] ? kFlutterAppExitTypeCancelable : kFlutterAppExitTypeRequired;
[self requestApplicationTermination:[NSApplication sharedApplication]
exitType:exitType
result:result];
}
// This is called by the FlutterAppDelegate whenever any termination request is
// received.
- (void)requestApplicationTermination:(id)sender
exitType:(FlutterAppExitType)type
result:(nullable FlutterResult)result {
_shouldTerminate = YES;
if (![self acceptingRequests]) {
// Until the Dart application has signaled that it is ready to handle
// termination requests, the app will just terminate when asked.
type = kFlutterAppExitTypeRequired;
}
switch (type) {
case kFlutterAppExitTypeCancelable: {
FlutterJSONMethodCodec* codec = [FlutterJSONMethodCodec sharedInstance];
FlutterMethodCall* methodCall =
[FlutterMethodCall methodCallWithMethodName:@"System.requestAppExit" arguments:nil];
[_engine sendOnChannel:kFlutterPlatformChannel
message:[codec encodeMethodCall:methodCall]
binaryReply:^(NSData* _Nullable reply) {
NSAssert(_terminator, @"terminator shouldn't be nil");
id decoded_reply = [codec decodeEnvelope:reply];
if ([decoded_reply isKindOfClass:[FlutterError class]]) {
FlutterError* error = (FlutterError*)decoded_reply;
NSLog(@"Method call returned error[%@]: %@ %@", [error code], [error message],
[error details]);
_terminator(sender);
return;
}
if (![decoded_reply isKindOfClass:[NSDictionary class]]) {
NSLog(@"Call to System.requestAppExit returned an unexpected object: %@",
decoded_reply);
_terminator(sender);
return;
}
NSDictionary* replyArgs = (NSDictionary*)decoded_reply;
if ([replyArgs[@"response"] isEqual:@"exit"]) {
_terminator(sender);
} else if ([replyArgs[@"response"] isEqual:@"cancel"]) {
_shouldTerminate = NO;
}
if (result != nil) {
result(replyArgs);
}
}];
break;
}
case kFlutterAppExitTypeRequired:
NSAssert(_terminator, @"terminator shouldn't be nil");
_terminator(sender);
break;
}
}
@end
#pragma mark -
@implementation FlutterPasteboard
- (NSInteger)clearContents {
return [[NSPasteboard generalPasteboard] clearContents];
}
- (NSString*)stringForType:(NSPasteboardType)dataType {
return [[NSPasteboard generalPasteboard] stringForType:dataType];
}
- (BOOL)setString:(nonnull NSString*)string forType:(nonnull NSPasteboardType)dataType {
return [[NSPasteboard generalPasteboard] setString:string forType:dataType];
}
@end
#pragma mark -
/**
* `FlutterPluginRegistrar` implementation handling a single plugin.
*/
@interface FlutterEngineRegistrar : NSObject <FlutterPluginRegistrar>
- (instancetype)initWithPlugin:(nonnull NSString*)pluginKey
flutterEngine:(nonnull FlutterEngine*)flutterEngine;
- (nullable NSView*)viewForId:(FlutterViewId)viewId;
/**
* The value published by this plugin, or NSNull if nothing has been published.
*
* The unusual NSNull is for the documented behavior of valuePublishedByPlugin:.
*/
@property(nonatomic, readonly, nonnull) NSObject* publishedValue;
@end
@implementation FlutterEngineRegistrar {
NSString* _pluginKey;
__weak FlutterEngine* _flutterEngine;
}
@dynamic view;
- (instancetype)initWithPlugin:(NSString*)pluginKey flutterEngine:(FlutterEngine*)flutterEngine {
self = [super init];
if (self) {
_pluginKey = [pluginKey copy];
_flutterEngine = flutterEngine;
_publishedValue = [NSNull null];
}
return self;
}
#pragma mark - FlutterPluginRegistrar
- (id<FlutterBinaryMessenger>)messenger {
return _flutterEngine.binaryMessenger;
}
- (id<FlutterTextureRegistry>)textures {
return _flutterEngine.renderer;
}
- (NSView*)view {
return [self viewForId:kFlutterImplicitViewId];
}
- (NSView*)viewForId:(FlutterViewId)viewId {
FlutterViewController* controller = [_flutterEngine viewControllerForId:viewId];
if (controller == nil) {
return nil;
}
if (!controller.viewLoaded) {
[controller loadView];
}
return controller.flutterView;
}
- (void)addMethodCallDelegate:(nonnull id<FlutterPlugin>)delegate
channel:(nonnull FlutterMethodChannel*)channel {
[channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[delegate handleMethodCall:call result:result];
}];
}
- (void)addApplicationDelegate:(NSObject<FlutterAppLifecycleDelegate>*)delegate {
id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
id<FlutterAppLifecycleProvider> lifeCycleProvider =
static_cast<id<FlutterAppLifecycleProvider>>(appDelegate);
[lifeCycleProvider addApplicationLifecycleDelegate:delegate];
[_flutterEngine.pluginAppDelegates addPointer:(__bridge void*)delegate];
}
}
- (void)registerViewFactory:(nonnull NSObject<FlutterPlatformViewFactory>*)factory
withId:(nonnull NSString*)factoryId {
[[_flutterEngine platformViewController] registerViewFactory:factory withId:factoryId];
}
- (void)publish:(NSObject*)value {
_publishedValue = value;
}
- (NSString*)lookupKeyForAsset:(NSString*)asset {
return [FlutterDartProject lookupKeyForAsset:asset];
}
- (NSString*)lookupKeyForAsset:(NSString*)asset fromPackage:(NSString*)package {
return [FlutterDartProject lookupKeyForAsset:asset fromPackage:package];
}
@end
// Callbacks provided to the engine. See the called methods for documentation.
#pragma mark - Static methods provided to engine configuration
static void OnPlatformMessage(const FlutterPlatformMessage* message, FlutterEngine* engine) {
[engine engineCallbackOnPlatformMessage:message];
}
#pragma mark -
@implementation FlutterEngine {
// The embedding-API-level engine object.
FLUTTER_API_SYMBOL(FlutterEngine) _engine;
// The project being run by this engine.
FlutterDartProject* _project;
// A mapping of channel names to the registered information for those channels.
NSMutableDictionary<NSString*, FlutterEngineHandlerInfo*>* _messengerHandlers;
// A self-incremental integer to assign to newly assigned channels as
// identification.
FlutterBinaryMessengerConnection _currentMessengerConnection;
// Whether the engine can continue running after the view controller is removed.
BOOL _allowHeadlessExecution;
// Pointer to the Dart AOT snapshot and instruction data.
_FlutterEngineAOTData* _aotData;
// _macOSCompositor is created when the engine is created and its destruction is handled by ARC
// when the engine is destroyed.
std::unique_ptr<flutter::FlutterCompositor> _macOSCompositor;
// The information of all views attached to this engine mapped from IDs.
//
// It can't use NSDictionary, because the values need to be weak references.
NSMapTable* _viewControllers;
// FlutterCompositor is copied and used in embedder.cc.
FlutterCompositor _compositor;
// Method channel for platform view functions. These functions include creating, disposing and
// mutating a platform view.
FlutterMethodChannel* _platformViewsChannel;
// Used to support creation and deletion of platform views and registering platform view
// factories. Lifecycle is tied to the engine.
FlutterPlatformViewController* _platformViewController;
// A message channel for sending user settings to the flutter engine.
FlutterBasicMessageChannel* _settingsChannel;
// A message channel for accessibility.
FlutterBasicMessageChannel* _accessibilityChannel;
// A method channel for miscellaneous platform functionality.
FlutterMethodChannel* _platformChannel;
FlutterThreadSynchronizer* _threadSynchronizer;
// The next available view ID.
int _nextViewId;
// Whether the application is currently the active application.
BOOL _active;
// Whether any portion of the application is currently visible.
BOOL _visible;
// Proxy to allow plugins, channels to hold a weak reference to the binary messenger (self).
FlutterBinaryMessengerRelay* _binaryMessenger;
// Map from ViewId to vsync waiter. Note that this is modified on main thread
// but accessed on UI thread, so access must be @synchronized.
NSMapTable<NSNumber*, FlutterVSyncWaiter*>* _vsyncWaiters;
}
- (instancetype)initWithName:(NSString*)labelPrefix project:(FlutterDartProject*)project {
return [self initWithName:labelPrefix project:project allowHeadlessExecution:YES];
}
static const int kMainThreadPriority = 47;
static void SetThreadPriority(FlutterThreadPriority priority) {
if (priority == kDisplay || priority == kRaster) {
pthread_t thread = pthread_self();
sched_param param;
int policy;
if (!pthread_getschedparam(thread, &policy, ¶m)) {
param.sched_priority = kMainThreadPriority;
pthread_setschedparam(thread, policy, ¶m);
}
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
}
}
- (instancetype)initWithName:(NSString*)labelPrefix
project:(FlutterDartProject*)project
allowHeadlessExecution:(BOOL)allowHeadlessExecution {
self = [super init];
NSAssert(self, @"Super init cannot be nil");
_pasteboard = [[FlutterPasteboard alloc] init];
_active = NO;
_visible = NO;
_project = project ?: [[FlutterDartProject alloc] init];
_messengerHandlers = [[NSMutableDictionary alloc] init];
_binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self];
_pluginAppDelegates = [NSPointerArray weakObjectsPointerArray];
_pluginRegistrars = [[NSMutableDictionary alloc] init];
_currentMessengerConnection = 1;
_allowHeadlessExecution = allowHeadlessExecution;
_semanticsEnabled = NO;
_binaryMessenger = [[FlutterBinaryMessengerRelay alloc] initWithParent:self];
_isResponseValid = [[NSMutableArray alloc] initWithCapacity:1];
[_isResponseValid addObject:@YES];
// kFlutterImplicitViewId is reserved for the implicit view.
_nextViewId = kFlutterImplicitViewId + 1;
_embedderAPI.struct_size = sizeof(FlutterEngineProcTable);
FlutterEngineGetProcAddresses(&_embedderAPI);
_viewControllers = [NSMapTable weakToWeakObjectsMapTable];
_renderer = [[FlutterRenderer alloc] initWithFlutterEngine:self];
NSNotificationCenter* notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(sendUserLocales)
name:NSCurrentLocaleDidChangeNotification
object:nil];
_platformViewController = [[FlutterPlatformViewController alloc] init];
_threadSynchronizer = [[FlutterThreadSynchronizer alloc] init];
[self setUpPlatformViewChannel];
[self setUpAccessibilityChannel];
[self setUpNotificationCenterListeners];
id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
_terminationHandler = [[FlutterEngineTerminationHandler alloc] initWithEngine:self
terminator:nil];
id<FlutterAppLifecycleProvider> lifecycleProvider =
static_cast<id<FlutterAppLifecycleProvider>>(appDelegate);
[lifecycleProvider addApplicationLifecycleDelegate:self];
} else {
_terminationHandler = nil;
}
_vsyncWaiters = [NSMapTable strongToStrongObjectsMapTable];
return self;
}
- (void)dealloc {
id<NSApplicationDelegate> appDelegate = [[NSApplication sharedApplication] delegate];
if ([appDelegate conformsToProtocol:@protocol(FlutterAppLifecycleProvider)]) {
id<FlutterAppLifecycleProvider> lifecycleProvider =
static_cast<id<FlutterAppLifecycleProvider>>(appDelegate);
[lifecycleProvider removeApplicationLifecycleDelegate:self];
// Unregister any plugins that registered as app delegates, since they are not guaranteed to
// live after the engine is destroyed, and their delegation registration is intended to be bound
// to the engine and its lifetime.
for (id<FlutterAppLifecycleDelegate> delegate in _pluginAppDelegates) {
if (delegate) {
[lifecycleProvider removeApplicationLifecycleDelegate:delegate];
}
}
}
// Clear any published values, just in case a plugin has created a retain cycle with the
// registrar.
for (NSString* pluginName in _pluginRegistrars) {
[_pluginRegistrars[pluginName] publish:[NSNull null]];
}
@synchronized(_isResponseValid) {
[_isResponseValid removeAllObjects];
[_isResponseValid addObject:@NO];
}
[self shutDownEngine];
if (_aotData) {
_embedderAPI.CollectAOTData(_aotData);
}
}
- (BOOL)runWithEntrypoint:(NSString*)entrypoint {
if (self.running) {
return NO;
}
if (!_allowHeadlessExecution && [_viewControllers count] == 0) {
NSLog(@"Attempted to run an engine with no view controller without headless mode enabled.");
return NO;
}
[self addInternalPlugins];
// The first argument of argv is required to be the executable name.
std::vector<const char*> argv = {[self.executableName UTF8String]};
std::vector<std::string> switches = self.switches;
// Enable Impeller only if specifically asked for from the project or cmdline arguments.
if (_project.enableImpeller ||
std::find(switches.begin(), switches.end(), "--enable-impeller=true") != switches.end()) {
switches.push_back("--enable-impeller=true");
}
std::transform(switches.begin(), switches.end(), std::back_inserter(argv),
[](const std::string& arg) -> const char* { return arg.c_str(); });
std::vector<const char*> dartEntrypointArgs;
for (NSString* argument in [_project dartEntrypointArguments]) {
dartEntrypointArgs.push_back([argument UTF8String]);
}
FlutterProjectArgs flutterArguments = {};
flutterArguments.struct_size = sizeof(FlutterProjectArgs);
flutterArguments.assets_path = _project.assetsPath.UTF8String;
flutterArguments.icu_data_path = _project.ICUDataPath.UTF8String;
flutterArguments.command_line_argc = static_cast<int>(argv.size());
flutterArguments.command_line_argv = argv.empty() ? nullptr : argv.data();
flutterArguments.platform_message_callback = (FlutterPlatformMessageCallback)OnPlatformMessage;
flutterArguments.update_semantics_callback2 = [](const FlutterSemanticsUpdate2* update,
void* user_data) {
// TODO(dkwingsmt): This callback only supports single-view, therefore it
// only operates on the implicit view. To support multi-view, we need a
// way to pass in the ID (probably through FlutterSemanticsUpdate).
FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
[[engine viewControllerForId:kFlutterImplicitViewId] updateSemantics:update];
};
flutterArguments.custom_dart_entrypoint = entrypoint.UTF8String;
flutterArguments.shutdown_dart_vm_when_done = true;
flutterArguments.dart_entrypoint_argc = dartEntrypointArgs.size();
flutterArguments.dart_entrypoint_argv = dartEntrypointArgs.data();
flutterArguments.root_isolate_create_callback = _project.rootIsolateCreateCallback;
flutterArguments.log_message_callback = [](const char* tag, const char* message,
void* user_data) {
if (tag && tag[0]) {
std::cout << tag << ": ";
}
std::cout << message << std::endl;
};
static size_t sTaskRunnerIdentifiers = 0;
const FlutterTaskRunnerDescription cocoa_task_runner_description = {
.struct_size = sizeof(FlutterTaskRunnerDescription),
.user_data = (void*)CFBridgingRetain(self),
.runs_task_on_current_thread_callback = [](void* user_data) -> bool {
return [[NSThread currentThread] isMainThread];
},
.post_task_callback = [](FlutterTask task, uint64_t target_time_nanos,
void* user_data) -> void {
[((__bridge FlutterEngine*)(user_data)) postMainThreadTask:task
targetTimeInNanoseconds:target_time_nanos];
},
.identifier = ++sTaskRunnerIdentifiers,
};
const FlutterCustomTaskRunners custom_task_runners = {
.struct_size = sizeof(FlutterCustomTaskRunners),
.platform_task_runner = &cocoa_task_runner_description,
.thread_priority_setter = SetThreadPriority};
flutterArguments.custom_task_runners = &custom_task_runners;
[self loadAOTData:_project.assetsPath];
if (_aotData) {
flutterArguments.aot_data = _aotData;
}
flutterArguments.compositor = [self createFlutterCompositor];
flutterArguments.on_pre_engine_restart_callback = [](void* user_data) {
FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
[engine engineCallbackOnPreEngineRestart];
};
flutterArguments.vsync_callback = [](void* user_data, intptr_t baton) {
FlutterEngine* engine = (__bridge FlutterEngine*)user_data;
[engine onVSync:baton];
};
FlutterRendererConfig rendererConfig = [_renderer createRendererConfig];
FlutterEngineResult result = _embedderAPI.Initialize(
FLUTTER_ENGINE_VERSION, &rendererConfig, &flutterArguments, (__bridge void*)(self), &_engine);
if (result != kSuccess) {
NSLog(@"Failed to initialize Flutter engine: error %d", result);
return NO;
}
result = _embedderAPI.RunInitialized(_engine);
if (result != kSuccess) {
NSLog(@"Failed to run an initialized engine: error %d", result);
return NO;
}
[self sendUserLocales];
// Update window metric for all view controllers.
NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
FlutterViewController* nextViewController;
while ((nextViewController = [viewControllerEnumerator nextObject])) {
[self updateWindowMetricsForViewController:nextViewController];
}
[self updateDisplayConfig];
// Send the initial user settings such as brightness and text scale factor
// to the engine.
[self sendInitialSettings];
return YES;
}
- (void)loadAOTData:(NSString*)assetsDir {
if (!_embedderAPI.RunsAOTCompiledDartCode()) {
return;
}
BOOL isDirOut = false; // required for NSFileManager fileExistsAtPath.
NSFileManager* fileManager = [NSFileManager defaultManager];
// This is the location where the test fixture places the snapshot file.
// For applications built by Flutter tool, this is in "App.framework".
NSString* elfPath = [NSString pathWithComponents:@[ assetsDir, @"app_elf_snapshot.so" ]];
if (![fileManager fileExistsAtPath:elfPath isDirectory:&isDirOut]) {
return;
}
FlutterEngineAOTDataSource source = {};
source.type = kFlutterEngineAOTDataSourceTypeElfPath;
source.elf_path = [elfPath cStringUsingEncoding:NSUTF8StringEncoding];
auto result = _embedderAPI.CreateAOTData(&source, &_aotData);
if (result != kSuccess) {
NSLog(@"Failed to load AOT data from: %@", elfPath);
}
}
- (void)registerViewController:(FlutterViewController*)controller forId:(FlutterViewId)viewId {
NSAssert(controller != nil, @"The controller must not be nil.");
NSAssert(![controller attached],
@"The incoming view controller is already attached to an engine.");
NSAssert([_viewControllers objectForKey:@(viewId)] == nil, @"The requested view ID is occupied.");
[controller setUpWithEngine:self viewId:viewId threadSynchronizer:_threadSynchronizer];
NSAssert(controller.viewId == viewId, @"Failed to assign view ID.");
[_viewControllers setObject:controller forKey:@(viewId)];
if (controller.viewLoaded) {
[self viewControllerViewDidLoad:controller];
}
}
- (void)viewControllerViewDidLoad:(FlutterViewController*)viewController {
__weak FlutterEngine* weakSelf = self;
FlutterTimeConverter* timeConverter = [[FlutterTimeConverter alloc] initWithEngine:self];
FlutterVSyncWaiter* waiter = [[FlutterVSyncWaiter alloc]
initWithDisplayLink:[FlutterDisplayLink displayLinkWithView:viewController.view]
block:^(CFTimeInterval timestamp, CFTimeInterval targetTimestamp,
uintptr_t baton) {
uint64_t timeNanos = [timeConverter CAMediaTimeToEngineTime:timestamp];
uint64_t targetTimeNanos =
[timeConverter CAMediaTimeToEngineTime:targetTimestamp];
FlutterEngine* engine = weakSelf;
if (engine) {
// It is a bit unfortunate that embedder requires OnVSync call on
// platform thread just to immediately redispatch it to UI thread.
// We are already on UI thread right now, but have to do the
// extra hop to main thread.
[engine->_threadSynchronizer performOnPlatformThread:^{
engine->_embedderAPI.OnVsync(_engine, baton, timeNanos, targetTimeNanos);
}];
}
}];
FML_DCHECK([_vsyncWaiters objectForKey:@(viewController.viewId)] == nil);
@synchronized(_vsyncWaiters) {
[_vsyncWaiters setObject:waiter forKey:@(viewController.viewId)];
}
}
- (void)deregisterViewControllerForId:(FlutterViewId)viewId {
FlutterViewController* oldController = [self viewControllerForId:viewId];
if (oldController != nil) {
[oldController detachFromEngine];
[_viewControllers removeObjectForKey:@(viewId)];
}
@synchronized(_vsyncWaiters) {
[_vsyncWaiters removeObjectForKey:@(viewId)];
}
}
- (void)shutDownIfNeeded {
if ([_viewControllers count] == 0 && !_allowHeadlessExecution) {
[self shutDownEngine];
}
}
- (FlutterViewController*)viewControllerForId:(FlutterViewId)viewId {
FlutterViewController* controller = [_viewControllers objectForKey:@(viewId)];
NSAssert(controller == nil || controller.viewId == viewId,
@"The stored controller has unexpected view ID.");
return controller;
}
- (void)setViewController:(FlutterViewController*)controller {
FlutterViewController* currentController =
[_viewControllers objectForKey:@(kFlutterImplicitViewId)];
if (currentController == controller) {
// From nil to nil, or from non-nil to the same controller.
return;
}
if (currentController == nil && controller != nil) {
// From nil to non-nil.
NSAssert(controller.engine == nil,
@"Failed to set view controller to the engine: "
@"The given FlutterViewController is already attached to an engine %@. "
@"If you wanted to create an FlutterViewController and set it to an existing engine, "
@"you should use FlutterViewController#init(engine:, nibName, bundle:) instead.",
controller.engine);
[self registerViewController:controller forId:kFlutterImplicitViewId];
} else if (currentController != nil && controller == nil) {
NSAssert(currentController.viewId == kFlutterImplicitViewId,
@"The default controller has an unexpected ID %llu", currentController.viewId);
// From non-nil to nil.
[self deregisterViewControllerForId:kFlutterImplicitViewId];
[self shutDownIfNeeded];
} else {
// From non-nil to a different non-nil view controller.
NSAssert(NO,
@"Failed to set view controller to the engine: "
@"The engine already has an implicit view controller %@. "
@"If you wanted to make the implicit view render in a different window, "
@"you should attach the current view controller to the window instead.",
[_viewControllers objectForKey:@(kFlutterImplicitViewId)]);
}
}
- (FlutterViewController*)viewController {
return [self viewControllerForId:kFlutterImplicitViewId];
}
- (FlutterCompositor*)createFlutterCompositor {
_macOSCompositor = std::make_unique<flutter::FlutterCompositor>(
[[FlutterViewEngineProvider alloc] initWithEngine:self],
[[FlutterTimeConverter alloc] initWithEngine:self], _platformViewController);
_compositor = {};
_compositor.struct_size = sizeof(FlutterCompositor);
_compositor.user_data = _macOSCompositor.get();
_compositor.create_backing_store_callback = [](const FlutterBackingStoreConfig* config, //
FlutterBackingStore* backing_store_out, //
void* user_data //
) {
return reinterpret_cast<flutter::FlutterCompositor*>(user_data)->CreateBackingStore(
config, backing_store_out);
};
_compositor.collect_backing_store_callback = [](const FlutterBackingStore* backing_store, //
void* user_data //
) { return true; };
_compositor.present_layers_callback = [](const FlutterLayer** layers, //
size_t layers_count, //
void* user_data //
) {
// TODO(dkwingsmt): This callback only supports single-view, therefore it
// only operates on the implicit view. To support multi-view, we need a new
// callback that also receives a view ID.
return reinterpret_cast<flutter::FlutterCompositor*>(user_data)->Present(kFlutterImplicitViewId,
layers, layers_count);
};
_compositor.avoid_backing_store_cache = true;
return &_compositor;
}
- (id<FlutterBinaryMessenger>)binaryMessenger {
return _binaryMessenger;
}
#pragma mark - Framework-internal methods
- (void)addViewController:(FlutterViewController*)controller {
[self registerViewController:controller forId:kFlutterImplicitViewId];
}
- (void)removeViewController:(nonnull FlutterViewController*)viewController {
NSAssert([viewController attached] && viewController.engine == self,
@"The given view controller is not associated with this engine.");
[self deregisterViewControllerForId:viewController.viewId];
[self shutDownIfNeeded];
}
- (BOOL)running {
return _engine != nullptr;
}
- (void)updateDisplayConfig:(NSNotification*)notification {
[self updateDisplayConfig];
}
- (NSArray<NSScreen*>*)screens {
return [NSScreen screens];
}
- (void)updateDisplayConfig {
if (!_engine) {
return;
}
std::vector<FlutterEngineDisplay> displays;
for (NSScreen* screen : [self screens]) {
CGDirectDisplayID displayID =
static_cast<CGDirectDisplayID>([screen.deviceDescription[@"NSScreenNumber"] integerValue]);
double devicePixelRatio = screen.backingScaleFactor;
FlutterEngineDisplay display;
display.struct_size = sizeof(display);
display.display_id = displayID;
display.single_display = false;
display.width = static_cast<size_t>(screen.frame.size.width) * devicePixelRatio;
display.height = static_cast<size_t>(screen.frame.size.height) * devicePixelRatio;
display.device_pixel_ratio = devicePixelRatio;
CVDisplayLinkRef displayLinkRef = nil;
CVReturn error = CVDisplayLinkCreateWithCGDisplay(displayID, &displayLinkRef);
if (error == 0) {
CVTime nominal = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(displayLinkRef);
if (!(nominal.flags & kCVTimeIsIndefinite)) {
double refreshRate = static_cast<double>(nominal.timeScale) / nominal.timeValue;
display.refresh_rate = round(refreshRate);
}
CVDisplayLinkRelease(displayLinkRef);
} else {
display.refresh_rate = 0;
}
displays.push_back(display);
}
_embedderAPI.NotifyDisplayUpdate(_engine, kFlutterEngineDisplaysUpdateTypeStartup,
displays.data(), displays.size());
}
- (void)onSettingsChanged:(NSNotification*)notification {
// TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015.
NSString* brightness =
[[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
[_settingsChannel sendMessage:@{
@"platformBrightness" : [brightness isEqualToString:@"Dark"] ? @"dark" : @"light",
// TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32006.
@"textScaleFactor" : @1.0,
@"alwaysUse24HourFormat" : @false
}];
}
- (void)sendInitialSettings {
// TODO(jonahwilliams): https://github.com/flutter/flutter/issues/32015.
[[NSDistributedNotificationCenter defaultCenter]
addObserver:self
selector:@selector(onSettingsChanged:)
name:@"AppleInterfaceThemeChangedNotification"
object:nil];
[self onSettingsChanged:nil];
}
- (FlutterEngineProcTable&)embedderAPI {
return _embedderAPI;
}
- (nonnull NSString*)executableName {
return [[[NSProcessInfo processInfo] arguments] firstObject] ?: @"Flutter";
}
- (void)updateWindowMetricsForViewController:(FlutterViewController*)viewController {
if (!_engine || !viewController || !viewController.viewLoaded) {
return;
}
NSAssert([self viewControllerForId:viewController.viewId] == viewController,
@"The provided view controller is not attached to this engine.");
NSView* view = viewController.flutterView;
CGRect scaledBounds = [view convertRectToBacking:view.bounds];
CGSize scaledSize = scaledBounds.size;
double pixelRatio = view.bounds.size.width == 0 ? 1 : scaledSize.width / view.bounds.size.width;
auto displayId = [view.window.screen.deviceDescription[@"NSScreenNumber"] integerValue];
const FlutterWindowMetricsEvent windowMetricsEvent = {
.struct_size = sizeof(windowMetricsEvent),
.width = static_cast<size_t>(scaledSize.width),
.height = static_cast<size_t>(scaledSize.height),
.pixel_ratio = pixelRatio,
.left = static_cast<size_t>(scaledBounds.origin.x),
.top = static_cast<size_t>(scaledBounds.origin.y),
.display_id = static_cast<uint64_t>(displayId),
.view_id = viewController.viewId,
};
_embedderAPI.SendWindowMetricsEvent(_engine, &windowMetricsEvent);
}
- (void)sendPointerEvent:(const FlutterPointerEvent&)event {
_embedderAPI.SendPointerEvent(_engine, &event, 1);
}
- (void)sendKeyEvent:(const FlutterKeyEvent&)event
callback:(FlutterKeyEventCallback)callback
userData:(void*)userData {
_embedderAPI.SendKeyEvent(_engine, &event, callback, userData);
}
- (void)setSemanticsEnabled:(BOOL)enabled {
if (_semanticsEnabled == enabled) {
return;
}
_semanticsEnabled = enabled;
// Update all view controllers' bridges.
NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
FlutterViewController* nextViewController;
while ((nextViewController = [viewControllerEnumerator nextObject])) {
[nextViewController notifySemanticsEnabledChanged];
}
_embedderAPI.UpdateSemanticsEnabled(_engine, _semanticsEnabled);
}
- (void)dispatchSemanticsAction:(FlutterSemanticsAction)action
toTarget:(uint16_t)target
withData:(fml::MallocMapping)data {
_embedderAPI.DispatchSemanticsAction(_engine, target, action, data.GetMapping(), data.GetSize());
}
- (FlutterPlatformViewController*)platformViewController {
return _platformViewController;
}
#pragma mark - Private methods
- (void)sendUserLocales {
if (!self.running) {
return;
}
// Create a list of FlutterLocales corresponding to the preferred languages.
NSMutableArray<NSLocale*>* locales = [NSMutableArray array];
std::vector<FlutterLocale> flutterLocales;
flutterLocales.reserve(locales.count);
for (NSString* localeID in [NSLocale preferredLanguages]) {
NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:localeID];
[locales addObject:locale];
flutterLocales.push_back(FlutterLocaleFromNSLocale(locale));
}
// Convert to a list of pointers, and send to the engine.
std::vector<const FlutterLocale*> flutterLocaleList;
flutterLocaleList.reserve(flutterLocales.size());
std::transform(flutterLocales.begin(), flutterLocales.end(),
std::back_inserter(flutterLocaleList),
[](const auto& arg) -> const auto* { return &arg; });
_embedderAPI.UpdateLocales(_engine, flutterLocaleList.data(), flutterLocaleList.size());
}
- (void)engineCallbackOnPlatformMessage:(const FlutterPlatformMessage*)message {
NSData* messageData = nil;
if (message->message_size > 0) {
messageData = [NSData dataWithBytesNoCopy:(void*)message->message
length:message->message_size
freeWhenDone:NO];
}
NSString* channel = @(message->channel);
__block const FlutterPlatformMessageResponseHandle* responseHandle = message->response_handle;
__block FlutterEngine* weakSelf = self;
NSMutableArray* isResponseValid = self.isResponseValid;
FlutterEngineSendPlatformMessageResponseFnPtr sendPlatformMessageResponse =
_embedderAPI.SendPlatformMessageResponse;
FlutterBinaryReply binaryResponseHandler = ^(NSData* response) {
@synchronized(isResponseValid) {
if (![isResponseValid[0] boolValue]) {
// Ignore, engine was killed.
return;
}
if (responseHandle) {
sendPlatformMessageResponse(weakSelf->_engine, responseHandle,
static_cast<const uint8_t*>(response.bytes), response.length);
responseHandle = NULL;
} else {
NSLog(@"Error: Message responses can be sent only once. Ignoring duplicate response "
"on channel '%@'.",
channel);
}
}
};
FlutterEngineHandlerInfo* handlerInfo = _messengerHandlers[channel];
if (handlerInfo) {
handlerInfo.handler(messageData, binaryResponseHandler);
} else {
binaryResponseHandler(nil);
}
}
- (void)engineCallbackOnPreEngineRestart {
NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
FlutterViewController* nextViewController;
while ((nextViewController = [viewControllerEnumerator nextObject])) {
[nextViewController onPreEngineRestart];
}
}
- (void)onVSync:(uintptr_t)baton {
@synchronized(_vsyncWaiters) {
// TODO(knopp): Use vsync waiter for correct view.
// https://github.com/flutter/flutter/issues/142845
FlutterVSyncWaiter* waiter = [_vsyncWaiters objectForKey:@(kFlutterImplicitViewId)];
[waiter waitForVSync:baton];
}
}
/**
* Note: Called from dealloc. Should not use accessors or other methods.
*/
- (void)shutDownEngine {
if (_engine == nullptr) {
return;
}
[_threadSynchronizer shutdown];
_threadSynchronizer = nil;
FlutterEngineResult result = _embedderAPI.Deinitialize(_engine);
if (result != kSuccess) {
NSLog(@"Could not de-initialize the Flutter engine: error %d", result);
}
// Balancing release for the retain in the task runner dispatch table.
CFRelease((CFTypeRef)self);
result = _embedderAPI.Shutdown(_engine);
if (result != kSuccess) {
NSLog(@"Failed to shut down Flutter engine: error %d", result);
}
_engine = nullptr;
}
- (void)setUpPlatformViewChannel {
_platformViewsChannel =
[FlutterMethodChannel methodChannelWithName:@"flutter/platform_views"
binaryMessenger:self.binaryMessenger
codec:[FlutterStandardMethodCodec sharedInstance]];
__weak FlutterEngine* weakSelf = self;
[_platformViewsChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[[weakSelf platformViewController] handleMethodCall:call result:result];
}];
}
- (void)setUpAccessibilityChannel {
_accessibilityChannel = [FlutterBasicMessageChannel
messageChannelWithName:@"flutter/accessibility"
binaryMessenger:self.binaryMessenger
codec:[FlutterStandardMessageCodec sharedInstance]];
__weak FlutterEngine* weakSelf = self;
[_accessibilityChannel setMessageHandler:^(id message, FlutterReply reply) {
[weakSelf handleAccessibilityEvent:message];
}];
}
- (void)setUpNotificationCenterListeners {
NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
// macOS fires this private message when VoiceOver turns on or off.
[center addObserver:self
selector:@selector(onAccessibilityStatusChanged:)
name:kEnhancedUserInterfaceNotification
object:nil];
[center addObserver:self
selector:@selector(applicationWillTerminate:)
name:NSApplicationWillTerminateNotification
object:nil];
[center addObserver:self
selector:@selector(windowDidChangeScreen:)
name:NSWindowDidChangeScreenNotification
object:nil];
[center addObserver:self
selector:@selector(updateDisplayConfig:)
name:NSApplicationDidChangeScreenParametersNotification
object:nil];
}
- (void)addInternalPlugins {
__weak FlutterEngine* weakSelf = self;
[FlutterMouseCursorPlugin registerWithRegistrar:[self registrarForPlugin:@"mousecursor"]];
[FlutterMenuPlugin registerWithRegistrar:[self registrarForPlugin:@"menu"]];
_settingsChannel =
[FlutterBasicMessageChannel messageChannelWithName:kFlutterSettingsChannel
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMessageCodec sharedInstance]];
_platformChannel =
[FlutterMethodChannel methodChannelWithName:kFlutterPlatformChannel
binaryMessenger:self.binaryMessenger
codec:[FlutterJSONMethodCodec sharedInstance]];
[_platformChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[weakSelf handleMethodCall:call result:result];
}];
}
- (void)applicationWillTerminate:(NSNotification*)notification {
[self shutDownEngine];
}
- (void)windowDidChangeScreen:(NSNotification*)notification {
// Update window metric for all view controllers since the display_id has
// changed.
NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
FlutterViewController* nextViewController;
while ((nextViewController = [viewControllerEnumerator nextObject])) {
[self updateWindowMetricsForViewController:nextViewController];
}
}
- (void)onAccessibilityStatusChanged:(NSNotification*)notification {
BOOL enabled = [notification.userInfo[kEnhancedUserInterfaceKey] boolValue];
NSEnumerator* viewControllerEnumerator = [_viewControllers objectEnumerator];
FlutterViewController* nextViewController;
while ((nextViewController = [viewControllerEnumerator nextObject])) {
[nextViewController onAccessibilityStatusChanged:enabled];
}
self.semanticsEnabled = enabled;
}
- (void)handleAccessibilityEvent:(NSDictionary<NSString*, id>*)annotatedEvent {
NSString* type = annotatedEvent[@"type"];
if ([type isEqualToString:@"announce"]) {
NSString* message = annotatedEvent[@"data"][@"message"];
NSNumber* assertiveness = annotatedEvent[@"data"][@"assertiveness"];
if (message == nil) {
return;
}
NSAccessibilityPriorityLevel priority = [assertiveness isEqualToNumber:@1]
? NSAccessibilityPriorityHigh
: NSAccessibilityPriorityMedium;
[self announceAccessibilityMessage:message withPriority:priority];
}
}
- (void)announceAccessibilityMessage:(NSString*)message
withPriority:(NSAccessibilityPriorityLevel)priority {
NSAccessibilityPostNotificationWithUserInfo(
[self viewControllerForId:kFlutterImplicitViewId].flutterView,
NSAccessibilityAnnouncementRequestedNotification,
@{NSAccessibilityAnnouncementKey : message, NSAccessibilityPriorityKey : @(priority)});
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([call.method isEqualToString:@"SystemNavigator.pop"]) {
[[NSApplication sharedApplication] terminate:self];
result(nil);
} else if ([call.method isEqualToString:@"SystemSound.play"]) {
[self playSystemSound:call.arguments];
result(nil);
} else if ([call.method isEqualToString:@"Clipboard.getData"]) {
result([self getClipboardData:call.arguments]);
} else if ([call.method isEqualToString:@"Clipboard.setData"]) {
[self setClipboardData:call.arguments];
result(nil);
} else if ([call.method isEqualToString:@"Clipboard.hasStrings"]) {
result(@{@"value" : @([self clipboardHasStrings])});
} else if ([call.method isEqualToString:@"System.exitApplication"]) {
if ([self terminationHandler] == nil) {
// If the termination handler isn't set, then either we haven't
// initialized it yet, or (more likely) the NSApp delegate isn't a
// FlutterAppDelegate, so it can't cancel requests to exit. So, in that
// case, just terminate when requested.
[NSApp terminate:self];
result(nil);
} else {
[[self terminationHandler] handleRequestAppExitMethodCall:call.arguments result:result];
}
} else if ([call.method isEqualToString:@"System.initializationComplete"]) {
if ([self terminationHandler] != nil) {
[self terminationHandler].acceptingRequests = YES;
}
result(nil);
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)playSystemSound:(NSString*)soundType {
if ([soundType isEqualToString:@"SystemSoundType.alert"]) {
NSBeep();
}
}
- (NSDictionary*)getClipboardData:(NSString*)format {
if ([format isEqualToString:@(kTextPlainFormat)]) {
NSString* stringInPasteboard = [self.pasteboard stringForType:NSPasteboardTypeString];
return stringInPasteboard == nil ? nil : @{@"text" : stringInPasteboard};
}
return nil;
}
- (void)setClipboardData:(NSDictionary*)data {
NSString* text = data[@"text"];
[self.pasteboard clearContents];
if (text && ![text isEqual:[NSNull null]]) {
[self.pasteboard setString:text forType:NSPasteboardTypeString];
}
}
- (BOOL)clipboardHasStrings {
return [self.pasteboard stringForType:NSPasteboardTypeString].length > 0;
}
- (std::vector<std::string>)switches {
return flutter::GetSwitchesFromEnvironment();
}
- (FlutterThreadSynchronizer*)testThreadSynchronizer {
return _threadSynchronizer;
}
#pragma mark - FlutterAppLifecycleDelegate
- (void)setApplicationState:(flutter::AppLifecycleState)state {
NSString* nextState =
[[NSString alloc] initWithCString:flutter::AppLifecycleStateToString(state)];
[self sendOnChannel:kFlutterLifecycleChannel
message:[nextState dataUsingEncoding:NSUTF8StringEncoding]];
}
/**
* Called when the |FlutterAppDelegate| gets the applicationWillBecomeActive
* notification.
*/
- (void)handleWillBecomeActive:(NSNotification*)notification {
_active = YES;
if (!_visible) {
[self setApplicationState:flutter::AppLifecycleState::kHidden];
} else {
[self setApplicationState:flutter::AppLifecycleState::kResumed];
}
}
/**
* Called when the |FlutterAppDelegate| gets the applicationWillResignActive
* notification.
*/
- (void)handleWillResignActive:(NSNotification*)notification {
_active = NO;
if (!_visible) {
[self setApplicationState:flutter::AppLifecycleState::kHidden];
} else {
[self setApplicationState:flutter::AppLifecycleState::kInactive];
}
}
/**
* Called when the |FlutterAppDelegate| gets the applicationDidUnhide
* notification.
*/
- (void)handleDidChangeOcclusionState:(NSNotification*)notification {
NSApplicationOcclusionState occlusionState = [[NSApplication sharedApplication] occlusionState];
if (occlusionState & NSApplicationOcclusionStateVisible) {
_visible = YES;
if (_active) {
[self setApplicationState:flutter::AppLifecycleState::kResumed];
} else {
[self setApplicationState:flutter::AppLifecycleState::kInactive];
}
} else {
_visible = NO;
[self setApplicationState:flutter::AppLifecycleState::kHidden];
}
}
#pragma mark - FlutterBinaryMessenger
- (void)sendOnChannel:(nonnull NSString*)channel message:(nullable NSData*)message {
[self sendOnChannel:channel message:message binaryReply:nil];
}
- (void)sendOnChannel:(NSString*)channel
message:(NSData* _Nullable)message
binaryReply:(FlutterBinaryReply _Nullable)callback {
FlutterPlatformMessageResponseHandle* response_handle = nullptr;
if (callback) {
struct Captures {
FlutterBinaryReply reply;
};
auto captures = std::make_unique<Captures>();
captures->reply = callback;
auto message_reply = [](const uint8_t* data, size_t data_size, void* user_data) {
auto captures = reinterpret_cast<Captures*>(user_data);
NSData* reply_data = nil;
if (data != nullptr && data_size > 0) {
reply_data = [NSData dataWithBytes:static_cast<const void*>(data) length:data_size];
}
captures->reply(reply_data);
delete captures;
};
FlutterEngineResult create_result = _embedderAPI.PlatformMessageCreateResponseHandle(
_engine, message_reply, captures.get(), &response_handle);
if (create_result != kSuccess) {
NSLog(@"Failed to create a FlutterPlatformMessageResponseHandle (%d)", create_result);
return;
}
captures.release();
}
FlutterPlatformMessage platformMessage = {
.struct_size = sizeof(FlutterPlatformMessage),
.channel = [channel UTF8String],
.message = static_cast<const uint8_t*>(message.bytes),
.message_size = message.length,
.response_handle = response_handle,
};
FlutterEngineResult message_result = _embedderAPI.SendPlatformMessage(_engine, &platformMessage);
if (message_result != kSuccess) {
NSLog(@"Failed to send message to Flutter engine on channel '%@' (%d).", channel,
message_result);
}
if (response_handle != nullptr) {
FlutterEngineResult release_result =
_embedderAPI.PlatformMessageReleaseResponseHandle(_engine, response_handle);
if (release_result != kSuccess) {
NSLog(@"Failed to release the response handle (%d).", release_result);
};
}
}
- (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(nonnull NSString*)channel
binaryMessageHandler:
(nullable FlutterBinaryMessageHandler)handler {
_currentMessengerConnection += 1;
_messengerHandlers[channel] =
[[FlutterEngineHandlerInfo alloc] initWithConnection:@(_currentMessengerConnection)
handler:[handler copy]];
return _currentMessengerConnection;
}
- (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection {
// Find the _messengerHandlers that has the required connection, and record its
// channel.
NSString* foundChannel = nil;
for (NSString* key in [_messengerHandlers allKeys]) {
FlutterEngineHandlerInfo* handlerInfo = [_messengerHandlers objectForKey:key];
if ([handlerInfo.connection isEqual:@(connection)]) {
foundChannel = key;
break;
}
}
if (foundChannel) {
[_messengerHandlers removeObjectForKey:foundChannel];
}
}
#pragma mark - FlutterPluginRegistry
- (id<FlutterPluginRegistrar>)registrarForPlugin:(NSString*)pluginName {
id<FlutterPluginRegistrar> registrar = self.pluginRegistrars[pluginName];
if (!registrar) {
FlutterEngineRegistrar* registrarImpl =
[[FlutterEngineRegistrar alloc] initWithPlugin:pluginName flutterEngine:self];
self.pluginRegistrars[pluginName] = registrarImpl;
registrar = registrarImpl;
}
return registrar;
}
- (nullable NSObject*)valuePublishedByPlugin:(NSString*)pluginName {
return self.pluginRegistrars[pluginName].publishedValue;
}
#pragma mark - FlutterTextureRegistrar
- (int64_t)registerTexture:(id<FlutterTexture>)texture {
return [_renderer registerTexture:texture];
}
- (BOOL)registerTextureWithID:(int64_t)textureId {
return _embedderAPI.RegisterExternalTexture(_engine, textureId) == kSuccess;
}
- (void)textureFrameAvailable:(int64_t)textureID {
[_renderer textureFrameAvailable:textureID];
}
- (BOOL)markTextureFrameAvailable:(int64_t)textureID {
return _embedderAPI.MarkExternalTextureFrameAvailable(_engine, textureID) == kSuccess;
}
- (void)unregisterTexture:(int64_t)textureID {
[_renderer unregisterTexture:textureID];
}
- (BOOL)unregisterTextureWithID:(int64_t)textureID {
return _embedderAPI.UnregisterExternalTexture(_engine, textureID) == kSuccess;
}
#pragma mark - Task runner integration
- (void)runTaskOnEmbedder:(FlutterTask)task {
if (_engine) {
auto result = _embedderAPI.RunTask(_engine, &task);
if (result != kSuccess) {
NSLog(@"Could not post a task to the Flutter engine.");
}
}
}
- (void)postMainThreadTask:(FlutterTask)task targetTimeInNanoseconds:(uint64_t)targetTime {
__weak FlutterEngine* weakSelf = self;
auto worker = ^{
[weakSelf runTaskOnEmbedder:task];
};
const auto engine_time = _embedderAPI.GetCurrentTime();
if (targetTime <= engine_time) {
dispatch_async(dispatch_get_main_queue(), worker);
} else {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, targetTime - engine_time),
dispatch_get_main_queue(), worker);
}
}
// Getter used by test harness, only exposed through the FlutterEngine(Test) category
- (flutter::FlutterCompositor*)macOSCompositor {
return _macOSCompositor.get();
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterEngine.mm",
"repo_id": "engine",
"token_count": 20867
} | 338 |
// 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_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMOUSECURSORPLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMOUSECURSORPLUGIN_H_
#import <Cocoa/Cocoa.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
/**
* A plugin to handle mouse cursor.
*
* Responsible for bridging the native macOS mouse cursor system with the
* Flutter framework mouse cursor classes, via system channels.
*/
@interface FlutterMouseCursorPlugin : NSObject <FlutterPlugin>
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMOUSECURSORPLUGIN_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.h",
"repo_id": "engine",
"token_count": 316
} | 339 |
// 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.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.h"
#import <Metal/Metal.h>
#include <algorithm>
#include "flutter/fml/logging.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h"
@implementation FlutterSurfacePresentInfo
@end
@interface FlutterSurfaceManager () {
id<MTLDevice> _device;
id<MTLCommandQueue> _commandQueue;
CALayer* _containingLayer;
__weak id<FlutterSurfaceManagerDelegate> _delegate;
// Available (cached) back buffer surfaces. These will be cleared during
// present and replaced by current frong surfaces.
FlutterBackBufferCache* _backBufferCache;
// Surfaces currently used to back visible layers.
NSMutableArray<FlutterSurface*>* _frontSurfaces;
// Currently visible layers.
NSMutableArray<CALayer*>* _layers;
// Whether to highlight borders of overlay surfaces. Determined by
// FLTEnableSurfaceDebugInfo value in main bundle Info.plist.
NSNumber* _enableSurfaceDebugInfo;
CATextLayer* _infoLayer;
CFTimeInterval _lastPresentationTime;
}
/**
* Updates underlying CALayers with the contents of the surfaces to present.
*/
- (void)commit:(NSArray<FlutterSurfacePresentInfo*>*)surfaces;
@end
static NSColor* GetBorderColorForLayer(int layer) {
NSArray* colors = @[
[NSColor yellowColor],
[NSColor cyanColor],
[NSColor magentaColor],
[NSColor greenColor],
[NSColor purpleColor],
[NSColor orangeColor],
[NSColor blueColor],
];
return colors[layer % colors.count];
}
/// Creates sublayers for given layer, each one displaying a portion of the
/// of the surface determined by a rectangle in the provided paint region.
static void UpdateContentSubLayers(CALayer* layer,
IOSurfaceRef surface,
CGFloat scale,
CGSize surfaceSize,
NSColor* borderColor,
const std::vector<FlutterRect>& paintRegion) {
// Adjust sublayer count to paintRegion count.
while (layer.sublayers.count > paintRegion.size()) {
[layer.sublayers.lastObject removeFromSuperlayer];
}
while (layer.sublayers.count < paintRegion.size()) {
CALayer* newLayer = [CALayer layer];
[layer addSublayer:newLayer];
}
for (size_t i = 0; i < paintRegion.size(); i++) {
CALayer* subLayer = [layer.sublayers objectAtIndex:i];
const auto& rect = paintRegion[i];
subLayer.frame = CGRectMake(rect.left / scale, rect.top / scale,
(rect.right - rect.left) / scale, (rect.bottom - rect.top) / scale);
double width = surfaceSize.width;
double height = surfaceSize.height;
subLayer.contentsRect =
CGRectMake(rect.left / width, rect.top / height, (rect.right - rect.left) / width,
(rect.bottom - rect.top) / height);
if (borderColor != nil) {
// Visualize sublayer
subLayer.borderColor = borderColor.CGColor;
subLayer.borderWidth = 1.0;
}
subLayer.contents = (__bridge id)surface;
}
}
@implementation FlutterSurfaceManager
- (instancetype)initWithDevice:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue
layer:(CALayer*)containingLayer
delegate:(__weak id<FlutterSurfaceManagerDelegate>)delegate {
if (self = [super init]) {
_device = device;
_commandQueue = commandQueue;
_containingLayer = containingLayer;
_delegate = delegate;
_backBufferCache = [[FlutterBackBufferCache alloc] init];
_frontSurfaces = [NSMutableArray array];
_layers = [NSMutableArray array];
}
return self;
}
- (FlutterBackBufferCache*)backBufferCache {
return _backBufferCache;
}
- (NSArray*)frontSurfaces {
return _frontSurfaces;
}
- (NSArray*)layers {
return _layers;
}
- (FlutterSurface*)surfaceForSize:(CGSize)size {
FlutterSurface* surface = [_backBufferCache removeSurfaceForSize:size];
if (surface == nil) {
surface = [[FlutterSurface alloc] initWithSize:size device:_device];
}
return surface;
}
- (BOOL)enableSurfaceDebugInfo {
if (_enableSurfaceDebugInfo == nil) {
_enableSurfaceDebugInfo =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"FLTEnableSurfaceDebugInfo"];
if (_enableSurfaceDebugInfo == nil) {
_enableSurfaceDebugInfo = @NO;
}
}
return [_enableSurfaceDebugInfo boolValue];
}
- (void)commit:(NSArray<FlutterSurfacePresentInfo*>*)surfaces {
FML_DCHECK([NSThread isMainThread]);
// Release all unused back buffer surfaces and replace them with front surfaces.
[_backBufferCache replaceSurfaces:_frontSurfaces];
// Front surfaces will be replaced by currently presented surfaces.
[_frontSurfaces removeAllObjects];
for (FlutterSurfacePresentInfo* info in surfaces) {
[_frontSurfaces addObject:info.surface];
}
// Add or remove layers to match the count of surfaces to present.
while (_layers.count > _frontSurfaces.count) {
[_layers.lastObject removeFromSuperlayer];
[_layers removeLastObject];
}
while (_layers.count < _frontSurfaces.count) {
CALayer* layer = [CALayer layer];
[_containingLayer addSublayer:layer];
[_layers addObject:layer];
}
bool enableSurfaceDebugInfo = self.enableSurfaceDebugInfo;
// Update contents of surfaces.
for (size_t i = 0; i < surfaces.count; ++i) {
FlutterSurfacePresentInfo* info = surfaces[i];
CALayer* layer = _layers[i];
CGFloat scale = _containingLayer.contentsScale;
if (i == 0) {
layer.frame = CGRectMake(info.offset.x / scale, info.offset.y / scale,
info.surface.size.width / scale, info.surface.size.height / scale);
layer.contents = (__bridge id)info.surface.ioSurface;
} else {
layer.frame = CGRectZero;
NSColor* borderColor = enableSurfaceDebugInfo ? GetBorderColorForLayer(i - 1) : nil;
UpdateContentSubLayers(layer, info.surface.ioSurface, scale, info.surface.size, borderColor,
info.paintRegion);
}
layer.zPosition = info.zIndex;
}
if (enableSurfaceDebugInfo) {
if (_infoLayer == nil) {
_infoLayer = [[CATextLayer alloc] init];
[_containingLayer addSublayer:_infoLayer];
_infoLayer.fontSize = 15;
_infoLayer.foregroundColor = [NSColor yellowColor].CGColor;
_infoLayer.frame = CGRectMake(15, 15, 300, 100);
_infoLayer.contentsScale = _containingLayer.contentsScale;
_infoLayer.zPosition = 100000;
}
_infoLayer.string = [NSString stringWithFormat:@"Surface count: %li", _layers.count];
}
}
static CGSize GetRequiredFrameSize(NSArray<FlutterSurfacePresentInfo*>* surfaces) {
CGSize size = CGSizeZero;
for (FlutterSurfacePresentInfo* info in surfaces) {
size = CGSizeMake(std::max(size.width, info.offset.x + info.surface.size.width),
std::max(size.height, info.offset.y + info.surface.size.height));
}
return size;
}
- (void)presentSurfaces:(NSArray<FlutterSurfacePresentInfo*>*)surfaces
atTime:(CFTimeInterval)presentationTime
notify:(dispatch_block_t)notify {
id<MTLCommandBuffer> commandBuffer = [_commandQueue commandBuffer];
[commandBuffer commit];
[commandBuffer waitUntilScheduled];
dispatch_block_t presentBlock = ^{
// Get the actual dimensions of the frame (relevant for thread synchronizer).
CGSize size = GetRequiredFrameSize(surfaces);
[_delegate onPresent:size
withBlock:^{
_lastPresentationTime = presentationTime;
[self commit:surfaces];
if (notify != nil) {
notify();
}
}];
};
if (presentationTime > 0) {
// Enforce frame pacing. It seems that the target timestamp of CVDisplayLink does not
// exactly correspond to core animation deadline. Especially with 120hz, setting the frame
// contents too close after previous target timestamp will result in uneven frame pacing.
// Empirically setting the content in the second half of frame interval seems to work
// well for both 60hz and 120hz.
//
// This schedules a timer on current (raster) thread runloop. Raster thread at
// this point should be idle (the next frame vsync has not been signalled yet).
//
// Alternative could be simply blocking the raster thread, but that would show
// as a average_frame_rasterizer_time_millis regresson.
CFTimeInterval minPresentationTime = (presentationTime + _lastPresentationTime) / 2.0;
CFTimeInterval now = CACurrentMediaTime();
if (now < minPresentationTime) {
NSTimer* timer = [NSTimer timerWithTimeInterval:minPresentationTime - now
repeats:NO
block:^(NSTimer* timer) {
presentBlock();
}];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
return;
}
}
presentBlock();
}
@end
// Cached back buffers will be released after kIdleDelay if there is no activity.
static const double kIdleDelay = 1.0;
@interface FlutterBackBufferCache () {
NSMutableArray<FlutterSurface*>* _surfaces;
}
@end
@implementation FlutterBackBufferCache
- (instancetype)init {
if (self = [super init]) {
self->_surfaces = [[NSMutableArray alloc] init];
}
return self;
}
- (nullable FlutterSurface*)removeSurfaceForSize:(CGSize)size {
@synchronized(self) {
for (FlutterSurface* surface in _surfaces) {
if (CGSizeEqualToSize(surface.size, size)) {
// By default ARC doesn't retain enumeration iteration variables.
FlutterSurface* res = surface;
[_surfaces removeObject:surface];
return res;
}
}
return nil;
}
}
- (void)replaceSurfaces:(nonnull NSArray<FlutterSurface*>*)surfaces {
@synchronized(self) {
[_surfaces removeAllObjects];
[_surfaces addObjectsFromArray:surfaces];
}
// performSelector:withObject:afterDelay needs to be performed on RunLoop thread
[self performSelectorOnMainThread:@selector(reschedule) withObject:nil waitUntilDone:NO];
}
- (NSUInteger)count {
@synchronized(self) {
return _surfaces.count;
}
}
- (void)onIdle {
@synchronized(self) {
[_surfaces removeAllObjects];
}
}
- (void)reschedule {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(onIdle) object:nil];
[self performSelector:@selector(onIdle) withObject:nil afterDelay:kIdleDelay];
}
- (void)dealloc {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(onIdle) object:nil];
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterSurfaceManager.mm",
"repo_id": "engine",
"token_count": 4180
} | 340 |
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVSYNCWAITER_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVSYNCWAITER_H_
#import <AppKit/AppKit.h>
@class FlutterDisplayLink;
@interface FlutterVSyncWaiter : NSObject
/// Creates new waiter instance tied to provided NSView.
/// This function must be called on the main thread.
///
/// Provided |block| will be invoked on same thread as -waitForVSync:.
- (instancetype)initWithDisplayLink:(FlutterDisplayLink*)displayLink
block:(void (^)(CFTimeInterval timestamp,
CFTimeInterval targetTimestamp,
uintptr_t baton))block;
/// Schedules |baton| to be signaled on next display refresh.
/// The block provided in the initializer will be invoked on same thread
/// as this method (there must be a run loop associated with current thread).
- (void)waitForVSync:(uintptr_t)baton;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERVSYNCWAITER_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterVSyncWaiter.h",
"repo_id": "engine",
"token_count": 450
} | 341 |
// 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.
#import "KeyCodeMap_Internal.h"
#import "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
namespace flutter {
bool operator==(const LayoutGoal& a, const LayoutGoal& b) {
return a.keyCode == b.keyCode && a.keyChar == b.keyChar && a.mandatory == b.mandatory;
}
namespace testing {
// Spot check some expected values so that we know that some classes of key
// aren't excluded.
TEST(KeyMappingTest, HasExpectedValues) {
// Has Space
EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x31, 0x20, false}),
kLayoutGoals.end());
// Has Digit0
EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x1d, 0x30, true}),
kLayoutGoals.end());
// Has KeyA
EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x00, 0x61, true}),
kLayoutGoals.end());
// Has Equal
EXPECT_NE(std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x18, 0x3d, false}),
kLayoutGoals.end());
// Has IntlBackslash
EXPECT_NE(
std::find(kLayoutGoals.begin(), kLayoutGoals.end(), LayoutGoal{0x0a, 0x200000020, false}),
kLayoutGoals.end());
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/darwin/macos/framework/Source/KeyCodeMapTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/KeyCodeMapTest.mm",
"repo_id": "engine",
"token_count": 543
} | 342 |
// 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 "flutter/shell/platform/embedder/embedder_external_texture_gl.h"
#include "flutter/fml/logging.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkPaint.h"
#include "third_party/skia/include/core/SkAlphaType.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/ganesh/SkImageGanesh.h"
#include "third_party/skia/include/gpu/ganesh/gl/GrGLBackendSurface.h"
#include "third_party/skia/include/gpu/gl/GrGLTypes.h"
namespace flutter {
EmbedderExternalTextureGL::EmbedderExternalTextureGL(
int64_t texture_identifier,
const ExternalTextureCallback& callback)
: Texture(texture_identifier), external_texture_callback_(callback) {
FML_DCHECK(external_texture_callback_);
}
EmbedderExternalTextureGL::~EmbedderExternalTextureGL() = default;
// |flutter::Texture|
void EmbedderExternalTextureGL::Paint(PaintContext& context,
const SkRect& bounds,
bool freeze,
const DlImageSampling sampling) {
if (last_image_ == nullptr) {
last_image_ =
ResolveTexture(Id(), //
context.gr_context, //
SkISize::Make(bounds.width(), bounds.height()) //
);
}
DlCanvas* canvas = context.canvas;
const DlPaint* paint = context.paint;
if (last_image_) {
SkRect image_bounds = SkRect::Make(last_image_->bounds());
if (bounds != image_bounds) {
canvas->DrawImageRect(last_image_, image_bounds, bounds, sampling, paint);
} else {
canvas->DrawImage(last_image_, {bounds.x(), bounds.y()}, sampling, paint);
}
}
}
sk_sp<DlImage> EmbedderExternalTextureGL::ResolveTexture(
int64_t texture_id,
GrDirectContext* context,
const SkISize& size) {
context->flushAndSubmit();
context->resetContext(kAll_GrBackendState);
std::unique_ptr<FlutterOpenGLTexture> texture =
external_texture_callback_(texture_id, size.width(), size.height());
if (!texture) {
return nullptr;
}
GrGLTextureInfo gr_texture_info = {texture->target, texture->name,
texture->format};
size_t width = size.width();
size_t height = size.height();
if (texture->width != 0 && texture->height != 0) {
width = texture->width;
height = texture->height;
}
auto gr_backend_texture = GrBackendTextures::MakeGL(
width, height, skgpu::Mipmapped::kNo, gr_texture_info);
SkImages::TextureReleaseProc release_proc = texture->destruction_callback;
auto image =
SkImages::BorrowTextureFrom(context, // context
gr_backend_texture, // texture handle
kTopLeft_GrSurfaceOrigin, // origin
kRGBA_8888_SkColorType, // color type
kPremul_SkAlphaType, // alpha type
nullptr, // colorspace
release_proc, // texture release proc
texture->user_data // texture release context
);
if (!image) {
// In case Skia rejects the image, call the release proc so that
// embedders can perform collection of intermediates.
if (release_proc) {
release_proc(texture->user_data);
}
FML_LOG(ERROR) << "Could not create external texture->";
return nullptr;
}
// This image should not escape local use by EmbedderExternalTextureGL
return DlImage::Make(std::move(image));
}
// |flutter::Texture|
void EmbedderExternalTextureGL::OnGrContextCreated() {}
// |flutter::Texture|
void EmbedderExternalTextureGL::OnGrContextDestroyed() {}
// |flutter::Texture|
void EmbedderExternalTextureGL::MarkNewFrameAvailable() {
last_image_ = nullptr;
}
// |flutter::Texture|
void EmbedderExternalTextureGL::OnTextureUnregistered() {}
} // namespace flutter
| engine/shell/platform/embedder/embedder_external_texture_gl.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_external_texture_gl.cc",
"repo_id": "engine",
"token_count": 1917
} | 343 |
// 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 "flutter/shell/platform/embedder/embedder_render_target.h"
#include <optional>
#include <utility>
namespace flutter {
EmbedderRenderTarget::EmbedderRenderTarget(FlutterBackingStore backing_store,
fml::closure on_release)
: backing_store_(backing_store), on_release_(std::move(on_release)) {
// TODO(38468): The optimization to elide backing store updates between frames
// has not been implemented yet.
backing_store_.did_update = true;
}
EmbedderRenderTarget::~EmbedderRenderTarget() {
if (on_release_) {
on_release_();
}
}
const FlutterBackingStore* EmbedderRenderTarget::GetBackingStore() const {
return &backing_store_;
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_render_target.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_render_target.cc",
"repo_id": "engine",
"token_count": 311
} | 344 |
// 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_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_GL_IMPELLER_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_GL_IMPELLER_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/gpu/gpu_surface_gl_impeller.h"
#include "flutter/shell/platform/embedder/embedder_external_view_embedder.h"
#include "flutter/shell/platform/embedder/embedder_surface.h"
#include "flutter/shell/platform/embedder/embedder_surface_gl.h"
namespace impeller {
class ContextGLES;
} // namespace impeller
namespace flutter {
class ReactorWorker;
class EmbedderSurfaceGLImpeller final : public EmbedderSurface,
public GPUSurfaceGLDelegate {
public:
EmbedderSurfaceGLImpeller(
EmbedderSurfaceGL::GLDispatchTable gl_dispatch_table,
bool fbo_reset_after_present,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder);
~EmbedderSurfaceGLImpeller() override;
private:
bool valid_ = false;
EmbedderSurfaceGL::GLDispatchTable gl_dispatch_table_;
bool fbo_reset_after_present_;
std::shared_ptr<impeller::ContextGLES> impeller_context_;
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_;
std::shared_ptr<ReactorWorker> worker_;
// |EmbedderSurface|
bool IsValid() const override;
// |EmbedderSurface|
std::unique_ptr<Surface> CreateGPUSurface() override;
// |EmbedderSurface|
std::shared_ptr<impeller::Context> CreateImpellerContext() const override;
// |GPUSurfaceGLDelegate|
std::unique_ptr<GLContextResult> GLContextMakeCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextClearCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextPresent(const GLPresentInfo& present_info) override;
// |GPUSurfaceGLDelegate|
GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override;
// |GPUSurfaceGLDelegate|
bool GLContextFBOResetAfterPresent() const override;
// |GPUSurfaceGLDelegate|
SkMatrix GLContextSurfaceTransformation() const override;
// |GPUSurfaceGLDelegate|
GLProcResolver GetGLProcResolver() const override;
// |GPUSurfaceGLDelegate|
SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const override;
// |EmbedderSurface|
sk_sp<GrDirectContext> CreateResourceContext() const override;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurfaceGLImpeller);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_GL_IMPELLER_H_
| engine/shell/platform/embedder/embedder_surface_gl_impeller.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_surface_gl_impeller.h",
"repo_id": "engine",
"token_count": 947
} | 345 |
// 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 "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/tests/embedder_frozen.h"
#include "flutter/testing/testing.h"
namespace flutter {
namespace testing {
// Assert that both types have the same member with the same offset.
// This prevents reordering of "frozen" embedder API struct members.
#define ASSERT_EQ_OFFSET(type1, type2, member) \
ASSERT_EQ(offsetof(type1, member), offsetof(type2, member))
// New members must not be added to `FlutterTransformation`
// as it would break the ABI of `FlutterSemanticsNode`.
// See: https://github.com/flutter/flutter/issues/121176
TEST(EmbedderFrozen, FlutterTransformationIsFrozen) {
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, scaleX);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, skewX);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, transX);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, skewY);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, scaleY);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, transY);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, pers0);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, pers1);
ASSERT_EQ_OFFSET(FlutterTransformation, FrozenFlutterTransformation, pers2);
}
// New members must not be added to `FlutterRect` as it would
// break the ABI of `FlutterSemanticsNode` and `FlutterDamage`.
// See: https://github.com/flutter/flutter/issues/121176
// See: https://github.com/flutter/flutter/issues/121347
TEST(EmbedderFrozen, FlutterRectIsFrozen) {
ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, left);
ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, top);
ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, right);
ASSERT_EQ_OFFSET(FlutterRect, FrozenFlutterRect, bottom);
}
// New members must not be added to `FlutterPoint` as it would
// break the ABI of `FlutterLayer`.
TEST(EmbedderFrozen, FlutterPointIsFrozen) {
ASSERT_EQ_OFFSET(FlutterPoint, FrozenFlutterPoint, x);
ASSERT_EQ_OFFSET(FlutterPoint, FrozenFlutterPoint, y);
}
// New members must not be added to `FlutterDamage` as it would
// break the ABI of `FlutterPresentInfo`.
TEST(EmbedderFrozen, FlutterDamageIsFrozen) {
ASSERT_EQ_OFFSET(FlutterDamage, FrozenFlutterDamage, struct_size);
ASSERT_EQ_OFFSET(FlutterDamage, FrozenFlutterDamage, num_rects);
ASSERT_EQ_OFFSET(FlutterDamage, FrozenFlutterDamage, damage);
}
// New members must not be added to `FlutterSemanticsNode`
// as it would break the ABI of `FlutterSemanticsUpdate`.
// See: https://github.com/flutter/flutter/issues/121176
TEST(EmbedderFrozen, FlutterSemanticsNodeIsFrozen) {
ASSERT_EQ(sizeof(FlutterSemanticsNode), sizeof(FrozenFlutterSemanticsNode));
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
struct_size);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, id);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, flags);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, actions);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
text_selection_base);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
text_selection_extent);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
scroll_child_count);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
scroll_index);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
scroll_position);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
scroll_extent_max);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
scroll_extent_min);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, elevation);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, thickness);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, label);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, hint);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, value);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
increased_value);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
decreased_value);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
text_direction);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, rect);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, transform);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
child_count);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
children_in_traversal_order);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
children_in_hit_test_order);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
custom_accessibility_actions_count);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
custom_accessibility_actions);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode,
platform_view_id);
ASSERT_EQ_OFFSET(FlutterSemanticsNode, FrozenFlutterSemanticsNode, tooltip);
}
// New members must not be added to `FlutterSemanticsCustomAction`
// as it would break the ABI of `FlutterSemanticsUpdate`.
// See: https://github.com/flutter/flutter/issues/121176
TEST(EmbedderFrozen, FlutterSemanticsCustomActionIsFrozen) {
ASSERT_EQ(sizeof(FlutterSemanticsCustomAction),
sizeof(FrozenFlutterSemanticsCustomAction));
ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction,
FrozenFlutterSemanticsCustomAction, struct_size);
ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction,
FrozenFlutterSemanticsCustomAction, id);
ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction,
FrozenFlutterSemanticsCustomAction, override_action);
ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction,
FrozenFlutterSemanticsCustomAction, label);
ASSERT_EQ_OFFSET(FlutterSemanticsCustomAction,
FrozenFlutterSemanticsCustomAction, hint);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/embedder/tests/embedder_frozen_unittests.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_frozen_unittests.cc",
"repo_id": "engine",
"token_count": 2490
} | 346 |
// 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h"
namespace flutter {
namespace testing {
class EmbedderTestCompositorVulkan : public EmbedderTestCompositor {
public:
EmbedderTestCompositorVulkan(SkISize surface_size,
sk_sp<GrDirectContext> context);
~EmbedderTestCompositorVulkan() override;
private:
bool UpdateOffscrenComposition(const FlutterLayer** layers,
size_t layers_count) override;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorVulkan);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_VULKAN_H_
| engine/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor_vulkan.h",
"repo_id": "engine",
"token_count": 454
} | 347 |
// 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 "flutter/shell/platform/embedder/vsync_waiter_embedder.h"
namespace flutter {
VsyncWaiterEmbedder::VsyncWaiterEmbedder(
const VsyncCallback& vsync_callback,
const flutter::TaskRunners& task_runners)
: VsyncWaiter(task_runners), vsync_callback_(vsync_callback) {
FML_DCHECK(vsync_callback_);
}
VsyncWaiterEmbedder::~VsyncWaiterEmbedder() = default;
// |VsyncWaiter|
void VsyncWaiterEmbedder::AwaitVSync() {
auto* weak_waiter = new std::weak_ptr<VsyncWaiter>(shared_from_this());
intptr_t baton = reinterpret_cast<intptr_t>(weak_waiter);
vsync_callback_(baton);
}
// static
bool VsyncWaiterEmbedder::OnEmbedderVsync(
const flutter::TaskRunners& task_runners,
intptr_t baton,
fml::TimePoint frame_start_time,
fml::TimePoint frame_target_time) {
if (baton == 0) {
return false;
}
// If the time here is in the future, the contract for `FlutterEngineOnVsync`
// says that the engine will only process the frame when the time becomes
// current.
task_runners.GetUITaskRunner()->PostTaskForTime(
[frame_start_time, frame_target_time, baton]() {
std::weak_ptr<VsyncWaiter>* weak_waiter =
reinterpret_cast<std::weak_ptr<VsyncWaiter>*>(baton);
auto vsync_waiter = weak_waiter->lock();
delete weak_waiter;
if (vsync_waiter) {
vsync_waiter->FireCallback(frame_start_time, frame_target_time);
}
},
frame_start_time);
return true;
}
} // namespace flutter
| engine/shell/platform/embedder/vsync_waiter_embedder.cc/0 | {
"file_path": "engine/shell/platform/embedder/vsync_waiter_embedder.cc",
"repo_id": "engine",
"token_count": 642
} | 348 |
// 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.
part of zircon;
final _kZirconFFILibName = 'libzircon_ffi.so';
final _kLibZirconDartPath = '/pkg/lib/$_kZirconFFILibName';
class _Bindings {
static ZirconFFIBindings? _bindings;
@pragma('vm:entry-point')
static ZirconFFIBindings? get() {
// For soft-transition until libzircon_ffi.so rolls into GI.
if (!File(_kLibZirconDartPath).existsSync()) {
return null;
}
if (_bindings == null) {
final _dylib = DynamicLibrary.open(_kZirconFFILibName);
_bindings = ZirconFFIBindings(_dylib);
}
final initializer = _bindings!.zircon_dart_dl_initialize;
if (initializer(NativeApi.initializeApiDLData) != 1) {
throw UnsupportedError('Unable to initialize dart:zircon_ffi.');
}
return _bindings;
}
}
final ZirconFFIBindings? zirconFFIBindings = _Bindings.get();
| engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/init.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/init.dart",
"repo_id": "engine",
"token_count": 387
} | 349 |
{
program: {
data: "data/zircon_tests",
runner: "dart_jit_runner",
},
}
| engine/shell/platform/fuchsia/dart-pkg/zircon/test/meta/zircon_tests.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/test/meta/zircon_tests.cml",
"repo_id": "engine",
"token_count": 53
} | 350 |
# 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.
import("//flutter/build/dart/rules.gni")
import("//flutter/tools/fuchsia/dart/dart_library.gni")
application_snapshot("kernel_compiler") {
main_dart = "compiler.dart"
deps = [ "../flutter/kernel:kernel_platform_files($host_toolchain)" ]
package_config = rebase_path("$dart_src/.dart_tool/package_config.json")
training_args = [
"--train",
rebase_path(main_dart),
]
kernel_compiler_files = exec_script("$dart_src/tools/list_dart_files.py",
[
"absolute",
rebase_path("."),
],
"list lines")
kernel_compiler_files += exec_script("$dart_src/tools/list_dart_files.py",
[
"absolute",
rebase_path("$dart_src/pkg"),
],
"list lines")
inputs = kernel_compiler_files
}
application_snapshot("_list_libraries_kernel") {
visibility = [ ":*" ]
snapshot_kind = "kernel"
main_dart = "$dart_src/pkg/vm/bin/list_libraries.dart"
package_config = rebase_path("$dart_src/.dart_tool/package_config.json")
training_args = []
output = "$target_gen_dir/list_libraries.dart.dill"
}
application_snapshot("list_libraries") {
deps = [ ":_list_libraries_kernel" ]
main_dart = "$dart_src/pkg/vm/bin/list_libraries.dart"
package_config = rebase_path("$dart_src/.dart_tool/package_config.json")
training_args = [
# train against the dill file which is generated for this snapshot.
rebase_path("$target_gen_dir/list_libraries.dart.dill"),
]
}
dart_library("async_helper") {
package_root = "$dart_src/pkg/async_helper"
package_name = "async_helper"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"async_helper.dart",
"async_minitest.dart",
]
}
dart_library("meta") {
package_root = "$dart_src/pkg/meta"
package_name = "meta"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"dart2js.dart",
"meta.dart",
"meta_meta.dart",
]
}
dart_library("expect") {
package_root = "$dart_src/pkg/expect"
package_name = "expect"
pubspec = "$package_root/pubspec.yaml"
deps = [ ":meta" ]
sources = [
"config.dart",
"expect.dart",
"minitest.dart",
"variations.dart",
]
}
dart_library("litetest") {
package_root = "//flutter/testing/litetest"
package_name = "litetest"
pubspec = "$package_root/pubspec.yaml"
source_dir = "lib"
deps = [
":async_helper",
":expect",
":meta",
]
sources = [
"litetest.dart",
"src/matchers.dart",
"src/test.dart",
"src/test_suite.dart",
]
}
dart_library("args") {
package_root = "$dart_src/third_party/pkg/args"
package_name = "args"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"args.dart",
"command_runner.dart",
"src/allow_anything_parser.dart",
"src/arg_parser.dart",
"src/arg_parser_exception.dart",
"src/arg_results.dart",
"src/help_command.dart",
"src/option.dart",
"src/parser.dart",
"src/usage.dart",
"src/usage_exception.dart",
"src/utils.dart",
]
}
dart_library("collection") {
package_root = "$dart_src/third_party/pkg/collection"
package_name = "collection"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"algorithms.dart",
"collection.dart",
"equality.dart",
"iterable_zip.dart",
"priority_queue.dart",
"src/algorithms.dart",
"src/canonicalized_map.dart",
"src/combined_wrappers/combined_iterable.dart",
"src/combined_wrappers/combined_iterator.dart",
"src/combined_wrappers/combined_list.dart",
"src/combined_wrappers/combined_map.dart",
"src/comparators.dart",
"src/empty_unmodifiable_set.dart",
"src/equality.dart",
"src/equality_map.dart",
"src/equality_set.dart",
"src/functions.dart",
"src/iterable_extensions.dart",
"src/iterable_zip.dart",
"src/list_extensions.dart",
"src/priority_queue.dart",
"src/queue_list.dart",
"src/union_set.dart",
"src/union_set_controller.dart",
"src/unmodifiable_wrappers.dart",
"src/utils.dart",
"src/wrappers.dart",
"wrappers.dart",
]
}
dart_library("logging") {
package_root = "$dart_src/third_party/pkg/logging"
package_name = "logging"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"logging.dart",
"src/level.dart",
"src/log_record.dart",
"src/logger.dart",
]
}
dart_library("path") {
package_root = "$dart_src/third_party/pkg/path"
package_name = "path"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"path.dart",
"src/characters.dart",
"src/context.dart",
"src/internal_style.dart",
"src/parsed_path.dart",
"src/path_exception.dart",
"src/path_map.dart",
"src/path_set.dart",
"src/style.dart",
"src/style/posix.dart",
"src/style/url.dart",
"src/style/windows.dart",
"src/utils.dart",
]
}
dart_library("stack_trace") {
package_root = "$dart_src/third_party/pkg/stack_trace"
package_name = "stack_trace"
pubspec = "$package_root/pubspec.yaml"
deps = [ ":path" ]
sources = [
"src/chain.dart",
"src/frame.dart",
"src/lazy_chain.dart",
"src/lazy_trace.dart",
"src/stack_zone_specification.dart",
"src/trace.dart",
"src/unparsed_frame.dart",
"src/utils.dart",
"src/vm_trace.dart",
"stack_trace.dart",
]
}
dart_library("matcher") {
package_root = "$dart_src/third_party/pkg/matcher"
package_name = "matcher"
pubspec = "$package_root/pubspec.yaml"
deps = [ ":stack_trace" ]
sources = [
"expect.dart",
"matcher.dart",
"mirror_matchers.dart",
"src/core_matchers.dart",
"src/custom_matcher.dart",
"src/description.dart",
"src/equals_matcher.dart",
"src/error_matchers.dart",
"src/expect/async_matcher.dart",
"src/expect/expect.dart",
"src/expect/expect_async.dart",
"src/expect/future_matchers.dart",
"src/expect/never_called.dart",
"src/expect/prints_matcher.dart",
"src/expect/stream_matcher.dart",
"src/expect/stream_matchers.dart",
"src/expect/throws_matcher.dart",
"src/expect/throws_matchers.dart",
"src/expect/util/placeholder.dart",
"src/expect/util/pretty_print.dart",
"src/feature_matcher.dart",
"src/having_matcher.dart",
"src/interfaces.dart",
"src/iterable_matchers.dart",
"src/map_matchers.dart",
"src/numeric_matchers.dart",
"src/operator_matchers.dart",
"src/order_matchers.dart",
"src/pretty_print.dart",
"src/string_matchers.dart",
"src/type_matcher.dart",
"src/util.dart",
]
}
dart_library("quiver") {
package_root = "//third_party/pkg/quiver"
package_name = "quiver"
pubspec = "$package_root/pubspec.yaml"
deps = [
":matcher",
":meta",
]
sources = [
"async.dart",
"cache.dart",
"check.dart",
"collection.dart",
"core.dart",
"iterables.dart",
"pattern.dart",
"src/async/collect.dart",
"src/async/concat.dart",
"src/async/countdown_timer.dart",
"src/async/enumerate.dart",
"src/async/future_stream.dart",
"src/async/metronome.dart",
"src/async/stream_buffer.dart",
"src/async/stream_router.dart",
"src/async/string.dart",
"src/cache/cache.dart",
"src/cache/map_cache.dart",
"src/collection/bimap.dart",
"src/collection/delegates/iterable.dart",
"src/collection/delegates/list.dart",
"src/collection/delegates/map.dart",
"src/collection/delegates/queue.dart",
"src/collection/delegates/set.dart",
"src/collection/lru_map.dart",
"src/collection/multimap.dart",
"src/collection/treeset.dart",
"src/collection/utils.dart",
"src/core/hash.dart",
"src/core/optional.dart",
"src/core/utils.dart",
"src/iterables/concat.dart",
"src/iterables/count.dart",
"src/iterables/cycle.dart",
"src/iterables/enumerate.dart",
"src/iterables/generating_iterable.dart",
"src/iterables/infinite_iterable.dart",
"src/iterables/merge.dart",
"src/iterables/min_max.dart",
"src/iterables/partition.dart",
"src/iterables/range.dart",
"src/iterables/zip.dart",
"src/time/clock.dart",
"src/time/duration_unit_constants.dart",
"src/time/util.dart",
"strings.dart",
"testing/async.dart",
"testing/equality.dart",
"testing/src/async/fake_async.dart",
"testing/src/equality/equality.dart",
"testing/src/time/time.dart",
"testing/time.dart",
"time.dart",
]
}
dart_library("vector_math") {
package_root = "//flutter/third_party/pkg/vector_math"
package_name = "vector_math"
pubspec = "$package_root/pubspec.yaml"
deps = []
sources = [
"hash.dart",
"src/vector_math/aabb2.dart",
"src/vector_math/aabb3.dart",
"src/vector_math/colors.dart",
"src/vector_math/constants.dart",
"src/vector_math/error_helpers.dart",
"src/vector_math/frustum.dart",
"src/vector_math/intersection_result.dart",
"src/vector_math/matrix2.dart",
"src/vector_math/matrix3.dart",
"src/vector_math/matrix4.dart",
"src/vector_math/obb3.dart",
"src/vector_math/opengl.dart",
"src/vector_math/plane.dart",
"src/vector_math/quad.dart",
"src/vector_math/quaternion.dart",
"src/vector_math/ray.dart",
"src/vector_math/sphere.dart",
"src/vector_math/third_party/noise.dart",
"src/vector_math/triangle.dart",
"src/vector_math/utilities.dart",
"src/vector_math/vector.dart",
"src/vector_math/vector2.dart",
"src/vector_math/vector3.dart",
"src/vector_math/vector4.dart",
"src/vector_math_64/aabb2.dart",
"src/vector_math_64/aabb3.dart",
"src/vector_math_64/colors.dart",
"src/vector_math_64/constants.dart",
"src/vector_math_64/error_helpers.dart",
"src/vector_math_64/frustum.dart",
"src/vector_math_64/intersection_result.dart",
"src/vector_math_64/matrix2.dart",
"src/vector_math_64/matrix3.dart",
"src/vector_math_64/matrix4.dart",
"src/vector_math_64/obb3.dart",
"src/vector_math_64/opengl.dart",
"src/vector_math_64/plane.dart",
"src/vector_math_64/quad.dart",
"src/vector_math_64/quaternion.dart",
"src/vector_math_64/ray.dart",
"src/vector_math_64/sphere.dart",
"src/vector_math_64/third_party/noise.dart",
"src/vector_math_64/triangle.dart",
"src/vector_math_64/utilities.dart",
"src/vector_math_64/vector.dart",
"src/vector_math_64/vector2.dart",
"src/vector_math_64/vector3.dart",
"src/vector_math_64/vector4.dart",
"src/vector_math_geometry/filters/barycentric_filter.dart",
"src/vector_math_geometry/filters/color_filter.dart",
"src/vector_math_geometry/filters/flat_shade_filter.dart",
"src/vector_math_geometry/filters/geometry_filter.dart",
"src/vector_math_geometry/filters/invert_filter.dart",
"src/vector_math_geometry/filters/transform_filter.dart",
"src/vector_math_geometry/generators/attribute_generators.dart",
"src/vector_math_geometry/generators/circle_generator.dart",
"src/vector_math_geometry/generators/cube_generator.dart",
"src/vector_math_geometry/generators/cylinder_generator.dart",
"src/vector_math_geometry/generators/geometry_generator.dart",
"src/vector_math_geometry/generators/ring_generator.dart",
"src/vector_math_geometry/generators/sphere_generator.dart",
"src/vector_math_geometry/mesh_geometry.dart",
"src/vector_math_lists/scalar_list_view.dart",
"src/vector_math_lists/vector2_list.dart",
"src/vector_math_lists/vector3_list.dart",
"src/vector_math_lists/vector4_list.dart",
"src/vector_math_lists/vector_list.dart",
"src/vector_math_operations/matrix.dart",
"src/vector_math_operations/vector.dart",
"vector_math.dart",
"vector_math_64.dart",
"vector_math_geometry.dart",
"vector_math_lists.dart",
"vector_math_operations.dart",
]
}
| engine/shell/platform/fuchsia/dart/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/dart/BUILD.gn",
"repo_id": "engine",
"token_count": 5772
} | 351 |
// 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 "service_isolate.h"
#include "flutter/fml/logging.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_microtask_queue.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/typed_data/typed_list.h"
#include "builtin_libraries.h"
#include "dart_component_controller.h"
namespace dart_runner {
namespace {
dart_utils::ElfSnapshot elf_snapshot; // AOT snapshot
dart_utils::MappedResource mapped_isolate_snapshot_data; // JIT snapshot
dart_utils::MappedResource
mapped_isolate_snapshot_instructions; // JIT snapshot
tonic::DartLibraryNatives* service_natives = nullptr;
Dart_NativeFunction GetNativeFunction(Dart_Handle name,
int argument_count,
bool* auto_setup_scope) {
FML_CHECK(service_natives);
return service_natives->GetNativeFunction(name, argument_count,
auto_setup_scope);
}
const uint8_t* GetSymbol(Dart_NativeFunction native_function) {
FML_CHECK(service_natives);
return service_natives->GetSymbol(native_function);
}
#define SHUTDOWN_ON_ERROR(handle) \
if (Dart_IsError(handle)) { \
*error = strdup(Dart_GetError(handle)); \
FML_LOG(ERROR) << error; \
Dart_ExitScope(); \
Dart_ShutdownIsolate(); \
return nullptr; \
}
void NotifyServerState(Dart_NativeArguments args) {
// NOP.
}
void Shutdown(Dart_NativeArguments args) {
// NOP.
}
void EmbedderInformationCallback(Dart_EmbedderInformation* info) {
info->version = DART_EMBEDDER_INFORMATION_CURRENT_VERSION;
info->name = "dart_runner";
info->current_rss = -1;
info->max_rss = -1;
zx_info_task_stats_t task_stats;
zx_handle_t process = zx_process_self();
zx_status_t status = zx_object_get_info(
process, ZX_INFO_TASK_STATS, &task_stats, sizeof(task_stats), NULL, NULL);
if (status == ZX_OK) {
info->current_rss =
task_stats.mem_private_bytes + task_stats.mem_shared_bytes;
}
}
} // namespace
Dart_Isolate CreateServiceIsolate(
const char* uri,
Dart_IsolateFlags* flags_unused, // These flags are currently unused
char** error) {
Dart_SetEmbedderInformationCallback(EmbedderInformationCallback);
const uint8_t *vmservice_data = nullptr, *vmservice_instructions = nullptr;
#if defined(AOT_RUNTIME)
// The VM service was compiled as a separate app.
const char* snapshot_path = "/pkg/data/vmservice_snapshot.so";
if (elf_snapshot.Load(nullptr, snapshot_path)) {
vmservice_data = elf_snapshot.IsolateData();
vmservice_instructions = elf_snapshot.IsolateInstrs();
if (vmservice_data == nullptr || vmservice_instructions == nullptr) {
return nullptr;
}
} else {
// The VM service was compiled as a separate app.
const char* snapshot_data_path =
"/pkg/data/vmservice_isolate_snapshot_data.bin";
const char* snapshot_instructions_path =
"/pkg/data/vmservice_isolate_snapshot_instructions.bin";
#else
// The VM service is embedded in the core snapshot.
const char* snapshot_data_path = "/pkg/data/isolate_core_snapshot_data.bin";
const char* snapshot_instructions_path =
"/pkg/data/isolate_core_snapshot_instructions.bin";
#endif
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, snapshot_data_path, mapped_isolate_snapshot_data)) {
*error = strdup("Failed to load snapshot for service isolate");
FML_LOG(ERROR) << *error;
return nullptr;
}
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, snapshot_instructions_path,
mapped_isolate_snapshot_instructions, true /* executable */)) {
*error = strdup("Failed to load snapshot for service isolate");
FML_LOG(ERROR) << *error;
return nullptr;
}
vmservice_data = mapped_isolate_snapshot_data.address();
vmservice_instructions = mapped_isolate_snapshot_instructions.address();
#if defined(AOT_RUNTIME)
}
#endif
Dart_IsolateFlags flags;
Dart_IsolateFlagsInitialize(&flags);
flags.null_safety = true;
auto state = new std::shared_ptr<tonic::DartState>(new tonic::DartState());
Dart_Isolate isolate = Dart_CreateIsolateGroup(
uri, DART_VM_SERVICE_ISOLATE_NAME, vmservice_data, vmservice_instructions,
&flags, state, state, error);
if (!isolate) {
FML_LOG(ERROR) << "Dart_CreateIsolateGroup failed: " << *error;
return nullptr;
}
state->get()->SetIsolate(isolate);
// Setup native entries.
service_natives = new tonic::DartLibraryNatives();
service_natives->Register({
{"VMServiceIO_NotifyServerState", NotifyServerState, 1, true},
{"VMServiceIO_Shutdown", Shutdown, 0, true},
});
Dart_EnterScope();
Dart_Handle library =
Dart_LookupLibrary(Dart_NewStringFromCString("dart:vmservice_io"));
SHUTDOWN_ON_ERROR(library);
Dart_Handle result = Dart_SetRootLibrary(library);
SHUTDOWN_ON_ERROR(result);
result = Dart_SetNativeResolver(library, GetNativeFunction, GetSymbol);
SHUTDOWN_ON_ERROR(result);
// _ip = '127.0.0.1'
result = Dart_SetField(library, Dart_NewStringFromCString("_ip"),
Dart_NewStringFromCString("127.0.0.1"));
SHUTDOWN_ON_ERROR(result);
// _port = 0
result = Dart_SetField(library, Dart_NewStringFromCString("_port"),
Dart_NewInteger(0));
SHUTDOWN_ON_ERROR(result);
// _autoStart = true
result = Dart_SetField(library, Dart_NewStringFromCString("_autoStart"),
Dart_NewBoolean(true));
SHUTDOWN_ON_ERROR(result);
// _originCheckDisabled = false
result =
Dart_SetField(library, Dart_NewStringFromCString("_originCheckDisabled"),
Dart_NewBoolean(false));
SHUTDOWN_ON_ERROR(result);
// _authCodesDisabled = false
result =
Dart_SetField(library, Dart_NewStringFromCString("_authCodesDisabled"),
Dart_NewBoolean(false));
SHUTDOWN_ON_ERROR(result);
InitBuiltinLibrariesForIsolate(std::string(uri), nullptr, fileno(stdout),
fileno(stderr), zx::channel(), true);
// Make runnable.
Dart_ExitScope();
Dart_ExitIsolate();
*error = Dart_IsolateMakeRunnable(isolate);
if (*error != nullptr) {
FML_LOG(ERROR) << *error;
Dart_EnterIsolate(isolate);
Dart_ShutdownIsolate();
return nullptr;
}
return isolate;
} // namespace dart_runner
Dart_Handle GetVMServiceAssetsArchiveCallback() {
dart_utils::MappedResource vm_service_tar;
if (!dart_utils::MappedResource::LoadFromNamespace(
nullptr, "/pkg/data/observatory.tar", vm_service_tar)) {
FML_LOG(ERROR) << "Failed to load Observatory assets";
return nullptr;
}
// TODO(rmacnak): Should we avoid copying the tar? Or does the service
// library not hold onto it anyway?
return tonic::DartConverter<tonic::Uint8List>::ToDart(
reinterpret_cast<const uint8_t*>(vm_service_tar.address()),
vm_service_tar.size());
}
} // namespace dart_runner
| engine/shell/platform/fuchsia/dart_runner/service_isolate.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/service_isolate.cc",
"repo_id": "engine",
"token_count": 3005
} | 352 |
// 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 "component_v2.h"
#include <dlfcn.h>
#include <fuchsia/mem/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/io.h>
#include <lib/fdio/namespace.h>
#include <lib/vfs/cpp/composed_service_dir.h>
#include <lib/vfs/cpp/remote_dir.h>
#include <lib/vfs/cpp/service.h>
#include <sys/stat.h>
#include <zircon/dlfcn.h>
#include <zircon/status.h>
#include <zircon/types.h>
#include <memory>
#include <regex>
#include <sstream>
#include "file_in_namespace_buffer.h"
#include "flutter/fml/command_line.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/platform/fuchsia/task_observers.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/unique_fd.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/shell/common/switches.h"
#include "runtime/dart/utils/files.h"
#include "runtime/dart/utils/handle_exception.h"
#include "runtime/dart/utils/mapped_resource.h"
#include "runtime/dart/utils/tempfs.h"
#include "runtime/dart/utils/vmo.h"
namespace flutter_runner {
namespace {
// "data" and "assets" are arguments that are specific to the Flutter runner.
// They will likely go away if we migrate to the ELF runner.
constexpr char kDataKey[] = "data";
constexpr char kAssetsKey[] = "assets";
// "args" are how the component specifies arguments to the runner.
constexpr char kArgsKey[] = "args";
constexpr char kOldGenHeapSizeKey[] = "old_gen_heap_size";
constexpr char kExposeDirsKey[] = "expose_dirs";
constexpr char kTmpPath[] = "/tmp";
constexpr char kServiceRootPath[] = "/svc";
constexpr char kRunnerConfigPath[] = "/config/data/flutter_runner_config";
std::string DebugLabelForUrl(const std::string& url) {
auto found = url.rfind("/");
if (found == std::string::npos) {
return url;
} else {
return {url, found + 1};
}
}
/// Parses the |args| field from the "program" field into
/// |metadata|.
void ParseArgs(std::vector<std::string>& args, ProgramMetadata* metadata) {
// fml::CommandLine expects the first argument to be the name of the program,
// so we prepend a dummy argument so we can use fml::CommandLine to parse the
// arguments for us.
std::vector<std::string> command_line_args = {""};
command_line_args.insert(command_line_args.end(), args.begin(), args.end());
fml::CommandLine parsed_args = fml::CommandLineFromIterators(
command_line_args.begin(), command_line_args.end());
std::string old_gen_heap_size_option;
if (parsed_args.GetOptionValue(kOldGenHeapSizeKey,
&old_gen_heap_size_option)) {
int64_t specified_old_gen_heap_size = strtol(
old_gen_heap_size_option.c_str(), nullptr /* endptr */, 10 /* base */);
if (specified_old_gen_heap_size != 0) {
metadata->old_gen_heap_size = specified_old_gen_heap_size;
} else {
FML_LOG(ERROR) << "Invalid old_gen_heap_size: "
<< old_gen_heap_size_option;
}
}
std::string expose_dirs_option;
if (parsed_args.GetOptionValue(kExposeDirsKey, &expose_dirs_option)) {
// Parse the comma delimited string
std::vector<std::string> expose_dirs;
std::stringstream s(expose_dirs_option);
while (s.good()) {
std::string dir;
getline(s, dir, ','); // get first string delimited by comma
metadata->expose_dirs.push_back(dir);
}
}
}
} // namespace
ProgramMetadata ComponentV2::ParseProgramMetadata(
const fuchsia::data::Dictionary& program_metadata) {
ProgramMetadata result;
for (const auto& entry : program_metadata.entries()) {
if (entry.key.compare(kDataKey) == 0 && entry.value != nullptr) {
result.data_path = "pkg/" + entry.value->str();
} else if (entry.key.compare(kAssetsKey) == 0 && entry.value != nullptr) {
result.assets_path = "pkg/" + entry.value->str();
} else if (entry.key.compare(kArgsKey) == 0 && entry.value != nullptr) {
ParseArgs(entry.value->str_vec(), &result);
}
}
// assets_path defaults to the same as data_path if omitted.
if (result.assets_path.empty()) {
result.assets_path = result.data_path;
}
return result;
}
ActiveComponentV2 ComponentV2::Create(
TerminationCallback termination_callback,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller) {
auto thread = std::make_unique<fml::Thread>();
std::unique_ptr<ComponentV2> component;
fml::AutoResetWaitableEvent latch;
thread->GetTaskRunner()->PostTask([&]() mutable {
component.reset(
new ComponentV2(std::move(termination_callback), std::move(start_info),
runner_incoming_services, std::move(controller)));
latch.Signal();
});
latch.Wait();
return {.platform_thread = std::move(thread),
.component = std::move(component)};
}
ComponentV2::ComponentV2(
TerminationCallback termination_callback,
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
component_controller_request)
: termination_callback_(std::move(termination_callback)),
debug_label_(DebugLabelForUrl(start_info.resolved_url())),
component_controller_(this),
outgoing_dir_(new vfs::PseudoDir()),
runtime_dir_(new vfs::PseudoDir()),
runner_incoming_services_(runner_incoming_services),
weak_factory_(this) {
component_controller_.set_error_handler([this](zx_status_t status) {
FML_LOG(ERROR) << "ComponentController binding error for component("
<< debug_label_ << "): " << zx_status_get_string(status);
KillWithEpitaph(
zx_status_t(fuchsia::component::Error::INSTANCE_CANNOT_START));
});
FML_DCHECK(fdio_ns_.is_valid());
// TODO(fxb/88391): Dart launch arguments.
FML_LOG(WARNING) << "program() arguments are currently ignored (fxb/88391).";
ProgramMetadata metadata = ParseProgramMetadata(start_info.program());
if (metadata.data_path.empty()) {
FML_LOG(ERROR) << "Could not find a /pkg/data directory for "
<< start_info.resolved_url();
return;
}
dart_utils::BindTemp(fdio_ns_.get());
// ComponentStartInfo::ns (optional)
if (start_info.has_ns()) {
for (auto& entry : *start_info.mutable_ns()) {
// /tmp/ is mapped separately to to a process-local virtual filesystem,
// so we ignore it here.
const auto& path = entry.path();
if (path == kTmpPath) {
continue;
}
// We should never receive namespace entries without a directory, but we
// check it anyways to avoid crashing if we do.
if (!entry.has_directory()) {
FML_LOG(ERROR) << "Namespace entry at path (" << path
<< ") has no directory.";
continue;
}
zx::channel dir;
if (path == kServiceRootPath) {
svc_ = std::make_unique<sys::ServiceDirectory>(
std::move(*entry.mutable_directory()));
dir = svc_->CloneChannel().TakeChannel();
} else {
dir = entry.mutable_directory()->TakeChannel();
}
zx_handle_t dir_handle = dir.release();
if (fdio_ns_bind(fdio_ns_.get(), path.data(), dir_handle) != ZX_OK) {
FML_LOG(ERROR) << "Could not bind path to namespace: " << path;
zx_handle_close(dir_handle);
}
}
}
// Open the data and assets directories inside our namespace.
{
fml::UniqueFD ns_fd(fdio_ns_opendir(fdio_ns_.get()));
FML_DCHECK(ns_fd.is_valid());
constexpr mode_t mode = O_RDONLY | O_DIRECTORY;
component_assets_directory_.reset(
openat(ns_fd.get(), metadata.assets_path.c_str(), mode));
FML_DCHECK(component_assets_directory_.is_valid());
component_data_directory_.reset(
openat(ns_fd.get(), metadata.data_path.c_str(), mode));
FML_DCHECK(component_data_directory_.is_valid());
}
// ComponentStartInfo::runtime_dir (optional).
if (start_info.has_runtime_dir()) {
runtime_dir_->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
fuchsia::io::OpenFlags::RIGHT_WRITABLE |
fuchsia::io::OpenFlags::DIRECTORY,
start_info.mutable_runtime_dir()->TakeChannel());
}
// ComponentStartInfo::outgoing_dir (optional).
if (start_info.has_outgoing_dir()) {
outgoing_dir_->Serve(fuchsia::io::OpenFlags::RIGHT_READABLE |
fuchsia::io::OpenFlags::RIGHT_WRITABLE |
fuchsia::io::OpenFlags::DIRECTORY,
start_info.mutable_outgoing_dir()->TakeChannel());
}
directory_request_ = directory_ptr_.NewRequest();
fuchsia::io::DirectoryHandle flutter_public_dir;
// TODO(anmittal): when fixing enumeration using new c++ vfs, make sure that
// flutter_public_dir is only accessed once we receive OnOpen Event.
// That will prevent FL-175 for public directory
auto request = flutter_public_dir.NewRequest().TakeChannel();
fdio_service_connect_at(directory_ptr_.channel().get(), "svc",
request.release());
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
auto composed_service_dir = std::make_unique<vfs::ComposedServiceDir>();
composed_service_dir->set_fallback(std::move(flutter_public_dir));
#pragma clang diagnostic pop
// Clone and check if client is servicing the directory.
directory_ptr_->Clone(fuchsia::io::OpenFlags::DESCRIBE |
fuchsia::io::OpenFlags::CLONE_SAME_RIGHTS,
cloned_directory_ptr_.NewRequest());
// Collect our standard set of directories along with directories that are
// included in the cml file to expose.
std::vector<std::string> other_dirs = {"debug", "ctrl"};
for (auto dir : metadata.expose_dirs) {
other_dirs.push_back(dir);
}
cloned_directory_ptr_.events().OnOpen = [this, other_dirs](zx_status_t status,
auto unused) {
cloned_directory_ptr_.Unbind();
if (status != ZX_OK) {
FML_LOG(ERROR) << "could not bind out directory for flutter component("
<< debug_label_ << "): " << zx_status_get_string(status);
return;
}
// add other directories as RemoteDirs.
for (auto& dir_str : other_dirs) {
fuchsia::io::DirectoryHandle dir;
auto request = dir.NewRequest().TakeChannel();
auto status = fdio_open_at(
directory_ptr_.channel().get(), dir_str.c_str(),
static_cast<uint32_t>(fuchsia::io::OpenFlags::DIRECTORY |
fuchsia::io::OpenFlags::RIGHT_READABLE),
request.release());
if (status == ZX_OK) {
outgoing_dir_->AddEntry(
dir_str.c_str(),
std::make_unique<vfs::RemoteDir>(dir.TakeChannel()));
} else {
FML_LOG(ERROR) << "could not add out directory entry(" << dir_str
<< ") for flutter component(" << debug_label_
<< "): " << zx_status_get_string(status);
}
}
};
cloned_directory_ptr_.set_error_handler(
[this](zx_status_t status) { cloned_directory_ptr_.Unbind(); });
// TODO(fxb/89162): Close handles from ComponentStartInfo::numbered_handles
// since we're not using them. See documentation from ComponentController:
// https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.component.runner/component_runner.fidl;l=97;drc=e3b39f2b57e720770773b857feca4f770ee0619e
// TODO(fxb/89162): There's an OnPublishDiagnostics event we may want to
// fire for diagnostics. See documentation from ComponentController:
// https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.component.runner/component_runner.fidl;l=181;drc=e3b39f2b57e720770773b857feca4f770ee0619e
// All launch arguments have been read. Perform service binding and
// final settings configuration. The next call will be to create a view
// for this component.
composed_service_dir->AddService(
fuchsia::ui::app::ViewProvider::Name_,
std::make_unique<vfs::Service>(
[this](zx::channel channel, async_dispatcher_t* dispatcher) {
shells_bindings_.AddBinding(
this, fidl::InterfaceRequest<fuchsia::ui::app::ViewProvider>(
std::move(channel)));
}));
outgoing_dir_->AddEntry("svc", std::move(composed_service_dir));
// Setup the component controller binding.
if (component_controller_request) {
component_controller_.Bind(std::move(component_controller_request));
}
// Load and use runner-specific configuration, if it exists.
std::string json_string;
if (dart_utils::ReadFileToString(kRunnerConfigPath, &json_string)) {
product_config_ = FlutterRunnerProductConfiguration(json_string);
FML_LOG(INFO) << "Successfully loaded runner configuration: "
<< json_string;
} else {
FML_LOG(WARNING) << "Failed to load runner configuration from "
<< kRunnerConfigPath << "; using default config values.";
}
// Load VM and component bytecode.
// For AOT, compare with flutter_aot_app in flutter_app.gni.
// For JIT, compare flutter_jit_runner in BUILD.gn.
if (flutter::DartVM::IsRunningPrecompiledCode()) {
std::shared_ptr<dart_utils::ElfSnapshot> snapshot =
std::make_shared<dart_utils::ElfSnapshot>();
if (snapshot->Load(component_data_directory_.get(),
"app_aot_snapshot.so")) {
const uint8_t* isolate_data = snapshot->IsolateData();
const uint8_t* isolate_instructions = snapshot->IsolateInstrs();
const uint8_t* vm_data = snapshot->VmData();
const uint8_t* vm_instructions = snapshot->VmInstrs();
if (isolate_data == nullptr || isolate_instructions == nullptr ||
vm_data == nullptr || vm_instructions == nullptr) {
FML_LOG(FATAL) << "ELF snapshot missing AOT symbols.";
return;
}
auto hold_snapshot = [snapshot](const uint8_t* _, size_t __) {};
settings_.vm_snapshot_data = [hold_snapshot, vm_data]() {
return std::make_unique<fml::NonOwnedMapping>(vm_data, 0, hold_snapshot,
true /* dontneed_safe */);
};
settings_.vm_snapshot_instr = [hold_snapshot, vm_instructions]() {
return std::make_unique<fml::NonOwnedMapping>(
vm_instructions, 0, hold_snapshot, true /* dontneed_safe */);
};
settings_.isolate_snapshot_data = [hold_snapshot, isolate_data]() {
return std::make_unique<fml::NonOwnedMapping>(
isolate_data, 0, hold_snapshot, true /* dontneed_safe */);
};
settings_.isolate_snapshot_instr = [hold_snapshot,
isolate_instructions]() {
return std::make_unique<fml::NonOwnedMapping>(
isolate_instructions, 0, hold_snapshot, true /* dontneed_safe */);
};
isolate_snapshot_ = fml::MakeRefCounted<flutter::DartSnapshot>(
std::make_shared<fml::NonOwnedMapping>(isolate_data, 0, hold_snapshot,
true /* dontneed_safe */),
std::make_shared<fml::NonOwnedMapping>(isolate_instructions, 0,
hold_snapshot,
true /* dontneed_safe */));
} else {
const int namespace_fd = component_data_directory_.get();
settings_.vm_snapshot_data = [namespace_fd]() {
return LoadFile(namespace_fd, "vm_snapshot_data.bin",
false /* executable */);
};
settings_.vm_snapshot_instr = [namespace_fd]() {
return LoadFile(namespace_fd, "vm_snapshot_instructions.bin",
true /* executable */);
};
settings_.isolate_snapshot_data = [namespace_fd]() {
return LoadFile(namespace_fd, "isolate_snapshot_data.bin",
false /* executable */);
};
settings_.isolate_snapshot_instr = [namespace_fd]() {
return LoadFile(namespace_fd, "isolate_snapshot_instructions.bin",
true /* executable */);
};
}
} else {
settings_.vm_snapshot_data = []() {
return MakeFileMapping("/pkg/data/vm_snapshot_data.bin",
false /* executable */);
};
settings_.isolate_snapshot_data = []() {
return MakeFileMapping("/pkg/data/isolate_core_snapshot_data.bin",
false /* executable */);
};
}
#if defined(DART_PRODUCT)
settings_.enable_vm_service = false;
#else
settings_.enable_vm_service = true;
// TODO(cbracken): pass this in as a param to allow 0.0.0.0, ::1, etc.
settings_.vm_service_host = "127.0.0.1";
#endif
// Controls whether category "skia" trace events are enabled.
settings_.trace_skia = true;
settings_.verbose_logging = true;
settings_.advisory_script_uri = debug_label_;
settings_.advisory_script_entrypoint = debug_label_;
settings_.icu_data_path = "";
settings_.assets_dir = component_assets_directory_.get();
// Compare flutter_jit_app in flutter_app.gni.
settings_.application_kernel_list_asset = "app.dilplist";
settings_.log_tag = debug_label_ + std::string{"(flutter)"};
if (metadata.old_gen_heap_size.has_value()) {
settings_.old_gen_heap_size = *metadata.old_gen_heap_size;
}
// No asserts in debug or release product.
// No asserts in release with flutter_profile=true (non-product)
// Yes asserts in non-product debug.
#if !defined(DART_PRODUCT) && (!defined(FLUTTER_PROFILE) || !defined(NDEBUG))
// Debug mode
settings_.disable_dart_asserts = false;
#else
// Release mode
settings_.disable_dart_asserts = true;
#endif
// Do not leak the VM; allow it to shut down normally when the last shell
// terminates.
settings_.leak_vm = false;
settings_.task_observer_add =
std::bind(&fml::CurrentMessageLoopAddAfterTaskObserver,
std::placeholders::_1, std::placeholders::_2);
settings_.task_observer_remove = std::bind(
&fml::CurrentMessageLoopRemoveAfterTaskObserver, std::placeholders::_1);
settings_.log_message_callback = [](const std::string& tag,
const std::string& message) {
if (!tag.empty()) {
std::cout << tag << ": ";
}
std::cout << message << std::endl;
};
settings_.dart_flags = {};
// Don't collect CPU samples from Dart VM C++ code.
settings_.dart_flags.push_back("--no_profile_vm");
// Scale back CPU profiler sampling period on ARM64 to avoid overloading
// the tracing engine.
#if defined(__aarch64__)
settings_.dart_flags.push_back("--profile_period=10000");
#endif // defined(__aarch64__)
auto platform_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
const std::string component_url = start_info.resolved_url();
settings_.unhandled_exception_callback = [weak = weak_factory_.GetWeakPtr(),
platform_task_runner,
runner_incoming_services,
component_url](
const std::string& error,
const std::string& stack_trace) {
if (weak) {
// TODO(cbracken): unsafe. The above check and the PostTask below are
// happening on the UI thread. If the Component dtor and thread
// termination happen (on the platform thread) between the previous
// line and the next line, a crash will occur since we'll be posting
// to a dead thread. See Runner::OnComponentV2Terminate() in
// runner.cc.
platform_task_runner->PostTask([weak, runner_incoming_services,
component_url, error, stack_trace]() {
if (weak) {
dart_utils::HandleException(runner_incoming_services, component_url,
error, stack_trace);
} else {
FML_LOG(WARNING)
<< "Exception was thrown which was not caught in Flutter app: "
<< error;
}
});
} else {
FML_LOG(WARNING)
<< "Exception was thrown which was not caught in Flutter app: "
<< error;
}
// Ideally we would return whether HandleException returned ZX_OK, but
// short of knowing if the exception was correctly handled, we return
// false to have the error and stack trace printed in the logs.
return false;
};
}
ComponentV2::~ComponentV2() = default;
const std::string& ComponentV2::GetDebugLabel() const {
return debug_label_;
}
void ComponentV2::Kill() {
FML_VLOG(1) << "received Kill event";
// From the documentation for ComponentController, ZX_OK should be sent when
// the ComponentController receives a termination request. However, if the
// component exited with a non-zero return code, we indicate this by sending
// an INTERNAL epitaph instead.
//
// TODO(fxb/86666): Communicate return code from the ComponentController once
// v2 has support.
auto [got_return_code, return_code] = last_return_code_;
if (got_return_code && return_code == 0) {
KillWithEpitaph(ZX_OK);
} else {
if (got_return_code) {
FML_LOG(ERROR) << "Component exited with non-zero return code: "
<< return_code;
} else {
FML_LOG(ERROR) << "Failed to get return code for component";
}
KillWithEpitaph(zx_status_t(fuchsia::component::Error::INTERNAL));
}
// WARNING: Don't do anything past this point as this instance may have been
// collected.
}
void ComponentV2::KillWithEpitaph(zx_status_t epitaph_status) {
component_controller_.set_error_handler(nullptr);
component_controller_.Close(epitaph_status);
termination_callback_(this);
// WARNING: Don't do anything past this point as this instance may have been
// collected.
}
void ComponentV2::Stop() {
FML_VLOG(1) << "received Stop event";
// TODO(fxb/89162): Any other cleanup logic we should do that's appropriate
// for Stop but not for Kill?
KillWithEpitaph(ZX_OK);
}
void ComponentV2::OnEngineTerminate(const Engine* shell_holder) {
auto found = std::find_if(shell_holders_.begin(), shell_holders_.end(),
[shell_holder](const auto& holder) {
return holder.get() == shell_holder;
});
if (found == shell_holders_.end()) {
// This indicates a deeper issue with memory management and should never
// happen.
FML_LOG(ERROR) << "Tried to terminate an unregistered shell holder.";
FML_DCHECK(false);
return;
}
// We may launch multiple shells in this component. However, we will
// terminate when the last shell goes away. The error code returned to the
// component controller will be the last isolate that had an error.
auto return_code = shell_holder->GetEngineReturnCode();
if (return_code.has_value()) {
last_return_code_ = {true, return_code.value()};
} else {
FML_LOG(ERROR) << "Failed to get return code from terminated shell holder.";
}
shell_holders_.erase(found);
if (shell_holders_.empty()) {
FML_VLOG(1) << "Killing component because all shell holders have been "
"terminated.";
Kill();
// WARNING: Don't do anything past this point because the delegate may have
// collected this instance via the termination callback.
}
}
void ComponentV2::CreateView2(fuchsia::ui::app::CreateView2Args view_args) {
if (!svc_) {
FML_LOG(ERROR)
<< "Component incoming services was invalid when attempting to "
"create a shell for a view provider request.";
return;
}
fuchsia::ui::views::ViewRefControl view_ref_control;
fuchsia::ui::views::ViewRef view_ref;
auto status = zx::eventpair::create(
/*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
ZX_ASSERT(status == ZX_OK);
view_ref_control.reference.replace(
ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
&view_ref_control.reference);
view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
auto view_ref_pair =
std::make_pair(std::move(view_ref_control), std::move(view_ref));
shell_holders_.emplace(std::make_unique<Engine>(
*this, // delegate
debug_label_, // thread label
svc_, // Component incoming services
runner_incoming_services_, // Runner incoming services
settings_, // settings
std::move(
*view_args.mutable_view_creation_token()), // view creation token
std::move(view_ref_pair), // view ref pair
std::move(fdio_ns_), // FDIO namespace
std::move(directory_request_), // outgoing request
product_config_, // product configuration
std::vector<std::string>() // dart entrypoint args
));
}
#if !defined(DART_PRODUCT)
void ComponentV2::WriteProfileToTrace() const {
for (const auto& engine : shell_holders_) {
engine->WriteProfileToTrace();
}
}
#endif // !defined(DART_PRODUCT)
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/component_v2.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/component_v2.cc",
"repo_id": "engine",
"token_count": 10444
} | 353 |
// 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 <fuchsia/ui/views/cpp/fidl.h>
#include <gtest/gtest.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/fidl/cpp/binding_set.h>
#include <lib/zx/eventpair.h>
#include "focus_delegate.h"
#include "tests/fakes/focuser.h"
#include "tests/fakes/platform_message.h"
#include "tests/fakes/view_ref_focused.h"
#include "third_party/rapidjson/include/rapidjson/document.h"
rapidjson::Value ParsePlatformMessage(std::string json) {
rapidjson::Document document;
document.Parse(json);
if (document.HasParseError() || !document.IsObject()) {
FML_LOG(ERROR) << "Could not parse document";
return rapidjson::Value();
}
return document.GetObject();
}
namespace flutter_runner::testing {
class FocusDelegateTest : public ::testing::Test {
protected:
FocusDelegateTest() : loop_(&kAsyncLoopConfigAttachToCurrentThread) {}
void RunLoopUntilIdle() { loop_.RunUntilIdle(); }
void SetUp() override {
vrf_ = std::make_unique<FakeViewRefFocused>();
focuser_ = std::make_unique<FakeFocuser>();
focus_delegate_ = std::make_unique<FocusDelegate>(
vrf_bindings.AddBinding(vrf_.get()),
focuser_bindings.AddBinding(focuser_.get()));
}
void TearDown() override {
vrf_bindings.CloseAll();
focuser_bindings.CloseAll();
loop_.Quit();
loop_.ResetQuit();
}
std::unique_ptr<FakeViewRefFocused> vrf_;
std::unique_ptr<FakeFocuser> focuser_;
std::unique_ptr<FocusDelegate> focus_delegate_;
private:
async::Loop loop_;
fidl::BindingSet<ViewRefFocused> vrf_bindings;
fidl::BindingSet<Focuser> focuser_bindings;
FML_DISALLOW_COPY_AND_ASSIGN(FocusDelegateTest);
};
// Tests that WatchLoop() should callback and complete PlatformMessageResponses
// correctly, given a series of vrf invocations.
TEST_F(FocusDelegateTest, WatchCallbackSeries) {
std::vector<bool> vrf_states{false, true, true, false,
true, false, true, true};
std::size_t vrf_index = 0;
std::size_t callback_index = 0;
focus_delegate_->WatchLoop([&](bool focus_state) {
// Make sure the focus state that FocusDelegate gives us is consistent with
// what was fired from the vrf.
EXPECT_EQ(vrf_states[callback_index], focus_state);
// View.focus.getCurrent should complete with the current (up to date) focus
// state.
auto response = FakePlatformMessageResponse::Create();
EXPECT_TRUE(focus_delegate_->HandlePlatformMessage(
ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"),
response));
response->ExpectCompleted(focus_state ? "[true]" : "[false]");
// Ensure this callback always happens in lockstep with
// vrf_->ScheduleCallback.
EXPECT_EQ(vrf_index, callback_index++);
});
// Subsequent WatchLoop calls should not be respected.
focus_delegate_->WatchLoop([](bool _) {
ADD_FAILURE() << "Subsequent WatchLoops should not be respected!";
});
do {
// Ensure the next focus state is handled correctly.
auto response1 = FakePlatformMessageResponse::Create();
EXPECT_TRUE(focus_delegate_->HandlePlatformMessage(
ParsePlatformMessage("{\"method\":\"View.focus.getNext\"}"),
response1));
// Since there's already an outstanding PlatformMessageResponse, this one
// should be completed null.
auto response2 = FakePlatformMessageResponse::Create();
EXPECT_TRUE(focus_delegate_->HandlePlatformMessage(
ParsePlatformMessage("{\"method\":\"View.focus.getNext\"}"),
response2));
response2->ExpectCompleted("[null]");
// Post watch events and trigger the next vrf event.
RunLoopUntilIdle();
vrf_->ScheduleCallback(vrf_states[vrf_index]);
RunLoopUntilIdle();
// Next focus state should be completed by now.
response1->ExpectCompleted(vrf_states[vrf_index] ? "[true]" : "[false]");
// Check View.focus.getCurrent again, and increment vrf_index since we move
// on to the next focus state.
auto response3 = FakePlatformMessageResponse::Create();
EXPECT_TRUE(focus_delegate_->HandlePlatformMessage(
ParsePlatformMessage("{\"method\":\"View.focus.getCurrent\"}"),
response3));
response3->ExpectCompleted(vrf_states[vrf_index++] ? "[true]" : "[false]");
// vrf_->times_watched should always be 1 more than the amount of vrf events
// emitted.
EXPECT_EQ(vrf_index + 1, vrf_->times_watched);
} while (vrf_index < vrf_states.size());
}
// Tests that HandlePlatformMessage() completes a "View.focus.request" response
// with a non-error status code.
TEST_F(FocusDelegateTest, RequestFocusTest) {
// This "Mock" ViewRef serves as the target for the RequestFocus operation.
fuchsia::ui::views::ViewRefControl view_ref_control;
fuchsia::ui::views::ViewRef view_ref;
auto status = zx::eventpair::create(
/*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
ZX_ASSERT(status == ZX_OK);
view_ref_control.reference.replace(
ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
&view_ref_control.reference);
view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// Create the platform message request.
std::ostringstream message;
message << "{" << " \"method\":\"View.focus.request\","
<< " \"args\": {"
<< " \"viewRef\":" << view_ref.reference.get() << " }"
<< "}";
// Dispatch the plaform message request with an expected completion response.
auto response = FakePlatformMessageResponse::Create();
EXPECT_TRUE(focus_delegate_->HandlePlatformMessage(
ParsePlatformMessage(message.str()), response));
RunLoopUntilIdle();
response->ExpectCompleted("[0]");
EXPECT_TRUE(focuser_->request_focus_called());
}
// Tests that HandlePlatformMessage() completes a "View.focus.request" response
// with a Error::DENIED status code.
TEST_F(FocusDelegateTest, RequestFocusFailTest) {
// This "Mock" ViewRef serves as the target for the RequestFocus operation.
fuchsia::ui::views::ViewRefControl view_ref_control;
fuchsia::ui::views::ViewRef view_ref;
auto status = zx::eventpair::create(
/*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
ZX_ASSERT(status == ZX_OK);
view_ref_control.reference.replace(
ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
&view_ref_control.reference);
view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
// We're testing the focus failure case.
focuser_->fail_request_focus();
// Create the platform message request.
std::ostringstream message;
message << "{" << " \"method\":\"View.focus.request\","
<< " \"args\": {"
<< " \"viewRef\":" << view_ref.reference.get() << " }"
<< "}";
// Dispatch the plaform message request with an expected completion response.
auto response = FakePlatformMessageResponse::Create();
EXPECT_TRUE(focus_delegate_->HandlePlatformMessage(
ParsePlatformMessage(message.str()), response));
RunLoopUntilIdle();
response->ExpectCompleted(
"[" +
std::to_string(
static_cast<std::underlying_type_t<fuchsia::ui::views::Error>>(
fuchsia::ui::views::Error::DENIED)) +
"]");
EXPECT_TRUE(focuser_->request_focus_called());
}
} // namespace flutter_runner::testing
| engine/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/focus_delegate_unittests.cc",
"repo_id": "engine",
"token_count": 2684
} | 354 |
// 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 <lib/async-loop/cpp/loop.h>
#include <lib/inspect/component/cpp/component.h>
#include <lib/trace-provider/provider.h>
#include <lib/trace/event.h>
#include <cstdlib>
#include "fml/message_loop.h"
#include "fml/platform/fuchsia/log_interest_listener.h"
#include "fml/platform/fuchsia/log_state.h"
#include "lib/async/default.h"
#include "logging.h"
#include "platform/utils.h"
#include "runner.h"
#include "runtime/dart/utils/build_info.h"
#include "runtime/dart/utils/root_inspect_node.h"
#include "runtime/dart/utils/tempfs.h"
int main(int argc, char const* argv[]) {
fml::MessageLoop::EnsureInitializedForCurrentThread();
// Setup logging.
fml::LogState::Default().SetTags({LOG_TAG});
fml::LogInterestListener listener(fml::LogState::Default().TakeClientEnd(),
async_get_default_dispatcher());
listener.AsyncWaitForInterestChanged();
// Create our component context which is served later.
auto context = sys::ComponentContext::Create();
dart_utils::RootInspectNode::Initialize(context.get());
auto build_info = dart_utils::RootInspectNode::CreateRootChild("build_info");
dart_utils::BuildInfo::Dump(build_info);
// We inject the 'vm' node into the dart vm so that it can add any inspect
// data that it needs to the inspect tree.
dart::SetDartVmNode(std::make_unique<inspect::Node>(
dart_utils::RootInspectNode::CreateRootChild("vm")));
std::unique_ptr<trace::TraceProviderWithFdio> provider;
{
bool already_started;
// Use CreateSynchronously to prevent loss of early events.
trace::TraceProviderWithFdio::CreateSynchronously(
async_get_default_dispatcher(), "flutter_runner", &provider,
&already_started);
}
fml::MessageLoop& loop = fml::MessageLoop::GetCurrent();
flutter_runner::Runner runner(loop.GetTaskRunner(), context.get());
// Wait to serve until we have finished all of our setup.
context->outgoing()->ServeFromStartupInfo();
loop.Run();
return EXIT_SUCCESS;
}
| engine/shell/platform/fuchsia/flutter/main.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/main.cc",
"repo_id": "engine",
"token_count": 749
} | 355 |
// 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 "flutter/shell/platform/fuchsia/flutter/rtree.h"
#include <list>
#include "flutter/display_list/geometry/dl_region.h"
#include "flutter/fml/logging.h"
#include "third_party/skia/include/core/SkBBHFactory.h"
#include "third_party/skia/include/core/SkRect.h"
namespace flutter {
RTree::RTree() : bbh_{SkRTreeFactory{}()}, all_ops_count_(0) {}
void RTree::insert(const SkRect boundsArray[],
const SkBBoxHierarchy::Metadata metadata[],
int N) {
FML_DCHECK(0 == all_ops_count_);
bbh_->insert(boundsArray, metadata, N);
for (int i = 0; i < N; i++) {
if (metadata != nullptr && metadata[i].isDraw) {
draw_op_[i] = boundsArray[i];
}
}
all_ops_count_ = N;
}
void RTree::insert(const SkRect boundsArray[], int N) {
insert(boundsArray, nullptr, N);
}
void RTree::search(const SkRect& query, std::vector<int>* results) const {
bbh_->search(query, results);
}
std::list<SkRect> RTree::searchNonOverlappingDrawnRects(
const SkRect& query) const {
// Get the indexes for the operations that intersect with the query rect.
std::vector<int> intermediary_results;
search(query, &intermediary_results);
std::vector<SkIRect> rects;
for (int index : intermediary_results) {
auto draw_op = draw_op_.find(index);
// Ignore records that don't draw anything.
if (draw_op == draw_op_.end()) {
continue;
}
SkIRect current_record_rect;
draw_op->second.roundOut(¤t_record_rect);
rects.push_back(current_record_rect);
}
DlRegion region(rects);
auto non_overlapping_rects = region.getRects(true);
std::list<SkRect> final_results;
for (const auto& rect : non_overlapping_rects) {
final_results.push_back(SkRect::Make(rect));
}
return final_results;
}
size_t RTree::bytesUsed() const {
return bbh_->bytesUsed();
}
RTreeFactory::RTreeFactory() {
r_tree_ = sk_make_sp<RTree>();
}
sk_sp<RTree> RTreeFactory::getInstance() {
return r_tree_;
}
sk_sp<SkBBoxHierarchy> RTreeFactory::operator()() const {
return r_tree_;
}
} // namespace flutter
| engine/shell/platform/fuchsia/flutter/rtree.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/rtree.cc",
"repo_id": "engine",
"token_count": 862
} | 356 |
// Copyright 2020 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 "flutter/shell/platform/fuchsia/flutter/engine.h"
#include "flutter/shell/common/thread_host.h"
#include "gtest/gtest.h"
using namespace flutter;
namespace flutter_runner {
namespace testing {
namespace {
std::string GetCurrentTestName() {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
} // namespace
TEST(EngineTest, ThreadNames) {
std::string prefix = GetCurrentTestName();
flutter::ThreadHost engine_thread_host = Engine::CreateThreadHost(prefix);
char thread_name[ZX_MAX_NAME_LEN];
zx::thread::self()->get_property(ZX_PROP_NAME, thread_name,
sizeof(thread_name));
EXPECT_EQ(std::string(thread_name), prefix + std::string(".platform"));
EXPECT_EQ(engine_thread_host.platform_thread, nullptr);
engine_thread_host.raster_thread->GetTaskRunner()->PostTask([&prefix]() {
char thread_name[ZX_MAX_NAME_LEN];
zx::thread::self()->get_property(ZX_PROP_NAME, thread_name,
sizeof(thread_name));
EXPECT_EQ(std::string(thread_name), prefix + std::string(".raster"));
});
engine_thread_host.raster_thread->Join();
engine_thread_host.ui_thread->GetTaskRunner()->PostTask([&prefix]() {
char thread_name[ZX_MAX_NAME_LEN];
zx::thread::self()->get_property(ZX_PROP_NAME, thread_name,
sizeof(thread_name));
EXPECT_EQ(std::string(thread_name), prefix + std::string(".ui"));
});
engine_thread_host.ui_thread->Join();
engine_thread_host.io_thread->GetTaskRunner()->PostTask([&prefix]() {
char thread_name[ZX_MAX_NAME_LEN];
zx::thread::self()->get_property(ZX_PROP_NAME, thread_name,
sizeof(thread_name));
EXPECT_EQ(std::string(thread_name), prefix + std::string(".io"));
});
engine_thread_host.io_thread->Join();
}
} // namespace testing
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/tests/engine_unittests.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/engine_unittests.cc",
"repo_id": "engine",
"token_count": 830
} | 357 |
// 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 <gtest/gtest.h>
#include "flutter/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.h"
using namespace flutter_runner;
namespace flutter_runner_test {
class FlutterRunnerProductConfigurationTest : public testing::Test {};
TEST_F(FlutterRunnerProductConfigurationTest, InvalidJsonString) {
const std::string json_string = "{ \"invalid json string\" }}} ";
const uint64_t expected_intercept_all_input = false;
FlutterRunnerProductConfiguration product_config =
FlutterRunnerProductConfiguration(json_string);
EXPECT_EQ(expected_intercept_all_input,
product_config.get_intercept_all_input());
}
TEST_F(FlutterRunnerProductConfigurationTest, EmptyJsonString) {
const std::string json_string = "";
const uint64_t expected_intercept_all_input = false;
FlutterRunnerProductConfiguration product_config =
FlutterRunnerProductConfiguration(json_string);
EXPECT_EQ(expected_intercept_all_input,
product_config.get_intercept_all_input());
}
TEST_F(FlutterRunnerProductConfigurationTest, ValidInterceptAllInput) {
const std::string json_string = "{ \"intercept_all_input\" : true } ";
const uint64_t expected_intercept_all_input = true;
FlutterRunnerProductConfiguration product_config =
FlutterRunnerProductConfiguration(json_string);
EXPECT_EQ(expected_intercept_all_input,
product_config.get_intercept_all_input());
}
TEST_F(FlutterRunnerProductConfigurationTest, MissingInterceptAllInput) {
const std::string json_string = "{ \"intercept_all_input\" : } ";
const uint64_t expected_intercept_all_input = false;
FlutterRunnerProductConfiguration product_config =
FlutterRunnerProductConfiguration(json_string);
EXPECT_EQ(expected_intercept_all_input,
product_config.get_intercept_all_input());
}
} // namespace flutter_runner_test
| engine/shell/platform/fuchsia/flutter/tests/flutter_runner_product_configuration_unittests.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/flutter_runner_product_configuration_unittests.cc",
"repo_id": "engine",
"token_count": 651
} | 358 |
// 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: [
"sys/testing/gtest_runner.shard.cml",
"sys/component/realm_builder_absolute.shard.cml",
// This test needs both the vulkan facet and the hermetic-tier-2 facet,
// so we are forced to make it a system test.
"sys/testing/system-test.shard.cml",
],
program: {
binary: "bin/app",
},
use: [
{
protocol: [
"fuchsia.ui.test.input.MouseInputListener",
]
}
],
offer: [
{
// Offer capabilities needed by components in this test realm.
// Keep it minimal, describe only what's actually needed.
protocol: [
"fuchsia.inspect.InspectSink",
"fuchsia.kernel.RootJobForInspect",
"fuchsia.kernel.Stats",
"fuchsia.logger.LogSink",
"fuchsia.scheduler.ProfileProvider",
"fuchsia.sysmem.Allocator",
"fuchsia.tracing.provider.Registry",
"fuchsia.ui.input.ImeService",
"fuchsia.vulkan.loader.Loader",
"fuchsia.ui.composition.Allocator",
"fuchsia.ui.composition.Flatland",
"fuchsia.ui.test.input.MouseInputListener",
"fuchsia.intl.PropertyProvider",
"fuchsia.posix.socket.Provider",
"fuchsia.ui.pointerinjector.Registry",
],
from: "parent",
to: "#realm_builder",
},
{
directory: "pkg",
subdir: "config",
as: "config-data",
from: "framework",
to: "#realm_builder",
},
// See common.shard.cml.
{
directory: "tzdata-icu",
from: "framework",
to: "#realm_builder",
},
],
// TODO(https://fxbug.dev/114584): Figure out how to bring these in as deps (if possible oot).
facets: {
"fuchsia.test": {
"deprecated-allowed-packages": [
"child-view",
"cursor",
"flatland-scene-manager-test-ui-stack",
"mouse-input-view",
"oot_flutter_aot_runner",
"oot_flutter_jit_runner",
"oot_flutter_jit_product_runner",
"oot_flutter_aot_product_runner",
"test_manager",
"test-ui-stack",
],
},
},
}
| engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/meta/mouse-input-test.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/meta/mouse-input-test.cml",
"repo_id": "engine",
"token_count": 1423
} | 359 |
// 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.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:io';
import 'dart:ui';
import 'dart:zircon';
import 'package:args/args.dart';
import 'package:vector_math/vector_math_64.dart' as vector_math_64;
final _argsCsvFilePath = '/config/data/args.csv';
void main(List<String> args) async {
print('Launching embedding-flutter-view');
args = args + _GetArgsFromConfigFile();
final parser = ArgParser()
..addFlag('showOverlay', defaultsTo: false)
..addFlag('focusable', defaultsTo: true);
final arguments = parser.parse(args);
for (final option in arguments.options) {
print('embedding-flutter-view args: $option: ${arguments[option]}');
}
TestApp app = TestApp(
ChildView(await _launchChildView()),
showOverlay: arguments['showOverlay'],
focusable: arguments['focusable'],
);
app.run();
}
class TestApp {
static const _black = Color.fromARGB(255, 0, 0, 0);
static const _blue = Color.fromARGB(255, 0, 0, 255);
final ChildView childView;
final bool showOverlay;
final bool focusable;
Color _backgroundColor = _blue;
TestApp(
this.childView,
{this.showOverlay = false,
this.focusable = true}) {
}
void run() {
childView.create(focusable, (ByteData? reply) {
// Set up window callbacks.
window.onPointerDataPacket = (PointerDataPacket packet) {
this.pointerDataPacket(packet);
};
window.onMetricsChanged = () {
window.scheduleFrame();
};
window.onBeginFrame = (Duration duration) {
this.beginFrame(duration);
};
// The child view should be attached to Scenic now.
// Ready to build the scene.
window.scheduleFrame();
});
}
void beginFrame(Duration duration) {
// Convert physical screen size of device to values
final pixelRatio = window.devicePixelRatio;
final size = window.physicalSize / pixelRatio;
final physicalBounds = Offset.zero & window.physicalSize;
final windowBounds = Offset.zero & size;
// Set up a Canvas that uses the screen size
final recorder = PictureRecorder();
final canvas = Canvas(recorder, physicalBounds);
canvas.scale(pixelRatio);
// Draw something
final paint = Paint()..color = this._backgroundColor;
canvas.drawRect(windowBounds, paint);
final picture = recorder.endRecording();
// Build the scene
final sceneBuilder = SceneBuilder()
..pushClipRect(physicalBounds)
..addPicture(Offset.zero, picture);
final childPhysicalSize = window.physicalSize * 0.25;
// Alignment.center
final windowCenter = size.center(Offset.zero);
final windowPhysicalCenter = window.physicalSize.center(Offset.zero);
final childPhysicalOffset = windowPhysicalCenter - childPhysicalSize.center(Offset.zero);
sceneBuilder
..pushTransform(
vector_math_64.Matrix4.translationValues(childPhysicalOffset.dx,
childPhysicalOffset.dy,
0.0).storage)
..addPlatformView(childView.viewId,
width: childPhysicalSize.width,
height: childPhysicalSize.height)
..pop();
if (showOverlay) {
final containerSize = size * 0.5;
// Alignment.center
final containerOffset = windowCenter - containerSize.center(Offset.zero);
final overlaySize = containerSize * 0.5;
// Alignment.topRight
final overlayOffset = Offset(
containerOffset.dx + containerSize.width - overlaySize.width,
containerOffset.dy);
final overlayPhysicalSize = overlaySize * pixelRatio;
final overlayPhysicalOffset = overlayOffset * pixelRatio;
final overlayPhysicalBounds = overlayPhysicalOffset & overlayPhysicalSize;
final recorder = PictureRecorder();
final overlayCullRect = Offset.zero & overlayPhysicalSize; // in canvas physical coordinates
final canvas = Canvas(recorder, overlayCullRect);
canvas.scale(pixelRatio);
final paint = Paint()..color = Color.fromARGB(255, 0, 255, 0);
canvas.drawRect(Offset.zero & overlaySize, paint);
final overlayPicture = recorder.endRecording();
sceneBuilder
..pushClipRect(overlayPhysicalBounds) // in window physical coordinates
..addPicture(overlayPhysicalOffset, overlayPicture)
..pop();
}
sceneBuilder.pop();
window.render(sceneBuilder.build());
}
void pointerDataPacket(PointerDataPacket packet) async {
int nowNanos = System.clockGetMonotonic();
for (PointerData data in packet.data) {
print('embedding-flutter-view received tap: ${data.toStringFull()}');
if (data.change == PointerChange.down) {
this._backgroundColor = _black;
}
if (data.change == PointerChange.down || data.change == PointerChange.move) {
_reportTouchInput(
localX: data.physicalX,
localY: data.physicalY,
timeReceived: nowNanos,
);
}
}
window.scheduleFrame();
}
void _reportTouchInput({required double localX, required double localY, required int timeReceived}) {
print('embedding-flutter-view reporting touch input to TouchInputListener');
final message = utf8.encode(json.encode({
'method': 'TouchInputListener.ReportTouchInput',
'local_x': localX,
'local_y': localY,
'time_received': timeReceived,
'component_name': 'embedding-flutter-view',
})).buffer.asByteData();
PlatformDispatcher.instance.sendPlatformMessage('fuchsia/input_test', message, null);
}
}
class ChildView {
final int viewId;
ChildView(this.viewId);
void create(
bool focusable,
PlatformMessageResponseCallback callback) {
// Construct the dart:ui platform message to create the view, and when the
// return callback is invoked, build the scene. At that point, it is safe
// to embed the child view in the scene.
final viewOcclusionHint = Rect.zero;
final Map<String, dynamic> args = <String, dynamic>{
'viewId': viewId,
// Flatland doesn't support disabling hit testing.
'hitTestable': true,
'focusable': focusable,
'viewOcclusionHintLTRB': <double>[
viewOcclusionHint.left,
viewOcclusionHint.top,
viewOcclusionHint.right,
viewOcclusionHint.bottom
],
};
final ByteData createViewMessage = utf8.encode(
json.encode(<String, Object>{
'method': 'View.create',
'args': args,
})
).buffer.asByteData();
final platformViewsChannel = 'flutter/platform_views';
PlatformDispatcher.instance.sendPlatformMessage(
platformViewsChannel,
createViewMessage,
callback);
}
}
Future<int> _launchChildView() async {
final message = Int8List.fromList([0x31]);
final completer = new Completer<ByteData>();
PlatformDispatcher.instance.sendPlatformMessage(
'fuchsia/child_view', ByteData.sublistView(message), (ByteData? reply) {
completer.complete(reply!);
});
return int.parse(
ascii.decode(((await completer.future).buffer.asUint8List())));
}
List<String> _GetArgsFromConfigFile() {
List<String> args;
final f = File(_argsCsvFilePath);
if (!f.existsSync()) {
return List.empty();
}
final fileContentCsv = f.readAsStringSync();
args = fileContentCsv.split('\n');
return args;
}
| engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/lib/embedding-flutter-view.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/embedding-flutter-view/lib/embedding-flutter-view.dart",
"repo_id": "engine",
"token_count": 2830
} | 360 |
// 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 <fuchsia/ui/composition/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl_test_base.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl_test_base.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/async/default.h>
#include <lib/fidl/cpp/binding_set.h>
#include <lib/zx/eventpair.h>
#include <memory>
#include <ostream>
#include <string>
#include <vector>
#include "flutter/flow/embedded_views.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "flutter/lib/ui/window/pointer_data.h"
#include "flutter/lib/ui/window/viewport_metrics.h"
#include "flutter/shell/common/context_options.h"
#include "flutter/shell/platform/fuchsia/flutter/platform_view.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "fakes/focuser.h"
#include "fakes/platform_message.h"
#include "fakes/touch_source.h"
#include "fakes/view_ref_focused.h"
#include "flutter/shell/platform/fuchsia/flutter/surface.h"
#include "flutter/shell/platform/fuchsia/flutter/task_runner_adapter.h"
#include "platform/assert.h"
#include "pointer_event_utility.h"
namespace flutter_runner::testing {
namespace {
class MockExternalViewEmbedder : public flutter::ExternalViewEmbedder {
public:
flutter::DlCanvas* GetRootCanvas() override { return nullptr; }
void CancelFrame() override {}
void BeginFrame(GrDirectContext* context,
const fml::RefPtr<fml::RasterThreadMerger>&
raster_thread_merger) override {}
void PrepareFlutterView(int64_t flutter_view_id,
SkISize frame_size,
double device_pixel_ratio) override {}
void SubmitFlutterView(
GrDirectContext* context,
const std::shared_ptr<impeller::AiksContext>& aiks_context,
std::unique_ptr<flutter::SurfaceFrame> frame) override {}
void PrerollCompositeEmbeddedView(
int64_t view_id,
std::unique_ptr<flutter::EmbeddedViewParams> params) override {}
flutter::DlCanvas* CompositeEmbeddedView(int64_t view_id) override {
return nullptr;
}
};
class MockPlatformViewDelegate : public flutter::PlatformView::Delegate {
public:
void Reset() {
message_ = nullptr;
metrics_ = flutter::ViewportMetrics{};
semantics_features_ = 0;
semantics_enabled_ = false;
pointer_packets_.clear();
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewCreated(std::unique_ptr<flutter::Surface> surface) {
ASSERT_EQ(surface_.get(), nullptr);
surface_ = std::move(surface);
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewDestroyed() {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewScheduleFrame() {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewSetNextFrameCallback(const fml::closure& closure) {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewSetViewportMetrics(
int64_t view_id,
const flutter::ViewportMetrics& metrics) {
metrics_ = metrics;
}
// |flutter::PlatformView::Delegate|
const flutter::Settings& OnPlatformViewGetSettings() const {
return settings_;
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewDispatchPlatformMessage(
std::unique_ptr<flutter::PlatformMessage> message) {
message_ = std::move(message);
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewDispatchPointerDataPacket(
std::unique_ptr<flutter::PointerDataPacket> packet) {
pointer_packets_.push_back(std::move(packet));
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewDispatchKeyDataPacket(
std::unique_ptr<flutter::KeyDataPacket> packet,
std::function<void(bool)> callback) {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewDispatchSemanticsAction(int32_t id,
flutter::SemanticsAction action,
fml::MallocMapping args) {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewSetSemanticsEnabled(bool enabled) {
semantics_enabled_ = enabled;
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewSetAccessibilityFeatures(int32_t flags) {
semantics_features_ = flags;
}
// |flutter::PlatformView::Delegate|
void OnPlatformViewRegisterTexture(
std::shared_ptr<flutter::Texture> texture) {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewUnregisterTexture(int64_t texture_id) {}
// |flutter::PlatformView::Delegate|
void OnPlatformViewMarkTextureFrameAvailable(int64_t texture_id) {}
// |flutter::PlatformView::Delegate|
std::unique_ptr<std::vector<std::string>> ComputePlatformViewResolvedLocale(
const std::vector<std::string>& supported_locale_data) {
return nullptr;
}
// |flutter::PlatformView::Delegate|
void LoadDartDeferredLibrary(
intptr_t loading_unit_id,
std::unique_ptr<const fml::Mapping> snapshot_data,
std::unique_ptr<const fml::Mapping> snapshot_instructions) {}
// |flutter::PlatformView::Delegate|
void LoadDartDeferredLibraryError(intptr_t loading_unit_id,
const std::string error_message,
bool transient) {}
// |flutter::PlatformView::Delegate|
void UpdateAssetResolverByType(
std::unique_ptr<flutter::AssetResolver> updated_asset_resolver,
flutter::AssetResolver::AssetResolverType type) {}
flutter::Surface* surface() const { return surface_.get(); }
flutter::PlatformMessage* message() const { return message_.get(); }
const flutter::ViewportMetrics& metrics() const { return metrics_; }
int32_t semantics_features() const { return semantics_features_; }
bool semantics_enabled() const { return semantics_enabled_; }
const std::vector<std::unique_ptr<flutter::PointerDataPacket>>&
pointer_packets() const {
return pointer_packets_;
}
std::vector<std::unique_ptr<flutter::PointerDataPacket>>
TakePointerDataPackets() {
auto tmp = std::move(pointer_packets_);
pointer_packets_.clear();
return tmp;
}
private:
std::unique_ptr<flutter::Surface> surface_;
std::unique_ptr<flutter::PlatformMessage> message_;
flutter::ViewportMetrics metrics_;
std::vector<std::unique_ptr<flutter::PointerDataPacket>> pointer_packets_;
int32_t semantics_features_ = 0;
bool semantics_enabled_ = false;
flutter::Settings settings_;
};
class MockResponse : public flutter::PlatformMessageResponse {
public:
MOCK_METHOD(void, Complete, (std::unique_ptr<fml::Mapping> data), (override));
MOCK_METHOD(void, CompleteEmpty, (), (override));
};
class TestPlatformMessageResponse : public flutter::PlatformMessageResponse {
public:
TestPlatformMessageResponse() {}
void Complete(std::unique_ptr<fml::Mapping> data) override {
result_string = std::string(
reinterpret_cast<const char*>(data->GetMapping()), data->GetSize());
is_complete_ = true;
}
void CompleteEmpty() override { is_complete_ = true; }
std::string result_string;
FML_DISALLOW_COPY_AND_ASSIGN(TestPlatformMessageResponse);
};
class MockKeyboard : public fuchsia::ui::input3::testing::Keyboard_TestBase {
public:
explicit MockKeyboard(
fidl::InterfaceRequest<fuchsia::ui::input3::Keyboard> keyboard)
: keyboard_(this, std::move(keyboard)) {}
~MockKeyboard() = default;
void AddListener(fuchsia::ui::views::ViewRef view_ref,
fuchsia::ui::input3::KeyboardListenerHandle listener,
AddListenerCallback callback) override {
FML_CHECK(!listener_.is_bound());
listener_ = listener.Bind();
view_ref_ = std::move(view_ref);
callback();
}
void NotImplemented_(const std::string& name) override { FAIL(); }
fidl::Binding<fuchsia::ui::input3::Keyboard> keyboard_;
fuchsia::ui::input3::KeyboardListenerPtr listener_{};
fuchsia::ui::views::ViewRef view_ref_{};
FML_DISALLOW_COPY_AND_ASSIGN(MockKeyboard);
};
class MockChildViewWatcher
: public fuchsia::ui::composition::testing::ChildViewWatcher_TestBase {
public:
explicit MockChildViewWatcher(
fidl::InterfaceRequest<fuchsia::ui::composition::ChildViewWatcher>
request)
: binding_(this, std::move(request)) {}
~MockChildViewWatcher() = default;
// |fuchsia::ui::composition::ChildViewWatcher|
void GetStatus(GetStatusCallback callback) override {
// GetStatus only returns once as per flatland.fidl comments
if (get_status_returned_) {
return;
}
callback(fuchsia::ui::composition::ChildViewStatus::CONTENT_HAS_PRESENTED);
get_status_returned_ = true;
}
// |fuchsia::ui::composition::ChildViewWatcher|
void GetViewRef(GetViewRefCallback callback) override {
// GetViewRef only returns once as per flatland.fidl comments
ASSERT_FALSE(control_ref_.reference);
fuchsia::ui::views::ViewRefControl view_ref_control;
fuchsia::ui::views::ViewRef view_ref;
auto status = zx::eventpair::create(
/*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
ZX_ASSERT(status == ZX_OK);
view_ref_control.reference.replace(
ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
&view_ref_control.reference);
view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
control_ref_ = std::move(view_ref_control);
callback(std::move(view_ref));
}
void NotImplemented_(const std::string& name) override { FAIL(); }
fidl::Binding<fuchsia::ui::composition::ChildViewWatcher> binding_;
fuchsia::ui::views::ViewRefControl control_ref_;
bool get_status_returned_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(MockChildViewWatcher);
};
class MockParentViewportWatcher
: public fuchsia::ui::composition::testing::ParentViewportWatcher_TestBase {
public:
explicit MockParentViewportWatcher() : binding_(this, handle_.NewRequest()) {}
~MockParentViewportWatcher() = default;
// |fuchsia::ui::composition::ParentViewportWatcher|
void GetStatus(GetStatusCallback callback) override {
// GetStatus only returns once as per flatland.fidl comments
if (get_status_returned_) {
return;
}
callback(
fuchsia::ui::composition::ParentViewportStatus::CONNECTED_TO_DISPLAY);
get_status_returned_ = true;
}
// |fuchsia::ui::composition::ParentViewportWatcher|
void GetLayout(GetLayoutCallback callback) override {
if (layout_changed_) {
callback(std::move(layout_));
} else {
FML_CHECK(!pending_callback_valid_);
pending_layout_callback_ = std::move(callback);
pending_callback_valid_ = true;
}
}
void SetLayout(uint32_t logical_size_x,
uint32_t logical_size_y,
float DPR = 1.0) {
::fuchsia::math::SizeU logical_size;
logical_size.width = logical_size_x;
logical_size.height = logical_size_y;
layout_.set_logical_size(logical_size);
layout_.set_device_pixel_ratio({DPR, DPR});
if (pending_callback_valid_) {
pending_layout_callback_(std::move(layout_));
pending_callback_valid_ = false;
} else {
layout_changed_ = true;
}
}
fuchsia::ui::composition::ParentViewportWatcherHandle GetHandle() {
FML_CHECK(handle_); // You can only get the handle once.
return std::move(handle_);
}
void NotImplemented_(const std::string& name) override { FAIL(); }
fuchsia::ui::composition::ParentViewportWatcherHandle handle_;
fidl::Binding<fuchsia::ui::composition::ParentViewportWatcher> binding_;
fuchsia::ui::composition::LayoutInfo layout_;
bool layout_changed_ = false;
GetLayoutCallback pending_layout_callback_;
bool pending_callback_valid_ = false;
bool get_status_returned_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(MockParentViewportWatcher);
};
// Used to construct partial instances of PlatformView for testing. The
// PlatformView constructor has many parameters, not all of which need to
// be filled out for each test. The builder allows you to initialize only
// those that matter to your specific test. Not all builder methods are
// provided: if you find some that are missing, feel free to add them.
class PlatformViewBuilder {
public:
PlatformViewBuilder(flutter::PlatformView::Delegate& delegate,
flutter::TaskRunners task_runners)
: delegate_(delegate), task_runners_(task_runners) {
fuchsia::ui::views::ViewRefControl view_ref_control;
fuchsia::ui::views::ViewRef view_ref;
auto status = zx::eventpair::create(
/*options*/ 0u, &view_ref_control.reference, &view_ref.reference);
ZX_ASSERT(status == ZX_OK);
view_ref_control.reference.replace(
ZX_DEFAULT_EVENTPAIR_RIGHTS & (~ZX_RIGHT_DUPLICATE),
&view_ref_control.reference);
view_ref.reference.replace(ZX_RIGHTS_BASIC, &view_ref.reference);
auto view_ref_pair =
std::make_pair(std::move(view_ref_control), std::move(view_ref));
view_ref_pair_ = std::move(view_ref_pair);
}
PlatformViewBuilder& SetExternalViewEmbedder(
std::shared_ptr<flutter::ExternalViewEmbedder> embedder) {
external_external_view_embedder_ = embedder;
return *this;
}
PlatformViewBuilder& SetImeService(
fuchsia::ui::input::ImeServiceHandle ime_service) {
ime_service_ = std::move(ime_service);
return *this;
}
PlatformViewBuilder& SetKeyboard(
fuchsia::ui::input3::KeyboardHandle keyboard) {
keyboard_ = std::move(keyboard);
return *this;
}
PlatformViewBuilder& SetTouchSource(
fuchsia::ui::pointer::TouchSourceHandle touch_source) {
touch_source_ = std::move(touch_source);
return *this;
}
PlatformViewBuilder& SetMouseSource(
fuchsia::ui::pointer::MouseSourceHandle mouse_source) {
mouse_source_ = std::move(mouse_source);
return *this;
}
PlatformViewBuilder& SetFocuser(fuchsia::ui::views::FocuserHandle focuser) {
focuser_ = std::move(focuser);
return *this;
}
PlatformViewBuilder& SetViewRefFocused(
fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused) {
view_ref_focused_ = std::move(view_ref_focused);
return *this;
}
PlatformViewBuilder& SetPointerInjectorRegistry(
fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry) {
pointerinjector_registry_ = std::move(pointerinjector_registry);
return *this;
}
PlatformViewBuilder& SetEnableWireframeCallback(
OnEnableWireframeCallback callback) {
wireframe_enabled_callback_ = std::move(callback);
return *this;
}
PlatformViewBuilder& SetParentViewportWatcher(
fuchsia::ui::composition::ParentViewportWatcherHandle
parent_viewport_watcher) {
parent_viewport_watcher_ = std::move(parent_viewport_watcher);
return *this;
}
PlatformViewBuilder& SetCreateViewCallback(OnCreateViewCallback callback) {
on_create_view_callback_ = std::move(callback);
return *this;
}
PlatformViewBuilder& SetDestroyViewCallback(OnDestroyViewCallback callback) {
on_destroy_view_callback_ = std::move(callback);
return *this;
}
PlatformViewBuilder& SetUpdateViewCallback(OnUpdateViewCallback callback) {
on_update_view_callback_ = std::move(callback);
return *this;
}
PlatformViewBuilder& SetCreateSurfaceCallback(
OnCreateSurfaceCallback callback) {
on_create_surface_callback_ = std::move(callback);
return *this;
}
PlatformViewBuilder& SetShaderWarmupCallback(
OnShaderWarmupCallback callback) {
on_shader_warmup_callback_ = std::move(callback);
return *this;
}
// Once Build is called, the instance is no longer usable.
PlatformView Build() {
EXPECT_FALSE(std::exchange(built_, true))
<< "Build() was already called, this builder is good for one use only.";
return PlatformView(
delegate_, task_runners_, std::move(view_ref_pair_.second),
external_external_view_embedder_, std::move(ime_service_),
std::move(keyboard_), std::move(touch_source_),
std::move(mouse_source_), std::move(focuser_),
std::move(view_ref_focused_), std::move(parent_viewport_watcher_),
std::move(pointerinjector_registry_),
std::move(wireframe_enabled_callback_),
std::move(on_create_view_callback_),
std::move(on_update_view_callback_),
std::move(on_destroy_view_callback_),
std::move(on_create_surface_callback_),
std::move(on_semantics_node_update_callback_),
std::move(on_request_announce_callback_),
std::move(on_shader_warmup_callback_), [](auto...) {}, [](auto...) {},
nullptr);
}
private:
PlatformViewBuilder() = delete;
flutter::PlatformView::Delegate& delegate_;
flutter::TaskRunners task_runners_;
std::pair<fuchsia::ui::views::ViewRefControl, fuchsia::ui::views::ViewRef>
view_ref_pair_;
std::shared_ptr<flutter::ExternalViewEmbedder>
external_external_view_embedder_;
fuchsia::ui::input::ImeServiceHandle ime_service_;
fuchsia::ui::input3::KeyboardHandle keyboard_;
fuchsia::ui::pointer::TouchSourceHandle touch_source_;
fuchsia::ui::pointer::MouseSourceHandle mouse_source_;
fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused_;
fuchsia::ui::views::FocuserHandle focuser_;
fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry_;
fit::closure on_session_listener_error_callback_;
OnEnableWireframeCallback wireframe_enabled_callback_;
fuchsia::ui::composition::ParentViewportWatcherHandle
parent_viewport_watcher_;
OnCreateViewCallback on_create_view_callback_;
OnDestroyViewCallback on_destroy_view_callback_;
OnUpdateViewCallback on_update_view_callback_;
OnCreateSurfaceCallback on_create_surface_callback_;
OnSemanticsNodeUpdateCallback on_semantics_node_update_callback_;
OnRequestAnnounceCallback on_request_announce_callback_;
OnShaderWarmupCallback on_shader_warmup_callback_;
bool built_{false};
};
std::string ToString(const fml::Mapping& mapping) {
return std::string(mapping.GetMapping(),
mapping.GetMapping() + mapping.GetSize());
}
// Stolen from pointer_data_packet_converter_unittests.cc.
void UnpackPointerPacket(std::vector<flutter::PointerData>& output, // NOLINT
std::unique_ptr<flutter::PointerDataPacket> packet) {
for (size_t i = 0; i < packet->GetLength(); i++) {
flutter::PointerData pointer_data = packet->GetPointerData(i);
output.push_back(pointer_data);
}
packet.reset();
}
} // namespace
class PlatformViewTests : public ::testing::Test {
protected:
PlatformViewTests() : loop_(&kAsyncLoopConfigAttachToCurrentThread) {}
async_dispatcher_t* dispatcher() { return loop_.dispatcher(); }
void RunLoopUntilIdle() {
loop_.RunUntilIdle();
loop_.ResetQuit();
}
void RunLoopOnce() {
loop_.Run(zx::time::infinite(), true);
loop_.ResetQuit();
}
fuchsia::ui::input3::KeyEvent MakeEvent(
fuchsia::ui::input3::KeyEventType event_type,
std::optional<fuchsia::ui::input3::Modifiers> modifiers,
fuchsia::input::Key key) {
fuchsia::ui::input3::KeyEvent event;
event.set_timestamp(++event_timestamp_);
event.set_type(event_type);
if (modifiers.has_value()) {
event.set_modifiers(modifiers.value());
}
event.set_key(key);
return event;
}
fuchsia::ui::composition::ChildViewWatcherPtr MakeChildViewWatcher() {
fuchsia::ui::composition::ChildViewWatcherPtr ptr;
auto watcher = std::make_unique<MockChildViewWatcher>(
ptr.NewRequest(loop_.dispatcher()));
child_view_watchers_.push_back(std::move(watcher));
return ptr;
}
private:
async::Loop loop_;
uint64_t event_timestamp_{42};
std::vector<std::unique_ptr<MockChildViewWatcher>> child_view_watchers_;
FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewTests);
};
// This test makes sure that the PlatformView always completes a platform
// message request, even for error conditions or if the request is malformed.
TEST_F(PlatformViewTests, InvalidPlatformMessageRequest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
FakeViewRefFocused vrf;
fidl::BindingSet<fuchsia::ui::views::ViewRefFocused> vrf_bindings;
auto vrf_handle = vrf_bindings.AddBinding(&vrf);
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetViewRefFocused(std::move(vrf_handle))
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
// Invalid platform channel.
auto response1 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response1->WithMessage(
"flutter/invalid", "{\"method\":\"Invalid.invalidMethod\"}"));
// Invalid json.
auto response2 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(
response2->WithMessage("flutter/platform_views", "{Invalid JSON"));
// Invalid method.
auto response3 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response3->WithMessage(
"flutter/platform_views", "{\"method\":\"View.focus.invalidMethod\"}"));
// Missing arguments.
auto response4 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response4->WithMessage(
"flutter/platform_views", "{\"method\":\"View.update\"}"));
auto response5 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(
response5->WithMessage("flutter/platform_views",
"{\"method\":\"View.update\",\"args\":{"
"\"irrelevantField\":\"irrelevantValue\"}}"));
// Wrong argument types.
auto response6 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response6->WithMessage(
"flutter/platform_views",
"{\"method\":\"View.update\",\"args\":{\"viewId\":false,\"hitTestable\":"
"123,\"focusable\":\"yes\"}}"));
// Run the event loop and check our responses.
RunLoopUntilIdle();
response1->ExpectCompleted("");
response2->ExpectCompleted("");
response3->ExpectCompleted("");
response4->ExpectCompleted("");
response5->ExpectCompleted("");
response6->ExpectCompleted("");
}
// This test makes sure that the PlatformView correctly returns a Surface
// instance that can surface the provided gr_context and external_view_embedder.
TEST_F(PlatformViewTests, CreateSurfaceTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", // label
nullptr, // platform
flutter_runner::CreateFMLTaskRunner(
async_get_default_dispatcher()), // raster
nullptr, // ui
nullptr // io
);
// Test create surface callback function.
sk_sp<GrDirectContext> gr_context = GrDirectContext::MakeMock(
nullptr,
flutter::MakeDefaultContextOptions(flutter::ContextType::kRender));
std::shared_ptr<MockExternalViewEmbedder> external_view_embedder =
std::make_shared<MockExternalViewEmbedder>();
auto CreateSurfaceCallback = [&external_view_embedder, gr_context]() {
return std::make_unique<flutter_runner::Surface>(
"PlatformViewTest", external_view_embedder, gr_context.get());
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetCreateSurfaceCallback(CreateSurfaceCallback)
.SetExternalViewEmbedder(external_view_embedder)
.Build();
platform_view.NotifyCreated();
RunLoopUntilIdle();
EXPECT_EQ(gr_context.get(), delegate.surface()->GetContext());
EXPECT_EQ(external_view_embedder.get(),
platform_view.CreateExternalViewEmbedder().get());
}
// This test makes sure that the PlatformView correctly registers Scenic
// MetricsEvents sent to it via FIDL, correctly parses the metrics it receives,
// and calls the SetViewportMetrics callback with the appropriate parameters.
TEST_F(PlatformViewTests, SetViewportMetrics) {
constexpr float kDPR = 2;
constexpr uint32_t width = 640;
constexpr uint32_t height = 480;
MockPlatformViewDelegate delegate;
EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
MockParentViewportWatcher watcher;
flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr,
nullptr);
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetParentViewportWatcher(watcher.GetHandle())
.Build();
RunLoopUntilIdle();
EXPECT_EQ(delegate.metrics(), flutter::ViewportMetrics());
watcher.SetLayout(width, height, kDPR);
RunLoopUntilIdle();
EXPECT_EQ(delegate.metrics(),
flutter::ViewportMetrics(kDPR, std::round(width * kDPR),
std::round(height * kDPR), -1.0, 0));
}
// This test makes sure that the PlatformView correctly registers semantics
// settings changes applied to it and calls the SetSemanticsEnabled /
// SetAccessibilityFeatures callbacks with the appropriate parameters.
TEST_F(PlatformViewTests, ChangesAccessibilitySettings) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
EXPECT_FALSE(delegate.semantics_enabled());
EXPECT_EQ(delegate.semantics_features(), 0);
auto platform_view =
PlatformViewBuilder(delegate, std::move(task_runners)).Build();
RunLoopUntilIdle();
platform_view.SetSemanticsEnabled(true);
EXPECT_TRUE(delegate.semantics_enabled());
EXPECT_EQ(delegate.semantics_features(),
static_cast<int32_t>(
flutter::AccessibilityFeatureFlag::kAccessibleNavigation));
platform_view.SetSemanticsEnabled(false);
EXPECT_FALSE(delegate.semantics_enabled());
EXPECT_EQ(delegate.semantics_features(), 0);
}
// This test makes sure that the PlatformView forwards messages on the
// "flutter/platform_views" channel for EnableWireframe.
TEST_F(PlatformViewTests, EnableWireframeTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
// Test wireframe callback function. If the message sent to the platform
// view was properly handled and parsed, this function should be called,
// setting |wireframe_enabled| to true.
bool wireframe_enabled = false;
auto EnableWireframeCallback = [&wireframe_enabled](bool should_enable) {
wireframe_enabled = should_enable;
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetEnableWireframeCallback(EnableWireframeCallback)
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
// JSON for the message to be passed into the PlatformView.
const uint8_t txt[] =
"{"
" \"method\":\"View.enableWireframe\","
" \"args\": {"
" \"enable\":true"
" }"
"}";
std::unique_ptr<flutter::PlatformMessage> message =
std::make_unique<flutter::PlatformMessage>(
"flutter/platform_views", fml::MallocMapping::Copy(txt, sizeof(txt)),
fml::RefPtr<flutter::PlatformMessageResponse>());
base_view->HandlePlatformMessage(std::move(message));
RunLoopUntilIdle();
EXPECT_TRUE(wireframe_enabled);
}
// This test makes sure that the PlatformView forwards messages on the
// "flutter/platform_views" channel for Createview.
TEST_F(PlatformViewTests, CreateViewTest) {
MockPlatformViewDelegate delegate;
const uint64_t view_id = 42;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", // label
flutter_runner::CreateFMLTaskRunner(
async_get_default_dispatcher()), // platform
nullptr, // raster
nullptr, // ui
nullptr // io
);
// Test wireframe callback function. If the message sent to the platform
// view was properly handled and parsed, this function should be called,
// setting |wireframe_enabled| to true.
bool create_view_called = false;
auto CreateViewCallback =
[&create_view_called, this](
int64_t view_id, flutter_runner::ViewCallback on_view_created,
flutter_runner::ViewCreatedCallback on_view_bound, bool hit_testable,
bool focusable) {
create_view_called = true;
on_view_created();
fuchsia::ui::composition::ContentId content_id;
on_view_bound(std::move(content_id), MakeChildViewWatcher());
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetCreateViewCallback(CreateViewCallback)
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
// JSON for the message to be passed into the PlatformView.
std::ostringstream create_view_message;
create_view_message << "{" << " \"method\":\"View.create\","
<< " \"args\":{" << " \"viewId\":" << view_id << ","
<< " \"hitTestable\":true," << " \"focusable\":true"
<< " }" << "}";
std::string create_view_call = create_view_message.str();
std::unique_ptr<flutter::PlatformMessage> message =
std::make_unique<flutter::PlatformMessage>(
"flutter/platform_views",
fml::MallocMapping::Copy(create_view_call.c_str(),
create_view_call.size()),
fml::RefPtr<flutter::PlatformMessageResponse>());
base_view->HandlePlatformMessage(std::move(message));
RunLoopUntilIdle();
EXPECT_TRUE(create_view_called);
// Platform view forwards the 'View.viewConnected' message on the
// 'flutter/platform_views' channel when a view gets created.
std::ostringstream view_connected_expected_out;
view_connected_expected_out << "{" << "\"method\":\"View.viewConnected\","
<< "\"args\":{" << " \"viewId\":" << view_id
<< " }" << "}";
ASSERT_NE(delegate.message(), nullptr);
EXPECT_EQ(view_connected_expected_out.str(),
ToString(delegate.message()->data()));
}
// This test makes sure that the PlatformView forwards messages on the
// "flutter/platform_views" channel for UpdateView.
TEST_F(PlatformViewTests, UpdateViewTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
std::optional<SkRect> occlusion_hint_for_test;
std::optional<bool> hit_testable_for_test;
std::optional<bool> focusable_for_test;
auto UpdateViewCallback = [&occlusion_hint_for_test, &hit_testable_for_test,
&focusable_for_test](
int64_t view_id, SkRect occlusion_hint,
bool hit_testable, bool focusable) {
occlusion_hint_for_test = occlusion_hint;
hit_testable_for_test = hit_testable;
focusable_for_test = focusable;
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetUpdateViewCallback(UpdateViewCallback)
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
// Send a basic message.
const uint8_t json[] =
"{"
" \"method\":\"View.update\","
" \"args\": {"
" \"viewId\":42,"
" \"hitTestable\":true,"
" \"focusable\":true"
" }"
"}";
std::unique_ptr<flutter::PlatformMessage> message =
std::make_unique<flutter::PlatformMessage>(
"flutter/platform_views",
fml::MallocMapping::Copy(json, sizeof(json)),
fml::RefPtr<flutter::PlatformMessageResponse>());
base_view->HandlePlatformMessage(std::move(message));
RunLoopUntilIdle();
ASSERT_TRUE(occlusion_hint_for_test.has_value());
ASSERT_TRUE(hit_testable_for_test.has_value());
ASSERT_TRUE(focusable_for_test.has_value());
EXPECT_EQ(occlusion_hint_for_test.value(), SkRect::MakeEmpty());
EXPECT_EQ(hit_testable_for_test.value(), true);
EXPECT_EQ(focusable_for_test.value(), true);
// Reset for the next message.
occlusion_hint_for_test.reset();
hit_testable_for_test.reset();
focusable_for_test.reset();
// Send another basic message.
const uint8_t json_false[] =
"{"
" \"method\":\"View.update\","
" \"args\": {"
" \"viewId\":42,"
" \"hitTestable\":false,"
" \"focusable\":false"
" }"
"}";
std::unique_ptr<flutter::PlatformMessage> message_false =
std::make_unique<flutter::PlatformMessage>(
"flutter/platform_views",
fml::MallocMapping::Copy(json_false, sizeof(json_false)),
fml::RefPtr<flutter::PlatformMessageResponse>());
base_view->HandlePlatformMessage(std::move(message_false));
RunLoopUntilIdle();
ASSERT_TRUE(occlusion_hint_for_test.has_value());
ASSERT_TRUE(hit_testable_for_test.has_value());
ASSERT_TRUE(focusable_for_test.has_value());
EXPECT_EQ(occlusion_hint_for_test.value(), SkRect::MakeEmpty());
EXPECT_EQ(hit_testable_for_test.value(), false);
EXPECT_EQ(focusable_for_test.value(), false);
// Reset for the next message.
occlusion_hint_for_test.reset();
hit_testable_for_test.reset();
focusable_for_test.reset();
// Send a message including an occlusion hint.
const uint8_t json_occlusion_hint[] =
"{"
" \"method\":\"View.update\","
" \"args\": {"
" \"viewId\":42,"
" \"hitTestable\":true,"
" \"focusable\":true,"
" \"viewOcclusionHintLTRB\":[0.1,0.2,0.3,0.4]"
" }"
"}";
std::unique_ptr<flutter::PlatformMessage> message_occlusion_hint =
std::make_unique<flutter::PlatformMessage>(
"flutter/platform_views",
fml::MallocMapping::Copy(json_occlusion_hint,
sizeof(json_occlusion_hint)),
fml::RefPtr<flutter::PlatformMessageResponse>());
base_view->HandlePlatformMessage(std::move(message_occlusion_hint));
RunLoopUntilIdle();
ASSERT_TRUE(occlusion_hint_for_test.has_value());
ASSERT_TRUE(hit_testable_for_test.has_value());
ASSERT_TRUE(focusable_for_test.has_value());
EXPECT_EQ(occlusion_hint_for_test.value(),
SkRect::MakeLTRB(0.1, 0.2, 0.3, 0.4));
EXPECT_EQ(hit_testable_for_test.value(), true);
EXPECT_EQ(focusable_for_test.value(), true);
}
// This test makes sure that the PlatformView forwards messages on the
// "flutter/platform_views" channel for DestroyView.
TEST_F(PlatformViewTests, DestroyViewTest) {
MockPlatformViewDelegate delegate;
const uint64_t view_id = 42;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", // label
flutter_runner::CreateFMLTaskRunner(
async_get_default_dispatcher()), // platform
nullptr, // raster
nullptr, // ui
nullptr // io
);
bool destroy_view_called = false;
auto on_destroy_view = [&destroy_view_called](
int64_t view_id,
flutter_runner::ViewIdCallback on_view_unbound) {
destroy_view_called = true;
fuchsia::ui::composition::ContentId content_id;
on_view_unbound(std::move(content_id));
};
bool create_view_called = false;
auto on_create_view = [&create_view_called, this](
int64_t view_id,
flutter_runner::ViewCallback on_view_created,
flutter_runner::ViewCreatedCallback on_view_bound,
bool hit_testable, bool focusable) {
create_view_called = true;
on_view_created();
fuchsia::ui::composition::ContentId content_id;
on_view_bound(std::move(content_id), MakeChildViewWatcher());
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetCreateViewCallback(on_create_view)
.SetDestroyViewCallback(on_destroy_view)
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
std::ostringstream create_message;
create_message << "{" << " \"method\":\"View.create\","
<< " \"args\": {" << " \"viewId\":" << view_id << ","
<< " \"hitTestable\":true,"
<< " \"focusable\":true" << " }" << "}";
auto create_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(create_response->WithMessage(
"flutter/platform_views", create_message.str()));
RunLoopUntilIdle();
delegate.Reset();
// JSON for the message to be passed into the PlatformView.
std::ostringstream dispose_message;
dispose_message << "{" << " \"method\":\"View.dispose\","
<< " \"args\": {" << " \"viewId\":" << view_id
<< " }" << "}";
std::string dispose_view_call = dispose_message.str();
std::unique_ptr<flutter::PlatformMessage> message =
std::make_unique<flutter::PlatformMessage>(
"flutter/platform_views",
fml::MallocMapping::Copy(dispose_view_call.c_str(),
dispose_view_call.size()),
fml::RefPtr<flutter::PlatformMessageResponse>());
base_view->HandlePlatformMessage(std::move(message));
RunLoopUntilIdle();
EXPECT_TRUE(destroy_view_called);
// Platform view forwards the 'View.viewDisconnected' message on the
// 'flutter/platform_views' channel when a view gets destroyed.
std::ostringstream view_disconnected_expected_out;
view_disconnected_expected_out
<< "{" << "\"method\":\"View.viewDisconnected\"," << "\"args\":{"
<< " \"viewId\":" << view_id << " }" << "}";
ASSERT_NE(delegate.message(), nullptr);
EXPECT_EQ(view_disconnected_expected_out.str(),
ToString(delegate.message()->data()));
}
// This test makes sure that the PlatformView forwards messages on the
// "flutter/platform_views" channel for View.focus.getCurrent and
// View.focus.getNext.
TEST_F(PlatformViewTests, GetFocusStatesTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
FakeViewRefFocused vrf;
fidl::BindingSet<fuchsia::ui::views::ViewRefFocused> vrf_bindings;
auto vrf_handle = vrf_bindings.AddBinding(&vrf);
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetViewRefFocused(std::move(vrf_handle))
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
std::vector<bool> vrf_states{false, true, true, false,
true, false, true, true};
for (std::size_t i = 0; i < vrf_states.size(); ++i) {
// View.focus.getNext should complete with the next focus state.
auto response1 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response1->WithMessage(
"flutter/platform_views", "{\"method\":\"View.focus.getNext\"}"));
// Duplicate View.focus.getNext requests should complete empty.
auto response2 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response2->WithMessage(
"flutter/platform_views", "{\"method\":\"View.focus.getNext\"}"));
// Post watch events and make sure the hanging get is invoked each time.
RunLoopUntilIdle();
EXPECT_EQ(vrf.times_watched, i + 1);
// Dispatch the next vrf event.
vrf.ScheduleCallback(vrf_states[i]);
RunLoopUntilIdle();
// Make sure View.focus.getCurrent completes with the current focus state.
auto response3 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response3->WithMessage(
"flutter/platform_views", "{\"method\":\"View.focus.getCurrent\"}"));
// Duplicate View.focus.getCurrent are allowed.
auto response4 = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(response4->WithMessage(
"flutter/platform_views", "{\"method\":\"View.focus.getCurrent\"}"));
// Run event loop and check our results.
RunLoopUntilIdle();
response1->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]");
response2->ExpectCompleted("[null]");
response3->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]");
response4->ExpectCompleted(vrf_states[i] ? "[true]" : "[false]");
}
}
// This test makes sure that the PlatformView forwards messages on the
// "flutter/platform_views" channel for View.focus.request.
TEST_F(PlatformViewTests, RequestFocusTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", // label
flutter_runner::CreateFMLTaskRunner(
async_get_default_dispatcher()), // platform
nullptr, // raster
nullptr, // ui
nullptr // io
);
FakeFocuser focuser;
fidl::BindingSet<fuchsia::ui::views::Focuser> focuser_bindings;
auto focuser_handle = focuser_bindings.AddBinding(&focuser);
bool create_view_called = false;
auto on_create_view = [&create_view_called, this](
int64_t view_id,
flutter_runner::ViewCallback on_view_created,
flutter_runner::ViewCreatedCallback on_view_bound,
bool hit_testable, bool focusable) {
create_view_called = true;
on_view_created();
fuchsia::ui::composition::ContentId content_id;
on_view_bound(std::move(content_id), MakeChildViewWatcher());
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetFocuser(std::move(focuser_handle))
.SetCreateViewCallback(on_create_view)
.Build();
// Cast platform_view to its base view so we can have access to the public
// "HandlePlatformMessage" function.
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
uint64_t view_id = 42;
std::ostringstream create_message;
create_message << "{" << " \"method\":\"View.create\","
<< " \"args\": {" << " \"viewId\":" << view_id << ","
<< " \"hitTestable\":true,"
<< " \"focusable\":true" << " }" << "}";
// Dispatch the plaform message request.
auto create_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(create_response->WithMessage(
"flutter/platform_views", create_message.str()));
RunLoopUntilIdle();
// JSON for the message to be passed into the PlatformView.
std::ostringstream focus_message;
focus_message << "{" << " \"method\":\"View.focus.requestById\","
<< " \"args\": {" << " \"viewId\":" << view_id
<< " }" << "}";
// Dispatch the plaform message request.
auto focus_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(focus_response->WithMessage(
"flutter/platform_views", focus_message.str()));
RunLoopUntilIdle();
focus_response->ExpectCompleted("[0]");
EXPECT_TRUE(focuser.request_focus_called());
}
// This test tries to set focus on a view without creating it first
TEST_F(PlatformViewTests, RequestFocusNeverCreatedTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", // label
flutter_runner::CreateFMLTaskRunner(
async_get_default_dispatcher()), // platform
nullptr, // raster
nullptr, // ui
nullptr // io
);
FakeFocuser focuser;
fidl::BindingSet<fuchsia::ui::views::Focuser> focuser_bindings;
auto focuser_handle = focuser_bindings.AddBinding(&focuser);
bool create_view_called = false;
auto on_create_view = [&create_view_called, this](
int64_t view_id,
flutter_runner::ViewCallback on_view_created,
flutter_runner::ViewCreatedCallback on_view_bound,
bool hit_testable, bool focusable) {
create_view_called = true;
on_view_created();
fuchsia::ui::composition::ContentId content_id;
on_view_bound(std::move(content_id), MakeChildViewWatcher());
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetFocuser(std::move(focuser_handle))
.SetCreateViewCallback(on_create_view)
.Build();
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
uint64_t view_id = 42;
std::ostringstream focus_message;
focus_message << "{" << " \"method\":\"View.focus.requestById\","
<< " \"args\": {" << " \"viewId\":" << view_id
<< " }" << "}";
// Dispatch the plaform message request.
auto focus_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(focus_response->WithMessage(
"flutter/platform_views", focus_message.str()));
RunLoopUntilIdle();
focus_response->ExpectCompleted("[1]");
EXPECT_FALSE(focuser.request_focus_called());
}
TEST_F(PlatformViewTests, RequestFocusDisposedTest) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", // label
flutter_runner::CreateFMLTaskRunner(
async_get_default_dispatcher()), // platform
nullptr, // raster
nullptr, // ui
nullptr // io
);
FakeFocuser focuser;
fidl::BindingSet<fuchsia::ui::views::Focuser> focuser_bindings;
auto focuser_handle = focuser_bindings.AddBinding(&focuser);
bool create_view_called = false;
auto on_create_view = [&create_view_called, this](
int64_t view_id,
flutter_runner::ViewCallback on_view_created,
flutter_runner::ViewCreatedCallback on_view_bound,
bool hit_testable, bool focusable) {
create_view_called = true;
on_view_created();
fuchsia::ui::composition::ContentId content_id;
on_view_bound(std::move(content_id), MakeChildViewWatcher());
};
bool destroy_view_called = false;
auto on_destroy_view = [&destroy_view_called](
int64_t view_id,
flutter_runner::ViewIdCallback on_view_unbound) {
destroy_view_called = true;
fuchsia::ui::composition::ContentId content_id;
on_view_unbound(std::move(content_id));
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetFocuser(std::move(focuser_handle))
.SetCreateViewCallback(on_create_view)
.SetDestroyViewCallback(on_destroy_view)
.Build();
auto base_view = static_cast<flutter::PlatformView*>(&platform_view);
EXPECT_TRUE(base_view);
uint64_t view_id = 42;
// Create a new view
std::ostringstream create_message;
create_message << "{" << " \"method\":\"View.create\","
<< " \"args\": {" << " \"viewId\":" << view_id << ","
<< " \"hitTestable\":true,"
<< " \"focusable\":true" << " }" << "}";
auto create_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(create_response->WithMessage(
"flutter/platform_views", create_message.str()));
RunLoopUntilIdle();
EXPECT_FALSE(destroy_view_called);
// Dispose of the view
std::ostringstream dispose_message;
dispose_message << "{" << " \"method\":\"View.dispose\","
<< " \"args\": {" << " \"viewId\":" << view_id
<< " }" << "}";
auto dispose_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(dispose_response->WithMessage(
"flutter/platform_views", dispose_message.str()));
RunLoopUntilIdle();
EXPECT_TRUE(destroy_view_called);
// Request focus on newly disposed view
std::ostringstream focus_message;
focus_message << "{" << " \"method\":\"View.focus.requestById\","
<< " \"args\": {" << " \"viewId\":" << view_id
<< " }" << "}";
auto focus_response = FakePlatformMessageResponse::Create();
base_view->HandlePlatformMessage(focus_response->WithMessage(
"flutter/platform_views", focus_message.str()));
RunLoopUntilIdle();
// Expect it to fail
focus_response->ExpectCompleted("[1]");
EXPECT_FALSE(focuser.request_focus_called());
}
// Makes sure that OnKeyEvent is dispatched as a platform message.
TEST_F(PlatformViewTests, OnKeyEvent) {
struct EventFlow {
fuchsia::ui::input3::KeyEvent event;
fuchsia::ui::input3::KeyEventStatus expected_key_event_status;
std::string expected_platform_message;
};
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
fuchsia::ui::input3::KeyboardHandle keyboard_service;
MockKeyboard keyboard(keyboard_service.NewRequest());
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetKeyboard(std::move(keyboard_service))
.Build();
RunLoopUntilIdle();
std::vector<EventFlow> events;
// Press A. Get 'a'.
// The HID usage for the key A is 0x70004, or 458756.
events.emplace_back(EventFlow{
MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt,
fuchsia::input::Key::A),
fuchsia::ui::input3::KeyEventStatus::HANDLED,
R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})",
});
// Release A. Get 'a' release.
events.emplace_back(EventFlow{
MakeEvent(fuchsia::ui::input3::KeyEventType::RELEASED, std::nullopt,
fuchsia::input::Key::A),
fuchsia::ui::input3::KeyEventStatus::HANDLED,
R"({"type":"keyup","keymap":"fuchsia","hidUsage":458756,"codePoint":97,"modifiers":0})",
});
// Press CAPS_LOCK. Modifier now active.
events.emplace_back(EventFlow{
MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED,
fuchsia::ui::input3::Modifiers::CAPS_LOCK,
fuchsia::input::Key::CAPS_LOCK),
fuchsia::ui::input3::KeyEventStatus::HANDLED,
R"({"type":"keydown","keymap":"fuchsia","hidUsage":458809,"codePoint":0,"modifiers":1})",
});
// Press A. Get 'A'.
events.emplace_back(EventFlow{
MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt,
fuchsia::input::Key::A),
fuchsia::ui::input3::KeyEventStatus::HANDLED,
R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":65,"modifiers":1})",
});
// Release CAPS_LOCK.
events.emplace_back(EventFlow{
MakeEvent(fuchsia::ui::input3::KeyEventType::RELEASED,
fuchsia::ui::input3::Modifiers::CAPS_LOCK,
fuchsia::input::Key::CAPS_LOCK),
fuchsia::ui::input3::KeyEventStatus::HANDLED,
R"({"type":"keyup","keymap":"fuchsia","hidUsage":458809,"codePoint":0,"modifiers":1})",
});
// Press A again. This time get 'A'.
// CAPS_LOCK is latched active even if it was just released.
events.emplace_back(EventFlow{
MakeEvent(fuchsia::ui::input3::KeyEventType::PRESSED, std::nullopt,
fuchsia::input::Key::A),
fuchsia::ui::input3::KeyEventStatus::HANDLED,
R"({"type":"keydown","keymap":"fuchsia","hidUsage":458756,"codePoint":65,"modifiers":1})",
});
for (const auto& event : events) {
fuchsia::ui::input3::KeyEvent e;
event.event.Clone(&e);
fuchsia::ui::input3::KeyEventStatus key_event_status{0u};
keyboard.listener_->OnKeyEvent(
std::move(e),
[&key_event_status](fuchsia::ui::input3::KeyEventStatus status) {
key_event_status = status;
});
RunLoopUntilIdle();
ASSERT_NOTNULL(delegate.message());
EXPECT_EQ(event.expected_platform_message,
ToString(delegate.message()->data()));
EXPECT_EQ(event.expected_key_event_status, key_event_status);
}
}
TEST_F(PlatformViewTests, OnShaderWarmup) {
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners =
flutter::TaskRunners("test_runners", nullptr, nullptr, nullptr, nullptr);
uint64_t width = 200;
uint64_t height = 100;
std::vector<std::string> shaders = {"foo.skp", "bar.skp", "baz.skp"};
OnShaderWarmupCallback on_shader_warmup_callback =
[&](const std::vector<std::string>& shaders_in,
std::function<void(uint32_t)> completion_callback, uint64_t width_in,
uint64_t height_in) {
ASSERT_EQ(shaders.size(), shaders_in.size());
for (size_t i = 0; i < shaders_in.size(); i++) {
ASSERT_EQ(shaders[i], shaders_in[i]);
}
ASSERT_EQ(width, width_in);
ASSERT_EQ(height, height_in);
completion_callback(shaders_in.size());
};
auto platform_view = PlatformViewBuilder(delegate, std::move(task_runners))
.SetShaderWarmupCallback(on_shader_warmup_callback)
.Build();
std::ostringstream shaders_array_ostream;
shaders_array_ostream << "[ ";
for (auto it = shaders.begin(); it != shaders.end(); ++it) {
shaders_array_ostream << "\"" << *it << "\"";
if (std::next(it) != shaders.end()) {
shaders_array_ostream << ", ";
}
}
shaders_array_ostream << "]";
std::string shaders_array_string = shaders_array_ostream.str();
// Create initial view for testing.
std::ostringstream warmup_shaders_ostream;
warmup_shaders_ostream << "{" << " \"method\":\"WarmupSkps\","
<< " \"args\":{"
<< " \"shaders\":" << shaders_array_string << ","
<< " \"width\":" << width << ","
<< " \"height\":" << height << " }" << "}\n";
std::string warmup_shaders_string = warmup_shaders_ostream.str();
fml::RefPtr<TestPlatformMessageResponse> response(
new TestPlatformMessageResponse);
static_cast<flutter::PlatformView*>(&platform_view)
->HandlePlatformMessage(std::make_unique<flutter::PlatformMessage>(
"fuchsia/shader_warmup",
fml::MallocMapping::Copy(warmup_shaders_string.c_str(),
warmup_shaders_string.size()),
response));
RunLoopUntilIdle();
ASSERT_TRUE(response->is_complete());
std::ostringstream expected_result_ostream;
expected_result_ostream << "[" << shaders.size() << "]";
std::string expected_result_string = expected_result_ostream.str();
EXPECT_EQ(expected_result_string, response->result_string);
}
TEST_F(PlatformViewTests, TouchSourceLogicalToPhysicalConversion) {
constexpr uint32_t width = 640;
constexpr uint32_t height = 480;
constexpr std::array<std::array<float, 2>, 2> kRect = {
{{0, 0}, {width, height}}};
constexpr std::array<float, 9> kIdentity = {1, 0, 0, 0, 1, 0, 0, 0, 1};
constexpr fuchsia::ui::pointer::TouchInteractionId kIxnOne = {
.device_id = 0u, .pointer_id = 1u, .interaction_id = 2u};
MockPlatformViewDelegate delegate;
flutter::TaskRunners task_runners("test_runners", nullptr, nullptr, nullptr,
nullptr);
MockParentViewportWatcher viewport_watcher;
FakeTouchSource touch_server;
fidl::BindingSet<fuchsia::ui::pointer::TouchSource> touch_bindings;
auto touch_handle = touch_bindings.AddBinding(&touch_server);
auto platform_view =
PlatformViewBuilder(delegate, std::move(task_runners))
.SetParentViewportWatcher(viewport_watcher.GetHandle())
.SetTouchSource(std::move(touch_handle))
.Build();
RunLoopUntilIdle();
EXPECT_EQ(delegate.pointer_packets().size(), 0u);
viewport_watcher.SetLayout(width, height);
RunLoopUntilIdle();
EXPECT_EQ(delegate.metrics(),
flutter::ViewportMetrics(1, width, height, -1, 0));
// Inject
std::vector<fuchsia::ui::pointer::TouchEvent> events =
TouchEventBuilder::New()
.AddTime(/* in nanoseconds */ 1111789u)
.AddViewParameters(kRect, kRect, kIdentity)
.AddSample(kIxnOne, fuchsia::ui::pointer::EventPhase::ADD,
{width / 2, height / 2})
.AddResult(
{.interaction = kIxnOne,
.status = fuchsia::ui::pointer::TouchInteractionStatus::GRANTED})
.BuildAsVector();
touch_server.ScheduleCallback(std::move(events));
RunLoopUntilIdle();
// Unpack
std::vector<std::unique_ptr<flutter::PointerDataPacket>> packets =
delegate.TakePointerDataPackets();
ASSERT_EQ(packets.size(), 1u);
std::vector<flutter::PointerData> flutter_events;
UnpackPointerPacket(flutter_events, std::move(packets[0]));
// Examine phases
ASSERT_EQ(flutter_events.size(), 2u);
EXPECT_EQ(flutter_events[0].change, flutter::PointerData::Change::kAdd);
EXPECT_EQ(flutter_events[1].change, flutter::PointerData::Change::kDown);
// Examine coordinates
EXPECT_EQ(flutter_events[0].physical_x, width / 2);
EXPECT_EQ(flutter_events[0].physical_y, height / 2);
EXPECT_EQ(flutter_events[1].physical_x, width / 2);
EXPECT_EQ(flutter_events[1].physical_y, height / 2);
}
} // namespace flutter_runner::testing
| engine/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/platform_view_unittest.cc",
"repo_id": "engine",
"token_count": 24129
} | 361 |
// 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_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_H_
#include <lib/async/cpp/wait.h>
#include <lib/zx/event.h>
#include <lib/zx/vmo.h>
#include <array>
#include <cstdint>
#include <memory>
#include "flutter/fml/macros.h"
#include "flutter/vulkan/procs/vulkan_handle.h"
#include "flutter/vulkan/procs/vulkan_proc_table.h"
#include "flutter/vulkan/vulkan_command_buffer.h"
#include "flutter/vulkan/vulkan_provider.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "surface_producer.h"
namespace flutter_runner {
// A |VkImage| and its relevant metadata.
struct VulkanImage {
VulkanImage() = default;
VulkanImage(VulkanImage&&) = default;
VulkanImage& operator=(VulkanImage&&) = default;
VkBufferCollectionImageCreateInfoFUCHSIA vk_collection_image_create_info;
VkImageCreateInfo vk_image_create_info;
VkMemoryRequirements vk_memory_requirements;
vulkan::VulkanHandle<VkImage> vk_image;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanImage);
};
class VulkanSurface final : public SurfaceProducerSurface {
public:
VulkanSurface(vulkan::VulkanProvider& vulkan_provider,
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
sk_sp<GrDirectContext> context,
const SkISize& size);
~VulkanSurface() override;
// |SurfaceProducerSurface|
size_t AdvanceAndGetAge() override;
// |SurfaceProducerSurface|
bool FlushSessionAcquireAndReleaseEvents() override;
// |SurfaceProducerSurface|
bool IsValid() const override;
// |SurfaceProducerSurface|
SkISize GetSize() const override;
// Note: It is safe for the caller to collect the surface in the
// |on_writes_committed| callback.
void SignalWritesFinished(
const std::function<void(void)>& on_writes_committed) override;
// |SurfaceProducerSurface|
void SetImageId(uint32_t image_id) override;
// |SurfaceProducerSurface|
uint32_t GetImageId() override;
// |SurfaceProducerSurface|
sk_sp<SkSurface> GetSkiaSurface() const override;
// |SurfaceProducerSurface|
fuchsia::ui::composition::BufferCollectionImportToken
GetBufferCollectionImportToken() override;
// |SurfaceProducerSurface|
zx::event GetAcquireFence() override;
// |SurfaceProducerSurface|
zx::event GetReleaseFence() override;
// |SurfaceProducerSurface|
void SetReleaseImageCallback(
ReleaseImageCallback release_image_callback) override;
const vulkan::VulkanHandle<VkImage>& GetVkImage() {
return vulkan_image_.vk_image;
}
const vulkan::VulkanHandle<VkSemaphore>& GetAcquireVkSemaphore() {
return acquire_semaphore_;
}
vulkan::VulkanCommandBuffer* GetCommandBuffer(
const vulkan::VulkanHandle<VkCommandPool>& pool) {
if (!command_buffer_)
command_buffer_ = std::make_unique<vulkan::VulkanCommandBuffer>(
vulkan_provider_.vk(), vulkan_provider_.vk_device(), pool);
return command_buffer_.get();
}
const vulkan::VulkanHandle<VkFence>& GetCommandBufferFence() {
return command_buffer_fence_;
}
size_t GetAllocationSize() const { return vk_memory_info_.allocationSize; }
size_t GetImageMemoryRequirementsSize() const {
return vulkan_image_.vk_memory_requirements.size;
}
bool IsOversized() const {
return GetAllocationSize() > GetImageMemoryRequirementsSize();
}
bool HasStableSizeHistory() const {
return std::equal(size_history_.begin() + 1, size_history_.end(),
size_history_.begin());
}
private:
static constexpr int kSizeHistorySize = 4;
void OnHandleReady(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal_t* signal);
bool AllocateDeviceMemory(
fuchsia::sysmem::AllocatorSyncPtr& sysmem_allocator,
fuchsia::ui::composition::AllocatorPtr& flatland_allocator,
sk_sp<GrDirectContext> context,
const SkISize& size);
bool CreateVulkanImage(vulkan::VulkanProvider& vulkan_provider,
const SkISize& size,
VulkanImage* out_vulkan_image);
bool SetupSkiaSurface(sk_sp<GrDirectContext> context,
const SkISize& size,
SkColorType color_type,
const VkImageCreateInfo& image_create_info,
const VkMemoryRequirements& memory_reqs);
bool CreateFences();
void Reset();
vulkan::VulkanHandle<VkSemaphore> SemaphoreFromEvent(
const zx::event& event) const;
vulkan::VulkanProvider& vulkan_provider_;
VulkanImage vulkan_image_;
vulkan::VulkanHandle<VkDeviceMemory> vk_memory_;
VkMemoryAllocateInfo vk_memory_info_;
vulkan::VulkanHandle<VkFence> command_buffer_fence_;
sk_sp<SkSurface> sk_surface_;
fuchsia::ui::composition::BufferCollectionImportToken import_token_;
uint32_t image_id_ = 0;
vulkan::VulkanHandle<VkBufferCollectionFUCHSIA> collection_;
zx::event acquire_event_;
vulkan::VulkanHandle<VkSemaphore> acquire_semaphore_;
std::unique_ptr<vulkan::VulkanCommandBuffer> command_buffer_;
zx::event release_event_;
async::WaitMethod<VulkanSurface, &VulkanSurface::OnHandleReady> wait_;
std::function<void()> pending_on_writes_committed_;
std::array<SkISize, kSizeHistorySize> size_history_;
int size_history_index_ = 0;
size_t age_ = 0;
bool valid_ = false;
ReleaseImageCallback release_image_callback_;
FML_DISALLOW_COPY_AND_ASSIGN(VulkanSurface);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_VULKAN_SURFACE_H_
| engine/shell/platform/fuchsia/flutter/vulkan_surface.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/vulkan_surface.h",
"repo_id": "engine",
"token_count": 2347
} | 362 |
// 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_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_HANDLE_EXCEPTION_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_HANDLE_EXCEPTION_H_
#include <lib/sys/cpp/service_directory.h>
#include <memory>
#include <string>
#include "third_party/dart/runtime/include/dart_api.h"
namespace dart_utils {
// If |result| is a Dart Exception, passes the exception message and stack trace
// to the crash analyzer service for further handling.
void HandleIfException(std::shared_ptr<::sys::ServiceDirectory> services,
const std::string& component_url,
Dart_Handle result);
// Passes the exception message and stack trace to the crash analyzer service
// for further handling.
void HandleException(std::shared_ptr<::sys::ServiceDirectory> services,
const std::string& component_url,
const std::string& error,
const std::string& stack_trace);
} // namespace dart_utils
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_HANDLE_EXCEPTION_H_
| engine/shell/platform/fuchsia/runtime/dart/utils/handle_exception.h/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/handle_exception.h",
"repo_id": "engine",
"token_count": 475
} | 363 |
# 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.
import("//flutter/shell/platform/common/client_wrapper/publish.gni")
import("//flutter/testing/testing.gni")
_wrapper_includes = [
"include/flutter/flutter_engine.h",
"include/flutter/flutter_window.h",
"include/flutter/flutter_window_controller.h",
"include/flutter/plugin_registrar_glfw.h",
]
_wrapper_sources = [
"flutter_engine.cc",
"flutter_window_controller.cc",
]
# This code will be merged into .../common/cpp/client_wrapper for client use,
# so uses header paths that assume the merged state. Include the header
# directory of the core wrapper files so these includes will work.
config("relative_core_wrapper_headers") {
include_dirs =
[ "//flutter/shell/platform/common/client_wrapper/include/flutter" ]
}
# GLFW client wrapper build for internal use by the shell implementation.
source_set("client_wrapper_glfw") {
sources = _wrapper_sources
public = _wrapper_includes
deps = [
"//flutter/shell/platform/common:common_cpp_library_headers",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/glfw:flutter_glfw_headers",
]
configs +=
[ "//flutter/shell/platform/common:desktop_library_implementation" ]
public_configs = [
":relative_core_wrapper_headers",
"//flutter/shell/platform/common:relative_flutter_library_headers",
"//flutter/shell/platform/glfw:relative_flutter_glfw_headers",
]
}
# Copies the GLFW client wrapper code to the output directory with a _glfw
# suffix.
publish_client_wrapper_extension("publish_wrapper_glfw") {
public = _wrapper_includes
sources = _wrapper_sources
directory_suffix = "glfw"
}
source_set("client_wrapper_library_stubs_glfw") {
sources = [
"testing/stub_flutter_glfw_api.cc",
"testing/stub_flutter_glfw_api.h",
]
defines = [ "FLUTTER_DESKTOP_LIBRARY" ]
public_deps = [ "//flutter/shell/platform/glfw:flutter_glfw_headers" ]
}
test_fixtures("client_wrapper_glfw_fixtures") {
fixtures = []
}
executable("client_wrapper_glfw_unittests") {
testonly = true
sources = [
"flutter_engine_unittests.cc",
"flutter_window_controller_unittests.cc",
"flutter_window_unittests.cc",
"plugin_registrar_glfw_unittests.cc",
]
defines = [ "FLUTTER_DESKTOP_LIBRARY" ]
deps = [
":client_wrapper_glfw",
":client_wrapper_glfw_fixtures",
":client_wrapper_library_stubs_glfw",
"//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs",
"//flutter/testing",
# TODO(chunhtai): Consider refactoring flutter_root/testing so that there's a testing
# target that doesn't require a Dart runtime to be linked in.
# https://github.com/flutter/flutter/issues/41414.
"$dart_src/runtime:libdart_jit",
]
}
| engine/shell/platform/glfw/client_wrapper/BUILD.gn/0 | {
"file_path": "engine/shell/platform/glfw/client_wrapper/BUILD.gn",
"repo_id": "engine",
"token_count": 1061
} | 364 |
// 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 "flutter/shell/platform/glfw/public/flutter_glfw.h"
#include <GLFW/glfw3.h>
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <string>
#include "flutter/common/constants.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h"
#include "flutter/shell/platform/common/incoming_message_dispatcher.h"
#include "flutter/shell/platform/common/path_utils.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/glfw/glfw_event_loop.h"
#include "flutter/shell/platform/glfw/headless_event_loop.h"
#include "flutter/shell/platform/glfw/key_event_handler.h"
#include "flutter/shell/platform/glfw/keyboard_hook_handler.h"
#include "flutter/shell/platform/glfw/platform_handler.h"
#include "flutter/shell/platform/glfw/system_utils.h"
#include "flutter/shell/platform/glfw/text_input_plugin.h"
// GLFW_TRUE & GLFW_FALSE are introduced since libglfw-3.3,
// add definitions here to compile under the old versions.
#ifndef GLFW_TRUE
#define GLFW_TRUE 1
#endif
#ifndef GLFW_FALSE
#define GLFW_FALSE 0
#endif
using UniqueGLFWwindowPtr = std::unique_ptr<GLFWwindow, void (*)(GLFWwindow*)>;
static_assert(FLUTTER_ENGINE_VERSION == 1, "");
const int kFlutterDesktopDontCare = GLFW_DONT_CARE;
static constexpr double kDpPerInch = 160.0;
// Struct for storing state within an instance of the GLFW Window.
struct FlutterDesktopWindowControllerState {
// The GLFW window that is bound to this state object.
UniqueGLFWwindowPtr window = UniqueGLFWwindowPtr(nullptr, glfwDestroyWindow);
// The invisible GLFW window used to upload resources in the background.
UniqueGLFWwindowPtr resource_window =
UniqueGLFWwindowPtr(nullptr, glfwDestroyWindow);
// The state associated with the engine.
std::unique_ptr<FlutterDesktopEngineState> engine;
// The window handle given to API clients.
std::unique_ptr<FlutterDesktopWindow> window_wrapper;
// Handlers for keyboard events from GLFW.
std::vector<std::unique_ptr<flutter::KeyboardHookHandler>>
keyboard_hook_handlers;
// Whether or not the pointer has been added (or if tracking is enabled,
// has been added since it was last removed).
bool pointer_currently_added = false;
// Whether or not the pointer is down.
bool pointer_currently_down = false;
// The currently pressed buttons, as represented in FlutterPointerEvent.
int64_t buttons = 0;
// The screen coordinates per inch on the primary monitor. Defaults to a sane
// value based on pixel_ratio 1.0.
double monitor_screen_coordinates_per_inch = kDpPerInch;
};
// Opaque reference for the GLFW window itself. This is separate from the
// controller so that it can be provided to plugins without giving them access
// to all of the controller-based functionality.
struct FlutterDesktopWindow {
// The GLFW window that (indirectly) owns this state object.
GLFWwindow* window;
// Whether or not to track mouse movements to send kHover events.
bool hover_tracking_enabled = true;
// The ratio of pixels per screen coordinate for the window.
double pixels_per_screen_coordinate = 1.0;
// If non-zero, a forced pixel ratio to use instead of one computed based on
// screen information.
double pixel_ratio_override = 0.0;
// Resizing triggers a window refresh, but the resize already updates Flutter.
// To avoid double messages, the refresh after each resize is skipped.
bool skip_next_window_refresh = false;
};
// Custom deleter for FlutterEngineAOTData.
struct AOTDataDeleter {
void operator()(FlutterEngineAOTData aot_data) {
FlutterEngineCollectAOTData(aot_data);
}
};
using UniqueAotDataPtr = std::unique_ptr<_FlutterEngineAOTData, AOTDataDeleter>;
/// Maintains one ref on the FlutterDesktopMessenger's internal reference count.
using FlutterDesktopMessengerReferenceOwner =
std::unique_ptr<FlutterDesktopMessenger,
decltype(&FlutterDesktopMessengerRelease)>;
// Struct for storing state of a Flutter engine instance.
struct FlutterDesktopEngineState {
// The handle to the Flutter engine instance.
FLUTTER_API_SYMBOL(FlutterEngine) flutter_engine;
// The event loop for the main thread that allows for delayed task execution.
std::unique_ptr<flutter::EventLoop> event_loop;
// The plugin messenger handle given to API clients.
FlutterDesktopMessengerReferenceOwner messenger = {
nullptr, [](FlutterDesktopMessengerRef ref) {}};
// Message dispatch manager for messages from the Flutter engine.
std::unique_ptr<flutter::IncomingMessageDispatcher> message_dispatcher;
// The plugin registrar handle given to API clients.
std::unique_ptr<FlutterDesktopPluginRegistrar> plugin_registrar;
// The plugin registrar managing internal plugins.
std::unique_ptr<flutter::PluginRegistrar> internal_plugin_registrar;
// Handler for the flutter/platform channel.
std::unique_ptr<flutter::PlatformHandler> platform_handler;
// The controller associated with this engine instance, if any.
// This will always be null for a headless engine.
FlutterDesktopWindowControllerState* window_controller = nullptr;
// AOT data for this engine instance, if applicable.
UniqueAotDataPtr aot_data = nullptr;
};
// State associated with the plugin registrar.
struct FlutterDesktopPluginRegistrar {
// The engine that backs this registrar.
FlutterDesktopEngineState* engine;
// Callback to be called on registrar destruction.
FlutterDesktopOnPluginRegistrarDestroyed destruction_handler;
};
// State associated with the messenger used to communicate with the engine.
struct FlutterDesktopMessenger {
FlutterDesktopMessenger() = default;
/// Increments the reference count.
///
/// Thread-safe.
void AddRef() { ref_count_.fetch_add(1); }
/// Decrements the reference count and deletes the object if the count has
/// gone to zero.
///
/// Thread-safe.
void Release() {
int32_t old_count = ref_count_.fetch_sub(1);
if (old_count <= 1) {
delete this;
}
}
/// Getter for the engine field.
FlutterDesktopEngineState* GetEngine() const { return engine_; }
/// Setter for the engine field.
/// Thread-safe.
void SetEngine(FlutterDesktopEngineState* engine) {
std::scoped_lock lock(mutex_);
engine_ = engine;
}
/// Returns the mutex associated with the |FlutterDesktopMessenger|.
///
/// This mutex is used to synchronize reading or writing state inside the
/// |FlutterDesktopMessenger| (ie |engine_|).
std::mutex& GetMutex() { return mutex_; }
FlutterDesktopMessenger(const FlutterDesktopMessenger& value) = delete;
FlutterDesktopMessenger& operator=(const FlutterDesktopMessenger& value) =
delete;
private:
// The engine that backs this messenger.
FlutterDesktopEngineState* engine_;
std::atomic<int32_t> ref_count_ = 0;
std::mutex mutex_;
};
FlutterDesktopMessengerRef FlutterDesktopMessengerAddRef(
FlutterDesktopMessengerRef messenger) {
messenger->AddRef();
return messenger;
}
void FlutterDesktopMessengerRelease(FlutterDesktopMessengerRef messenger) {
messenger->Release();
}
bool FlutterDesktopMessengerIsAvailable(FlutterDesktopMessengerRef messenger) {
return messenger->GetEngine() != nullptr;
}
FlutterDesktopMessengerRef FlutterDesktopMessengerLock(
FlutterDesktopMessengerRef messenger) {
messenger->GetMutex().lock();
return messenger;
}
void FlutterDesktopMessengerUnlock(FlutterDesktopMessengerRef messenger) {
messenger->GetMutex().unlock();
}
// Retrieves state bag for the window in question from the GLFWWindow.
static FlutterDesktopWindowControllerState* GetWindowController(
GLFWwindow* window) {
return reinterpret_cast<FlutterDesktopWindowControllerState*>(
glfwGetWindowUserPointer(window));
}
// Creates and returns an invisible GLFW window that shares |window|'s resource
// context.
static UniqueGLFWwindowPtr CreateShareWindowForWindow(GLFWwindow* window) {
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
#if defined(__linux__)
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
#endif
GLFWwindow* share_window = glfwCreateWindow(1, 1, "", NULL, window);
glfwDefaultWindowHints();
return UniqueGLFWwindowPtr(share_window, glfwDestroyWindow);
}
// Converts a FlutterPlatformMessage to an equivalent FlutterDesktopMessage.
static FlutterDesktopMessage ConvertToDesktopMessage(
const FlutterPlatformMessage& engine_message) {
FlutterDesktopMessage message = {};
message.struct_size = sizeof(message);
message.channel = engine_message.channel;
message.message = engine_message.message;
message.message_size = engine_message.message_size;
message.response_handle = engine_message.response_handle;
return message;
}
// Returns the number of screen coordinates per inch for the main monitor.
// If the information is unavailable, returns a default value that assumes
// that a screen coordinate is one dp.
static double GetScreenCoordinatesPerInch() {
auto* primary_monitor = glfwGetPrimaryMonitor();
if (primary_monitor == nullptr) {
return kDpPerInch;
}
auto* primary_monitor_mode = glfwGetVideoMode(primary_monitor);
int primary_monitor_width_mm;
glfwGetMonitorPhysicalSize(primary_monitor, &primary_monitor_width_mm,
nullptr);
if (primary_monitor_width_mm == 0) {
return kDpPerInch;
}
return primary_monitor_mode->width / (primary_monitor_width_mm / 25.4);
}
// Sends a window metrics update to the Flutter engine using the given
// framebuffer size and the current window information in |state|.
static void SendWindowMetrics(FlutterDesktopWindowControllerState* controller,
int width,
int height) {
double dpi = controller->window_wrapper->pixels_per_screen_coordinate *
controller->monitor_screen_coordinates_per_inch;
FlutterWindowMetricsEvent event = {};
event.struct_size = sizeof(event);
event.width = width;
event.height = height;
if (controller->window_wrapper->pixel_ratio_override == 0.0) {
// The Flutter pixel_ratio is defined as DPI/dp. Limit the ratio to a
// minimum of 1 to avoid rendering a smaller UI on standard resolution
// monitors.
event.pixel_ratio = std::max(dpi / kDpPerInch, 1.0);
} else {
event.pixel_ratio = controller->window_wrapper->pixel_ratio_override;
}
// The GLFW embedder doesn't support multiple views. We assume all pointer
// events come from the only view, the implicit view.
event.view_id = flutter::kFlutterImplicitViewId;
FlutterEngineSendWindowMetricsEvent(controller->engine->flutter_engine,
&event);
}
// Populates |task_runner| with a description that uses |engine_state|'s event
// loop to run tasks.
static void ConfigurePlatformTaskRunner(
FlutterTaskRunnerDescription* task_runner,
FlutterDesktopEngineState* engine_state) {
task_runner->struct_size = sizeof(FlutterTaskRunnerDescription);
task_runner->user_data = engine_state;
task_runner->runs_task_on_current_thread_callback = [](void* state) -> bool {
return reinterpret_cast<FlutterDesktopEngineState*>(state)
->event_loop->RunsTasksOnCurrentThread();
};
task_runner->post_task_callback =
[](FlutterTask task, uint64_t target_time_nanos, void* state) -> void {
reinterpret_cast<FlutterDesktopEngineState*>(state)->event_loop->PostTask(
task, target_time_nanos);
};
}
// When GLFW calls back to the window with a framebuffer size change, notify
// FlutterEngine about the new window metrics.
static void GLFWFramebufferSizeCallback(GLFWwindow* window,
int width_px,
int height_px) {
int width;
glfwGetWindowSize(window, &width, nullptr);
auto* controller = GetWindowController(window);
controller->window_wrapper->pixels_per_screen_coordinate =
width > 0 ? width_px / width : 1;
SendWindowMetrics(controller, width_px, height_px);
controller->window_wrapper->skip_next_window_refresh = true;
}
// Indicates that the window needs to be redrawn.
void GLFWWindowRefreshCallback(GLFWwindow* window) {
auto* controller = GetWindowController(window);
if (controller->window_wrapper->skip_next_window_refresh) {
controller->window_wrapper->skip_next_window_refresh = false;
return;
}
// There's no engine API to request a redraw explicitly, so instead send a
// window metrics event with the current size to trigger it.
int width_px, height_px;
glfwGetFramebufferSize(window, &width_px, &height_px);
if (width_px > 0 && height_px > 0) {
SendWindowMetrics(controller, width_px, height_px);
}
}
// Sends a pointer event to the Flutter engine based on the given data.
//
// Any coordinate/distance values in |event_data| should be in screen
// coordinates; they will be adjusted to pixel values before being sent.
static void SendPointerEventWithData(GLFWwindow* window,
const FlutterPointerEvent& event_data) {
auto* controller = GetWindowController(window);
// If sending anything other than an add, and the pointer isn't already added,
// synthesize an add to satisfy Flutter's expectations about events.
if (!controller->pointer_currently_added &&
event_data.phase != FlutterPointerPhase::kAdd) {
FlutterPointerEvent event = {};
event.phase = FlutterPointerPhase::kAdd;
event.x = event_data.x;
event.y = event_data.y;
SendPointerEventWithData(window, event);
}
// Don't double-add (e.g., if events are delivered out of order, so an add has
// already been synthesized).
if (controller->pointer_currently_added &&
event_data.phase == FlutterPointerPhase::kAdd) {
return;
}
FlutterPointerEvent event = event_data;
// Set metadata that's always the same regardless of the event.
event.struct_size = sizeof(event);
event.timestamp =
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch())
.count();
event.device_kind = FlutterPointerDeviceKind::kFlutterPointerDeviceKindMouse;
event.buttons =
(event.phase == FlutterPointerPhase::kAdd) ? 0 : controller->buttons;
// Convert all screen coordinates to pixel coordinates.
double pixels_per_coordinate =
controller->window_wrapper->pixels_per_screen_coordinate;
event.x *= pixels_per_coordinate;
event.y *= pixels_per_coordinate;
event.scroll_delta_x *= pixels_per_coordinate;
event.scroll_delta_y *= pixels_per_coordinate;
// The GLFW embedder doesn't support multiple views. We assume all pointer
// events come from the only view, the implicit view.
event.view_id = flutter::kFlutterImplicitViewId;
FlutterEngineSendPointerEvent(controller->engine->flutter_engine, &event, 1);
if (event_data.phase == FlutterPointerPhase::kAdd) {
controller->pointer_currently_added = true;
} else if (event_data.phase == FlutterPointerPhase::kRemove) {
controller->pointer_currently_added = false;
} else if (event_data.phase == FlutterPointerPhase::kDown) {
controller->pointer_currently_down = true;
} else if (event_data.phase == FlutterPointerPhase::kUp) {
controller->pointer_currently_down = false;
}
}
// Updates |event_data| with the current location of the mouse cursor.
static void SetEventLocationFromCursorPosition(
GLFWwindow* window,
FlutterPointerEvent* event_data) {
glfwGetCursorPos(window, &event_data->x, &event_data->y);
}
// Set's |event_data|'s phase depending on the current mouse state.
// If a kUp or kDown event is triggered while the current state is already
// up/down, a hover/move will be called instead to avoid a crash in the Flutter
// engine.
static void SetEventPhaseFromCursorButtonState(GLFWwindow* window,
FlutterPointerEvent* event_data,
int64_t buttons) {
auto* controller = GetWindowController(window);
event_data->phase =
(buttons == 0)
? (controller->pointer_currently_down ? FlutterPointerPhase::kUp
: FlutterPointerPhase::kHover)
: (controller->pointer_currently_down ? FlutterPointerPhase::kMove
: FlutterPointerPhase::kDown);
}
// Reports the mouse entering or leaving the Flutter view.
static void GLFWCursorEnterCallback(GLFWwindow* window, int entered) {
FlutterPointerEvent event = {};
event.phase =
entered ? FlutterPointerPhase::kAdd : FlutterPointerPhase::kRemove;
SetEventLocationFromCursorPosition(window, &event);
SendPointerEventWithData(window, event);
}
// Reports mouse movement to the Flutter engine.
static void GLFWCursorPositionCallback(GLFWwindow* window, double x, double y) {
FlutterPointerEvent event = {};
event.x = x;
event.y = y;
auto* controller = GetWindowController(window);
SetEventPhaseFromCursorButtonState(window, &event, controller->buttons);
SendPointerEventWithData(window, event);
}
// Reports mouse button press to the Flutter engine.
static void GLFWMouseButtonCallback(GLFWwindow* window,
int key,
int action,
int mods) {
int64_t button;
if (key == GLFW_MOUSE_BUTTON_LEFT) {
button = FlutterPointerMouseButtons::kFlutterPointerButtonMousePrimary;
} else if (key == GLFW_MOUSE_BUTTON_RIGHT) {
button = FlutterPointerMouseButtons::kFlutterPointerButtonMouseSecondary;
} else {
return;
}
auto* controller = GetWindowController(window);
controller->buttons = (action == GLFW_PRESS) ? controller->buttons | button
: controller->buttons & ~button;
FlutterPointerEvent event = {};
SetEventPhaseFromCursorButtonState(window, &event, controller->buttons);
SetEventLocationFromCursorPosition(window, &event);
SendPointerEventWithData(window, event);
// If mouse tracking isn't already enabled, turn it on for the duration of
// the drag to generate kMove events.
bool hover_enabled =
GetWindowController(window)->window_wrapper->hover_tracking_enabled;
if (!hover_enabled) {
glfwSetCursorPosCallback(window, (controller->buttons != 0)
? GLFWCursorPositionCallback
: nullptr);
}
// Disable enter/exit events while the mouse button is down; GLFW will send
// an exit event when the mouse button is released, and the pointer should
// stay valid until then.
if (hover_enabled) {
glfwSetCursorEnterCallback(
window, (controller->buttons != 0) ? nullptr : GLFWCursorEnterCallback);
}
}
// Reports scroll wheel events to the Flutter engine.
static void GLFWScrollCallback(GLFWwindow* window,
double delta_x,
double delta_y) {
FlutterPointerEvent event = {};
SetEventLocationFromCursorPosition(window, &event);
auto* controller = GetWindowController(window);
SetEventPhaseFromCursorButtonState(window, &event, controller->buttons);
event.signal_kind = FlutterPointerSignalKind::kFlutterPointerSignalKindScroll;
// TODO(chrome-bot): See if this can be queried from the OS; this value is
// chosen arbitrarily to get something that feels reasonable.
const int kScrollOffsetMultiplier = 20;
event.scroll_delta_x = delta_x * kScrollOffsetMultiplier;
event.scroll_delta_y = -delta_y * kScrollOffsetMultiplier;
SendPointerEventWithData(window, event);
}
// Passes character input events to registered handlers.
static void GLFWCharCallback(GLFWwindow* window, unsigned int code_point) {
for (const auto& handler :
GetWindowController(window)->keyboard_hook_handlers) {
handler->CharHook(window, code_point);
}
}
// Passes raw key events to registered handlers.
static void GLFWKeyCallback(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
for (const auto& handler :
GetWindowController(window)->keyboard_hook_handlers) {
handler->KeyboardHook(window, key, scancode, action, mods);
}
}
// Enables/disables the callbacks related to mouse tracking.
static void SetHoverCallbacksEnabled(GLFWwindow* window, bool enabled) {
glfwSetCursorEnterCallback(window,
enabled ? GLFWCursorEnterCallback : nullptr);
glfwSetCursorPosCallback(window,
enabled ? GLFWCursorPositionCallback : nullptr);
}
// Flushes event queue and then assigns default window callbacks.
static void GLFWAssignEventCallbacks(GLFWwindow* window) {
glfwPollEvents();
glfwSetKeyCallback(window, GLFWKeyCallback);
glfwSetCharCallback(window, GLFWCharCallback);
glfwSetMouseButtonCallback(window, GLFWMouseButtonCallback);
glfwSetScrollCallback(window, GLFWScrollCallback);
if (GetWindowController(window)->window_wrapper->hover_tracking_enabled) {
SetHoverCallbacksEnabled(window, true);
}
}
// Clears default window events.
static void GLFWClearEventCallbacks(GLFWwindow* window) {
glfwSetKeyCallback(window, nullptr);
glfwSetCharCallback(window, nullptr);
glfwSetMouseButtonCallback(window, nullptr);
glfwSetScrollCallback(window, nullptr);
SetHoverCallbacksEnabled(window, false);
}
// The Flutter Engine calls out to this function when new platform messages are
// available
static void EngineOnFlutterPlatformMessage(
const FlutterPlatformMessage* engine_message,
void* user_data) {
if (engine_message->struct_size != sizeof(FlutterPlatformMessage)) {
std::cerr << "Invalid message size received. Expected: "
<< sizeof(FlutterPlatformMessage) << " but received "
<< engine_message->struct_size << std::endl;
return;
}
FlutterDesktopEngineState* engine_state =
static_cast<FlutterDesktopEngineState*>(user_data);
GLFWwindow* window = engine_state->window_controller == nullptr
? nullptr
: engine_state->window_controller->window.get();
auto message = ConvertToDesktopMessage(*engine_message);
engine_state->message_dispatcher->HandleMessage(
message,
[window] {
if (window) {
GLFWClearEventCallbacks(window);
}
},
[window] {
if (window) {
GLFWAssignEventCallbacks(window);
}
});
}
static bool EngineMakeContextCurrent(void* user_data) {
FlutterDesktopEngineState* engine_state =
static_cast<FlutterDesktopEngineState*>(user_data);
FlutterDesktopWindowControllerState* window_controller =
engine_state->window_controller;
if (!window_controller) {
return false;
}
glfwMakeContextCurrent(window_controller->window.get());
return true;
}
static bool EngineMakeResourceContextCurrent(void* user_data) {
FlutterDesktopEngineState* engine_state =
static_cast<FlutterDesktopEngineState*>(user_data);
FlutterDesktopWindowControllerState* window_controller =
engine_state->window_controller;
if (!window_controller) {
return false;
}
glfwMakeContextCurrent(window_controller->resource_window.get());
return true;
}
static bool EngineClearContext(void* user_data) {
FlutterDesktopEngineState* engine_state =
static_cast<FlutterDesktopEngineState*>(user_data);
FlutterDesktopWindowControllerState* window_controller =
engine_state->window_controller;
if (!window_controller) {
return false;
}
glfwMakeContextCurrent(nullptr);
return true;
}
static bool EnginePresent(void* user_data) {
FlutterDesktopEngineState* engine_state =
static_cast<FlutterDesktopEngineState*>(user_data);
FlutterDesktopWindowControllerState* window_controller =
engine_state->window_controller;
if (!window_controller) {
return false;
}
glfwSwapBuffers(window_controller->window.get());
return true;
}
static uint32_t EngineGetActiveFbo(void* user_data) {
return 0;
}
// Resolves the address of the specified OpenGL or OpenGL ES
// core or extension function, if it is supported by the current context.
static void* EngineProcResolver(void* user_data, const char* name) {
return reinterpret_cast<void*>(glfwGetProcAddress(name));
}
// Clears the GLFW window to Material Blue-Grey.
//
// This function is primarily to fix an issue when the Flutter Engine is
// spinning up, wherein artifacts of existing windows are rendered onto the
// canvas for a few moments.
//
// This function isn't necessary, but makes starting the window much easier on
// the eyes.
static void GLFWClearCanvas(GLFWwindow* window) {
glfwMakeContextCurrent(window);
// This color is Material Blue Grey.
glClearColor(236.0f / 255.0f, 239.0f / 255.0f, 241.0f / 255.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glFlush();
glfwSwapBuffers(window);
glfwMakeContextCurrent(nullptr);
}
static void GLFWErrorCallback(int error_code, const char* description) {
std::cerr << "GLFW error " << error_code << ": " << description << std::endl;
}
// Attempts to load AOT data from the given path, which must be absolute and
// non-empty. Logs and returns nullptr on failure.
UniqueAotDataPtr LoadAotData(const std::filesystem::path& aot_data_path) {
if (aot_data_path.empty()) {
std::cerr
<< "Attempted to load AOT data, but no aot_data_path was provided."
<< std::endl;
return nullptr;
}
std::string path_string = aot_data_path.string();
if (!std::filesystem::exists(aot_data_path)) {
std::cerr << "Can't load AOT data from " << path_string << "; no such file."
<< std::endl;
return nullptr;
}
FlutterEngineAOTDataSource source = {};
source.type = kFlutterEngineAOTDataSourceTypeElfPath;
source.elf_path = path_string.c_str();
FlutterEngineAOTData data = nullptr;
auto result = FlutterEngineCreateAOTData(&source, &data);
if (result != kSuccess) {
std::cerr << "Failed to load AOT data from: " << path_string << std::endl;
return nullptr;
}
return UniqueAotDataPtr(data);
}
// Starts an instance of the Flutter Engine.
//
// Configures the engine according to |engine_propreties| and using |event_loop|
// to schedule engine tasks.
//
// Returns true on success, in which case |engine_state|'s 'engine' field will
// be updated to point to the started engine.
static bool RunFlutterEngine(
FlutterDesktopEngineState* engine_state,
const FlutterDesktopEngineProperties& engine_properties,
std::unique_ptr<flutter::EventLoop> event_loop) {
// FlutterProjectArgs is expecting a full argv, so when processing it for
// flags the first item is treated as the executable and ignored. Add a dummy
// value so that all provided arguments are used.
std::vector<const char*> argv = {"placeholder"};
if (engine_properties.switches_count > 0) {
argv.insert(argv.end(), &engine_properties.switches[0],
&engine_properties.switches[engine_properties.switches_count]);
}
std::filesystem::path assets_path =
std::filesystem::u8path(engine_properties.assets_path);
std::filesystem::path icu_path =
std::filesystem::u8path(engine_properties.icu_data_path);
std::filesystem::path aot_library_path =
std::filesystem::u8path(engine_properties.aot_library_path);
if (assets_path.is_relative() || icu_path.is_relative() ||
(!aot_library_path.empty() && aot_library_path.is_relative())) {
// Treat relative paths as relative to the directory of this executable.
std::filesystem::path executable_location =
flutter::GetExecutableDirectory();
if (executable_location.empty()) {
std::cerr << "Unable to find executable location to resolve paths."
<< std::endl;
return false;
}
assets_path = std::filesystem::path(executable_location) / assets_path;
icu_path = std::filesystem::path(executable_location) / icu_path;
if (!aot_library_path.empty()) {
aot_library_path =
std::filesystem::path(executable_location) / aot_library_path;
}
}
// Configure a task runner using the event loop.
engine_state->event_loop = std::move(event_loop);
FlutterTaskRunnerDescription platform_task_runner = {};
ConfigurePlatformTaskRunner(&platform_task_runner, engine_state);
FlutterCustomTaskRunners task_runners = {};
task_runners.struct_size = sizeof(FlutterCustomTaskRunners);
task_runners.platform_task_runner = &platform_task_runner;
FlutterRendererConfig config = {};
config.type = kOpenGL;
config.open_gl.struct_size = sizeof(config.open_gl);
config.open_gl.make_current = EngineMakeContextCurrent;
config.open_gl.clear_current = EngineClearContext;
config.open_gl.present = EnginePresent;
config.open_gl.fbo_callback = EngineGetActiveFbo;
config.open_gl.make_resource_current = EngineMakeResourceContextCurrent;
// Don't provide a resolver in headless mode, since headless mode should
// work even if GLFW initialization failed.
if (engine_state->window_controller != nullptr) {
config.open_gl.gl_proc_resolver = EngineProcResolver;
}
const std::string assets_path_string = assets_path.string();
const std::string icu_path_string = icu_path.string();
FlutterProjectArgs args = {};
args.struct_size = sizeof(FlutterProjectArgs);
args.assets_path = assets_path_string.c_str();
args.icu_data_path = icu_path_string.c_str();
args.command_line_argc = static_cast<int>(argv.size());
args.command_line_argv = &argv[0];
args.platform_message_callback = EngineOnFlutterPlatformMessage;
args.custom_task_runners = &task_runners;
if (FlutterEngineRunsAOTCompiledDartCode()) {
engine_state->aot_data = LoadAotData(aot_library_path);
if (!engine_state->aot_data) {
std::cerr << "Unable to start engine without AOT data." << std::endl;
return false;
}
args.aot_data = engine_state->aot_data.get();
}
FLUTTER_API_SYMBOL(FlutterEngine) engine = nullptr;
auto result = FlutterEngineRun(FLUTTER_ENGINE_VERSION, &config, &args,
engine_state, &engine);
if (result != kSuccess || engine == nullptr) {
std::cerr << "Failed to start Flutter engine: error " << result
<< std::endl;
return false;
}
engine_state->flutter_engine = engine;
return true;
}
// Passes locale information to the Flutter engine.
static void SetUpLocales(FlutterDesktopEngineState* state) {
std::vector<flutter::LanguageInfo> languages =
flutter::GetPreferredLanguageInfo();
std::vector<FlutterLocale> flutter_locales =
flutter::ConvertToFlutterLocale(languages);
// Convert the locale list to the locale pointer list that must be provided.
std::vector<const FlutterLocale*> flutter_locale_list;
flutter_locale_list.reserve(flutter_locales.size());
std::transform(flutter_locales.begin(), flutter_locales.end(),
std::back_inserter(flutter_locale_list),
[](const auto& arg) -> const auto* { return &arg; });
FlutterEngineResult result = FlutterEngineUpdateLocales(
state->flutter_engine, flutter_locale_list.data(),
flutter_locale_list.size());
if (result != kSuccess) {
std::cerr << "Failed to set up Flutter locales." << std::endl;
}
}
// Populates |state|'s helper object fields that are common to normal and
// headless mode.
//
// Window is optional; if present it will be provided to the created
// PlatformHandler.
static void SetUpCommonEngineState(FlutterDesktopEngineState* state,
GLFWwindow* window) {
// Messaging.
state->messenger = FlutterDesktopMessengerReferenceOwner(
FlutterDesktopMessengerAddRef(new FlutterDesktopMessenger()),
&FlutterDesktopMessengerRelease);
state->messenger->SetEngine(state);
state->message_dispatcher =
std::make_unique<flutter::IncomingMessageDispatcher>(
state->messenger.get());
// Plugins.
state->plugin_registrar = std::make_unique<FlutterDesktopPluginRegistrar>();
state->plugin_registrar->engine = state;
state->internal_plugin_registrar =
std::make_unique<flutter::PluginRegistrar>(state->plugin_registrar.get());
// System channel handler.
state->platform_handler = std::make_unique<flutter::PlatformHandler>(
state->internal_plugin_registrar->messenger(), window);
SetUpLocales(state);
}
bool FlutterDesktopInit() {
// Before making any GLFW calls, set up a logging error handler.
glfwSetErrorCallback(GLFWErrorCallback);
return glfwInit();
}
void FlutterDesktopTerminate() {
glfwTerminate();
}
FlutterDesktopWindowControllerRef FlutterDesktopCreateWindow(
const FlutterDesktopWindowProperties& window_properties,
const FlutterDesktopEngineProperties& engine_properties) {
auto state = std::make_unique<FlutterDesktopWindowControllerState>();
// Create the window, and set the state as its user data.
if (window_properties.prevent_resize) {
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
}
#if defined(__linux__)
glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API);
#endif
state->window = UniqueGLFWwindowPtr(
glfwCreateWindow(window_properties.width, window_properties.height,
window_properties.title, NULL, NULL),
glfwDestroyWindow);
glfwDefaultWindowHints();
GLFWwindow* window = state->window.get();
if (window == nullptr) {
return nullptr;
}
GLFWClearCanvas(window);
glfwSetWindowUserPointer(window, state.get());
// Create the share window before starting the engine, since it may call
// EngineMakeResourceContextCurrent immediately.
state->resource_window = CreateShareWindowForWindow(window);
state->engine = std::make_unique<FlutterDesktopEngineState>();
state->engine->window_controller = state.get();
// Create an event loop for the window. It is not running yet.
auto event_loop = std::make_unique<flutter::GLFWEventLoop>(
std::this_thread::get_id(), // main GLFW thread
[engine_state = state->engine.get()](const auto* task) {
if (FlutterEngineRunTask(engine_state->flutter_engine, task) !=
kSuccess) {
std::cerr << "Could not post an engine task." << std::endl;
}
});
// Start the engine.
if (!RunFlutterEngine(state->engine.get(), engine_properties,
std::move(event_loop))) {
return nullptr;
}
SetUpCommonEngineState(state->engine.get(), window);
state->window_wrapper = std::make_unique<FlutterDesktopWindow>();
state->window_wrapper->window = window;
// Set up the keyboard handlers
auto internal_plugin_messenger =
state->engine->internal_plugin_registrar->messenger();
state->keyboard_hook_handlers.push_back(
std::make_unique<flutter::KeyEventHandler>(internal_plugin_messenger));
state->keyboard_hook_handlers.push_back(
std::make_unique<flutter::TextInputPlugin>(internal_plugin_messenger));
// Trigger an initial size callback to send size information to Flutter.
state->monitor_screen_coordinates_per_inch = GetScreenCoordinatesPerInch();
int width_px, height_px;
glfwGetFramebufferSize(window, &width_px, &height_px);
GLFWFramebufferSizeCallback(window, width_px, height_px);
// Set up GLFW callbacks for the window.
glfwSetFramebufferSizeCallback(window, GLFWFramebufferSizeCallback);
glfwSetWindowRefreshCallback(window, GLFWWindowRefreshCallback);
GLFWAssignEventCallbacks(window);
return state.release();
}
void FlutterDesktopDestroyWindow(FlutterDesktopWindowControllerRef controller) {
controller->engine->messenger->SetEngine(nullptr);
FlutterDesktopPluginRegistrarRef registrar =
controller->engine->plugin_registrar.get();
if (registrar->destruction_handler) {
registrar->destruction_handler(registrar);
}
FlutterEngineShutdown(controller->engine->flutter_engine);
delete controller;
}
void FlutterDesktopWindowSetHoverEnabled(FlutterDesktopWindowRef flutter_window,
bool enabled) {
flutter_window->hover_tracking_enabled = enabled;
SetHoverCallbacksEnabled(flutter_window->window, enabled);
}
void FlutterDesktopWindowSetTitle(FlutterDesktopWindowRef flutter_window,
const char* title) {
GLFWwindow* window = flutter_window->window;
glfwSetWindowTitle(window, title);
}
void FlutterDesktopWindowSetIcon(FlutterDesktopWindowRef flutter_window,
uint8_t* pixel_data,
int width,
int height) {
GLFWimage image = {width, height, static_cast<unsigned char*>(pixel_data)};
glfwSetWindowIcon(flutter_window->window, pixel_data ? 1 : 0, &image);
}
void FlutterDesktopWindowGetFrame(FlutterDesktopWindowRef flutter_window,
int* x,
int* y,
int* width,
int* height) {
glfwGetWindowPos(flutter_window->window, x, y);
glfwGetWindowSize(flutter_window->window, width, height);
// The above gives content area size and position; adjust for the window
// decoration to give actual window frame.
int frame_left, frame_top, frame_right, frame_bottom;
glfwGetWindowFrameSize(flutter_window->window, &frame_left, &frame_top,
&frame_right, &frame_bottom);
if (x) {
*x -= frame_left;
}
if (y) {
*y -= frame_top;
}
if (width) {
*width += frame_left + frame_right;
}
if (height) {
*height += frame_top + frame_bottom;
}
}
void FlutterDesktopWindowSetFrame(FlutterDesktopWindowRef flutter_window,
int x,
int y,
int width,
int height) {
// Get the window decoration sizes to adjust, since the GLFW setters take
// content position and size.
int frame_left, frame_top, frame_right, frame_bottom;
glfwGetWindowFrameSize(flutter_window->window, &frame_left, &frame_top,
&frame_right, &frame_bottom);
glfwSetWindowPos(flutter_window->window, x + frame_left, y + frame_top);
glfwSetWindowSize(flutter_window->window, width - frame_left - frame_right,
height - frame_top - frame_bottom);
}
double FlutterDesktopWindowGetScaleFactor(
FlutterDesktopWindowRef flutter_window) {
return flutter_window->pixels_per_screen_coordinate;
}
void FlutterDesktopWindowSetPixelRatioOverride(
FlutterDesktopWindowRef flutter_window,
double pixel_ratio) {
flutter_window->pixel_ratio_override = pixel_ratio;
// Send a metrics update using the new pixel ratio.
int width_px, height_px;
glfwGetFramebufferSize(flutter_window->window, &width_px, &height_px);
if (width_px > 0 && height_px > 0) {
auto* controller = GetWindowController(flutter_window->window);
SendWindowMetrics(controller, width_px, height_px);
}
}
void FlutterDesktopWindowSetSizeLimits(FlutterDesktopWindowRef flutter_window,
FlutterDesktopSize minimum_size,
FlutterDesktopSize maximum_size) {
glfwSetWindowSizeLimits(flutter_window->window, minimum_size.width,
minimum_size.height, maximum_size.width,
maximum_size.height);
}
bool FlutterDesktopRunWindowEventLoopWithTimeout(
FlutterDesktopWindowControllerRef controller,
uint32_t timeout_milliseconds) {
FlutterDesktopRunEngineEventLoopWithTimeout(controller->engine.get(),
timeout_milliseconds);
return !glfwWindowShouldClose(controller->window.get());
}
FlutterDesktopWindowRef FlutterDesktopGetWindow(
FlutterDesktopWindowControllerRef controller) {
// Currently, one registrar acts as the registrar for all plugins, so the
// name is ignored. It is part of the API to reduce churn in the future when
// aligning more closely with the Flutter registrar system.
return controller->window_wrapper.get();
}
FlutterDesktopEngineRef FlutterDesktopGetEngine(
FlutterDesktopWindowControllerRef controller) {
return controller->engine.get();
}
FlutterDesktopPluginRegistrarRef FlutterDesktopGetPluginRegistrar(
FlutterDesktopEngineRef engine,
const char* plugin_name) {
// Currently, one registrar acts as the registrar for all plugins, so the
// name is ignored. It is part of the API to reduce churn in the future when
// aligning more closely with the Flutter registrar system.
return engine->plugin_registrar.get();
}
FlutterDesktopEngineRef FlutterDesktopRunEngine(
const FlutterDesktopEngineProperties& properties) {
auto engine_state = std::make_unique<FlutterDesktopEngineState>();
auto event_loop = std::make_unique<flutter::HeadlessEventLoop>(
std::this_thread::get_id(),
[state = engine_state.get()](const auto* task) {
if (FlutterEngineRunTask(state->flutter_engine, task) != kSuccess) {
std::cerr << "Could not post an engine task." << std::endl;
}
});
if (!RunFlutterEngine(engine_state.get(), properties,
std::move(event_loop))) {
return nullptr;
}
SetUpCommonEngineState(engine_state.get(), nullptr);
return engine_state.release();
}
void FlutterDesktopRunEngineEventLoopWithTimeout(
FlutterDesktopEngineRef engine,
uint32_t timeout_milliseconds) {
std::chrono::nanoseconds wait_duration =
timeout_milliseconds == 0
? std::chrono::nanoseconds::max()
: std::chrono::milliseconds(timeout_milliseconds);
engine->event_loop->WaitForEvents(wait_duration);
}
bool FlutterDesktopShutDownEngine(FlutterDesktopEngineRef engine) {
auto result = FlutterEngineShutdown(engine->flutter_engine);
delete engine;
return (result == kSuccess);
}
void FlutterDesktopPluginRegistrarEnableInputBlocking(
FlutterDesktopPluginRegistrarRef registrar,
const char* channel) {
registrar->engine->message_dispatcher->EnableInputBlockingForChannel(channel);
}
FlutterDesktopMessengerRef FlutterDesktopPluginRegistrarGetMessenger(
FlutterDesktopPluginRegistrarRef registrar) {
return registrar->engine->messenger.get();
}
void FlutterDesktopPluginRegistrarSetDestructionHandler(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopOnPluginRegistrarDestroyed callback) {
registrar->destruction_handler = callback;
}
FlutterDesktopWindowRef FlutterDesktopPluginRegistrarGetWindow(
FlutterDesktopPluginRegistrarRef registrar) {
FlutterDesktopWindowControllerState* controller =
registrar->engine->window_controller;
if (!controller) {
return nullptr;
}
return controller->window_wrapper.get();
}
bool FlutterDesktopMessengerSendWithReply(FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size,
const FlutterDesktopBinaryReply reply,
void* user_data) {
FlutterPlatformMessageResponseHandle* response_handle = nullptr;
if (reply != nullptr && user_data != nullptr) {
FlutterEngineResult result = FlutterPlatformMessageCreateResponseHandle(
messenger->GetEngine()->flutter_engine, reply, user_data,
&response_handle);
if (result != kSuccess) {
std::cout << "Failed to create response handle\n";
return false;
}
}
FlutterPlatformMessage platform_message = {
sizeof(FlutterPlatformMessage),
channel,
message,
message_size,
response_handle,
};
FlutterEngineResult message_result = FlutterEngineSendPlatformMessage(
messenger->GetEngine()->flutter_engine, &platform_message);
if (response_handle != nullptr) {
FlutterPlatformMessageReleaseResponseHandle(
messenger->GetEngine()->flutter_engine, response_handle);
}
return message_result == kSuccess;
}
bool FlutterDesktopMessengerSend(FlutterDesktopMessengerRef messenger,
const char* channel,
const uint8_t* message,
const size_t message_size) {
return FlutterDesktopMessengerSendWithReply(messenger, channel, message,
message_size, nullptr, nullptr);
}
void FlutterDesktopMessengerSendResponse(
FlutterDesktopMessengerRef messenger,
const FlutterDesktopMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {
FlutterEngineSendPlatformMessageResponse(
messenger->GetEngine()->flutter_engine, handle, data, data_length);
}
void FlutterDesktopMessengerSetCallback(FlutterDesktopMessengerRef messenger,
const char* channel,
FlutterDesktopMessageCallback callback,
void* user_data) {
messenger->GetEngine()->message_dispatcher->SetMessageCallback(
channel, callback, user_data);
}
FlutterDesktopTextureRegistrarRef FlutterDesktopRegistrarGetTextureRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
std::cerr << "GLFW Texture support is not implemented yet." << std::endl;
return nullptr;
}
int64_t FlutterDesktopTextureRegistrarRegisterExternalTexture(
FlutterDesktopTextureRegistrarRef texture_registrar,
const FlutterDesktopTextureInfo* texture_info) {
std::cerr << "GLFW Texture support is not implemented yet." << std::endl;
return -1;
}
void FlutterDesktopTextureRegistrarUnregisterExternalTexture(
FlutterDesktopTextureRegistrarRef texture_registrar,
int64_t texture_id,
void (*callback)(void* user_data),
void* user_data) {
std::cerr << "GLFW Texture support is not implemented yet." << std::endl;
}
bool FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable(
FlutterDesktopTextureRegistrarRef texture_registrar,
int64_t texture_id) {
std::cerr << "GLFW Texture support is not implemented yet." << std::endl;
return false;
}
| engine/shell/platform/glfw/flutter_glfw.cc/0 | {
"file_path": "engine/shell/platform/glfw/flutter_glfw.cc",
"repo_id": "engine",
"token_count": 16453
} | 365 |
# 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.
assert(is_linux)
import("//flutter/build/zip_bundle.gni")
import("//flutter/shell/platform/glfw/config.gni")
import("//flutter/testing/testing.gni")
group("linux") {
deps = [
":flutter_linux_gtk",
":publish_headers_linux",
]
if (build_glfw_shell) {
deps += [
":flutter_linux_glfw",
"//flutter/shell/platform/glfw:publish_headers_glfw",
"//flutter/shell/platform/glfw/client_wrapper:publish_wrapper_glfw",
]
}
}
# Temporary workaround for the issue describe in
# https://github.com/flutter/flutter/issues/14509 and
# https://github.com/flutter/flutter/issues/14438
# Remove once the build infrastructure moves to Ubuntu 18.04 or newer, where
# the underlying issue is fixed.
config("disable_fatal_link_warnings") {
visibility = [ ":*" ]
ldflags = [ "-Wl,--no-fatal-warnings" ]
}
if (build_glfw_shell) {
shared_library("flutter_linux_glfw") {
deps = [ "//flutter/shell/platform/glfw:flutter_glfw" ]
configs += [ ":disable_fatal_link_warnings" ]
public_configs = [ "//flutter:config" ]
}
}
_public_headers = [
"public/flutter_linux/fl_basic_message_channel.h",
"public/flutter_linux/fl_binary_codec.h",
"public/flutter_linux/fl_binary_messenger.h",
"public/flutter_linux/fl_dart_project.h",
"public/flutter_linux/fl_engine.h",
"public/flutter_linux/fl_event_channel.h",
"public/flutter_linux/fl_json_message_codec.h",
"public/flutter_linux/fl_json_method_codec.h",
"public/flutter_linux/fl_message_codec.h",
"public/flutter_linux/fl_method_call.h",
"public/flutter_linux/fl_method_channel.h",
"public/flutter_linux/fl_method_codec.h",
"public/flutter_linux/fl_method_response.h",
"public/flutter_linux/fl_pixel_buffer_texture.h",
"public/flutter_linux/fl_plugin_registrar.h",
"public/flutter_linux/fl_plugin_registry.h",
"public/flutter_linux/fl_standard_message_codec.h",
"public/flutter_linux/fl_standard_method_codec.h",
"public/flutter_linux/fl_string_codec.h",
"public/flutter_linux/fl_texture.h",
"public/flutter_linux/fl_texture_gl.h",
"public/flutter_linux/fl_texture_registrar.h",
"public/flutter_linux/fl_value.h",
"public/flutter_linux/fl_view.h",
"public/flutter_linux/flutter_linux.h",
]
config("relative_flutter_linux_headers") {
include_dirs = [ "public" ]
}
source_set("flutter_linux_sources") {
public = _public_headers + [
"fl_binary_messenger_private.h",
"fl_dart_project_private.h",
"fl_engine_private.h",
"fl_keyboard_manager.h",
"fl_keyboard_view_delegate.h",
"fl_key_event.h",
"fl_key_responder.h",
"fl_key_channel_responder.h",
"fl_key_embedder_responder.h",
"fl_key_embedder_responder_private.h",
"fl_method_call_private.h",
"fl_method_channel_private.h",
"fl_method_codec_private.h",
"fl_plugin_registrar_private.h",
"key_mapping.h",
]
configs += [ "//flutter/shell/platform/linux/config:gtk" ]
sources = [
"fl_accessible_node.cc",
"fl_accessible_text_field.cc",
"fl_backing_store_provider.cc",
"fl_basic_message_channel.cc",
"fl_binary_codec.cc",
"fl_binary_messenger.cc",
"fl_dart_project.cc",
"fl_engine.cc",
"fl_event_channel.cc",
"fl_gnome_settings.cc",
"fl_json_message_codec.cc",
"fl_json_method_codec.cc",
"fl_key_channel_responder.cc",
"fl_key_embedder_responder.cc",
"fl_key_event.cc",
"fl_key_responder.cc",
"fl_keyboard_manager.cc",
"fl_keyboard_view_delegate.cc",
"fl_message_codec.cc",
"fl_method_call.cc",
"fl_method_channel.cc",
"fl_method_codec.cc",
"fl_method_response.cc",
"fl_mouse_cursor_plugin.cc",
"fl_pixel_buffer_texture.cc",
"fl_platform_plugin.cc",
"fl_plugin_registrar.cc",
"fl_plugin_registry.cc",
"fl_renderer.cc",
"fl_renderer_gdk.cc",
"fl_renderer_headless.cc",
"fl_scrolling_manager.cc",
"fl_scrolling_view_delegate.cc",
"fl_settings.cc",
"fl_settings_plugin.cc",
"fl_settings_portal.cc",
"fl_standard_message_codec.cc",
"fl_standard_method_codec.cc",
"fl_string_codec.cc",
"fl_task_runner.cc",
"fl_task_runner.h",
"fl_text_input_plugin.cc",
"fl_text_input_view_delegate.cc",
"fl_texture.cc",
"fl_texture_gl.cc",
"fl_texture_registrar.cc",
"fl_value.cc",
"fl_view.cc",
"fl_view_accessible.cc",
"key_mapping.g.cc",
]
# Set flag to stop headers being directly included (library users should not do this)
defines = [
"FLUTTER_LINUX_COMPILATION",
"FLUTTER_ENGINE_NO_PROTOTYPES",
]
deps = [
"//flutter/fml",
"//flutter/shell/platform/common:common_cpp_enums",
"//flutter/shell/platform/common:common_cpp_input",
"//flutter/shell/platform/common:common_cpp_switches",
"//flutter/shell/platform/embedder:embedder_headers",
"//flutter/third_party/rapidjson",
]
}
source_set("flutter_linux") {
configs += [
"//flutter/shell/platform/linux/config:gtk",
"//flutter/shell/platform/linux/config:epoxy",
]
defines = [ "FLUTTER_ENGINE_NO_PROTOTYPES" ]
public_deps = [ ":flutter_linux_sources" ]
deps = [ "//flutter/shell/platform/embedder:embedder_as_internal_library" ]
}
test_fixtures("flutter_linux_fixtures") {
fixtures = []
}
copy("flutter_linux_gschemas") {
testonly = true
sources = [ "testing/gschemas/ubuntu-20.04.compiled" ]
outputs = [ "$target_gen_dir/assets/{{source_name_part}}/gschemas.compiled" ]
}
executable("flutter_linux_unittests") {
testonly = true
sources = [
"fl_accessible_node_test.cc",
"fl_accessible_text_field_test.cc",
"fl_basic_message_channel_test.cc",
"fl_binary_codec_test.cc",
"fl_binary_messenger_test.cc",
"fl_dart_project_test.cc",
"fl_engine_test.cc",
"fl_event_channel_test.cc",
"fl_gnome_settings_test.cc",
"fl_json_message_codec_test.cc",
"fl_json_method_codec_test.cc",
"fl_key_channel_responder_test.cc",
"fl_key_embedder_responder_test.cc",
"fl_keyboard_manager_test.cc",
"fl_message_codec_test.cc",
"fl_method_channel_test.cc",
"fl_method_codec_test.cc",
"fl_method_response_test.cc",
"fl_pixel_buffer_texture_test.cc",
"fl_platform_plugin_test.cc",
"fl_plugin_registrar_test.cc",
"fl_scrolling_manager_test.cc",
"fl_settings_plugin_test.cc",
"fl_settings_portal_test.cc",
"fl_standard_message_codec_test.cc",
"fl_standard_method_codec_test.cc",
"fl_string_codec_test.cc",
"fl_text_input_plugin_test.cc",
"fl_texture_gl_test.cc",
"fl_texture_registrar_test.cc",
"fl_value_test.cc",
"fl_view_accessible_test.cc",
"fl_view_test.cc",
"key_mapping_test.cc",
"testing/fl_test.cc",
"testing/fl_test_gtk_logs.cc",
"testing/fl_test_gtk_logs.h",
"testing/mock_binary_messenger.cc",
"testing/mock_binary_messenger_response_handle.cc",
"testing/mock_engine.cc",
"testing/mock_epoxy.cc",
"testing/mock_im_context.cc",
"testing/mock_plugin_registrar.cc",
"testing/mock_renderer.cc",
"testing/mock_settings.cc",
"testing/mock_signal_handler.cc",
"testing/mock_text_input_plugin.cc",
"testing/mock_text_input_view_delegate.cc",
"testing/mock_texture_registrar.cc",
]
public_configs = [ "//flutter:config" ]
configs += [
"//flutter/shell/platform/linux/config:gtk",
"//flutter/shell/platform/linux/config:epoxy",
]
defines = [
"FLUTTER_ENGINE_NO_PROTOTYPES",
# Set flag to allow public headers to be directly included
# (library users should not do this)
"FLUTTER_LINUX_COMPILATION",
]
deps = [
":flutter_linux_fixtures",
":flutter_linux_gschemas",
":flutter_linux_sources",
"//flutter/runtime:libdart",
"//flutter/shell/platform/common:common_cpp_enums",
"//flutter/shell/platform/embedder:embedder_headers",
"//flutter/shell/platform/embedder:embedder_test_utils",
"//flutter/testing",
]
}
shared_library("flutter_linux_gtk") {
deps = [ ":flutter_linux" ]
ldflags = [ "-Wl,-rpath,\$ORIGIN" ]
public_configs = [ "//flutter:config" ]
}
copy("publish_headers_linux") {
sources = _public_headers
outputs = [ "$root_out_dir/flutter_linux/{{source_file_part}}" ]
}
zip_bundle("flutter_gtk") {
prefix = "$full_target_platform_name-$flutter_runtime_mode/"
output = "${prefix}${full_target_platform_name}-flutter-gtk.zip"
deps = [
":flutter_linux_gtk",
":publish_headers_linux",
"$dart_src/runtime/bin:gen_snapshot",
]
sources = get_target_outputs(":publish_headers_linux")
tmp_files = []
foreach(source, sources) {
tmp_files += [
{
source = source
destination = rebase_path(source, "$root_build_dir")
},
]
}
tmp_files += [
{
source = "$root_build_dir/libflutter_${host_os}_gtk.so"
destination = "libflutter_${host_os}_gtk.so"
},
{
source = "$root_build_dir/gen_snapshot"
destination = "gen_snapshot"
},
]
files = tmp_files
}
| engine/shell/platform/linux/BUILD.gn/0 | {
"file_path": "engine/shell/platform/linux/BUILD.gn",
"repo_id": "engine",
"token_count": 4113
} | 366 |
// 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.
// Included first as it collides with the X11 headers.
#include "gtest/gtest.h"
#include <pthread.h>
#include <cstring>
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/linux/fl_binary_messenger_private.h"
#include "flutter/shell/platform/linux/fl_engine_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "flutter/shell/platform/linux/testing/mock_binary_messenger_response_handle.h"
#include "flutter/shell/platform/linux/testing/mock_renderer.h"
G_DECLARE_FINAL_TYPE(FlFakeBinaryMessenger,
fl_fake_binary_messenger,
FL,
FAKE_BINARY_MESSENGER,
GObject)
struct _FlFakeBinaryMessenger {
GObject parent_instance;
GMainLoop* loop;
GAsyncReadyCallback send_callback;
gpointer send_callback_user_data;
FlBinaryMessengerMessageHandler message_handler;
gpointer message_handler_user_data;
};
static void fl_fake_binary_messenger_iface_init(
FlBinaryMessengerInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlFakeBinaryMessenger,
fl_fake_binary_messenger,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_binary_messenger_get_type(),
fl_fake_binary_messenger_iface_init))
static void fl_fake_binary_messenger_class_init(
FlFakeBinaryMessengerClass* klass) {}
static gboolean send_message_cb(gpointer user_data) {
FlFakeBinaryMessenger* self = FL_FAKE_BINARY_MESSENGER(user_data);
const char* text = "Marco!";
g_autoptr(GBytes) message = g_bytes_new(text, strlen(text));
self->message_handler(FL_BINARY_MESSENGER(self), "CHANNEL", message,
FL_BINARY_MESSENGER_RESPONSE_HANDLE(
fl_mock_binary_messenger_response_handle_new()),
self->message_handler_user_data);
return FALSE;
}
static void set_message_handler_on_channel(
FlBinaryMessenger* messenger,
const gchar* channel,
FlBinaryMessengerMessageHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
FlFakeBinaryMessenger* self = FL_FAKE_BINARY_MESSENGER(messenger);
EXPECT_STREQ(channel, "CHANNEL");
// Send message.
self->message_handler = handler;
self->message_handler_user_data = user_data;
g_idle_add(send_message_cb, messenger);
}
static gboolean send_response(FlBinaryMessenger* messenger,
FlBinaryMessengerResponseHandle* response_handle,
GBytes* response,
GError** error) {
FlFakeBinaryMessenger* self = FL_FAKE_BINARY_MESSENGER(messenger);
EXPECT_TRUE(FL_IS_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle));
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(response, nullptr)),
g_bytes_get_size(response));
EXPECT_STREQ(text, "Polo!");
g_main_loop_quit(self->loop);
return TRUE;
}
static gboolean send_ready_cb(gpointer user_data) {
FlFakeBinaryMessenger* self = FL_FAKE_BINARY_MESSENGER(user_data);
self->send_callback(G_OBJECT(self), NULL, self->send_callback_user_data);
return FALSE;
}
static void send_on_channel(FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data) {
FlFakeBinaryMessenger* self = FL_FAKE_BINARY_MESSENGER(messenger);
EXPECT_STREQ(channel, "CHANNEL");
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
EXPECT_STREQ(text, "Marco!");
// Send response.
self->send_callback = callback;
self->send_callback_user_data = user_data;
g_idle_add(send_ready_cb, messenger);
}
static GBytes* send_on_channel_finish(FlBinaryMessenger* messenger,
GAsyncResult* result,
GError** error) {
const char* text = "Polo!";
return g_bytes_new(text, strlen(text));
}
static void resize_channel(FlBinaryMessenger* messenger,
const gchar* channel,
int64_t new_size) {
// Fake implementation. Do nothing.
}
static void set_warns_on_channel_overflow(FlBinaryMessenger* messenger,
const gchar* channel,
bool warns) {
// Fake implementation. Do nothing.
}
static void fl_fake_binary_messenger_iface_init(
FlBinaryMessengerInterface* iface) {
iface->set_message_handler_on_channel = set_message_handler_on_channel;
iface->send_response = send_response;
iface->send_on_channel = send_on_channel;
iface->send_on_channel_finish = send_on_channel_finish;
iface->resize_channel = resize_channel;
iface->set_warns_on_channel_overflow = set_warns_on_channel_overflow;
}
static void fl_fake_binary_messenger_init(FlFakeBinaryMessenger* self) {}
static FlBinaryMessenger* fl_fake_binary_messenger_new(GMainLoop* loop) {
FlFakeBinaryMessenger* self = FL_FAKE_BINARY_MESSENGER(
g_object_new(fl_fake_binary_messenger_get_type(), NULL));
self->loop = loop;
return FL_BINARY_MESSENGER(self);
}
// Called when the message response is received in the FakeMessengerSend test.
static void fake_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_binary_messenger_send_on_channel_finish(
FL_BINARY_MESSENGER(object), result, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
EXPECT_STREQ(text, "Polo!");
g_main_loop_quit(static_cast<GMainLoop*>(user_data));
}
// Checks can make a fake messenger and send a message.
TEST(FlBinaryMessengerTest, FakeMessengerSend) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlBinaryMessenger) messenger = fl_fake_binary_messenger_new(loop);
EXPECT_TRUE(FL_IS_FAKE_BINARY_MESSENGER(messenger));
const char* text = "Marco!";
g_autoptr(GBytes) message = g_bytes_new(text, strlen(text));
fl_binary_messenger_send_on_channel(messenger, "CHANNEL", message, nullptr,
fake_response_cb, loop);
// Blocks here until fake_response_cb is called.
g_main_loop_run(loop);
}
// Called when a message is received in the FakeMessengerReceive test.
static void fake_message_cb(FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
FlBinaryMessengerResponseHandle* response_handle,
gpointer user_data) {
EXPECT_STREQ(channel, "CHANNEL");
EXPECT_NE(message, nullptr);
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
EXPECT_STREQ(text, "Marco!");
const char* response_text = "Polo!";
g_autoptr(GBytes) response =
g_bytes_new(response_text, strlen(response_text));
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_binary_messenger_send_response(messenger, response_handle,
response, &error));
EXPECT_EQ(error, nullptr);
}
// Checks can make a fake messenger and receive a message.
TEST(FlBinaryMessengerTest, FakeMessengerReceive) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlBinaryMessenger) messenger = fl_fake_binary_messenger_new(loop);
EXPECT_TRUE(FL_IS_FAKE_BINARY_MESSENGER(messenger));
fl_binary_messenger_set_message_handler_on_channel(
messenger, "CHANNEL", fake_message_cb, nullptr, nullptr);
// Blocks here until response is received in fake messenger.
g_main_loop_run(loop);
}
// Checks sending nullptr for a message works.
TEST(FlBinaryMessengerTest, SendNullptrMessage) {
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
fl_binary_messenger_send_on_channel(messenger, "test/echo", nullptr, nullptr,
nullptr, nullptr);
}
// Checks sending a zero length message works.
TEST(FlBinaryMessengerTest, SendEmptyMessage) {
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
g_autoptr(GBytes) message = g_bytes_new(nullptr, 0);
fl_binary_messenger_send_on_channel(messenger, "test/echo", message, nullptr,
nullptr, nullptr);
}
// Called when the message response is received in the SendMessage test.
static void echo_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_binary_messenger_send_on_channel_finish(
FL_BINARY_MESSENGER(object), result, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
EXPECT_STREQ(text, "Hello World!");
g_main_loop_quit(static_cast<GMainLoop*>(user_data));
}
// Checks sending a message works.
TEST(FlBinaryMessengerTest, SendMessage) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
const char* text = "Hello World!";
g_autoptr(GBytes) message = g_bytes_new(text, strlen(text));
fl_binary_messenger_send_on_channel(messenger, "test/echo", message, nullptr,
echo_response_cb, loop);
// Blocks here until echo_response_cb is called.
g_main_loop_run(loop);
}
// Called when the message response is received in the NullptrResponse test.
static void nullptr_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_binary_messenger_send_on_channel_finish(
FL_BINARY_MESSENGER(object), result, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
EXPECT_EQ(g_bytes_get_size(message), static_cast<gsize>(0));
g_main_loop_quit(static_cast<GMainLoop*>(user_data));
}
// Checks the engine returning a nullptr message work.
TEST(FlBinaryMessengerTest, NullptrResponse) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
const char* text = "Hello World!";
g_autoptr(GBytes) message = g_bytes_new(text, strlen(text));
fl_binary_messenger_send_on_channel(messenger, "test/nullptr-response",
message, nullptr, nullptr_response_cb,
loop);
// Blocks here until nullptr_response_cb is called.
g_main_loop_run(loop);
}
// Called when the message response is received in the SendFailure test.
static void failure_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_binary_messenger_send_on_channel_finish(
FL_BINARY_MESSENGER(object), result, &error);
EXPECT_EQ(message, nullptr);
EXPECT_NE(error, nullptr);
g_main_loop_quit(static_cast<GMainLoop*>(user_data));
}
// Checks the engine reporting a send failure is handled.
TEST(FlBinaryMessengerTest, SendFailure) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
fl_binary_messenger_send_on_channel(messenger, "test/failure", nullptr,
nullptr, failure_response_cb, loop);
// Blocks here until failure_response_cb is called.
g_main_loop_run(loop);
}
// Called when a message is received from the engine in the ReceiveMessage test.
static void message_cb(FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
FlBinaryMessengerResponseHandle* response_handle,
gpointer user_data) {
EXPECT_NE(message, nullptr);
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
EXPECT_STREQ(text, "Marco!");
const char* response_text = "Polo!";
g_autoptr(GBytes) response =
g_bytes_new(response_text, strlen(response_text));
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_binary_messenger_send_response(messenger, response_handle,
response, &error));
EXPECT_EQ(error, nullptr);
}
// Called when a the test engine notifies us what response we sent in the
// ReceiveMessage test.
static void response_cb(FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
FlBinaryMessengerResponseHandle* response_handle,
gpointer user_data) {
EXPECT_NE(message, nullptr);
g_autofree gchar* text =
g_strndup(static_cast<const gchar*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
EXPECT_STREQ(text, "Polo!");
fl_binary_messenger_send_response(messenger, response_handle, nullptr,
nullptr);
g_main_loop_quit(static_cast<GMainLoop*>(user_data));
}
// Checks the shell able to receive and respond to messages from the engine.
TEST(FlBinaryMessengerTest, ReceiveMessage) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
// Listen for messages from the engine.
fl_binary_messenger_set_message_handler_on_channel(
messenger, "test/messages", message_cb, nullptr, nullptr);
// Listen for response from the engine.
fl_binary_messenger_set_message_handler_on_channel(
messenger, "test/responses", response_cb, loop, nullptr);
// Trigger the engine to send a message.
const char* text = "Marco!";
g_autoptr(GBytes) message = g_bytes_new(text, strlen(text));
fl_binary_messenger_send_on_channel(messenger, "test/send-message", message,
nullptr, nullptr, nullptr);
// Blocks here until response_cb is called.
g_main_loop_run(loop);
}
// MOCK_ENGINE_PROC is leaky by design.
// NOLINTBEGIN(clang-analyzer-core.StackAddressEscape)
// Checks if the 'resize' command is sent and is well-formed.
TEST(FlBinaryMessengerTest, ResizeChannel) {
g_autoptr(FlEngine) engine = make_mock_engine();
FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);
bool called = false;
FlutterEngineSendPlatformMessageFnPtr old_handler =
embedder_api->SendPlatformMessage;
embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage,
([&called, old_handler](auto engine,
const FlutterPlatformMessage* message) {
// Expect to receive a message on the "control" channel.
if (strcmp(message->channel, "dev.flutter/channel-buffers") != 0) {
return old_handler(engine, message);
}
called = true;
// The expected content was created from the following Dart code:
// MethodCall call = MethodCall('resize', ['flutter/test',3]);
// StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List();
const int expected_message_size = 29;
EXPECT_EQ(message->message_size,
static_cast<size_t>(expected_message_size));
int expected[expected_message_size] = {
7, 6, 114, 101, 115, 105, 122, 101, 12, 2,
7, 12, 102, 108, 117, 116, 116, 101, 114, 47,
116, 101, 115, 116, 3, 3, 0, 0, 0};
for (size_t i = 0; i < expected_message_size; i++) {
EXPECT_EQ(message->message[i], expected[i]);
}
return kSuccess;
}));
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_engine_start(engine, &error));
EXPECT_EQ(error, nullptr);
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
fl_binary_messenger_resize_channel(messenger, "flutter/test", 3);
EXPECT_TRUE(called);
}
// Checks if the 'overflow' command is sent and is well-formed.
TEST(FlBinaryMessengerTest, WarnsOnOverflowChannel) {
g_autoptr(FlEngine) engine = make_mock_engine();
FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);
bool called = false;
FlutterEngineSendPlatformMessageFnPtr old_handler =
embedder_api->SendPlatformMessage;
embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage,
([&called, old_handler](auto engine,
const FlutterPlatformMessage* message) {
// Expect to receive a message on the "control" channel.
if (strcmp(message->channel, "dev.flutter/channel-buffers") != 0) {
return old_handler(engine, message);
}
called = true;
// The expected content was created from the following Dart code:
// MethodCall call = MethodCall('overflow',['flutter/test', true]);
// StandardMethodCodec().encodeMethodCall(call).buffer.asUint8List();
const int expected_message_size = 27;
EXPECT_EQ(message->message_size,
static_cast<size_t>(expected_message_size));
int expected[expected_message_size] = {
7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 12,
102, 108, 117, 116, 116, 101, 114, 47, 116, 101, 115, 116, 1};
for (size_t i = 0; i < expected_message_size; i++) {
EXPECT_EQ(message->message[i], expected[i]);
}
return kSuccess;
}));
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_engine_start(engine, &error));
EXPECT_EQ(error, nullptr);
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
fl_binary_messenger_set_warns_on_channel_overflow(messenger, "flutter/test",
false);
EXPECT_TRUE(called);
}
static gboolean quit_main_loop_cb(gpointer user_data) {
g_main_loop_quit(static_cast<GMainLoop*>(user_data));
return FALSE;
}
// Checks if error returned when invoking a command on the control channel
// are handled.
TEST(FlBinaryMessengerTest, ControlChannelErrorResponse) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_engine_start(engine, &error));
EXPECT_EQ(error, nullptr);
FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);
bool called = false;
FlutterEngineSendPlatformMessageFnPtr old_handler =
embedder_api->SendPlatformMessage;
embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC(
SendPlatformMessage,
([&called, old_handler, loop](auto engine,
const FlutterPlatformMessage* message) {
// Expect to receive a message on the "control" channel.
if (strcmp(message->channel, "dev.flutter/channel-buffers") != 0) {
return old_handler(engine, message);
}
called = true;
// Register a callback to quit the main loop when binary messenger work
// ends.
g_idle_add(quit_main_loop_cb, loop);
// Simulates an internal error.
return kInvalidArguments;
}));
fl_binary_messenger_set_warns_on_channel_overflow(messenger, "flutter/test",
false);
EXPECT_TRUE(called);
// Blocks here until quit_main_loop_cb is called.
g_main_loop_run(loop);
}
// NOLINTEND(clang-analyzer-core.StackAddressEscape)
struct RespondsOnBackgroundThreadInfo {
FlBinaryMessenger* messenger;
FlBinaryMessengerResponseHandle* response_handle;
GMainLoop* loop;
};
static gboolean cleanup_responds_on_background_thread_info(gpointer user_data) {
RespondsOnBackgroundThreadInfo* info =
static_cast<RespondsOnBackgroundThreadInfo*>(user_data);
GMainLoop* loop = info->loop;
g_object_unref(info->messenger);
g_object_unref(info->response_handle);
free(info);
g_main_loop_quit(static_cast<GMainLoop*>(loop));
return G_SOURCE_REMOVE;
}
static void* response_from_thread_main(void* user_data) {
RespondsOnBackgroundThreadInfo* info =
static_cast<RespondsOnBackgroundThreadInfo*>(user_data);
fl_binary_messenger_send_response(info->messenger, info->response_handle,
nullptr, nullptr);
g_idle_add(cleanup_responds_on_background_thread_info, info);
return nullptr;
}
static void response_from_thread_cb(
FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
FlBinaryMessengerResponseHandle* response_handle,
gpointer user_data) {
EXPECT_NE(message, nullptr);
pthread_t thread;
RespondsOnBackgroundThreadInfo* info =
static_cast<RespondsOnBackgroundThreadInfo*>(
malloc(sizeof(RespondsOnBackgroundThreadInfo)));
info->messenger = FL_BINARY_MESSENGER(g_object_ref(messenger));
info->response_handle =
FL_BINARY_MESSENGER_RESPONSE_HANDLE(g_object_ref(response_handle));
info->loop = static_cast<GMainLoop*>(user_data);
EXPECT_EQ(0,
pthread_create(&thread, nullptr, &response_from_thread_main, info));
}
TEST(FlBinaryMessengerTest, RespondOnBackgroundThread) {
g_autoptr(GMainLoop) loop = g_main_loop_new(nullptr, 0);
g_autoptr(FlEngine) engine = make_mock_engine();
FlBinaryMessenger* messenger = fl_binary_messenger_new(engine);
// Listen for messages from the engine.
fl_binary_messenger_set_message_handler_on_channel(
messenger, "test/messages", message_cb, nullptr, nullptr);
// Listen for response from the engine.
fl_binary_messenger_set_message_handler_on_channel(
messenger, "test/responses", response_from_thread_cb, loop, nullptr);
// Trigger the engine to send a message.
const char* text = "Marco!";
g_autoptr(GBytes) message = g_bytes_new(text, strlen(text));
fl_binary_messenger_send_on_channel(messenger, "test/send-message", message,
nullptr, nullptr, nullptr);
// Blocks here until response_cb is called.
g_main_loop_run(loop);
}
static void kill_handler_notify_cb(gpointer was_called) {
*static_cast<gboolean*>(was_called) = TRUE;
}
TEST(FlBinaryMessengerTest, DeletingEngineClearsHandlers) {
FlEngine* engine = make_mock_engine();
g_autoptr(FlBinaryMessenger) messenger = fl_binary_messenger_new(engine);
gboolean was_killed = FALSE;
// Listen for messages from the engine.
fl_binary_messenger_set_message_handler_on_channel(messenger, "test/messages",
message_cb, &was_killed,
kill_handler_notify_cb);
g_clear_object(&engine);
ASSERT_TRUE(was_killed);
}
| engine/shell/platform/linux/fl_binary_messenger_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_binary_messenger_test.cc",
"repo_id": "engine",
"token_count": 10248
} | 367 |
// 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 "flutter/shell/platform/linux/fl_key_channel_responder.h"
#include <gtk/gtk.h>
#include <cinttypes>
#include "flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h"
static constexpr char kChannelName[] = "flutter/keyevent";
static constexpr char kTypeKey[] = "type";
static constexpr char kTypeValueUp[] = "keyup";
static constexpr char kTypeValueDown[] = "keydown";
static constexpr char kKeymapKey[] = "keymap";
static constexpr char kKeyCodeKey[] = "keyCode";
static constexpr char kScanCodeKey[] = "scanCode";
static constexpr char kModifiersKey[] = "modifiers";
static constexpr char kToolkitKey[] = "toolkit";
static constexpr char kSpecifiedLogicalKey[] = "specifiedLogicalKey";
static constexpr char kUnicodeScalarValuesKey[] = "unicodeScalarValues";
static constexpr char kGtkToolkit[] = "gtk";
static constexpr char kLinuxKeymap[] = "linux";
/* Declare and define FlKeyChannelUserData */
/**
* FlKeyChannelUserData:
* The user_data used when #FlKeyChannelResponder sends message through the
* channel.
*/
G_DECLARE_FINAL_TYPE(FlKeyChannelUserData,
fl_key_channel_user_data,
FL,
KEY_CHANNEL_USER_DATA,
GObject);
struct _FlKeyChannelUserData {
GObject parent_instance;
// The current responder.
FlKeyChannelResponder* responder;
// The callback provided by the caller #FlKeyboardManager.
FlKeyResponderAsyncCallback callback;
// The user_data provided by the caller #FlKeyboardManager.
gpointer user_data;
};
// Definition for FlKeyChannelUserData private class.
G_DEFINE_TYPE(FlKeyChannelUserData, fl_key_channel_user_data, G_TYPE_OBJECT)
// Dispose method for FlKeyChannelUserData private class.
static void fl_key_channel_user_data_dispose(GObject* object) {
g_return_if_fail(FL_IS_KEY_CHANNEL_USER_DATA(object));
FlKeyChannelUserData* self = FL_KEY_CHANNEL_USER_DATA(object);
if (self->responder != nullptr) {
g_object_remove_weak_pointer(
G_OBJECT(self->responder),
reinterpret_cast<gpointer*>(&(self->responder)));
self->responder = nullptr;
}
}
// Class initialization method for FlKeyChannelUserData private class.
static void fl_key_channel_user_data_class_init(
FlKeyChannelUserDataClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_key_channel_user_data_dispose;
}
// Instance initialization method for FlKeyChannelUserData private class.
static void fl_key_channel_user_data_init(FlKeyChannelUserData* self) {}
// Creates a new FlKeyChannelUserData private class with all information.
//
// The callback and the user_data might be nullptr.
static FlKeyChannelUserData* fl_key_channel_user_data_new(
FlKeyChannelResponder* responder,
FlKeyResponderAsyncCallback callback,
gpointer user_data) {
FlKeyChannelUserData* self = FL_KEY_CHANNEL_USER_DATA(
g_object_new(fl_key_channel_user_data_get_type(), nullptr));
self->responder = responder;
// Add a weak pointer so we can know if the key event responder disappeared
// while the framework was responding.
g_object_add_weak_pointer(G_OBJECT(responder),
reinterpret_cast<gpointer*>(&(self->responder)));
self->callback = callback;
self->user_data = user_data;
return self;
}
/* Define FlKeyChannelResponder */
// Definition of the FlKeyChannelResponder GObject class.
struct _FlKeyChannelResponder {
GObject parent_instance;
FlBasicMessageChannel* channel;
FlKeyChannelResponderMock* mock;
};
static void fl_key_channel_responder_iface_init(FlKeyResponderInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlKeyChannelResponder,
fl_key_channel_responder,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(FL_TYPE_KEY_RESPONDER,
fl_key_channel_responder_iface_init))
static void fl_key_channel_responder_handle_event(
FlKeyResponder* responder,
FlKeyEvent* event,
uint64_t specified_logical_key,
FlKeyResponderAsyncCallback callback,
gpointer user_data);
static void fl_key_channel_responder_iface_init(
FlKeyResponderInterface* iface) {
iface->handle_event = fl_key_channel_responder_handle_event;
}
/* Implement FlKeyChannelResponder */
// Handles a response from the method channel to a key event sent to the
// framework earlier.
static void handle_response(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(FlKeyChannelUserData) data = FL_KEY_CHANNEL_USER_DATA(user_data);
// This is true if the weak pointer has been destroyed.
if (data->responder == nullptr) {
return;
}
FlKeyChannelResponder* self = data->responder;
g_autoptr(GError) error = nullptr;
FlBasicMessageChannel* messageChannel = FL_BASIC_MESSAGE_CHANNEL(object);
FlValue* message =
fl_basic_message_channel_send_finish(messageChannel, result, &error);
if (self->mock != nullptr && self->mock->value_converter != nullptr) {
message = self->mock->value_converter(message);
}
bool handled = false;
if (error != nullptr) {
g_warning("Unable to retrieve framework response: %s", error->message);
} else {
g_autoptr(FlValue) handled_value =
fl_value_lookup_string(message, "handled");
handled = fl_value_get_bool(handled_value);
}
data->callback(handled, data->user_data);
}
// Disposes of an FlKeyChannelResponder instance.
static void fl_key_channel_responder_dispose(GObject* object) {
FlKeyChannelResponder* self = FL_KEY_CHANNEL_RESPONDER(object);
g_clear_object(&self->channel);
G_OBJECT_CLASS(fl_key_channel_responder_parent_class)->dispose(object);
}
// Initializes the FlKeyChannelResponder class methods.
static void fl_key_channel_responder_class_init(
FlKeyChannelResponderClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_key_channel_responder_dispose;
}
// Initializes an FlKeyChannelResponder instance.
static void fl_key_channel_responder_init(FlKeyChannelResponder* self) {}
// Creates a new FlKeyChannelResponder instance, with a messenger used to send
// messages to the framework, and an FlTextInputPlugin that is used to handle
// key events that the framework doesn't handle. Mainly for testing purposes, it
// also takes an optional callback to call when a response is received, and an
// optional channel name to use when sending messages.
FlKeyChannelResponder* fl_key_channel_responder_new(
FlBinaryMessenger* messenger,
FlKeyChannelResponderMock* mock) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr);
FlKeyChannelResponder* self = FL_KEY_CHANNEL_RESPONDER(
g_object_new(fl_key_channel_responder_get_type(), nullptr));
self->mock = mock;
g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new();
const char* channel_name =
mock == nullptr ? kChannelName : mock->channel_name;
self->channel = fl_basic_message_channel_new(messenger, channel_name,
FL_MESSAGE_CODEC(codec));
return self;
}
// Sends a key event to the framework.
static void fl_key_channel_responder_handle_event(
FlKeyResponder* responder,
FlKeyEvent* event,
uint64_t specified_logical_key,
FlKeyResponderAsyncCallback callback,
gpointer user_data) {
FlKeyChannelResponder* self = FL_KEY_CHANNEL_RESPONDER(responder);
g_return_if_fail(event != nullptr);
g_return_if_fail(callback != nullptr);
const gchar* type = event->is_press ? kTypeValueDown : kTypeValueUp;
int64_t scan_code = event->keycode;
int64_t unicode_scarlar_values = gdk_keyval_to_unicode(event->keyval);
// For most modifier keys, GTK keeps track of the "pressed" state of the
// modifier keys. Flutter uses this information to keep modifier keys from
// being "stuck" when a key-up event is lost because it happens after the app
// loses focus.
//
// For Lock keys (ShiftLock, CapsLock, NumLock), however, GTK keeps track of
// the state of the locks themselves, not the "pressed" state of the key.
//
// Since Flutter expects the "pressed" state of the modifier keys, the lock
// state for these keys is discarded here, and it is substituted for the
// pressed state of the key.
//
// This code has the flaw that if a key event is missed due to the app losing
// focus, then this state will still think the key is pressed when it isn't,
// but that is no worse than for "regular" keys until we implement the
// sync/cancel events on app focus changes.
//
// This is necessary to do here instead of in the framework because Flutter
// does modifier key syncing in the framework, and will turn on/off these keys
// as being "pressed" whenever the lock is on, which breaks a lot of
// interactions (for example, if shift-lock is on, tab traversal is broken).
// Remove lock states from state mask.
guint state = event->state & ~(GDK_LOCK_MASK | GDK_MOD2_MASK);
static bool shift_lock_pressed = FALSE;
static bool caps_lock_pressed = FALSE;
static bool num_lock_pressed = FALSE;
switch (event->keyval) {
case GDK_KEY_Num_Lock:
num_lock_pressed = event->is_press;
break;
case GDK_KEY_Caps_Lock:
caps_lock_pressed = event->is_press;
break;
case GDK_KEY_Shift_Lock:
shift_lock_pressed = event->is_press;
break;
}
// Add back in the state matching the actual pressed state of the lock keys,
// not the lock states.
state |= (shift_lock_pressed || caps_lock_pressed) ? GDK_LOCK_MASK : 0x0;
state |= num_lock_pressed ? GDK_MOD2_MASK : 0x0;
g_autoptr(FlValue) message = fl_value_new_map();
fl_value_set_string_take(message, kTypeKey, fl_value_new_string(type));
fl_value_set_string_take(message, kKeymapKey,
fl_value_new_string(kLinuxKeymap));
fl_value_set_string_take(message, kScanCodeKey, fl_value_new_int(scan_code));
fl_value_set_string_take(message, kToolkitKey,
fl_value_new_string(kGtkToolkit));
fl_value_set_string_take(message, kKeyCodeKey,
fl_value_new_int(event->keyval));
fl_value_set_string_take(message, kModifiersKey, fl_value_new_int(state));
if (unicode_scarlar_values != 0) {
fl_value_set_string_take(message, kUnicodeScalarValuesKey,
fl_value_new_int(unicode_scarlar_values));
}
if (specified_logical_key != 0) {
fl_value_set_string_take(message, kSpecifiedLogicalKey,
fl_value_new_int(specified_logical_key));
}
FlKeyChannelUserData* data =
fl_key_channel_user_data_new(self, callback, user_data);
// Send the message off to the framework for handling (or not).
fl_basic_message_channel_send(self->channel, message, nullptr,
handle_response, data);
}
| engine/shell/platform/linux/fl_key_channel_responder.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_key_channel_responder.cc",
"repo_id": "engine",
"token_count": 3984
} | 368 |
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_message_codec.h"
#include <gmodule.h>
G_DEFINE_QUARK(fl_message_codec_error_quark, fl_message_codec_error)
G_DEFINE_TYPE(FlMessageCodec, fl_message_codec, G_TYPE_OBJECT)
static void fl_message_codec_class_init(FlMessageCodecClass* klass) {}
static void fl_message_codec_init(FlMessageCodec* self) {}
G_MODULE_EXPORT GBytes* fl_message_codec_encode_message(FlMessageCodec* self,
FlValue* message,
GError** error) {
g_return_val_if_fail(FL_IS_MESSAGE_CODEC(self), nullptr);
// If the user provided NULL, then make a temporary FlValue object for this to
// make it simpler for the subclasses.
g_autoptr(FlValue) null_value = nullptr;
if (message == nullptr) {
null_value = fl_value_new_null();
message = null_value;
}
return FL_MESSAGE_CODEC_GET_CLASS(self)->encode_message(self, message, error);
}
G_MODULE_EXPORT FlValue* fl_message_codec_decode_message(FlMessageCodec* self,
GBytes* message,
GError** error) {
g_return_val_if_fail(FL_IS_MESSAGE_CODEC(self), nullptr);
g_return_val_if_fail(message != nullptr, nullptr);
return FL_MESSAGE_CODEC_GET_CLASS(self)->decode_message(self, message, error);
}
| engine/shell/platform/linux/fl_message_codec.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_message_codec.cc",
"repo_id": "engine",
"token_count": 731
} | 369 |
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h"
#include "flutter/shell/platform/linux/fl_pixel_buffer_texture_private.h"
#include "flutter/shell/platform/linux/fl_texture_private.h"
#include "flutter/shell/platform/linux/fl_texture_registrar_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "gtest/gtest.h"
#include <epoxy/gl.h>
static constexpr uint32_t kBufferWidth = 4u;
static constexpr uint32_t kBufferHeight = 4u;
static constexpr uint32_t kRealBufferWidth = 2u;
static constexpr uint32_t kRealBufferHeight = 2u;
G_DECLARE_FINAL_TYPE(FlTestPixelBufferTexture,
fl_test_pixel_buffer_texture,
FL,
TEST_PIXEL_BUFFER_TEXTURE,
FlPixelBufferTexture)
/// A simple texture with fixed contents.
struct _FlTestPixelBufferTexture {
FlPixelBufferTexture parent_instance;
};
G_DEFINE_TYPE(FlTestPixelBufferTexture,
fl_test_pixel_buffer_texture,
fl_pixel_buffer_texture_get_type())
static gboolean fl_test_pixel_buffer_texture_copy_pixels(
FlPixelBufferTexture* texture,
const uint8_t** out_buffer,
uint32_t* width,
uint32_t* height,
GError** error) {
EXPECT_TRUE(FL_IS_TEST_PIXEL_BUFFER_TEXTURE(texture));
// RGBA
static const uint8_t buffer[] = {0x0a, 0x1a, 0x2a, 0x3a, 0x4a, 0x5a,
0x6a, 0x7a, 0x8a, 0x9a, 0xaa, 0xba,
0xca, 0xda, 0xea, 0xfa};
EXPECT_EQ(*width, kBufferWidth);
EXPECT_EQ(*height, kBufferHeight);
*out_buffer = buffer;
*width = kRealBufferWidth;
*height = kRealBufferHeight;
return TRUE;
}
static void fl_test_pixel_buffer_texture_class_init(
FlTestPixelBufferTextureClass* klass) {
FL_PIXEL_BUFFER_TEXTURE_CLASS(klass)->copy_pixels =
fl_test_pixel_buffer_texture_copy_pixels;
}
static void fl_test_pixel_buffer_texture_init(FlTestPixelBufferTexture* self) {}
static FlTestPixelBufferTexture* fl_test_pixel_buffer_texture_new() {
return FL_TEST_PIXEL_BUFFER_TEXTURE(
g_object_new(fl_test_pixel_buffer_texture_get_type(), nullptr));
}
// Test that getting the texture ID works.
TEST(FlPixelBufferTextureTest, TextureID) {
g_autoptr(FlTexture) texture = FL_TEXTURE(fl_test_pixel_buffer_texture_new());
fl_texture_set_id(texture, 42);
EXPECT_EQ(fl_texture_get_id(texture), static_cast<int64_t>(42));
}
// Test that populating an OpenGL texture works.
TEST(FlPixelBufferTextureTest, PopulateTexture) {
g_autoptr(FlPixelBufferTexture) texture =
FL_PIXEL_BUFFER_TEXTURE(fl_test_pixel_buffer_texture_new());
FlutterOpenGLTexture opengl_texture = {0};
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_pixel_buffer_texture_populate(
texture, kBufferWidth, kBufferHeight, &opengl_texture, &error));
EXPECT_EQ(error, nullptr);
EXPECT_EQ(opengl_texture.width, kRealBufferWidth);
EXPECT_EQ(opengl_texture.height, kRealBufferHeight);
}
| engine/shell/platform/linux/fl_pixel_buffer_texture_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_pixel_buffer_texture_test.cc",
"repo_id": "engine",
"token_count": 1316
} | 370 |
// 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 "flutter/shell/platform/linux/fl_scrolling_manager.h"
#include <cstring>
#include <vector>
#include "gtest/gtest.h"
namespace {
typedef std::function<void(FlutterPointerPhase phase,
size_t timestamp,
double x,
double y,
double scroll_delta_x,
double scroll_delta_y,
int64_t buttons)>
MousePointerCallHandler;
typedef std::function<void(size_t timestamp,
double x,
double y,
FlutterPointerPhase phase,
double pan_x,
double pan_y,
double scale,
double rotation)>
PointerPanZoomCallHandler;
typedef struct {
FlutterPointerPhase phase;
size_t timestamp;
double x;
double y;
double scroll_delta_x;
double scroll_delta_y;
int64_t buttons;
} MousePointerEventRecord;
typedef struct {
size_t timestamp;
double x;
double y;
FlutterPointerPhase phase;
double pan_x;
double pan_y;
double scale;
double rotation;
} PointerPanZoomEventRecord;
G_BEGIN_DECLS
G_DECLARE_FINAL_TYPE(FlMockScrollingViewDelegate,
fl_mock_scrolling_view_delegate,
FL,
MOCK_SCROLLING_VIEW_DELEGATE,
GObject)
G_END_DECLS
/***** FlMockScrollingViewDelegate *****/
struct _FlMockScrollingViewDelegate {
GObject parent_instance;
};
struct FlMockScrollingViewDelegatePrivate {
MousePointerCallHandler mouse_handler;
PointerPanZoomCallHandler pan_zoom_handler;
};
static void fl_mock_view_scroll_delegate_iface_init(
FlScrollingViewDelegateInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlMockScrollingViewDelegate,
fl_mock_scrolling_view_delegate,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_scrolling_view_delegate_get_type(),
fl_mock_view_scroll_delegate_iface_init);
G_ADD_PRIVATE(FlMockScrollingViewDelegate))
#define FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(obj) \
static_cast<FlMockScrollingViewDelegatePrivate*>( \
fl_mock_scrolling_view_delegate_get_instance_private( \
FL_MOCK_SCROLLING_VIEW_DELEGATE(obj)))
static void fl_mock_scrolling_view_delegate_init(
FlMockScrollingViewDelegate* self) {
FlMockScrollingViewDelegatePrivate* priv =
FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(self);
new (priv) FlMockScrollingViewDelegatePrivate();
}
static void fl_mock_scrolling_view_delegate_finalize(GObject* object) {
FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(object)
->~FlMockScrollingViewDelegatePrivate();
}
static void fl_mock_scrolling_view_delegate_dispose(GObject* object) {
G_OBJECT_CLASS(fl_mock_scrolling_view_delegate_parent_class)->dispose(object);
}
static void fl_mock_scrolling_view_delegate_class_init(
FlMockScrollingViewDelegateClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_mock_scrolling_view_delegate_dispose;
G_OBJECT_CLASS(klass)->finalize = fl_mock_scrolling_view_delegate_finalize;
}
static void fl_mock_view_send_mouse_pointer_event(
FlScrollingViewDelegate* delegate,
FlutterPointerPhase phase,
size_t timestamp,
double x,
double y,
double scroll_delta_x,
double scroll_delta_y,
int64_t buttons) {
FlMockScrollingViewDelegatePrivate* priv =
FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(delegate);
priv->mouse_handler(phase, timestamp, x, y, scroll_delta_x, scroll_delta_y,
buttons);
}
static void fl_mock_view_send_pointer_pan_zoom_event(
FlScrollingViewDelegate* delegate,
size_t timestamp,
double x,
double y,
FlutterPointerPhase phase,
double pan_x,
double pan_y,
double scale,
double rotation) {
FlMockScrollingViewDelegatePrivate* priv =
FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(delegate);
priv->pan_zoom_handler(timestamp, x, y, phase, pan_x, pan_y, scale, rotation);
}
static void fl_mock_view_scroll_delegate_iface_init(
FlScrollingViewDelegateInterface* iface) {
iface->send_mouse_pointer_event = fl_mock_view_send_mouse_pointer_event;
iface->send_pointer_pan_zoom_event = fl_mock_view_send_pointer_pan_zoom_event;
}
static FlMockScrollingViewDelegate* fl_mock_scrolling_view_delegate_new() {
FlMockScrollingViewDelegate* self = FL_MOCK_SCROLLING_VIEW_DELEGATE(
g_object_new(fl_mock_scrolling_view_delegate_get_type(), nullptr));
// Added to stop compiler complaining about an unused function.
FL_IS_MOCK_SCROLLING_VIEW_DELEGATE(self);
return self;
}
static void fl_mock_scrolling_view_set_mouse_handler(
FlMockScrollingViewDelegate* self,
MousePointerCallHandler handler) {
FlMockScrollingViewDelegatePrivate* priv =
FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(self);
priv->mouse_handler = std::move(handler);
}
static void fl_mock_scrolling_view_set_pan_zoom_handler(
FlMockScrollingViewDelegate* self,
PointerPanZoomCallHandler handler) {
FlMockScrollingViewDelegatePrivate* priv =
FL_MOCK_SCROLLING_VIEW_DELEGATE_GET_PRIVATE(self);
priv->pan_zoom_handler = std::move(handler);
}
/***** End FlMockScrollingViewDelegate *****/
class ScrollingTester {
public:
ScrollingTester() {
view_ = fl_mock_scrolling_view_delegate_new();
manager_ = fl_scrolling_manager_new(FL_SCROLLING_VIEW_DELEGATE(view_));
fl_mock_scrolling_view_set_mouse_handler(
view_,
[](FlutterPointerPhase phase, size_t timestamp, double x, double y,
double scroll_delta_x, double scroll_delta_y, int64_t buttons) {
// do nothing
});
fl_mock_scrolling_view_set_pan_zoom_handler(
view_,
[](size_t timestamp, double x, double y, FlutterPointerPhase phase,
double pan_x, double pan_y, double scale, double rotation) {
// do nothing
});
}
~ScrollingTester() {
g_clear_object(&view_);
g_clear_object(&manager_);
}
FlScrollingManager* manager() { return manager_; }
void recordMousePointerCallsTo(
std::vector<MousePointerEventRecord>& storage) {
fl_mock_scrolling_view_set_mouse_handler(
view_, [&storage](FlutterPointerPhase phase, size_t timestamp, double x,
double y, double scroll_delta_x,
double scroll_delta_y, int64_t buttons) {
storage.push_back(MousePointerEventRecord{
.phase = phase,
.timestamp = timestamp,
.x = x,
.y = y,
.scroll_delta_x = scroll_delta_x,
.scroll_delta_y = scroll_delta_y,
.buttons = buttons,
});
});
}
void recordPointerPanZoomCallsTo(
std::vector<PointerPanZoomEventRecord>& storage) {
fl_mock_scrolling_view_set_pan_zoom_handler(
view_, [&storage](size_t timestamp, double x, double y,
FlutterPointerPhase phase, double pan_x, double pan_y,
double scale, double rotation) {
storage.push_back(PointerPanZoomEventRecord{
.timestamp = timestamp,
.x = x,
.y = y,
.phase = phase,
.pan_x = pan_x,
.pan_y = pan_y,
.scale = scale,
.rotation = rotation,
});
});
}
private:
FlMockScrollingViewDelegate* view_;
FlScrollingManager* manager_;
};
// Disgusting hack but could not find any way to create a GdkDevice
struct _FakeGdkDevice {
GObject parent_instance;
gchar* name;
GdkInputSource source;
};
GdkDevice* makeFakeDevice(GdkInputSource source) {
_FakeGdkDevice* device =
static_cast<_FakeGdkDevice*>(g_malloc0(sizeof(_FakeGdkDevice)));
device->source = source;
// Bully the type checker
(reinterpret_cast<GTypeInstance*>(device))->g_class =
static_cast<GTypeClass*>(g_malloc0(sizeof(GTypeClass)));
(reinterpret_cast<GTypeInstance*>(device))->g_class->g_type = GDK_TYPE_DEVICE;
return reinterpret_cast<GdkDevice*>(device);
}
TEST(FlScrollingManagerTest, DiscreteDirectionional) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
GdkDevice* mouse = makeFakeDevice(GDK_SOURCE_MOUSE);
GdkEventScroll* event =
reinterpret_cast<GdkEventScroll*>(gdk_event_new(GDK_SCROLL));
event->time = 1;
event->x = 4.0;
event->y = 8.0;
event->device = mouse;
event->direction = GDK_SCROLL_UP;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 0u);
EXPECT_EQ(mouse_records.size(), 1u);
EXPECT_EQ(mouse_records[0].x, 4.0);
EXPECT_EQ(mouse_records[0].y, 8.0);
EXPECT_EQ(mouse_records[0].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(mouse_records[0].scroll_delta_x, 0);
EXPECT_EQ(mouse_records[0].scroll_delta_y, 53 * -1.0);
event->direction = GDK_SCROLL_DOWN;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 0u);
EXPECT_EQ(mouse_records.size(), 2u);
EXPECT_EQ(mouse_records[1].x, 4.0);
EXPECT_EQ(mouse_records[1].y, 8.0);
EXPECT_EQ(mouse_records[1].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(mouse_records[1].scroll_delta_x, 0);
EXPECT_EQ(mouse_records[1].scroll_delta_y, 53 * 1.0);
event->direction = GDK_SCROLL_LEFT;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 0u);
EXPECT_EQ(mouse_records.size(), 3u);
EXPECT_EQ(mouse_records[2].x, 4.0);
EXPECT_EQ(mouse_records[2].y, 8.0);
EXPECT_EQ(mouse_records[2].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(mouse_records[2].scroll_delta_x, 53 * -1.0);
EXPECT_EQ(mouse_records[2].scroll_delta_y, 0);
event->direction = GDK_SCROLL_RIGHT;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 0u);
EXPECT_EQ(mouse_records.size(), 4u);
EXPECT_EQ(mouse_records[3].x, 4.0);
EXPECT_EQ(mouse_records[3].y, 8.0);
EXPECT_EQ(mouse_records[3].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(mouse_records[3].scroll_delta_x, 53 * 1.0);
EXPECT_EQ(mouse_records[3].scroll_delta_y, 0);
}
TEST(FlScrollingManagerTest, DiscreteScrolling) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
GdkDevice* mouse = makeFakeDevice(GDK_SOURCE_MOUSE);
GdkEventScroll* event =
reinterpret_cast<GdkEventScroll*>(gdk_event_new(GDK_SCROLL));
event->time = 1;
event->x = 4.0;
event->y = 8.0;
event->delta_x = 1.0;
event->delta_y = 2.0;
event->device = mouse;
event->direction = GDK_SCROLL_SMOOTH;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 0u);
EXPECT_EQ(mouse_records.size(), 1u);
EXPECT_EQ(mouse_records[0].x, 4.0);
EXPECT_EQ(mouse_records[0].y, 8.0);
EXPECT_EQ(mouse_records[0].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(mouse_records[0].scroll_delta_x, 53 * 1.0);
EXPECT_EQ(mouse_records[0].scroll_delta_y, 53 * 2.0);
}
TEST(FlScrollingManagerTest, Panning) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
GdkDevice* touchpad = makeFakeDevice(GDK_SOURCE_TOUCHPAD);
GdkEventScroll* event =
reinterpret_cast<GdkEventScroll*>(gdk_event_new(GDK_SCROLL));
event->time = 1;
event->x = 4.0;
event->y = 8.0;
event->delta_x = 1.0;
event->delta_y = 2.0;
event->device = touchpad;
event->direction = GDK_SCROLL_SMOOTH;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[0].x, 4.0);
EXPECT_EQ(pan_zoom_records[0].y, 8.0);
EXPECT_EQ(pan_zoom_records[0].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(pan_zoom_records[0].phase, kPanZoomStart);
EXPECT_EQ(pan_zoom_records[1].x, 4.0);
EXPECT_EQ(pan_zoom_records[1].y, 8.0);
EXPECT_EQ(pan_zoom_records[1].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(pan_zoom_records[1].phase, kPanZoomUpdate);
EXPECT_EQ(pan_zoom_records[1].pan_x, 53 * -1.0); // directions get swapped
EXPECT_EQ(pan_zoom_records[1].pan_y, 53 * -2.0);
EXPECT_EQ(pan_zoom_records[1].scale, 1.0);
EXPECT_EQ(pan_zoom_records[1].rotation, 0.0);
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 3u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[2].x, 4.0);
EXPECT_EQ(pan_zoom_records[2].y, 8.0);
EXPECT_EQ(pan_zoom_records[2].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(pan_zoom_records[2].phase, kPanZoomUpdate);
EXPECT_EQ(pan_zoom_records[2].pan_x, 53 * -2.0); // directions get swapped
EXPECT_EQ(pan_zoom_records[2].pan_y, 53 * -4.0);
EXPECT_EQ(pan_zoom_records[2].scale, 1.0);
EXPECT_EQ(pan_zoom_records[2].rotation, 0.0);
event->is_stop = true;
fl_scrolling_manager_handle_scroll_event(tester.manager(), event, 1.0);
EXPECT_EQ(pan_zoom_records.size(), 4u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[3].x, 4.0);
EXPECT_EQ(pan_zoom_records[3].y, 8.0);
EXPECT_EQ(pan_zoom_records[3].timestamp,
1000lu); // Milliseconds -> Microseconds
EXPECT_EQ(pan_zoom_records[3].phase, kPanZoomEnd);
}
TEST(FlScrollingManagerTest, Zooming) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
size_t time_start = g_get_real_time();
fl_scrolling_manager_handle_zoom_begin(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 1u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[0].x, 0);
EXPECT_EQ(pan_zoom_records[0].y, 0);
EXPECT_EQ(pan_zoom_records[0].phase, kPanZoomStart);
EXPECT_GE(pan_zoom_records[0].timestamp, time_start);
fl_scrolling_manager_handle_zoom_update(tester.manager(), 1.1);
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[1].x, 0);
EXPECT_EQ(pan_zoom_records[1].y, 0);
EXPECT_EQ(pan_zoom_records[1].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[1].timestamp, pan_zoom_records[0].timestamp);
EXPECT_EQ(pan_zoom_records[1].pan_x, 0);
EXPECT_EQ(pan_zoom_records[1].pan_y, 0);
EXPECT_EQ(pan_zoom_records[1].scale, 1.1);
EXPECT_EQ(pan_zoom_records[1].rotation, 0);
fl_scrolling_manager_handle_zoom_end(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 3u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[2].x, 0);
EXPECT_EQ(pan_zoom_records[2].y, 0);
EXPECT_EQ(pan_zoom_records[2].phase, kPanZoomEnd);
EXPECT_GE(pan_zoom_records[2].timestamp, pan_zoom_records[1].timestamp);
}
TEST(FlScrollingManagerTest, Rotating) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
size_t time_start = g_get_real_time();
fl_scrolling_manager_handle_rotation_begin(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 1u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[0].x, 0);
EXPECT_EQ(pan_zoom_records[0].y, 0);
EXPECT_EQ(pan_zoom_records[0].phase, kPanZoomStart);
EXPECT_GE(pan_zoom_records[0].timestamp, time_start);
fl_scrolling_manager_handle_rotation_update(tester.manager(), 0.5);
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[1].x, 0);
EXPECT_EQ(pan_zoom_records[1].y, 0);
EXPECT_EQ(pan_zoom_records[1].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[1].timestamp, pan_zoom_records[0].timestamp);
EXPECT_EQ(pan_zoom_records[1].pan_x, 0);
EXPECT_EQ(pan_zoom_records[1].pan_y, 0);
EXPECT_EQ(pan_zoom_records[1].scale, 1.0);
EXPECT_EQ(pan_zoom_records[1].rotation, 0.5);
fl_scrolling_manager_handle_rotation_end(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 3u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[2].x, 0);
EXPECT_EQ(pan_zoom_records[2].y, 0);
EXPECT_EQ(pan_zoom_records[2].phase, kPanZoomEnd);
EXPECT_GE(pan_zoom_records[2].timestamp, pan_zoom_records[1].timestamp);
}
TEST(FlScrollingManagerTest, SynchronizedZoomingAndRotating) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
size_t time_start = g_get_real_time();
fl_scrolling_manager_handle_zoom_begin(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 1u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[0].x, 0);
EXPECT_EQ(pan_zoom_records[0].y, 0);
EXPECT_EQ(pan_zoom_records[0].phase, kPanZoomStart);
EXPECT_GE(pan_zoom_records[0].timestamp, time_start);
fl_scrolling_manager_handle_zoom_update(tester.manager(), 1.1);
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[1].x, 0);
EXPECT_EQ(pan_zoom_records[1].y, 0);
EXPECT_EQ(pan_zoom_records[1].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[1].timestamp, pan_zoom_records[0].timestamp);
EXPECT_EQ(pan_zoom_records[1].pan_x, 0);
EXPECT_EQ(pan_zoom_records[1].pan_y, 0);
EXPECT_EQ(pan_zoom_records[1].scale, 1.1);
EXPECT_EQ(pan_zoom_records[1].rotation, 0);
fl_scrolling_manager_handle_rotation_begin(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
fl_scrolling_manager_handle_rotation_update(tester.manager(), 0.5);
EXPECT_EQ(pan_zoom_records.size(), 3u);
EXPECT_EQ(pan_zoom_records[2].x, 0);
EXPECT_EQ(pan_zoom_records[2].y, 0);
EXPECT_EQ(pan_zoom_records[2].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[2].timestamp, pan_zoom_records[1].timestamp);
EXPECT_EQ(pan_zoom_records[2].pan_x, 0);
EXPECT_EQ(pan_zoom_records[2].pan_y, 0);
EXPECT_EQ(pan_zoom_records[2].scale, 1.1);
EXPECT_EQ(pan_zoom_records[2].rotation, 0.5);
fl_scrolling_manager_handle_zoom_end(tester.manager());
// End event should only be sent after both zoom and rotate complete.
EXPECT_EQ(pan_zoom_records.size(), 3u);
fl_scrolling_manager_handle_rotation_end(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 4u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[3].x, 0);
EXPECT_EQ(pan_zoom_records[3].y, 0);
EXPECT_EQ(pan_zoom_records[3].phase, kPanZoomEnd);
EXPECT_GE(pan_zoom_records[3].timestamp, pan_zoom_records[2].timestamp);
}
// Make sure that zoom and rotate sequences which don't end at the same time
// don't cause any problems.
TEST(FlScrollingManagerTest, UnsynchronizedZoomingAndRotating) {
ScrollingTester tester;
std::vector<MousePointerEventRecord> mouse_records;
std::vector<PointerPanZoomEventRecord> pan_zoom_records;
tester.recordMousePointerCallsTo(mouse_records);
tester.recordPointerPanZoomCallsTo(pan_zoom_records);
size_t time_start = g_get_real_time();
fl_scrolling_manager_handle_zoom_begin(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 1u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[0].x, 0);
EXPECT_EQ(pan_zoom_records[0].y, 0);
EXPECT_EQ(pan_zoom_records[0].phase, kPanZoomStart);
EXPECT_GE(pan_zoom_records[0].timestamp, time_start);
fl_scrolling_manager_handle_zoom_update(tester.manager(), 1.1);
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[1].x, 0);
EXPECT_EQ(pan_zoom_records[1].y, 0);
EXPECT_EQ(pan_zoom_records[1].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[1].timestamp, pan_zoom_records[0].timestamp);
EXPECT_EQ(pan_zoom_records[1].pan_x, 0);
EXPECT_EQ(pan_zoom_records[1].pan_y, 0);
EXPECT_EQ(pan_zoom_records[1].scale, 1.1);
EXPECT_EQ(pan_zoom_records[1].rotation, 0);
fl_scrolling_manager_handle_rotation_begin(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 2u);
EXPECT_EQ(mouse_records.size(), 0u);
fl_scrolling_manager_handle_rotation_update(tester.manager(), 0.5);
EXPECT_EQ(pan_zoom_records.size(), 3u);
EXPECT_EQ(pan_zoom_records[2].x, 0);
EXPECT_EQ(pan_zoom_records[2].y, 0);
EXPECT_EQ(pan_zoom_records[2].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[2].timestamp, pan_zoom_records[1].timestamp);
EXPECT_EQ(pan_zoom_records[2].pan_x, 0);
EXPECT_EQ(pan_zoom_records[2].pan_y, 0);
EXPECT_EQ(pan_zoom_records[2].scale, 1.1);
EXPECT_EQ(pan_zoom_records[2].rotation, 0.5);
fl_scrolling_manager_handle_zoom_end(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 3u);
fl_scrolling_manager_handle_rotation_update(tester.manager(), 1.0);
EXPECT_EQ(pan_zoom_records.size(), 4u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[3].x, 0);
EXPECT_EQ(pan_zoom_records[3].y, 0);
EXPECT_EQ(pan_zoom_records[3].phase, kPanZoomUpdate);
EXPECT_GE(pan_zoom_records[3].timestamp, pan_zoom_records[2].timestamp);
EXPECT_EQ(pan_zoom_records[3].pan_x, 0);
EXPECT_EQ(pan_zoom_records[3].pan_y, 0);
EXPECT_EQ(pan_zoom_records[3].scale, 1.1);
EXPECT_EQ(pan_zoom_records[3].rotation, 1.0);
fl_scrolling_manager_handle_rotation_end(tester.manager());
EXPECT_EQ(pan_zoom_records.size(), 5u);
EXPECT_EQ(mouse_records.size(), 0u);
EXPECT_EQ(pan_zoom_records[4].x, 0);
EXPECT_EQ(pan_zoom_records[4].y, 0);
EXPECT_EQ(pan_zoom_records[4].phase, kPanZoomEnd);
EXPECT_GE(pan_zoom_records[4].timestamp, pan_zoom_records[3].timestamp);
}
} // namespace
| engine/shell/platform/linux/fl_scrolling_manager_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_scrolling_manager_test.cc",
"repo_id": "engine",
"token_count": 10266
} | 371 |
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "gtest/gtest.h"
// Encodes a message using a FlStringCodec. Return a hex string with the encoded
// binary output.
static gchar* encode_message(FlValue* value) {
g_autoptr(FlStringCodec) codec = fl_string_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return bytes_to_hex_string(message);
}
// Encodes a message using a FlStringCodec. Expect the given error.
static void encode_message_error(FlValue* value, GQuark domain, int code) {
g_autoptr(FlStringCodec) codec = fl_string_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error);
EXPECT_EQ(message, nullptr);
EXPECT_TRUE(g_error_matches(error, domain, code));
}
// Decodes a message using a FlStringCodec. The binary data is given in the form
// of a hex string.
static FlValue* decode_message(const char* hex_string) {
g_autoptr(FlStringCodec) codec = fl_string_codec_new();
g_autoptr(GBytes) message = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autoptr(FlValue) value =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(value, nullptr);
return fl_value_ref(value);
}
TEST(FlStringCodecTest, EncodeData) {
g_autoptr(FlValue) value = fl_value_new_string("hello");
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "68656c6c6f");
}
TEST(FlStringCodecTest, EncodeEmpty) {
g_autoptr(FlValue) value = fl_value_new_string("");
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "");
}
TEST(FlStringCodecTest, EncodeNullptr) {
encode_message_error(nullptr, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE);
}
TEST(FlStringCodecTest, EncodeUnknownType) {
g_autoptr(FlValue) value = fl_value_new_null();
encode_message_error(value, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE);
}
TEST(FlStringCodecTest, DecodeData) {
g_autoptr(FlValue) value = decode_message("68656c6c6f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING);
ASSERT_STREQ(fl_value_get_string(value), "hello");
}
TEST(FlStringCodecTest, DecodeEmpty) {
g_autoptr(FlValue) value = decode_message("");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING);
ASSERT_STREQ(fl_value_get_string(value), "");
}
TEST(FlStringCodecTest, EncodeDecode) {
g_autoptr(FlStringCodec) codec = fl_string_codec_new();
g_autoptr(FlValue) input = fl_value_new_string("hello");
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), input, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
g_autoptr(FlValue) output =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(output, nullptr);
ASSERT_TRUE(fl_value_equal(input, output));
}
| engine/shell/platform/linux/fl_string_codec_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_string_codec_test.cc",
"repo_id": "engine",
"token_count": 1422
} | 372 |
// 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 "flutter/shell/platform/linux/public/flutter_linux/fl_value.h"
#include <gmodule.h>
#include <cstring>
struct _FlValue {
FlValueType type;
int ref_count;
};
typedef struct {
FlValue parent;
bool value;
} FlValueBool;
typedef struct {
FlValue parent;
int64_t value;
} FlValueInt;
typedef struct {
FlValue parent;
double value;
} FlValueDouble;
typedef struct {
FlValue parent;
gchar* value;
} FlValueString;
typedef struct {
FlValue parent;
uint8_t* values;
size_t values_length;
} FlValueUint8List;
typedef struct {
FlValue parent;
int32_t* values;
size_t values_length;
} FlValueInt32List;
typedef struct {
FlValue parent;
int64_t* values;
size_t values_length;
} FlValueInt64List;
typedef struct {
FlValue parent;
float* values;
size_t values_length;
} FlValueFloat32List;
typedef struct {
FlValue parent;
double* values;
size_t values_length;
} FlValueFloatList;
typedef struct {
FlValue parent;
GPtrArray* values;
} FlValueList;
typedef struct {
FlValue parent;
GPtrArray* keys;
GPtrArray* values;
} FlValueMap;
typedef struct {
FlValue parent;
int type;
gconstpointer value;
GDestroyNotify destroy_notify;
} FlValueCustom;
static FlValue* fl_value_new(FlValueType type, size_t size) {
FlValue* self = static_cast<FlValue*>(g_malloc0(size));
self->type = type;
self->ref_count = 1;
return self;
}
// Helper function to match GDestroyNotify type.
static void fl_value_destroy(gpointer value) {
fl_value_unref(static_cast<FlValue*>(value));
}
// Finds the index of a key in a FlValueMap.
// FIXME(robert-ancell) This is highly inefficient, and should be optimized if
// necessary.
static ssize_t fl_value_lookup_index(FlValue* self, FlValue* key) {
g_return_val_if_fail(self->type == FL_VALUE_TYPE_MAP, -1);
for (size_t i = 0; i < fl_value_get_length(self); i++) {
FlValue* k = fl_value_get_map_key(self, i);
if (fl_value_equal(k, key)) {
return i;
}
}
return -1;
}
// Converts an integer to a string and adds it to the buffer.
static void int_to_string(int64_t value, GString* buffer) {
g_string_append_printf(buffer, "%" G_GINT64_FORMAT, value);
}
// Converts a floating point number to a string and adds it to the buffer.
static void float_to_string(double value, GString* buffer) {
g_string_append_printf(buffer, "%.16f", value);
// Strip trailing zeros.
int zero_count = 0;
for (int i = buffer->len - 1; i >= 0; i--) {
// Leave one zero after a decimal point.
if (buffer->str[i] == '.') {
zero_count = zero_count == 0 ? 0 : zero_count - 1;
break;
}
if (buffer->str[i] != '0') {
break;
}
zero_count++;
}
g_string_truncate(buffer, buffer->len - zero_count);
}
static void value_to_string(FlValue* value, GString* buffer) {
switch (value->type) {
case FL_VALUE_TYPE_NULL:
g_string_append(buffer, "null");
return;
case FL_VALUE_TYPE_BOOL:
if (fl_value_get_bool(value)) {
g_string_append(buffer, "true");
} else {
g_string_append(buffer, "false");
}
return;
case FL_VALUE_TYPE_INT:
int_to_string(fl_value_get_int(value), buffer);
return;
case FL_VALUE_TYPE_FLOAT:
float_to_string(fl_value_get_float(value), buffer);
return;
case FL_VALUE_TYPE_STRING: {
g_string_append(buffer, fl_value_get_string(value));
return;
}
case FL_VALUE_TYPE_UINT8_LIST: {
g_string_append(buffer, "[");
const uint8_t* values = fl_value_get_uint8_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
int_to_string(values[i], buffer);
}
g_string_append(buffer, "]");
return;
}
case FL_VALUE_TYPE_INT32_LIST: {
g_string_append(buffer, "[");
const int32_t* values = fl_value_get_int32_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
int_to_string(values[i], buffer);
}
g_string_append(buffer, "]");
return;
}
case FL_VALUE_TYPE_INT64_LIST: {
g_string_append(buffer, "[");
const int64_t* values = fl_value_get_int64_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
int_to_string(values[i], buffer);
}
g_string_append(buffer, "]");
return;
}
case FL_VALUE_TYPE_FLOAT32_LIST: {
g_string_append(buffer, "[");
const float* values = fl_value_get_float32_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
float_to_string(values[i], buffer);
}
g_string_append(buffer, "]");
return;
}
case FL_VALUE_TYPE_FLOAT_LIST: {
g_string_append(buffer, "[");
const double* values = fl_value_get_float_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
float_to_string(values[i], buffer);
}
g_string_append(buffer, "]");
return;
}
case FL_VALUE_TYPE_LIST: {
g_string_append(buffer, "[");
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
value_to_string(fl_value_get_list_value(value, i), buffer);
}
g_string_append(buffer, "]");
return;
}
case FL_VALUE_TYPE_MAP: {
g_string_append(buffer, "{");
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (i != 0) {
g_string_append(buffer, ", ");
}
value_to_string(fl_value_get_map_key(value, i), buffer);
g_string_append(buffer, ": ");
value_to_string(fl_value_get_map_value(value, i), buffer);
}
g_string_append(buffer, "}");
return;
}
case FL_VALUE_TYPE_CUSTOM:
g_string_append_printf(buffer, "(custom %d)",
fl_value_get_custom_type(value));
return;
default:
g_string_append_printf(buffer, "<unknown type %d>", value->type);
}
}
G_MODULE_EXPORT FlValue* fl_value_new_null() {
return fl_value_new(FL_VALUE_TYPE_NULL, sizeof(FlValue));
}
G_MODULE_EXPORT FlValue* fl_value_new_bool(bool value) {
FlValueBool* self = reinterpret_cast<FlValueBool*>(
fl_value_new(FL_VALUE_TYPE_BOOL, sizeof(FlValueBool)));
self->value = value ? true : false;
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_int(int64_t value) {
FlValueInt* self = reinterpret_cast<FlValueInt*>(
fl_value_new(FL_VALUE_TYPE_INT, sizeof(FlValueInt)));
self->value = value;
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_float(double value) {
FlValueDouble* self = reinterpret_cast<FlValueDouble*>(
fl_value_new(FL_VALUE_TYPE_FLOAT, sizeof(FlValueDouble)));
self->value = value;
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_string(const gchar* value) {
FlValueString* self = reinterpret_cast<FlValueString*>(
fl_value_new(FL_VALUE_TYPE_STRING, sizeof(FlValueString)));
self->value = g_strdup(value);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_string_sized(const gchar* value,
size_t value_length) {
FlValueString* self = reinterpret_cast<FlValueString*>(
fl_value_new(FL_VALUE_TYPE_STRING, sizeof(FlValueString)));
self->value =
value_length == 0 ? g_strdup("") : g_strndup(value, value_length);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_uint8_list(const uint8_t* data,
size_t data_length) {
FlValueUint8List* self = reinterpret_cast<FlValueUint8List*>(
fl_value_new(FL_VALUE_TYPE_UINT8_LIST, sizeof(FlValueUint8List)));
self->values_length = data_length;
self->values = static_cast<uint8_t*>(g_malloc(sizeof(uint8_t) * data_length));
memcpy(self->values, data, sizeof(uint8_t) * data_length);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_uint8_list_from_bytes(GBytes* data) {
gsize length;
const uint8_t* d =
static_cast<const uint8_t*>(g_bytes_get_data(data, &length));
return fl_value_new_uint8_list(d, length);
}
G_MODULE_EXPORT FlValue* fl_value_new_int32_list(const int32_t* data,
size_t data_length) {
FlValueInt32List* self = reinterpret_cast<FlValueInt32List*>(
fl_value_new(FL_VALUE_TYPE_INT32_LIST, sizeof(FlValueInt32List)));
self->values_length = data_length;
self->values = static_cast<int32_t*>(g_malloc(sizeof(int32_t) * data_length));
memcpy(self->values, data, sizeof(int32_t) * data_length);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_int64_list(const int64_t* data,
size_t data_length) {
FlValueInt64List* self = reinterpret_cast<FlValueInt64List*>(
fl_value_new(FL_VALUE_TYPE_INT64_LIST, sizeof(FlValueInt64List)));
self->values_length = data_length;
self->values = static_cast<int64_t*>(g_malloc(sizeof(int64_t) * data_length));
memcpy(self->values, data, sizeof(int64_t) * data_length);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_float32_list(const float* data,
size_t data_length) {
FlValueFloat32List* self = reinterpret_cast<FlValueFloat32List*>(
fl_value_new(FL_VALUE_TYPE_FLOAT32_LIST, sizeof(FlValueFloat32List)));
self->values_length = data_length;
self->values = static_cast<float*>(g_malloc(sizeof(float) * data_length));
memcpy(self->values, data, sizeof(float) * data_length);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_float_list(const double* data,
size_t data_length) {
FlValueFloatList* self = reinterpret_cast<FlValueFloatList*>(
fl_value_new(FL_VALUE_TYPE_FLOAT_LIST, sizeof(FlValueFloatList)));
self->values_length = data_length;
self->values = static_cast<double*>(g_malloc(sizeof(double) * data_length));
memcpy(self->values, data, sizeof(double) * data_length);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_list() {
FlValueList* self = reinterpret_cast<FlValueList*>(
fl_value_new(FL_VALUE_TYPE_LIST, sizeof(FlValueList)));
self->values = g_ptr_array_new_with_free_func(fl_value_destroy);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_list_from_strv(
const gchar* const* str_array) {
g_return_val_if_fail(str_array != nullptr, nullptr);
g_autoptr(FlValue) value = fl_value_new_list();
for (int i = 0; str_array[i] != nullptr; i++) {
fl_value_append_take(value, fl_value_new_string(str_array[i]));
}
return fl_value_ref(value);
}
G_MODULE_EXPORT FlValue* fl_value_new_map() {
FlValueMap* self = reinterpret_cast<FlValueMap*>(
fl_value_new(FL_VALUE_TYPE_MAP, sizeof(FlValueMap)));
self->keys = g_ptr_array_new_with_free_func(fl_value_destroy);
self->values = g_ptr_array_new_with_free_func(fl_value_destroy);
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_custom(int type,
gconstpointer value,
GDestroyNotify destroy_notify) {
FlValueCustom* self = reinterpret_cast<FlValueCustom*>(
fl_value_new(FL_VALUE_TYPE_CUSTOM, sizeof(FlValueCustom)));
self->type = type;
self->value = value;
self->destroy_notify = destroy_notify;
return reinterpret_cast<FlValue*>(self);
}
G_MODULE_EXPORT FlValue* fl_value_new_custom_object(int type, GObject* object) {
return fl_value_new_custom(type, g_object_ref(object), g_object_unref);
}
G_MODULE_EXPORT FlValue* fl_value_new_custom_object_take(int type,
GObject* object) {
return fl_value_new_custom(type, object, g_object_unref);
}
G_MODULE_EXPORT FlValue* fl_value_ref(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
self->ref_count++;
return self;
}
G_MODULE_EXPORT void fl_value_unref(FlValue* self) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->ref_count > 0);
self->ref_count--;
if (self->ref_count != 0) {
return;
}
switch (self->type) {
case FL_VALUE_TYPE_STRING: {
FlValueString* v = reinterpret_cast<FlValueString*>(self);
g_free(v->value);
break;
}
case FL_VALUE_TYPE_UINT8_LIST: {
FlValueUint8List* v = reinterpret_cast<FlValueUint8List*>(self);
g_free(v->values);
break;
}
case FL_VALUE_TYPE_INT32_LIST: {
FlValueInt32List* v = reinterpret_cast<FlValueInt32List*>(self);
g_free(v->values);
break;
}
case FL_VALUE_TYPE_INT64_LIST: {
FlValueInt64List* v = reinterpret_cast<FlValueInt64List*>(self);
g_free(v->values);
break;
}
case FL_VALUE_TYPE_FLOAT32_LIST: {
FlValueFloat32List* v = reinterpret_cast<FlValueFloat32List*>(self);
g_free(v->values);
break;
}
case FL_VALUE_TYPE_FLOAT_LIST: {
FlValueFloatList* v = reinterpret_cast<FlValueFloatList*>(self);
g_free(v->values);
break;
}
case FL_VALUE_TYPE_LIST: {
FlValueList* v = reinterpret_cast<FlValueList*>(self);
g_ptr_array_unref(v->values);
break;
}
case FL_VALUE_TYPE_MAP: {
FlValueMap* v = reinterpret_cast<FlValueMap*>(self);
g_ptr_array_unref(v->keys);
g_ptr_array_unref(v->values);
break;
}
case FL_VALUE_TYPE_CUSTOM: {
FlValueCustom* v = reinterpret_cast<FlValueCustom*>(self);
if (v->destroy_notify != nullptr) {
v->destroy_notify((gpointer)v->value);
}
break;
}
case FL_VALUE_TYPE_NULL:
case FL_VALUE_TYPE_BOOL:
case FL_VALUE_TYPE_INT:
case FL_VALUE_TYPE_FLOAT:
break;
}
g_free(self);
}
G_MODULE_EXPORT FlValueType fl_value_get_type(FlValue* self) {
g_return_val_if_fail(self != nullptr, FL_VALUE_TYPE_NULL);
return self->type;
}
G_MODULE_EXPORT bool fl_value_equal(FlValue* a, FlValue* b) {
g_return_val_if_fail(a != nullptr, false);
g_return_val_if_fail(b != nullptr, false);
if (a->type != b->type) {
return false;
}
switch (a->type) {
case FL_VALUE_TYPE_NULL:
return true;
case FL_VALUE_TYPE_BOOL:
return fl_value_get_bool(a) == fl_value_get_bool(b);
case FL_VALUE_TYPE_INT:
return fl_value_get_int(a) == fl_value_get_int(b);
case FL_VALUE_TYPE_FLOAT:
return fl_value_get_float(a) == fl_value_get_float(b);
case FL_VALUE_TYPE_STRING: {
FlValueString* a_ = reinterpret_cast<FlValueString*>(a);
FlValueString* b_ = reinterpret_cast<FlValueString*>(b);
return g_strcmp0(a_->value, b_->value) == 0;
}
case FL_VALUE_TYPE_UINT8_LIST: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
const uint8_t* values_a = fl_value_get_uint8_list(a);
const uint8_t* values_b = fl_value_get_uint8_list(b);
for (size_t i = 0; i < fl_value_get_length(a); i++) {
if (values_a[i] != values_b[i]) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_INT32_LIST: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
const int32_t* values_a = fl_value_get_int32_list(a);
const int32_t* values_b = fl_value_get_int32_list(b);
for (size_t i = 0; i < fl_value_get_length(a); i++) {
if (values_a[i] != values_b[i]) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_INT64_LIST: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
const int64_t* values_a = fl_value_get_int64_list(a);
const int64_t* values_b = fl_value_get_int64_list(b);
for (size_t i = 0; i < fl_value_get_length(a); i++) {
if (values_a[i] != values_b[i]) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_FLOAT32_LIST: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
const float* values_a = fl_value_get_float32_list(a);
const float* values_b = fl_value_get_float32_list(b);
for (size_t i = 0; i < fl_value_get_length(a); i++) {
if (values_a[i] != values_b[i]) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_FLOAT_LIST: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
const double* values_a = fl_value_get_float_list(a);
const double* values_b = fl_value_get_float_list(b);
for (size_t i = 0; i < fl_value_get_length(a); i++) {
if (values_a[i] != values_b[i]) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_LIST: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
for (size_t i = 0; i < fl_value_get_length(a); i++) {
if (!fl_value_equal(fl_value_get_list_value(a, i),
fl_value_get_list_value(b, i))) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_MAP: {
if (fl_value_get_length(a) != fl_value_get_length(b)) {
return false;
}
for (size_t i = 0; i < fl_value_get_length(a); i++) {
FlValue* key = fl_value_get_map_key(a, i);
FlValue* value_b = fl_value_lookup(b, key);
if (value_b == nullptr) {
return false;
}
FlValue* value_a = fl_value_get_map_value(a, i);
if (!fl_value_equal(value_a, value_b)) {
return false;
}
}
return true;
}
case FL_VALUE_TYPE_CUSTOM:
return false;
}
}
G_MODULE_EXPORT void fl_value_append(FlValue* self, FlValue* value) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->type == FL_VALUE_TYPE_LIST);
g_return_if_fail(value != nullptr);
fl_value_append_take(self, fl_value_ref(value));
}
G_MODULE_EXPORT void fl_value_append_take(FlValue* self, FlValue* value) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->type == FL_VALUE_TYPE_LIST);
g_return_if_fail(value != nullptr);
FlValueList* v = reinterpret_cast<FlValueList*>(self);
g_ptr_array_add(v->values, value);
}
G_MODULE_EXPORT void fl_value_set(FlValue* self, FlValue* key, FlValue* value) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->type == FL_VALUE_TYPE_MAP);
g_return_if_fail(key != nullptr);
g_return_if_fail(value != nullptr);
fl_value_set_take(self, fl_value_ref(key), fl_value_ref(value));
}
G_MODULE_EXPORT void fl_value_set_take(FlValue* self,
FlValue* key,
FlValue* value) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->type == FL_VALUE_TYPE_MAP);
g_return_if_fail(key != nullptr);
g_return_if_fail(value != nullptr);
FlValueMap* v = reinterpret_cast<FlValueMap*>(self);
ssize_t index = fl_value_lookup_index(self, key);
if (index < 0) {
g_ptr_array_add(v->keys, key);
g_ptr_array_add(v->values, value);
} else {
fl_value_destroy(v->keys->pdata[index]);
v->keys->pdata[index] = key;
fl_value_destroy(v->values->pdata[index]);
v->values->pdata[index] = value;
}
}
G_MODULE_EXPORT void fl_value_set_string(FlValue* self,
const gchar* key,
FlValue* value) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->type == FL_VALUE_TYPE_MAP);
g_return_if_fail(key != nullptr);
g_return_if_fail(value != nullptr);
fl_value_set_take(self, fl_value_new_string(key), fl_value_ref(value));
}
G_MODULE_EXPORT void fl_value_set_string_take(FlValue* self,
const gchar* key,
FlValue* value) {
g_return_if_fail(self != nullptr);
g_return_if_fail(self->type == FL_VALUE_TYPE_MAP);
g_return_if_fail(key != nullptr);
g_return_if_fail(value != nullptr);
fl_value_set_take(self, fl_value_new_string(key), value);
}
G_MODULE_EXPORT bool fl_value_get_bool(FlValue* self) {
g_return_val_if_fail(self != nullptr, FALSE);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_BOOL, FALSE);
FlValueBool* v = reinterpret_cast<FlValueBool*>(self);
return v->value;
}
G_MODULE_EXPORT int64_t fl_value_get_int(FlValue* self) {
g_return_val_if_fail(self != nullptr, 0);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_INT, 0);
FlValueInt* v = reinterpret_cast<FlValueInt*>(self);
return v->value;
}
G_MODULE_EXPORT double fl_value_get_float(FlValue* self) {
g_return_val_if_fail(self != nullptr, 0.0);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_FLOAT, 0.0);
FlValueDouble* v = reinterpret_cast<FlValueDouble*>(self);
return v->value;
}
G_MODULE_EXPORT const gchar* fl_value_get_string(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_STRING, nullptr);
FlValueString* v = reinterpret_cast<FlValueString*>(self);
return v->value;
}
G_MODULE_EXPORT const uint8_t* fl_value_get_uint8_list(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_UINT8_LIST, nullptr);
FlValueUint8List* v = reinterpret_cast<FlValueUint8List*>(self);
return v->values;
}
G_MODULE_EXPORT const int32_t* fl_value_get_int32_list(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_INT32_LIST, nullptr);
FlValueInt32List* v = reinterpret_cast<FlValueInt32List*>(self);
return v->values;
}
G_MODULE_EXPORT const int64_t* fl_value_get_int64_list(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_INT64_LIST, nullptr);
FlValueInt64List* v = reinterpret_cast<FlValueInt64List*>(self);
return v->values;
}
G_MODULE_EXPORT const float* fl_value_get_float32_list(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_FLOAT32_LIST, nullptr);
FlValueFloat32List* v = reinterpret_cast<FlValueFloat32List*>(self);
return v->values;
}
G_MODULE_EXPORT const double* fl_value_get_float_list(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_FLOAT_LIST, nullptr);
FlValueFloatList* v = reinterpret_cast<FlValueFloatList*>(self);
return v->values;
}
G_MODULE_EXPORT size_t fl_value_get_length(FlValue* self) {
g_return_val_if_fail(self != nullptr, 0);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_UINT8_LIST ||
self->type == FL_VALUE_TYPE_INT32_LIST ||
self->type == FL_VALUE_TYPE_INT64_LIST ||
self->type == FL_VALUE_TYPE_FLOAT32_LIST ||
self->type == FL_VALUE_TYPE_FLOAT_LIST ||
self->type == FL_VALUE_TYPE_LIST ||
self->type == FL_VALUE_TYPE_MAP,
0);
switch (self->type) {
case FL_VALUE_TYPE_UINT8_LIST: {
FlValueUint8List* v = reinterpret_cast<FlValueUint8List*>(self);
return v->values_length;
}
case FL_VALUE_TYPE_INT32_LIST: {
FlValueInt32List* v = reinterpret_cast<FlValueInt32List*>(self);
return v->values_length;
}
case FL_VALUE_TYPE_INT64_LIST: {
FlValueInt64List* v = reinterpret_cast<FlValueInt64List*>(self);
return v->values_length;
}
case FL_VALUE_TYPE_FLOAT32_LIST: {
FlValueFloat32List* v = reinterpret_cast<FlValueFloat32List*>(self);
return v->values_length;
}
case FL_VALUE_TYPE_FLOAT_LIST: {
FlValueFloatList* v = reinterpret_cast<FlValueFloatList*>(self);
return v->values_length;
}
case FL_VALUE_TYPE_LIST: {
FlValueList* v = reinterpret_cast<FlValueList*>(self);
return v->values->len;
}
case FL_VALUE_TYPE_MAP: {
FlValueMap* v = reinterpret_cast<FlValueMap*>(self);
return v->keys->len;
}
case FL_VALUE_TYPE_NULL:
case FL_VALUE_TYPE_BOOL:
case FL_VALUE_TYPE_INT:
case FL_VALUE_TYPE_FLOAT:
case FL_VALUE_TYPE_STRING:
case FL_VALUE_TYPE_CUSTOM:
return 0;
}
return 0;
}
G_MODULE_EXPORT FlValue* fl_value_get_list_value(FlValue* self, size_t index) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_LIST, nullptr);
FlValueList* v = reinterpret_cast<FlValueList*>(self);
return static_cast<FlValue*>(g_ptr_array_index(v->values, index));
}
G_MODULE_EXPORT FlValue* fl_value_get_map_key(FlValue* self, size_t index) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_MAP, nullptr);
FlValueMap* v = reinterpret_cast<FlValueMap*>(self);
return static_cast<FlValue*>(g_ptr_array_index(v->keys, index));
}
G_MODULE_EXPORT FlValue* fl_value_get_map_value(FlValue* self, size_t index) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_MAP, nullptr);
FlValueMap* v = reinterpret_cast<FlValueMap*>(self);
return static_cast<FlValue*>(g_ptr_array_index(v->values, index));
}
G_MODULE_EXPORT FlValue* fl_value_lookup(FlValue* self, FlValue* key) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_MAP, nullptr);
ssize_t index = fl_value_lookup_index(self, key);
if (index < 0) {
return nullptr;
}
return fl_value_get_map_value(self, index);
}
G_MODULE_EXPORT FlValue* fl_value_lookup_string(FlValue* self,
const gchar* key) {
g_return_val_if_fail(self != nullptr, nullptr);
FlValue* string_key = fl_value_new_string(key);
FlValue* value = fl_value_lookup(self, string_key);
// Explicit unref used because the g_autoptr is triggering a false positive
// with clang-tidy.
fl_value_unref(string_key);
return value;
}
G_MODULE_EXPORT int fl_value_get_custom_type(FlValue* self) {
g_return_val_if_fail(self != nullptr, -1);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_CUSTOM, -1);
FlValueCustom* v = reinterpret_cast<FlValueCustom*>(self);
return v->type;
}
G_MODULE_EXPORT gconstpointer fl_value_get_custom_value(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_CUSTOM, nullptr);
FlValueCustom* v = reinterpret_cast<FlValueCustom*>(self);
return v->value;
}
G_MODULE_EXPORT GObject* fl_value_get_custom_value_object(FlValue* self) {
g_return_val_if_fail(self != nullptr, nullptr);
g_return_val_if_fail(self->type == FL_VALUE_TYPE_CUSTOM, nullptr);
FlValueCustom* v = reinterpret_cast<FlValueCustom*>(self);
return G_OBJECT(v->value);
}
G_MODULE_EXPORT gchar* fl_value_to_string(FlValue* value) {
GString* buffer = g_string_new("");
value_to_string(value, buffer);
return g_string_free(buffer, FALSE);
}
| engine/shell/platform/linux/fl_value.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_value.cc",
"repo_id": "engine",
"token_count": 12547
} | 373 |
// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_EVENT_CHANNEL_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_EVENT_CHANNEL_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <gio/gio.h>
#include <glib-object.h>
#include <gmodule.h>
#include "fl_binary_messenger.h"
#include "fl_method_channel.h"
#include "fl_method_response.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlEventChannel,
fl_event_channel,
FL,
EVENT_CHANNEL,
GObject)
/**
* FlEventChannel:
*
* #FlEventChannel is an object that allows sending
* an events stream to Dart code over platform channels.
*
* The following example shows how to send events on a channel:
*
* |[<!-- language="C" -->
* static FlEventChannel *channel = NULL;
* static gboolean send_events = FALSE;
*
* static void event_occurs_cb (FooEvent *event) {
* if (send_events) {
* g_autoptr(FlValue) message = foo_event_to_value (event);
* g_autoptr(GError) error = NULL;
* if (!fl_event_channel_send (channel, message, NULL, &error)) {
* g_warning ("Failed to send event: %s", error->message);
* }
* }
* }
*
* static FlMethodErrorResponse* listen_cb (FlEventChannel* channel,
* FlValue *args,
* gpointer user_data) {
* send_events = TRUE;
* return NULL;
* }
*
* static FlMethodErrorResponse* cancel_cb (GObject *object,
* FlValue *args,
* gpointer user_data) {
* send_events = FALSE;
* return NULL;
* }
*
* static void setup_channel () {
* g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new ();
* channel = fl_event_channel_new (messenger, "flutter/foo",
* FL_METHOD_CODEC (codec));
* fl_event_channel_set_stream_handlers (channel, listen_cb, cancel_cb,
* NULL, NULL);
* }
* ]|
*
* #FlEventChannel matches the EventChannel class in the Flutter
* services library.
*/
/**
* FlEventChannelHandler:
* @channel: an #FlEventChannel.
* @args: arguments passed from the Dart end of the channel.
* @user_data: (closure): data provided when registering this handler.
*
* Function called when the stream is listened to or cancelled.
*
* Returns: (transfer full): an #FlMethodErrorResponse or %NULL if no error.
*/
typedef FlMethodErrorResponse* (*FlEventChannelHandler)(FlEventChannel* channel,
FlValue* args,
gpointer user_data);
/**
* fl_event_channel_new:
* @messenger: an #FlBinaryMessenger.
* @name: a channel name.
* @codec: the message codec.
*
* Creates an event channel. @codec must match the codec used on the Dart
* end of the channel.
*
* Returns: a new #FlEventChannel.
*/
FlEventChannel* fl_event_channel_new(FlBinaryMessenger* messenger,
const gchar* name,
FlMethodCodec* codec);
/**
* fl_event_channel_set_stream_handlers:
* @channel: an #FlEventChannel.
* @listen_handler: (allow-none): function to call when the Dart side of the
* channel starts listening to the stream.
* @cancel_handler: (allow-none): function to call when the Dart side of the
* channel cancels their subscription to the stream.
* @user_data: (closure): user data to pass to @listen_handler and
* @cancel_handler.
* @destroy_notify: (allow-none): a function which gets called to free
* @user_data, or %NULL.
*
* Sets the functions called when the Dart side requests the stream to start and
* finish.
*
* The handlers are removed if the channel is closed or is replaced by another
* handler, set @destroy_notify if you want to detect this.
*/
void fl_event_channel_set_stream_handlers(FlEventChannel* channel,
FlEventChannelHandler listen_handler,
FlEventChannelHandler cancel_handler,
gpointer user_data,
GDestroyNotify destroy_notify);
/**
* fl_event_channel_send:
* @channel: an #FlEventChannel.
* @event: event to send, must match what the #FlMethodCodec supports.
* @cancellable: (allow-none): a #GCancellable or %NULL.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Sends an event on the channel.
* Events should only be sent once the channel is being listened to.
*
* Returns: %TRUE if successful.
*/
gboolean fl_event_channel_send(FlEventChannel* channel,
FlValue* event,
GCancellable* cancellable,
GError** error);
/**
* fl_event_channel_send_error:
* @channel: an #FlEventChannel.
* @code: error code to send.
* @message: error message to send.
* @details: (allow-none): error details or %NULL.
* @cancellable: (allow-none): a #GCancellable or %NULL.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Sends an error on the channel.
* Errors should only be sent once the channel is being listened to.
*
* Returns: %TRUE if successful.
*/
gboolean fl_event_channel_send_error(FlEventChannel* channel,
const gchar* code,
const gchar* message,
FlValue* details,
GCancellable* cancellable,
GError** error);
/**
* fl_event_channel_send_end_of_stream:
* @channel: an #FlEventChannel.
* @cancellable: (allow-none): a #GCancellable or %NULL.
* @error: (allow-none): #GError location to store the error occurring, or %NULL
* to ignore.
*
* Indicates the stream has completed.
* It is a programmer error to send any more events after calling this.
*
* Returns: %TRUE if successful.
*/
gboolean fl_event_channel_send_end_of_stream(FlEventChannel* channel,
GCancellable* cancellable,
GError** error);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_EVENT_CHANNEL_H_
| engine/shell/platform/linux/public/flutter_linux/fl_event_channel.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_event_channel.h",
"repo_id": "engine",
"token_count": 2925
} | 374 |
// 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_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_REGISTRAR_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <glib-object.h>
#include <gmodule.h>
#include <stdint.h>
#include "fl_texture.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_INTERFACE(FlTextureRegistrar,
fl_texture_registrar,
FL,
TEXTURE_REGISTRAR,
GObject)
struct _FlTextureRegistrarInterface {
GTypeInterface parent_iface;
gboolean (*register_texture)(FlTextureRegistrar* registrar,
FlTexture* texture);
FlTexture* (*lookup_texture)(FlTextureRegistrar* registrar, int64_t id);
gboolean (*mark_texture_frame_available)(FlTextureRegistrar* registrar,
FlTexture* texture);
gboolean (*unregister_texture)(FlTextureRegistrar* registrar,
FlTexture* texture);
};
/**
* FlTextureRegistrar:
*
* #FlTextureRegistrar is used when registering textures.
*
* Flutter Framework accesses your texture by the related unique texture ID. To
* draw your texture in Dart, you should add Texture widget in your widget tree
* with the same texture ID. Use platform channels to send this unique texture
* ID to the Dart side.
*/
/**
* fl_texture_registrar_register_texture:
* @registrar: an #FlTextureRegistrar.
* @texture: an #FlTexture for registration.
*
* Registers a texture.
*
* Returns: %TRUE on success.
*/
gboolean fl_texture_registrar_register_texture(FlTextureRegistrar* registrar,
FlTexture* texture);
/**
* fl_texture_registrar_mark_texture_frame_available:
* @registrar: an #FlTextureRegistrar.
* @texture: the texture that has a frame available.
*
* Notifies the flutter engine that the texture object has updated and needs to
* be rerendered.
*
* Returns: %TRUE on success.
*/
gboolean fl_texture_registrar_mark_texture_frame_available(
FlTextureRegistrar* registrar,
FlTexture* texture);
/**
* fl_texture_registrar_unregister_texture:
* @registrar: an #FlTextureRegistrar.
* @texture: the texture being unregistered.
*
* Unregisters an existing texture object.
*
* Returns: %TRUE on success.
*/
gboolean fl_texture_registrar_unregister_texture(FlTextureRegistrar* registrar,
FlTexture* texture);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_REGISTRAR_H_
| engine/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h",
"repo_id": "engine",
"token_count": 1152
} | 375 |
// 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 "flutter/shell/platform/linux/testing/mock_im_context.h"
using namespace flutter::testing;
G_DECLARE_FINAL_TYPE(FlMockIMContext,
fl_mock_im_context,
FL,
MOCK_IM_CONTEXT,
GtkIMContext)
struct _FlMockIMContext {
GtkIMContext parent_instance;
MockIMContext* mock;
};
G_DEFINE_TYPE(FlMockIMContext, fl_mock_im_context, GTK_TYPE_IM_CONTEXT)
static void fl_mock_im_context_set_client_window(GtkIMContext* context,
GdkWindow* window) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_set_client_window(context, window);
}
static void fl_mock_im_context_get_preedit_string(GtkIMContext* context,
gchar** str,
PangoAttrList** attrs,
gint* cursor_pos) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_get_preedit_string(context, str, attrs,
cursor_pos);
}
static gboolean fl_mock_im_context_filter_keypress(GtkIMContext* context,
GdkEventKey* event) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
return self->mock->gtk_im_context_filter_keypress(context, event);
}
static void fl_mock_im_context_focus_in(GtkIMContext* context) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_focus_in(context);
}
static void fl_mock_im_context_focus_out(GtkIMContext* context) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_focus_out(context);
}
static void fl_mock_im_context_reset(GtkIMContext* context) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_reset(context);
}
static void fl_mock_im_context_set_cursor_location(GtkIMContext* context,
GdkRectangle* area) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_set_cursor_location(context, area);
}
static void fl_mock_im_context_set_use_preedit(GtkIMContext* context,
gboolean use_preedit) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_set_use_preedit(context, use_preedit);
}
static void fl_mock_im_context_set_surrounding(GtkIMContext* context,
const gchar* text,
gint len,
gint cursor_index) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
self->mock->gtk_im_context_set_surrounding(context, text, len, cursor_index);
}
static gboolean fl_mock_im_context_get_surrounding(GtkIMContext* context,
gchar** text,
gint* cursor_index) {
FlMockIMContext* self = FL_MOCK_IM_CONTEXT(context);
return self->mock->gtk_im_context_get_surrounding(context, text,
cursor_index);
}
static void fl_mock_im_context_class_init(FlMockIMContextClass* klass) {
GtkIMContextClass* im_context_class = GTK_IM_CONTEXT_CLASS(klass);
im_context_class->set_client_window = fl_mock_im_context_set_client_window;
im_context_class->get_preedit_string = fl_mock_im_context_get_preedit_string;
im_context_class->filter_keypress = fl_mock_im_context_filter_keypress;
im_context_class->focus_in = fl_mock_im_context_focus_in;
im_context_class->focus_out = fl_mock_im_context_focus_out;
im_context_class->reset = fl_mock_im_context_reset;
im_context_class->set_cursor_location =
fl_mock_im_context_set_cursor_location;
im_context_class->set_use_preedit = fl_mock_im_context_set_use_preedit;
im_context_class->set_surrounding = fl_mock_im_context_set_surrounding;
im_context_class->get_surrounding = fl_mock_im_context_get_surrounding;
}
static void fl_mock_im_context_init(FlMockIMContext* self) {}
static GtkIMContext* fl_mock_im_context_new(MockIMContext* mock) {
FlMockIMContext* self =
FL_MOCK_IM_CONTEXT(g_object_new(fl_mock_im_context_get_type(), nullptr));
self->mock = mock;
return GTK_IM_CONTEXT(self);
}
MockIMContext::~MockIMContext() {
if (FL_IS_MOCK_IM_CONTEXT(instance_)) {
g_clear_object(&instance_);
}
}
MockIMContext::operator GtkIMContext*() {
if (instance_ == nullptr) {
instance_ = fl_mock_im_context_new(this);
}
return instance_;
}
| engine/shell/platform/linux/testing/mock_im_context.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_im_context.cc",
"repo_id": "engine",
"token_count": 2365
} | 376 |
# 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.
assert(is_win)
import("//flutter/shell/platform/glfw/config.gni")
import("//flutter/testing/testing.gni")
_public_headers = [ "public/flutter_windows.h" ]
_internal_headers = [ "flutter_windows_internal.h" ]
config("relative_angle_headers") {
include_dirs = [ "//flutter/third_party/angle/include" ]
}
# Any files that are built by clients (client_wrapper code, library headers for
# implementations using this shared code, etc.) include the public headers
# assuming they are in the include path. This configuration should be added to
# any such code that is also built by GN to make the includes work.
config("relative_flutter_windows_headers") {
include_dirs = [ "public" ]
}
# The headers are a separate source set since the client wrapper is allowed
# to depend on the public headers, but none of the rest of the code.
source_set("flutter_windows_headers") {
public = _public_headers + _internal_headers
public_deps = [ "//flutter/shell/platform/common:common_cpp_library_headers" ]
configs +=
[ "//flutter/shell/platform/common:desktop_library_implementation" ]
public_configs =
[ "//flutter/shell/platform/common:relative_flutter_library_headers" ]
}
source_set("flutter_windows_source") {
# Common Windows sources.
sources = [
"accessibility_bridge_windows.cc",
"accessibility_bridge_windows.h",
"accessibility_plugin.cc",
"accessibility_plugin.h",
"compositor.h",
"compositor_opengl.cc",
"compositor_opengl.h",
"compositor_software.cc",
"compositor_software.h",
"cursor_handler.cc",
"cursor_handler.h",
"direct_manipulation.cc",
"direct_manipulation.h",
"dpi_utils.cc",
"dpi_utils.h",
"egl/context.cc",
"egl/context.h",
"egl/egl.cc",
"egl/egl.h",
"egl/manager.cc",
"egl/manager.h",
"egl/proc_table.cc",
"egl/proc_table.h",
"egl/surface.cc",
"egl/surface.h",
"egl/window_surface.cc",
"egl/window_surface.h",
"event_watcher.cc",
"event_watcher.h",
"external_texture.h",
"external_texture_d3d.cc",
"external_texture_d3d.h",
"external_texture_pixelbuffer.cc",
"external_texture_pixelbuffer.h",
"flutter_key_map.g.cc",
"flutter_platform_node_delegate_windows.cc",
"flutter_platform_node_delegate_windows.h",
"flutter_project_bundle.cc",
"flutter_project_bundle.h",
"flutter_window.cc",
"flutter_window.h",
"flutter_windows.cc",
"flutter_windows_engine.cc",
"flutter_windows_engine.h",
"flutter_windows_texture_registrar.cc",
"flutter_windows_texture_registrar.h",
"flutter_windows_view.cc",
"flutter_windows_view.h",
"flutter_windows_view_controller.h",
"keyboard_handler_base.h",
"keyboard_key_channel_handler.cc",
"keyboard_key_channel_handler.h",
"keyboard_key_embedder_handler.cc",
"keyboard_key_embedder_handler.h",
"keyboard_key_handler.cc",
"keyboard_key_handler.h",
"keyboard_manager.cc",
"keyboard_manager.h",
"keyboard_utils.cc",
"keyboard_utils.h",
"platform_handler.cc",
"platform_handler.h",
"platform_view_manager.cc",
"platform_view_manager.h",
"platform_view_plugin.cc",
"platform_view_plugin.h",
"sequential_id_generator.cc",
"sequential_id_generator.h",
"settings_plugin.cc",
"settings_plugin.h",
"system_utils.cc",
"system_utils.h",
"task_runner.cc",
"task_runner.h",
"task_runner_window.cc",
"task_runner_window.h",
"text_input_manager.cc",
"text_input_manager.h",
"text_input_plugin.cc",
"text_input_plugin.h",
"window_binding_handler.h",
"window_binding_handler_delegate.h",
"window_proc_delegate_manager.cc",
"window_proc_delegate_manager.h",
"window_state.h",
"windows_lifecycle_manager.cc",
"windows_lifecycle_manager.h",
"windows_proc_table.cc",
"windows_proc_table.h",
"windowsx_shim.h",
]
libs = [
"dwmapi.lib",
"imm32.lib",
]
configs += [
"//flutter/shell/platform/common:desktop_library_implementation",
"//flutter/third_party/angle:gl_prototypes",
]
public_configs = [ ":relative_angle_headers" ]
defines = [ "FLUTTER_ENGINE_NO_PROTOTYPES" ]
public_deps = [
"//flutter/fml:string_conversion",
"//flutter/shell/platform/common:common_cpp_accessibility",
"//flutter/shell/platform/common:common_cpp_enums",
]
deps = [
":flutter_windows_headers",
"//flutter/fml:fml",
"//flutter/impeller/renderer/backend/gles",
"//flutter/shell/platform/common:common_cpp",
"//flutter/shell/platform/common:common_cpp_input",
"//flutter/shell/platform/common:common_cpp_switches",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/embedder:embedder_as_internal_library",
"//flutter/shell/platform/windows/client_wrapper:client_wrapper_windows",
# libEGL_static MUST be ordered before libGLESv2_static in this list. If
# reversed, a linker error will occur, reporting DllMain already defined in
# LIBCMTD.lib
"//flutter/third_party/angle:libEGL_static",
"//flutter/third_party/angle:libGLESv2_static",
"//flutter/third_party/rapidjson",
]
}
copy("publish_headers_windows") {
sources = _public_headers
outputs = [ "$root_out_dir/{{source_file_part}}" ]
# The Windows header assumes the presence of the common headers.
deps = [ "//flutter/shell/platform/common:publish_headers" ]
}
shared_library("flutter_windows") {
deps = [ ":flutter_windows_source" ]
public_configs = [ "//flutter:config" ]
}
test_fixtures("flutter_windows_fixtures") {
dart_main = "fixtures/main.dart"
fixtures = []
}
executable("flutter_windows_unittests") {
testonly = true
# Common Windows test sources.
sources = [
"accessibility_bridge_windows_unittests.cc",
"compositor_opengl_unittests.cc",
"compositor_software_unittests.cc",
"cursor_handler_unittests.cc",
"direct_manipulation_unittests.cc",
"dpi_utils_unittests.cc",
"flutter_project_bundle_unittests.cc",
"flutter_window_unittests.cc",
"flutter_windows_engine_unittests.cc",
"flutter_windows_texture_registrar_unittests.cc",
"flutter_windows_unittests.cc",
"flutter_windows_view_unittests.cc",
"keyboard_key_channel_handler_unittests.cc",
"keyboard_key_embedder_handler_unittests.cc",
"keyboard_key_handler_unittests.cc",
"keyboard_unittests.cc",
"keyboard_utils_unittests.cc",
"platform_handler_unittests.cc",
"sequential_id_generator_unittests.cc",
"settings_plugin_unittests.cc",
"system_utils_unittests.cc",
"task_runner_unittests.cc",
"testing/egl/mock_context.h",
"testing/egl/mock_manager.h",
"testing/egl/mock_proc_table.h",
"testing/egl/mock_window_surface.h",
"testing/engine_modifier.h",
"testing/flutter_windows_engine_builder.cc",
"testing/flutter_windows_engine_builder.h",
"testing/mock_direct_manipulation.h",
"testing/mock_platform_view_manager.h",
"testing/mock_text_input_manager.cc",
"testing/mock_text_input_manager.h",
"testing/mock_window.cc",
"testing/mock_window.h",
"testing/mock_window_binding_handler.cc",
"testing/mock_window_binding_handler.h",
"testing/mock_windows_proc_table.h",
"testing/test_keyboard.cc",
"testing/test_keyboard.h",
"testing/test_keyboard_unittests.cc",
"testing/view_modifier.h",
"testing/windows_test.cc",
"testing/windows_test.h",
"testing/windows_test_config_builder.cc",
"testing/windows_test_config_builder.h",
"testing/windows_test_context.cc",
"testing/windows_test_context.h",
"testing/wm_builders.cc",
"testing/wm_builders.h",
"text_input_plugin_unittest.cc",
"window_proc_delegate_manager_unittests.cc",
"window_unittests.cc",
"windows_lifecycle_manager_unittests.cc",
]
configs +=
[ "//flutter/shell/platform/common:desktop_library_implementation" ]
public_configs = [ "//flutter:config" ]
deps = [
":flutter_windows_fixtures",
":flutter_windows_headers",
":flutter_windows_source",
"//flutter/impeller/renderer/backend/gles",
"//flutter/shell/platform/common:common_cpp",
"//flutter/shell/platform/common/client_wrapper:client_wrapper",
"//flutter/shell/platform/embedder:embedder_as_internal_library",
"//flutter/shell/platform/embedder:embedder_test_utils",
"//flutter/testing",
"//flutter/testing:dart",
"//flutter/third_party/rapidjson",
"//flutter/third_party/tonic",
]
}
shared_library("flutter_windows_glfw") {
deps = [ "//flutter/shell/platform/glfw:flutter_glfw" ]
public_configs = [ "//flutter:config" ]
}
group("windows_glfw") {
deps = [
":flutter_windows",
":flutter_windows_glfw",
"//flutter/shell/platform/glfw:publish_headers_glfw",
"//flutter/shell/platform/glfw/client_wrapper:publish_wrapper_glfw",
]
}
group("windows") {
deps = [
":flutter_windows",
":publish_headers_windows",
"//flutter/shell/platform/windows/client_wrapper:publish_wrapper_windows",
]
if (build_glfw_shell) {
deps += [ ":windows_glfw" ]
}
}
| engine/shell/platform/windows/BUILD.gn/0 | {
"file_path": "engine/shell/platform/windows/BUILD.gn",
"repo_id": "engine",
"token_count": 3785
} | 377 |
// 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_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_
#include <flutter_windows.h>
namespace flutter {
// The unique identifier for a view.
typedef int64_t FlutterViewId;
// A view displaying Flutter content.
class FlutterView {
public:
explicit FlutterView(FlutterDesktopViewRef view) : view_(view) {}
// Destroys this reference to the view. The underlying view is not destroyed.
virtual ~FlutterView() = default;
// Prevent copying.
FlutterView(FlutterView const&) = delete;
FlutterView& operator=(FlutterView const&) = delete;
// Returns the backing HWND for the view.
HWND GetNativeWindow() { return FlutterDesktopViewGetHWND(view_); }
// Returns the DXGI adapter used for rendering or nullptr in case of error.
IDXGIAdapter* GetGraphicsAdapter() {
return FlutterDesktopViewGetGraphicsAdapter(view_);
}
private:
// Handle for interacting with the C API's view.
FlutterDesktopViewRef view_ = nullptr;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_
| engine/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h/0 | {
"file_path": "engine/shell/platform/windows/client_wrapper/include/flutter/flutter_view.h",
"repo_id": "engine",
"token_count": 440
} | 378 |
// 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 "flutter/fml/logging.h"
#include <algorithm>
#include "flutter/shell/platform/windows/direct_manipulation.h"
#include "flutter/shell/platform/windows/flutter_window.h"
#include "flutter/shell/platform/windows/window_binding_handler_delegate.h"
#define RETURN_IF_FAILED(operation) \
if (FAILED(operation)) { \
FML_LOG(ERROR) << #operation << " failed"; \
manager_ = nullptr; \
updateManager_ = nullptr; \
viewport_ = nullptr; \
return -1; \
}
#define WARN_IF_FAILED(operation) \
if (FAILED(operation)) { \
FML_LOG(ERROR) << #operation << " failed"; \
}
namespace flutter {
int32_t DirectManipulationEventHandler::GetDeviceId() {
return (int32_t) reinterpret_cast<int64_t>(this);
}
STDMETHODIMP DirectManipulationEventHandler::QueryInterface(REFIID iid,
void** ppv) {
if ((iid == IID_IUnknown) ||
(iid == IID_IDirectManipulationViewportEventHandler)) {
*ppv = static_cast<IDirectManipulationViewportEventHandler*>(this);
AddRef();
return S_OK;
} else if (iid == IID_IDirectManipulationInteractionEventHandler) {
*ppv = static_cast<IDirectManipulationInteractionEventHandler*>(this);
AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
DirectManipulationEventHandler::GestureData
DirectManipulationEventHandler::ConvertToGestureData(float transform[6]) {
// DirectManipulation provides updates with very high precision. If the user
// holds their fingers steady on a trackpad, DirectManipulation sends
// jittery updates. This calculation will reduce the precision of the scale
// value of the event to avoid jitter.
const int mantissa_bits_chop = 2;
const float factor = (1 << mantissa_bits_chop) + 1;
float c = factor * transform[0];
return GestureData{
c - (c - transform[0]), // scale
transform[4], // pan_x
transform[5], // pan_y
};
}
HRESULT DirectManipulationEventHandler::OnViewportStatusChanged(
IDirectManipulationViewport* viewport,
DIRECTMANIPULATION_STATUS current,
DIRECTMANIPULATION_STATUS previous) {
if (during_synthesized_reset_) {
during_synthesized_reset_ = current != DIRECTMANIPULATION_READY;
return S_OK;
}
during_inertia_ = current == DIRECTMANIPULATION_INERTIA;
if (current == DIRECTMANIPULATION_RUNNING) {
IDirectManipulationContent* content;
HRESULT hr = viewport->GetPrimaryContent(IID_PPV_ARGS(&content));
if (SUCCEEDED(hr)) {
float transform[6];
hr = content->GetContentTransform(transform, ARRAYSIZE(transform));
if (SUCCEEDED(hr)) {
initial_gesture_data_ = ConvertToGestureData(transform);
} else {
FML_LOG(ERROR) << "GetContentTransform failed";
}
} else {
FML_LOG(ERROR) << "GetPrimaryContent failed";
}
if (owner_->binding_handler_delegate) {
owner_->binding_handler_delegate->OnPointerPanZoomStart(GetDeviceId());
}
} else if (previous == DIRECTMANIPULATION_RUNNING) {
// Reset deltas to ensure only inertia values will be compared later.
last_pan_delta_x_ = 0.0;
last_pan_delta_y_ = 0.0;
if (owner_->binding_handler_delegate) {
owner_->binding_handler_delegate->OnPointerPanZoomEnd(GetDeviceId());
}
} else if (previous == DIRECTMANIPULATION_INERTIA) {
if (owner_->binding_handler_delegate &&
(std::max)(std::abs(last_pan_delta_x_), std::abs(last_pan_delta_y_)) >
0.01) {
owner_->binding_handler_delegate->OnScrollInertiaCancel(GetDeviceId());
}
// Need to reset the content transform to its original position
// so that we are ready for the next gesture.
// Use during_synthesized_reset_ flag to prevent sending reset also to the
// framework.
during_synthesized_reset_ = true;
last_pan_x_ = 0.0;
last_pan_y_ = 0.0;
last_pan_delta_x_ = 0.0;
last_pan_delta_y_ = 0.0;
RECT rect;
HRESULT hr = viewport->GetViewportRect(&rect);
if (FAILED(hr)) {
FML_LOG(ERROR) << "Failed to get the current viewport rect";
return E_FAIL;
}
hr = viewport->ZoomToRect(rect.left, rect.top, rect.right, rect.bottom,
false);
if (FAILED(hr)) {
FML_LOG(ERROR) << "Failed to reset the gesture using ZoomToRect";
return E_FAIL;
}
}
return S_OK;
}
HRESULT DirectManipulationEventHandler::OnViewportUpdated(
IDirectManipulationViewport* viewport) {
return S_OK;
}
HRESULT DirectManipulationEventHandler::OnContentUpdated(
IDirectManipulationViewport* viewport,
IDirectManipulationContent* content) {
float transform[6];
HRESULT hr = content->GetContentTransform(transform, ARRAYSIZE(transform));
if (FAILED(hr)) {
FML_LOG(ERROR) << "GetContentTransform failed";
return S_OK;
}
if (!during_synthesized_reset_) {
GestureData data = ConvertToGestureData(transform);
float scale = data.scale / initial_gesture_data_.scale;
float pan_x = data.pan_x - initial_gesture_data_.pan_x;
float pan_y = data.pan_y - initial_gesture_data_.pan_y;
last_pan_delta_x_ = pan_x - last_pan_x_;
last_pan_delta_y_ = pan_y - last_pan_y_;
last_pan_x_ = pan_x;
last_pan_y_ = pan_y;
if (owner_->binding_handler_delegate && !during_inertia_) {
owner_->binding_handler_delegate->OnPointerPanZoomUpdate(
GetDeviceId(), pan_x, pan_y, scale, 0);
}
}
return S_OK;
}
HRESULT DirectManipulationEventHandler::OnInteraction(
IDirectManipulationViewport2* viewport,
DIRECTMANIPULATION_INTERACTION_TYPE interaction) {
return S_OK;
}
ULONG STDMETHODCALLTYPE DirectManipulationEventHandler::AddRef() {
RefCountedThreadSafe::AddRef();
return 0;
}
ULONG STDMETHODCALLTYPE DirectManipulationEventHandler::Release() {
RefCountedThreadSafe::Release();
return 0;
}
DirectManipulationOwner::DirectManipulationOwner(FlutterWindow* window)
: window_(window) {}
int DirectManipulationOwner::Init(unsigned int width, unsigned int height) {
RETURN_IF_FAILED(CoCreateInstance(CLSID_DirectManipulationManager, nullptr,
CLSCTX_INPROC_SERVER,
IID_IDirectManipulationManager, &manager_));
RETURN_IF_FAILED(manager_->GetUpdateManager(
IID_IDirectManipulationUpdateManager, &updateManager_));
RETURN_IF_FAILED(manager_->CreateViewport(nullptr, window_->GetWindowHandle(),
IID_IDirectManipulationViewport,
&viewport_));
DIRECTMANIPULATION_CONFIGURATION configuration =
DIRECTMANIPULATION_CONFIGURATION_INTERACTION |
DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X |
DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y |
DIRECTMANIPULATION_CONFIGURATION_SCALING |
DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA;
RETURN_IF_FAILED(viewport_->ActivateConfiguration(configuration));
RETURN_IF_FAILED(viewport_->SetViewportOptions(
DIRECTMANIPULATION_VIEWPORT_OPTIONS_MANUALUPDATE));
handler_ = fml::MakeRefCounted<DirectManipulationEventHandler>(this);
RETURN_IF_FAILED(viewport_->AddEventHandler(
window_->GetWindowHandle(), handler_.get(), &viewportHandlerCookie_));
RECT rect = {0, 0, (LONG)width, (LONG)height};
RETURN_IF_FAILED(viewport_->SetViewportRect(&rect));
RETURN_IF_FAILED(manager_->Activate(window_->GetWindowHandle()));
RETURN_IF_FAILED(viewport_->Enable());
RETURN_IF_FAILED(updateManager_->Update(nullptr));
return 0;
}
void DirectManipulationOwner::ResizeViewport(unsigned int width,
unsigned int height) {
if (viewport_) {
RECT rect = {0, 0, (LONG)width, (LONG)height};
WARN_IF_FAILED(viewport_->SetViewportRect(&rect));
}
}
void DirectManipulationOwner::Destroy() {
if (handler_) {
handler_->owner_ = nullptr;
}
if (viewport_) {
WARN_IF_FAILED(viewport_->Disable());
WARN_IF_FAILED(viewport_->Disable());
WARN_IF_FAILED(viewport_->RemoveEventHandler(viewportHandlerCookie_));
WARN_IF_FAILED(viewport_->Abandon());
}
if (window_ && manager_) {
WARN_IF_FAILED(manager_->Deactivate(window_->GetWindowHandle()));
}
handler_ = nullptr;
viewport_ = nullptr;
updateManager_ = nullptr;
manager_ = nullptr;
window_ = nullptr;
}
void DirectManipulationOwner::SetContact(UINT contactId) {
if (viewport_) {
viewport_->SetContact(contactId);
}
}
void DirectManipulationOwner::SetBindingHandlerDelegate(
WindowBindingHandlerDelegate* delegate) {
binding_handler_delegate = delegate;
}
void DirectManipulationOwner::Update() {
if (updateManager_) {
HRESULT hr = updateManager_->Update(nullptr);
if (FAILED(hr)) {
FML_LOG(ERROR) << "updateManager_->Update failed";
auto error = GetLastError();
FML_LOG(ERROR) << error;
LPWSTR message = nullptr;
size_t size = FormatMessageW(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPWSTR>(&message), 0, NULL);
FML_LOG(ERROR) << message;
}
}
}
} // namespace flutter
| engine/shell/platform/windows/direct_manipulation.cc/0 | {
"file_path": "engine/shell/platform/windows/direct_manipulation.cc",
"repo_id": "engine",
"token_count": 3961
} | 379 |
// 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 "flutter/shell/platform/windows/egl/window_surface.h"
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/windows/egl/egl.h"
namespace flutter {
namespace egl {
WindowSurface::WindowSurface(EGLDisplay display,
EGLContext context,
EGLSurface surface,
size_t width,
size_t height)
: Surface(display, context, surface), width_(width), height_(height) {}
bool WindowSurface::SetVSyncEnabled(bool enabled) {
FML_DCHECK(IsCurrent());
if (::eglSwapInterval(display_, enabled ? 1 : 0) != EGL_TRUE) {
WINDOWS_LOG_EGL_ERROR;
return false;
}
vsync_enabled_ = enabled;
return true;
}
size_t WindowSurface::width() const {
return width_;
}
size_t WindowSurface::height() const {
return height_;
}
bool WindowSurface::vsync_enabled() const {
return vsync_enabled_;
}
} // namespace egl
} // namespace flutter
| engine/shell/platform/windows/egl/window_surface.cc/0 | {
"file_path": "engine/shell/platform/windows/egl/window_surface.cc",
"repo_id": "engine",
"token_count": 466
} | 380 |
// 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 "flutter/shell/platform/windows/flutter_project_bundle.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(FlutterProjectBundle, BasicPropertiesAbsolutePaths) {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"C:\\foo\\flutter_assets";
properties.icu_data_path = L"C:\\foo\\icudtl.dat";
FlutterProjectBundle project(properties);
EXPECT_TRUE(project.HasValidPaths());
EXPECT_EQ(project.assets_path().string(), "C:\\foo\\flutter_assets");
EXPECT_EQ(project.icu_path().string(), "C:\\foo\\icudtl.dat");
}
TEST(FlutterProjectBundle, BasicPropertiesRelativePaths) {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"foo\\flutter_assets";
properties.icu_data_path = L"foo\\icudtl.dat";
FlutterProjectBundle project(properties);
EXPECT_TRUE(project.HasValidPaths());
EXPECT_TRUE(project.assets_path().is_absolute());
EXPECT_EQ(project.assets_path().filename().string(), "flutter_assets");
EXPECT_TRUE(project.icu_path().is_absolute());
EXPECT_EQ(project.icu_path().filename().string(), "icudtl.dat");
}
TEST(FlutterProjectBundle, SwitchesEmpty) {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"foo\\flutter_assets";
properties.icu_data_path = L"foo\\icudtl.dat";
// Clear the main environment variable, since test order is not guaranteed.
_putenv_s("FLUTTER_ENGINE_SWITCHES", "");
FlutterProjectBundle project(properties);
EXPECT_EQ(project.GetSwitches().size(), 0);
}
TEST(FlutterProjectBundle, DartEntrypointArguments) {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"foo\\flutter_assets";
properties.icu_data_path = L"foo\\icudtl.dat";
std::vector<const char*> test_arguments = {"arg1", "arg2"};
properties.dart_entrypoint_argc = test_arguments.size();
properties.dart_entrypoint_argv = test_arguments.data();
FlutterProjectBundle project(properties);
std::vector<std::string> retrieved_arguments =
project.dart_entrypoint_arguments();
EXPECT_EQ(retrieved_arguments.size(), 2U);
EXPECT_EQ(retrieved_arguments[0], "arg1");
EXPECT_EQ(retrieved_arguments[1], "arg2");
}
#ifndef FLUTTER_RELEASE
TEST(FlutterProjectBundle, Switches) {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"foo\\flutter_assets";
properties.icu_data_path = L"foo\\icudtl.dat";
_putenv_s("FLUTTER_ENGINE_SWITCHES", "2");
_putenv_s("FLUTTER_ENGINE_SWITCH_1", "abc");
_putenv_s("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\"");
FlutterProjectBundle project(properties);
std::vector<std::string> switches = project.GetSwitches();
EXPECT_EQ(switches.size(), 2);
EXPECT_EQ(switches[0], "--abc");
EXPECT_EQ(switches[1], "--foo=\"bar, baz\"");
}
#endif // !FLUTTER_RELEASE
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/flutter_project_bundle_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_project_bundle_unittests.cc",
"repo_id": "engine",
"token_count": 1066
} | 381 |
// 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 "flutter/shell/platform/windows/flutter_windows_view.h"
#include <UIAutomation.h>
#include <comdef.h>
#include <comutil.h>
#include <oleacc.h>
#include <future>
#include <vector>
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/shell/platform/common/json_message_codec.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/windows/flutter_window.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/flutter_windows_texture_registrar.h"
#include "flutter/shell/platform/windows/testing/egl/mock_context.h"
#include "flutter/shell/platform/windows/testing/egl/mock_manager.h"
#include "flutter/shell/platform/windows/testing/egl/mock_window_surface.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
#include "flutter/shell/platform/windows/testing/mock_windows_proc_table.h"
#include "flutter/shell/platform/windows/testing/test_keyboard.h"
#include "flutter/shell/platform/windows/testing/view_modifier.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
using ::testing::_;
using ::testing::InSequence;
using ::testing::NiceMock;
using ::testing::Return;
constexpr uint64_t kScanCodeKeyA = 0x1e;
constexpr uint64_t kVirtualKeyA = 0x41;
namespace {
// A struct to use as a FlutterPlatformMessageResponseHandle so it can keep the
// callbacks and user data passed to the engine's
// PlatformMessageCreateResponseHandle for use in the SendPlatformMessage
// overridden function.
struct TestResponseHandle {
FlutterDesktopBinaryReply callback;
void* user_data;
};
static bool test_response = false;
constexpr uint64_t kKeyEventFromChannel = 0x11;
constexpr uint64_t kKeyEventFromEmbedder = 0x22;
static std::vector<int> key_event_logs;
std::unique_ptr<std::vector<uint8_t>> keyHandlingResponse(bool handled) {
rapidjson::Document document;
auto& allocator = document.GetAllocator();
document.SetObject();
document.AddMember("handled", test_response, allocator);
return flutter::JsonMessageCodec::GetInstance().EncodeMessage(document);
}
// Returns a Flutter project with the required path values to create
// a test engine.
FlutterProjectBundle GetTestProject() {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"C:\\foo\\flutter_assets";
properties.icu_data_path = L"C:\\foo\\icudtl.dat";
properties.aot_library_path = L"C:\\foo\\aot.so";
return FlutterProjectBundle{properties};
}
// Returns an engine instance configured with test project path values, and
// overridden methods for sending platform messages, so that the engine can
// respond as if the framework were connected.
std::unique_ptr<FlutterWindowsEngine> GetTestEngine(
std::shared_ptr<WindowsProcTable> windows_proc_table = nullptr) {
auto engine = std::make_unique<FlutterWindowsEngine>(
GetTestProject(), std::move(windows_proc_table));
EngineModifier modifier(engine.get());
auto key_response_controller = std::make_shared<MockKeyResponseController>();
key_response_controller->SetChannelResponse(
[](MockKeyResponseController::ResponseCallback callback) {
key_event_logs.push_back(kKeyEventFromChannel);
callback(test_response);
});
key_response_controller->SetEmbedderResponse(
[](const FlutterKeyEvent* event,
MockKeyResponseController::ResponseCallback callback) {
key_event_logs.push_back(kKeyEventFromEmbedder);
callback(test_response);
});
modifier.embedder_api().NotifyDisplayUpdate =
MOCK_ENGINE_PROC(NotifyDisplayUpdate,
([engine_instance = engine.get()](
FLUTTER_API_SYMBOL(FlutterEngine) raw_engine,
const FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* embedder_displays,
size_t display_count) { return kSuccess; }));
MockEmbedderApiForKeyboard(modifier, key_response_controller);
engine->Run();
return engine;
}
class MockFlutterWindowsEngine : public FlutterWindowsEngine {
public:
explicit MockFlutterWindowsEngine(
std::shared_ptr<WindowsProcTable> windows_proc_table = nullptr)
: FlutterWindowsEngine(GetTestProject(), std::move(windows_proc_table)) {}
MOCK_METHOD(bool, running, (), (const));
MOCK_METHOD(bool, Stop, (), ());
MOCK_METHOD(bool, PostRasterThreadTask, (fml::closure), (const));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindowsEngine);
};
} // namespace
// Ensure that submenu buttons have their expanded/collapsed status set
// apropriately.
TEST(FlutterWindowsViewTest, SubMenuExpandedState) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
auto window_binding_handler =
std::make_unique<NiceMock<MockWindowBindingHandler>>();
std::unique_ptr<FlutterWindowsView> view =
engine->CreateView(std::move(window_binding_handler));
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
FlutterSemanticsNode2 root{sizeof(FlutterSemanticsNode2), 0};
root.id = 0;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasExpandedState |
FlutterSemanticsFlag::kFlutterSemanticsFlagIsExpanded);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_TRUE(root_node->GetData().HasState(ax::mojom::State::kExpanded));
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
// Verify the submenu is expanded.
varchild.lVal = CHILDID_SELF;
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_TRUE(native_state.lVal & STATE_SYSTEM_EXPANDED);
// Perform similar tests for UIA value;
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_ExpandCollapseExpandCollapseStatePropertyId, &native_state)));
EXPECT_EQ(native_state.lVal, ExpandCollapseState_Expanded);
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_AriaPropertiesPropertyId, &native_state)));
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"expanded=true"), nullptr);
}
// Test collapsed too.
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasExpandedState);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_TRUE(root_node->GetData().HasState(ax::mojom::State::kCollapsed));
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
// Verify the submenu is collapsed.
varchild.lVal = CHILDID_SELF;
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_TRUE(native_state.lVal & STATE_SYSTEM_COLLAPSED);
// Perform similar tests for UIA value;
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_ExpandCollapseExpandCollapseStatePropertyId, &native_state)));
EXPECT_EQ(native_state.lVal, ExpandCollapseState_Collapsed);
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_AriaPropertiesPropertyId, &native_state)));
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"expanded=false"), nullptr);
}
}
// The view's surface must be destroyed after the engine is shutdown.
// See: https://github.com/flutter/flutter/issues/124463
TEST(FlutterWindowsViewTest, Shutdown) {
auto engine = std::make_unique<MockFlutterWindowsEngine>();
auto window_binding_handler =
std::make_unique<NiceMock<MockWindowBindingHandler>>();
auto egl_manager = std::make_unique<egl::MockManager>();
auto surface = std::make_unique<egl::MockWindowSurface>();
auto surface_ptr = surface.get();
EngineModifier modifier{engine.get()};
modifier.SetEGLManager(std::move(egl_manager));
{
std::unique_ptr<FlutterWindowsView> view =
engine->CreateView(std::move(window_binding_handler));
ViewModifier view_modifier{view.get()};
view_modifier.SetSurface(std::move(surface));
// The engine must be stopped before the surface can be destroyed.
InSequence s;
EXPECT_CALL(*engine.get(), Stop).Times(1);
EXPECT_CALL(*surface_ptr, Destroy).Times(1);
}
}
TEST(FlutterWindowsViewTest, KeySequence) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
test_response = false;
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
view->OnKey(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false, false,
[](bool handled) {});
EXPECT_EQ(key_event_logs.size(), 2);
EXPECT_EQ(key_event_logs[0], kKeyEventFromEmbedder);
EXPECT_EQ(key_event_logs[1], kKeyEventFromChannel);
key_event_logs.clear();
}
TEST(FlutterWindowsViewTest, EnableSemantics) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
bool semantics_enabled = false;
modifier.embedder_api().UpdateSemanticsEnabled = MOCK_ENGINE_PROC(
UpdateSemanticsEnabled,
[&semantics_enabled](FLUTTER_API_SYMBOL(FlutterEngine) engine,
bool enabled) {
semantics_enabled = enabled;
return kSuccess;
});
auto window_binding_handler =
std::make_unique<NiceMock<MockWindowBindingHandler>>();
std::unique_ptr<FlutterWindowsView> view =
engine->CreateView(std::move(window_binding_handler));
view->OnUpdateSemanticsEnabled(true);
EXPECT_TRUE(semantics_enabled);
}
TEST(FlutterWindowsViewTest, AddSemanticsNodeUpdate) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
auto window_binding_handler =
std::make_unique<NiceMock<MockWindowBindingHandler>>();
std::unique_ptr<FlutterWindowsView> view =
engine->CreateView(std::move(window_binding_handler));
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
// Add root node.
FlutterSemanticsNode2 node{sizeof(FlutterSemanticsNode2), 0};
node.label = "name";
node.value = "value";
node.platform_view_id = -1;
bridge->AddFlutterSemanticsNodeUpdate(node);
bridge->CommitUpdates();
// Look up the root windows node delegate.
auto node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
ASSERT_TRUE(node_delegate);
EXPECT_EQ(node_delegate->GetChildCount(), 0);
// Get the native IAccessible object.
IAccessible* native_view = node_delegate->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Property lookups will be made against this node itself.
VARIANT varchild{};
varchild.vt = VT_I4;
varchild.lVal = CHILDID_SELF;
// Verify node name matches our label.
BSTR bname = nullptr;
ASSERT_EQ(native_view->get_accName(varchild, &bname), S_OK);
std::string name(_com_util::ConvertBSTRToString(bname));
EXPECT_EQ(name, "name");
// Verify node value matches.
BSTR bvalue = nullptr;
ASSERT_EQ(native_view->get_accValue(varchild, &bvalue), S_OK);
std::string value(_com_util::ConvertBSTRToString(bvalue));
EXPECT_EQ(value, "value");
// Verify node type is static text.
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(native_view->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT);
// Get the IRawElementProviderFragment object.
IRawElementProviderSimple* uia_view;
native_view->QueryInterface(IID_PPV_ARGS(&uia_view));
ASSERT_TRUE(uia_view != nullptr);
// Verify name property matches our label.
VARIANT varname{};
ASSERT_EQ(uia_view->GetPropertyValue(UIA_NamePropertyId, &varname), S_OK);
EXPECT_EQ(varname.vt, VT_BSTR);
name = _com_util::ConvertBSTRToString(varname.bstrVal);
EXPECT_EQ(name, "name");
// Verify value property matches our label.
VARIANT varvalue{};
ASSERT_EQ(uia_view->GetPropertyValue(UIA_ValueValuePropertyId, &varvalue),
S_OK);
EXPECT_EQ(varvalue.vt, VT_BSTR);
value = _com_util::ConvertBSTRToString(varvalue.bstrVal);
EXPECT_EQ(value, "value");
// Verify node control type is text.
varrole = {};
ASSERT_EQ(uia_view->GetPropertyValue(UIA_ControlTypePropertyId, &varrole),
S_OK);
EXPECT_EQ(varrole.vt, VT_I4);
EXPECT_EQ(varrole.lVal, UIA_TextControlTypeId);
}
// Verify the native IAccessible COM object tree is an accurate reflection of
// the platform-agnostic tree. Verify both a root node with children as well as
// a non-root node with children, since the AX tree includes special handling
// for the root.
//
// node0
// / \
// node1 node2
// |
// node3
//
// node0 and node2 are grouping nodes. node1 and node2 are static text nodes.
TEST(FlutterWindowsViewTest, AddSemanticsNodeUpdateWithChildren) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
// Add root node.
FlutterSemanticsNode2 node0{sizeof(FlutterSemanticsNode2), 0};
std::vector<int32_t> node0_children{1, 2};
node0.child_count = node0_children.size();
node0.children_in_traversal_order = node0_children.data();
node0.children_in_hit_test_order = node0_children.data();
FlutterSemanticsNode2 node1{sizeof(FlutterSemanticsNode2), 1};
node1.label = "prefecture";
node1.value = "Kyoto";
FlutterSemanticsNode2 node2{sizeof(FlutterSemanticsNode2), 2};
std::vector<int32_t> node2_children{3};
node2.child_count = node2_children.size();
node2.children_in_traversal_order = node2_children.data();
node2.children_in_hit_test_order = node2_children.data();
FlutterSemanticsNode2 node3{sizeof(FlutterSemanticsNode2), 3};
node3.label = "city";
node3.value = "Uji";
bridge->AddFlutterSemanticsNodeUpdate(node0);
bridge->AddFlutterSemanticsNodeUpdate(node1);
bridge->AddFlutterSemanticsNodeUpdate(node2);
bridge->AddFlutterSemanticsNodeUpdate(node3);
bridge->CommitUpdates();
// Look up the root windows node delegate.
auto node_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
ASSERT_TRUE(node_delegate);
EXPECT_EQ(node_delegate->GetChildCount(), 2);
// Get the native IAccessible object.
IAccessible* node0_accessible = node_delegate->GetNativeViewAccessible();
ASSERT_TRUE(node0_accessible != nullptr);
// Property lookups will be made against this node itself.
VARIANT varchild{};
varchild.vt = VT_I4;
varchild.lVal = CHILDID_SELF;
// Verify node type is a group.
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(node0_accessible->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_GROUPING);
// Verify child count.
long node0_child_count = 0;
ASSERT_EQ(node0_accessible->get_accChildCount(&node0_child_count), S_OK);
EXPECT_EQ(node0_child_count, 2);
{
// Look up first child of node0 (node1), a static text node.
varchild.lVal = 1;
IDispatch* node1_dispatch = nullptr;
ASSERT_EQ(node0_accessible->get_accChild(varchild, &node1_dispatch), S_OK);
ASSERT_TRUE(node1_dispatch != nullptr);
IAccessible* node1_accessible = nullptr;
ASSERT_EQ(node1_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&node1_accessible)),
S_OK);
ASSERT_TRUE(node1_accessible != nullptr);
// Verify node name matches our label.
varchild.lVal = CHILDID_SELF;
BSTR bname = nullptr;
ASSERT_EQ(node1_accessible->get_accName(varchild, &bname), S_OK);
std::string name(_com_util::ConvertBSTRToString(bname));
EXPECT_EQ(name, "prefecture");
// Verify node value matches.
BSTR bvalue = nullptr;
ASSERT_EQ(node1_accessible->get_accValue(varchild, &bvalue), S_OK);
std::string value(_com_util::ConvertBSTRToString(bvalue));
EXPECT_EQ(value, "Kyoto");
// Verify node type is static text.
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(node1_accessible->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT);
// Verify the parent node is the root.
IDispatch* parent_dispatch;
node1_accessible->get_accParent(&parent_dispatch);
IAccessible* parent_accessible;
ASSERT_EQ(
parent_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)),
S_OK);
EXPECT_EQ(parent_accessible, node0_accessible);
}
// Look up second child of node0 (node2), a parent group for node3.
varchild.lVal = 2;
IDispatch* node2_dispatch = nullptr;
ASSERT_EQ(node0_accessible->get_accChild(varchild, &node2_dispatch), S_OK);
ASSERT_TRUE(node2_dispatch != nullptr);
IAccessible* node2_accessible = nullptr;
ASSERT_EQ(node2_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&node2_accessible)),
S_OK);
ASSERT_TRUE(node2_accessible != nullptr);
{
// Verify child count.
long node2_child_count = 0;
ASSERT_EQ(node2_accessible->get_accChildCount(&node2_child_count), S_OK);
EXPECT_EQ(node2_child_count, 1);
// Verify node type is static text.
varchild.lVal = CHILDID_SELF;
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(node2_accessible->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_GROUPING);
// Verify the parent node is the root.
IDispatch* parent_dispatch;
node2_accessible->get_accParent(&parent_dispatch);
IAccessible* parent_accessible;
ASSERT_EQ(
parent_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)),
S_OK);
EXPECT_EQ(parent_accessible, node0_accessible);
}
{
// Look up only child of node2 (node3), a static text node.
varchild.lVal = 1;
IDispatch* node3_dispatch = nullptr;
ASSERT_EQ(node2_accessible->get_accChild(varchild, &node3_dispatch), S_OK);
ASSERT_TRUE(node3_dispatch != nullptr);
IAccessible* node3_accessible = nullptr;
ASSERT_EQ(node3_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&node3_accessible)),
S_OK);
ASSERT_TRUE(node3_accessible != nullptr);
// Verify node name matches our label.
varchild.lVal = CHILDID_SELF;
BSTR bname = nullptr;
ASSERT_EQ(node3_accessible->get_accName(varchild, &bname), S_OK);
std::string name(_com_util::ConvertBSTRToString(bname));
EXPECT_EQ(name, "city");
// Verify node value matches.
BSTR bvalue = nullptr;
ASSERT_EQ(node3_accessible->get_accValue(varchild, &bvalue), S_OK);
std::string value(_com_util::ConvertBSTRToString(bvalue));
EXPECT_EQ(value, "Uji");
// Verify node type is static text.
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(node3_accessible->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT);
// Verify the parent node is node2.
IDispatch* parent_dispatch;
node3_accessible->get_accParent(&parent_dispatch);
IAccessible* parent_accessible;
ASSERT_EQ(
parent_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)),
S_OK);
EXPECT_EQ(parent_accessible, node2_accessible);
}
}
// Flutter used to assume that the accessibility root had ID 0.
// In a multi-view world, each view has its own accessibility root
// with a globally unique node ID.
//
// node1
// |
// node2
//
// node1 is a grouping node, node0 is a static text node.
TEST(FlutterWindowsViewTest, NonZeroSemanticsRoot) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
// Add root node.
FlutterSemanticsNode2 node1{sizeof(FlutterSemanticsNode2), 1};
std::vector<int32_t> node1_children{2};
node1.child_count = node1_children.size();
node1.children_in_traversal_order = node1_children.data();
node1.children_in_hit_test_order = node1_children.data();
FlutterSemanticsNode2 node2{sizeof(FlutterSemanticsNode2), 2};
node2.label = "prefecture";
node2.value = "Kyoto";
bridge->AddFlutterSemanticsNodeUpdate(node1);
bridge->AddFlutterSemanticsNodeUpdate(node2);
bridge->CommitUpdates();
// Look up the root windows node delegate.
auto root_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock();
ASSERT_TRUE(root_delegate);
EXPECT_EQ(root_delegate->GetChildCount(), 1);
// Look up the child node delegate
auto child_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock();
ASSERT_TRUE(child_delegate);
EXPECT_EQ(child_delegate->GetChildCount(), 0);
// Ensure a node with ID 0 does not exist.
auto fake_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
ASSERT_FALSE(fake_delegate);
// Get the root's native IAccessible object.
IAccessible* node1_accessible = root_delegate->GetNativeViewAccessible();
ASSERT_TRUE(node1_accessible != nullptr);
// Property lookups will be made against this node itself.
VARIANT varchild{};
varchild.vt = VT_I4;
varchild.lVal = CHILDID_SELF;
// Verify node type is a group.
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(node1_accessible->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_GROUPING);
// Verify child count.
long node1_child_count = 0;
ASSERT_EQ(node1_accessible->get_accChildCount(&node1_child_count), S_OK);
EXPECT_EQ(node1_child_count, 1);
{
// Look up first child of node1 (node0), a static text node.
varchild.lVal = 1;
IDispatch* node2_dispatch = nullptr;
ASSERT_EQ(node1_accessible->get_accChild(varchild, &node2_dispatch), S_OK);
ASSERT_TRUE(node2_dispatch != nullptr);
IAccessible* node2_accessible = nullptr;
ASSERT_EQ(node2_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&node2_accessible)),
S_OK);
ASSERT_TRUE(node2_accessible != nullptr);
// Verify node name matches our label.
varchild.lVal = CHILDID_SELF;
BSTR bname = nullptr;
ASSERT_EQ(node2_accessible->get_accName(varchild, &bname), S_OK);
std::string name(_com_util::ConvertBSTRToString(bname));
EXPECT_EQ(name, "prefecture");
// Verify node value matches.
BSTR bvalue = nullptr;
ASSERT_EQ(node2_accessible->get_accValue(varchild, &bvalue), S_OK);
std::string value(_com_util::ConvertBSTRToString(bvalue));
EXPECT_EQ(value, "Kyoto");
// Verify node type is static text.
VARIANT varrole{};
varrole.vt = VT_I4;
ASSERT_EQ(node2_accessible->get_accRole(varchild, &varrole), S_OK);
EXPECT_EQ(varrole.lVal, ROLE_SYSTEM_STATICTEXT);
// Verify the parent node is the root.
IDispatch* parent_dispatch;
node2_accessible->get_accParent(&parent_dispatch);
IAccessible* parent_accessible;
ASSERT_EQ(
parent_dispatch->QueryInterface(
IID_IAccessible, reinterpret_cast<void**>(&parent_accessible)),
S_OK);
EXPECT_EQ(parent_accessible, node1_accessible);
}
}
// Verify the native IAccessible accHitTest method returns the correct
// IAccessible COM object for the given coordinates.
//
// +-----------+
// | | |
// node0 | | B |
// / \ | A |-----|
// node1 node2 | | C |
// | | | |
// node3 +-----------+
//
// node0 and node2 are grouping nodes. node1 and node2 are static text nodes.
//
// node0 is located at 0,0 with size 500x500. It spans areas A, B, and C.
// node1 is located at 0,0 with size 250x500. It spans area A.
// node2 is located at 250,0 with size 250x500. It spans areas B and C.
// node3 is located at 250,250 with size 250x250. It spans area C.
TEST(FlutterWindowsViewTest, AccessibilityHitTesting) {
constexpr FlutterTransformation kIdentityTransform = {1, 0, 0, //
0, 1, 0, //
0, 0, 1};
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
// Add root node at origin. Size 500x500.
FlutterSemanticsNode2 node0{sizeof(FlutterSemanticsNode2), 0};
std::vector<int32_t> node0_children{1, 2};
node0.rect = {0, 0, 500, 500};
node0.transform = kIdentityTransform;
node0.child_count = node0_children.size();
node0.children_in_traversal_order = node0_children.data();
node0.children_in_hit_test_order = node0_children.data();
// Add node 1 located at 0,0 relative to node 0. Size 250x500.
FlutterSemanticsNode2 node1{sizeof(FlutterSemanticsNode2), 1};
node1.rect = {0, 0, 250, 500};
node1.transform = kIdentityTransform;
node1.label = "prefecture";
node1.value = "Kyoto";
// Add node 2 located at 250,0 relative to node 0. Size 250x500.
FlutterSemanticsNode2 node2{sizeof(FlutterSemanticsNode2), 2};
std::vector<int32_t> node2_children{3};
node2.rect = {0, 0, 250, 500};
node2.transform = {1, 0, 250, 0, 1, 0, 0, 0, 1};
node2.child_count = node2_children.size();
node2.children_in_traversal_order = node2_children.data();
node2.children_in_hit_test_order = node2_children.data();
// Add node 3 located at 0,250 relative to node 2. Size 250, 250.
FlutterSemanticsNode2 node3{sizeof(FlutterSemanticsNode2), 3};
node3.rect = {0, 0, 250, 250};
node3.transform = {1, 0, 0, 0, 1, 250, 0, 0, 1};
node3.label = "city";
node3.value = "Uji";
bridge->AddFlutterSemanticsNodeUpdate(node0);
bridge->AddFlutterSemanticsNodeUpdate(node1);
bridge->AddFlutterSemanticsNodeUpdate(node2);
bridge->AddFlutterSemanticsNodeUpdate(node3);
bridge->CommitUpdates();
// Look up the root windows node delegate.
auto node0_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
ASSERT_TRUE(node0_delegate);
auto node1_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(1).lock();
ASSERT_TRUE(node1_delegate);
auto node2_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(2).lock();
ASSERT_TRUE(node2_delegate);
auto node3_delegate = bridge->GetFlutterPlatformNodeDelegateFromID(3).lock();
ASSERT_TRUE(node3_delegate);
// Get the native IAccessible root object.
IAccessible* node0_accessible = node0_delegate->GetNativeViewAccessible();
ASSERT_TRUE(node0_accessible != nullptr);
// Perform a hit test that should hit node 1.
VARIANT varchild{};
ASSERT_TRUE(SUCCEEDED(node0_accessible->accHitTest(150, 150, &varchild)));
EXPECT_EQ(varchild.vt, VT_DISPATCH);
EXPECT_EQ(varchild.pdispVal, node1_delegate->GetNativeViewAccessible());
// Perform a hit test that should hit node 2.
varchild = {};
ASSERT_TRUE(SUCCEEDED(node0_accessible->accHitTest(450, 150, &varchild)));
EXPECT_EQ(varchild.vt, VT_DISPATCH);
EXPECT_EQ(varchild.pdispVal, node2_delegate->GetNativeViewAccessible());
// Perform a hit test that should hit node 3.
varchild = {};
ASSERT_TRUE(SUCCEEDED(node0_accessible->accHitTest(450, 450, &varchild)));
EXPECT_EQ(varchild.vt, VT_DISPATCH);
EXPECT_EQ(varchild.pdispVal, node3_delegate->GetNativeViewAccessible());
}
TEST(FlutterWindowsViewTest, WindowResizeTests) {
auto windows_proc_table = std::make_shared<NiceMock<MockWindowsProcTable>>();
std::unique_ptr<FlutterWindowsEngine> engine =
GetTestEngine(windows_proc_table);
EngineModifier engine_modifier{engine.get()};
auto egl_manager = std::make_unique<egl::MockManager>();
auto surface = std::make_unique<egl::MockWindowSurface>();
auto resized_surface = std::make_unique<egl::MockWindowSurface>();
auto resized_surface_ptr = resized_surface.get();
EXPECT_CALL(*surface.get(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface.get(), Destroy).WillOnce(Return(true));
EXPECT_CALL(*egl_manager.get(),
CreateWindowSurface(_, /*width=*/500, /*height=*/500))
.WillOnce(Return(std::move((resized_surface))));
EXPECT_CALL(*resized_surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*resized_surface_ptr, SetVSyncEnabled).WillOnce(Return(true));
EXPECT_CALL(*windows_proc_table.get(), DwmFlush).WillOnce(Return(S_OK));
EXPECT_CALL(*resized_surface_ptr, Destroy).WillOnce(Return(true));
engine_modifier.SetEGLManager(std::move(egl_manager));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
ViewModifier view_modifier{view.get()};
view_modifier.SetSurface(std::move(surface));
fml::AutoResetWaitableEvent metrics_sent_latch;
engine_modifier.embedder_api().SendWindowMetricsEvent = MOCK_ENGINE_PROC(
SendWindowMetricsEvent,
([&metrics_sent_latch](auto engine,
const FlutterWindowMetricsEvent* event) {
metrics_sent_latch.Signal();
return kSuccess;
}));
fml::AutoResetWaitableEvent resized_latch;
std::thread([&resized_latch, &view]() {
// Start the window resize. This sends the new window metrics
// and then blocks until another thread completes the window resize.
EXPECT_TRUE(view->OnWindowSizeChanged(500, 500));
resized_latch.Signal();
}).detach();
// Wait until the platform thread has started the window resize.
metrics_sent_latch.Wait();
// Complete the window resize by reporting a frame with the new window size.
ASSERT_TRUE(view->OnFrameGenerated(500, 500));
view->OnFramePresented();
resized_latch.Wait();
}
// Verify that an empty frame completes a view resize.
TEST(FlutterWindowsViewTest, TestEmptyFrameResizes) {
auto windows_proc_table = std::make_shared<NiceMock<MockWindowsProcTable>>();
std::unique_ptr<FlutterWindowsEngine> engine =
GetTestEngine(windows_proc_table);
EngineModifier engine_modifier{engine.get()};
auto egl_manager = std::make_unique<egl::MockManager>();
auto surface = std::make_unique<egl::MockWindowSurface>();
auto resized_surface = std::make_unique<egl::MockWindowSurface>();
auto resized_surface_ptr = resized_surface.get();
EXPECT_CALL(*surface.get(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface.get(), Destroy).WillOnce(Return(true));
EXPECT_CALL(*egl_manager.get(),
CreateWindowSurface(_, /*width=*/500, /*height=*/500))
.WillOnce(Return(std::move((resized_surface))));
EXPECT_CALL(*resized_surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*resized_surface_ptr, SetVSyncEnabled).WillOnce(Return(true));
EXPECT_CALL(*windows_proc_table.get(), DwmFlush).WillOnce(Return(S_OK));
EXPECT_CALL(*resized_surface_ptr, Destroy).WillOnce(Return(true));
fml::AutoResetWaitableEvent metrics_sent_latch;
engine_modifier.embedder_api().SendWindowMetricsEvent = MOCK_ENGINE_PROC(
SendWindowMetricsEvent,
([&metrics_sent_latch](auto engine,
const FlutterWindowMetricsEvent* event) {
metrics_sent_latch.Signal();
return kSuccess;
}));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
ViewModifier view_modifier{view.get()};
engine_modifier.SetEGLManager(std::move(egl_manager));
view_modifier.SetSurface(std::move(surface));
fml::AutoResetWaitableEvent resized_latch;
std::thread([&resized_latch, &view]() {
// Start the window resize. This sends the new window metrics
// and then blocks until another thread completes the window resize.
EXPECT_TRUE(view->OnWindowSizeChanged(500, 500));
resized_latch.Signal();
}).detach();
// Wait until the platform thread has started the window resize.
metrics_sent_latch.Wait();
// Complete the window resize by reporting an empty frame.
view->OnEmptyFrameGenerated();
view->OnFramePresented();
resized_latch.Wait();
}
// A window resize can be interleaved between a frame generation and
// presentation. This should not crash the app. Regression test for:
// https://github.com/flutter/flutter/issues/141855
TEST(FlutterWindowsViewTest, WindowResizeRace) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier engine_modifier(engine.get());
auto egl_manager = std::make_unique<egl::MockManager>();
auto surface = std::make_unique<egl::MockWindowSurface>();
EXPECT_CALL(*surface.get(), IsValid).WillRepeatedly(Return(true));
EXPECT_CALL(*surface.get(), Destroy).WillOnce(Return(true));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
ViewModifier view_modifier{view.get()};
engine_modifier.SetEGLManager(std::move(egl_manager));
view_modifier.SetSurface(std::move(surface));
// Begin a frame.
ASSERT_TRUE(view->OnFrameGenerated(100, 100));
// Inject a window resize between the frame generation and
// frame presentation. The new size invalidates the current frame.
fml::AutoResetWaitableEvent resized_latch;
std::thread([&resized_latch, &view]() {
// The resize is never completed. The view times out and returns false.
EXPECT_FALSE(view->OnWindowSizeChanged(500, 500));
resized_latch.Signal();
}).detach();
// Wait until the platform thread has started the window resize.
resized_latch.Wait();
// Complete the invalidated frame while a resize is pending. Although this
// might mean that we presented a frame with the wrong size, this should not
// crash the app.
view->OnFramePresented();
}
// Window resize should succeed even if the render surface could not be created
// even though EGL initialized successfully.
TEST(FlutterWindowsViewTest, WindowResizeInvalidSurface) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier engine_modifier(engine.get());
auto egl_manager = std::make_unique<egl::MockManager>();
auto surface = std::make_unique<egl::MockWindowSurface>();
EXPECT_CALL(*egl_manager.get(), CreateWindowSurface).Times(0);
EXPECT_CALL(*surface.get(), IsValid).WillRepeatedly(Return(false));
EXPECT_CALL(*surface.get(), Destroy).WillOnce(Return(false));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
ViewModifier view_modifier{view.get()};
engine_modifier.SetEGLManager(std::move(egl_manager));
view_modifier.SetSurface(std::move(surface));
auto metrics_sent = false;
engine_modifier.embedder_api().SendWindowMetricsEvent = MOCK_ENGINE_PROC(
SendWindowMetricsEvent,
([&metrics_sent](auto engine, const FlutterWindowMetricsEvent* event) {
metrics_sent = true;
return kSuccess;
}));
view->OnWindowSizeChanged(500, 500);
}
// Window resize should succeed even if EGL initialized successfully
// but the EGL surface could not be created.
TEST(FlutterWindowsViewTest, WindowResizeWithoutSurface) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
auto egl_manager = std::make_unique<egl::MockManager>();
EXPECT_CALL(*egl_manager.get(), CreateWindowSurface).Times(0);
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
modifier.SetEGLManager(std::move(egl_manager));
auto metrics_sent = false;
modifier.embedder_api().SendWindowMetricsEvent = MOCK_ENGINE_PROC(
SendWindowMetricsEvent,
([&metrics_sent](auto engine, const FlutterWindowMetricsEvent* event) {
metrics_sent = true;
return kSuccess;
}));
view->OnWindowSizeChanged(500, 500);
}
TEST(FlutterWindowsViewTest, WindowRepaintTests) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
FlutterWindowsView view{kImplicitViewId, engine.get(),
std::make_unique<flutter::FlutterWindow>(100, 100)};
bool schedule_frame_called = false;
modifier.embedder_api().ScheduleFrame =
MOCK_ENGINE_PROC(ScheduleFrame, ([&schedule_frame_called](auto engine) {
schedule_frame_called = true;
return kSuccess;
}));
view.OnWindowRepaint();
EXPECT_TRUE(schedule_frame_called);
}
// Ensure that checkboxes have their checked status set apropriately
// Previously, only Radios could have this flag updated
// Resulted in the issue seen at
// https://github.com/flutter/flutter/issues/96218
// This test ensures that the native state of Checkboxes on Windows,
// specifically, is updated as desired.
TEST(FlutterWindowsViewTest, CheckboxNativeState) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
FlutterSemanticsNode2 root{sizeof(FlutterSemanticsNode2), 0};
root.id = 0;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasCheckedState |
FlutterSemanticsFlag::kFlutterSemanticsFlagIsChecked);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kCheckBox);
EXPECT_EQ(root_node->GetData().GetCheckedState(),
ax::mojom::CheckedState::kTrue);
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
// Verify the checkbox is checked.
varchild.lVal = CHILDID_SELF;
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_TRUE(native_state.lVal & STATE_SYSTEM_CHECKED);
// Perform similar tests for UIA value;
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_ToggleToggleStatePropertyId, &native_state)));
EXPECT_EQ(native_state.lVal, ToggleState_On);
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_AriaPropertiesPropertyId, &native_state)));
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"checked=true"), nullptr);
}
// Test unchecked too.
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasCheckedState);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kCheckBox);
EXPECT_EQ(root_node->GetData().GetCheckedState(),
ax::mojom::CheckedState::kFalse);
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
// Verify the checkbox is unchecked.
varchild.lVal = CHILDID_SELF;
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_FALSE(native_state.lVal & STATE_SYSTEM_CHECKED);
// Perform similar tests for UIA value;
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_ToggleToggleStatePropertyId, &native_state)));
EXPECT_EQ(native_state.lVal, ToggleState_Off);
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_AriaPropertiesPropertyId, &native_state)));
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"checked=false"), nullptr);
}
// Now check mixed state.
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasCheckedState |
FlutterSemanticsFlag::kFlutterSemanticsFlagIsCheckStateMixed);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kCheckBox);
EXPECT_EQ(root_node->GetData().GetCheckedState(),
ax::mojom::CheckedState::kMixed);
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
// Verify the checkbox is mixed.
varchild.lVal = CHILDID_SELF;
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_TRUE(native_state.lVal & STATE_SYSTEM_MIXED);
// Perform similar tests for UIA value;
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_ToggleToggleStatePropertyId, &native_state)));
EXPECT_EQ(native_state.lVal, ToggleState_Indeterminate);
ASSERT_TRUE(SUCCEEDED(uia_node->GetPropertyValue(
UIA_AriaPropertiesPropertyId, &native_state)));
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"checked=mixed"), nullptr);
}
}
// Ensure that switches have their toggle status set apropriately
TEST(FlutterWindowsViewTest, SwitchNativeState) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
FlutterSemanticsNode2 root{sizeof(FlutterSemanticsNode2), 0};
root.id = 0;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasToggledState |
FlutterSemanticsFlag::kFlutterSemanticsFlagIsToggled);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kSwitch);
EXPECT_EQ(root_node->GetData().GetCheckedState(),
ax::mojom::CheckedState::kTrue);
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
varchild.lVal = CHILDID_SELF;
VARIANT varrole = {};
// Verify the role of the switch is CHECKBUTTON
ASSERT_EQ(native_view->get_accRole(varchild, &varrole), S_OK);
ASSERT_EQ(varrole.lVal, ROLE_SYSTEM_CHECKBUTTON);
// Verify the switch is pressed.
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_TRUE(native_state.lVal & STATE_SYSTEM_PRESSED);
EXPECT_TRUE(native_state.lVal & STATE_SYSTEM_CHECKED);
// Test similarly on UIA node.
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_EQ(uia_node->GetPropertyValue(UIA_ControlTypePropertyId, &varrole),
S_OK);
EXPECT_EQ(varrole.lVal, UIA_ButtonControlTypeId);
ASSERT_EQ(uia_node->GetPropertyValue(UIA_ToggleToggleStatePropertyId,
&native_state),
S_OK);
EXPECT_EQ(native_state.lVal, ToggleState_On);
ASSERT_EQ(
uia_node->GetPropertyValue(UIA_AriaPropertiesPropertyId, &native_state),
S_OK);
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"pressed=true"), nullptr);
}
// Test unpressed too.
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagHasToggledState);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
{
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
EXPECT_EQ(root_node->GetData().role, ax::mojom::Role::kSwitch);
EXPECT_EQ(root_node->GetData().GetCheckedState(),
ax::mojom::CheckedState::kFalse);
// Get the IAccessible for the root node.
IAccessible* native_view = root_node->GetNativeViewAccessible();
ASSERT_TRUE(native_view != nullptr);
// Look up against the node itself (not one of its children).
VARIANT varchild = {};
varchild.vt = VT_I4;
// Verify the switch is not pressed.
varchild.lVal = CHILDID_SELF;
VARIANT native_state = {};
ASSERT_TRUE(SUCCEEDED(native_view->get_accState(varchild, &native_state)));
EXPECT_FALSE(native_state.lVal & STATE_SYSTEM_PRESSED);
EXPECT_FALSE(native_state.lVal & STATE_SYSTEM_CHECKED);
// Test similarly on UIA node.
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
ASSERT_EQ(uia_node->GetPropertyValue(UIA_ToggleToggleStatePropertyId,
&native_state),
S_OK);
EXPECT_EQ(native_state.lVal, ToggleState_Off);
ASSERT_EQ(
uia_node->GetPropertyValue(UIA_AriaPropertiesPropertyId, &native_state),
S_OK);
EXPECT_NE(std::wcsstr(native_state.bstrVal, L"pressed=false"), nullptr);
}
}
TEST(FlutterWindowsViewTest, TooltipNodeData) {
std::unique_ptr<FlutterWindowsEngine> engine = GetTestEngine();
EngineModifier modifier(engine.get());
modifier.embedder_api().UpdateSemanticsEnabled =
[](FLUTTER_API_SYMBOL(FlutterEngine) engine, bool enabled) {
return kSuccess;
};
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
// Enable semantics to instantiate accessibility bridge.
view->OnUpdateSemanticsEnabled(true);
auto bridge = view->accessibility_bridge().lock();
ASSERT_TRUE(bridge);
FlutterSemanticsNode2 root{sizeof(FlutterSemanticsNode2), 0};
root.id = 0;
root.label = "root";
root.hint = "";
root.value = "";
root.increased_value = "";
root.decreased_value = "";
root.tooltip = "tooltip";
root.child_count = 0;
root.custom_accessibility_actions_count = 0;
root.flags = static_cast<FlutterSemanticsFlag>(
FlutterSemanticsFlag::kFlutterSemanticsFlagIsTextField);
bridge->AddFlutterSemanticsNodeUpdate(root);
bridge->CommitUpdates();
auto root_node = bridge->GetFlutterPlatformNodeDelegateFromID(0).lock();
std::string tooltip = root_node->GetData().GetStringAttribute(
ax::mojom::StringAttribute::kTooltip);
EXPECT_EQ(tooltip, "tooltip");
// Check that MSAA name contains the tooltip.
IAccessible* native_view = bridge->GetFlutterPlatformNodeDelegateFromID(0)
.lock()
->GetNativeViewAccessible();
VARIANT varchild = {.vt = VT_I4, .lVal = CHILDID_SELF};
BSTR bname;
ASSERT_EQ(native_view->get_accName(varchild, &bname), S_OK);
EXPECT_NE(std::wcsstr(bname, L"tooltip"), nullptr);
// Check that UIA help text is equal to the tooltip.
IRawElementProviderSimple* uia_node;
native_view->QueryInterface(IID_PPV_ARGS(&uia_node));
VARIANT varname{};
ASSERT_EQ(uia_node->GetPropertyValue(UIA_HelpTextPropertyId, &varname), S_OK);
std::string uia_tooltip = _com_util::ConvertBSTRToString(varname.bstrVal);
EXPECT_EQ(uia_tooltip, "tooltip");
}
// Don't block until the v-blank if it is disabled by the window.
// The surface is updated on the platform thread at startup.
TEST(FlutterWindowsViewTest, DisablesVSyncAtStartup) {
auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
auto engine = std::make_unique<MockFlutterWindowsEngine>(windows_proc_table);
auto egl_manager = std::make_unique<egl::MockManager>();
egl::MockContext render_context;
auto surface = std::make_unique<egl::MockWindowSurface>();
auto surface_ptr = surface.get();
EXPECT_CALL(*engine.get(), running).WillRepeatedly(Return(false));
EXPECT_CALL(*engine.get(), PostRasterThreadTask).Times(0);
EXPECT_CALL(*windows_proc_table.get(), DwmIsCompositionEnabled)
.WillOnce(Return(true));
EXPECT_CALL(*egl_manager.get(), render_context)
.WillOnce(Return(&render_context));
EXPECT_CALL(*surface_ptr, IsValid).WillOnce(Return(true));
InSequence s;
EXPECT_CALL(*egl_manager.get(), CreateWindowSurface)
.WillOnce(Return(std::move(surface)));
EXPECT_CALL(*surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, SetVSyncEnabled(false)).WillOnce(Return(true));
EXPECT_CALL(render_context, ClearCurrent).WillOnce(Return(true));
EXPECT_CALL(*engine.get(), Stop).Times(1);
EXPECT_CALL(*surface_ptr, Destroy).Times(1);
EngineModifier modifier{engine.get()};
modifier.SetEGLManager(std::move(egl_manager));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
view->CreateRenderSurface();
}
// Blocks until the v-blank if it is enabled by the window.
// The surface is updated on the platform thread at startup.
TEST(FlutterWindowsViewTest, EnablesVSyncAtStartup) {
auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
auto engine = std::make_unique<MockFlutterWindowsEngine>(windows_proc_table);
auto egl_manager = std::make_unique<egl::MockManager>();
egl::MockContext render_context;
auto surface = std::make_unique<egl::MockWindowSurface>();
auto surface_ptr = surface.get();
EXPECT_CALL(*engine.get(), running).WillRepeatedly(Return(false));
EXPECT_CALL(*engine.get(), PostRasterThreadTask).Times(0);
EXPECT_CALL(*windows_proc_table.get(), DwmIsCompositionEnabled)
.WillOnce(Return(false));
EXPECT_CALL(*egl_manager.get(), render_context)
.WillOnce(Return(&render_context));
EXPECT_CALL(*surface_ptr, IsValid).WillOnce(Return(true));
InSequence s;
EXPECT_CALL(*egl_manager.get(), CreateWindowSurface)
.WillOnce(Return(std::move(surface)));
EXPECT_CALL(*surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, SetVSyncEnabled(true)).WillOnce(Return(true));
EXPECT_CALL(render_context, ClearCurrent).WillOnce(Return(true));
EXPECT_CALL(*engine.get(), Stop).Times(1);
EXPECT_CALL(*surface_ptr, Destroy).Times(1);
EngineModifier modifier{engine.get()};
modifier.SetEGLManager(std::move(egl_manager));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
view->CreateRenderSurface();
}
// Don't block until the v-blank if it is disabled by the window.
// The surface is updated on the raster thread if the engine is running.
TEST(FlutterWindowsViewTest, DisablesVSyncAfterStartup) {
auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
auto engine = std::make_unique<MockFlutterWindowsEngine>(windows_proc_table);
auto egl_manager = std::make_unique<egl::MockManager>();
egl::MockContext render_context;
auto surface = std::make_unique<egl::MockWindowSurface>();
auto surface_ptr = surface.get();
EXPECT_CALL(*engine.get(), running).WillRepeatedly(Return(true));
EXPECT_CALL(*windows_proc_table.get(), DwmIsCompositionEnabled)
.WillOnce(Return(true));
EXPECT_CALL(*egl_manager.get(), render_context)
.WillOnce(Return(&render_context));
EXPECT_CALL(*surface_ptr, IsValid).WillOnce(Return(true));
InSequence s;
EXPECT_CALL(*egl_manager.get(), CreateWindowSurface)
.WillOnce(Return(std::move(surface)));
EXPECT_CALL(*engine.get(), PostRasterThreadTask)
.WillOnce([](fml::closure callback) {
callback();
return true;
});
EXPECT_CALL(*surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, SetVSyncEnabled(false)).WillOnce(Return(true));
EXPECT_CALL(render_context, ClearCurrent).WillOnce(Return(true));
EXPECT_CALL(*engine.get(), Stop).Times(1);
EXPECT_CALL(*surface_ptr, Destroy).Times(1);
EngineModifier modifier{engine.get()};
modifier.SetEGLManager(std::move(egl_manager));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
view->CreateRenderSurface();
}
// Blocks until the v-blank if it is enabled by the window.
// The surface is updated on the raster thread if the engine is running.
TEST(FlutterWindowsViewTest, EnablesVSyncAfterStartup) {
auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
auto engine = std::make_unique<MockFlutterWindowsEngine>(windows_proc_table);
auto egl_manager = std::make_unique<egl::MockManager>();
egl::MockContext render_context;
auto surface = std::make_unique<egl::MockWindowSurface>();
auto surface_ptr = surface.get();
EXPECT_CALL(*engine.get(), running).WillRepeatedly(Return(true));
EXPECT_CALL(*windows_proc_table.get(), DwmIsCompositionEnabled)
.WillOnce(Return(false));
EXPECT_CALL(*egl_manager.get(), render_context)
.WillOnce(Return(&render_context));
EXPECT_CALL(*surface_ptr, IsValid).WillOnce(Return(true));
InSequence s;
EXPECT_CALL(*egl_manager.get(), CreateWindowSurface)
.WillOnce(Return(std::move(surface)));
EXPECT_CALL(*engine.get(), PostRasterThreadTask)
.WillOnce([](fml::closure callback) {
callback();
return true;
});
EXPECT_CALL(*surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, SetVSyncEnabled(true)).WillOnce(Return(true));
EXPECT_CALL(render_context, ClearCurrent).WillOnce(Return(true));
EXPECT_CALL(*engine.get(), Stop).Times(1);
EXPECT_CALL(*surface_ptr, Destroy).Times(1);
EngineModifier modifier{engine.get()};
modifier.SetEGLManager(std::move(egl_manager));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
view->CreateRenderSurface();
}
// Desktop Window Manager composition can be disabled on Windows 7.
// If this happens, the app must synchronize with the vsync to prevent
// screen tearing.
TEST(FlutterWindowsViewTest, UpdatesVSyncOnDwmUpdates) {
auto windows_proc_table = std::make_shared<MockWindowsProcTable>();
auto engine = std::make_unique<MockFlutterWindowsEngine>(windows_proc_table);
auto egl_manager = std::make_unique<egl::MockManager>();
egl::MockContext render_context;
auto surface = std::make_unique<egl::MockWindowSurface>();
auto surface_ptr = surface.get();
EXPECT_CALL(*engine.get(), running).WillRepeatedly(Return(true));
EXPECT_CALL(*engine.get(), PostRasterThreadTask)
.WillRepeatedly([](fml::closure callback) {
callback();
return true;
});
EXPECT_CALL(*windows_proc_table.get(), DwmIsCompositionEnabled)
.WillOnce(Return(false))
.WillOnce(Return(true));
EXPECT_CALL(*egl_manager.get(), render_context)
.WillRepeatedly(Return(&render_context));
EXPECT_CALL(*surface_ptr, IsValid).WillRepeatedly(Return(true));
InSequence s;
EXPECT_CALL(*surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, SetVSyncEnabled(true)).WillOnce(Return(true));
EXPECT_CALL(render_context, ClearCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, MakeCurrent).WillOnce(Return(true));
EXPECT_CALL(*surface_ptr, SetVSyncEnabled(false)).WillOnce(Return(true));
EXPECT_CALL(render_context, ClearCurrent).WillOnce(Return(true));
EXPECT_CALL(*engine.get(), Stop).Times(1);
EXPECT_CALL(*surface_ptr, Destroy).Times(1);
EngineModifier engine_modifier{engine.get()};
engine_modifier.SetEGLManager(std::move(egl_manager));
std::unique_ptr<FlutterWindowsView> view = engine->CreateView(
std::make_unique<NiceMock<MockWindowBindingHandler>>());
ViewModifier view_modifier{view.get()};
view_modifier.SetSurface(std::move(surface));
engine->OnDwmCompositionChanged();
engine->OnDwmCompositionChanged();
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/flutter_windows_view_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_view_unittests.cc",
"repo_id": "engine",
"token_count": 22323
} | 382 |
// 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 "flutter/shell/platform/windows/keyboard_utils.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
TEST(KeyboardWin32CommonTest, EncodeUtf16) {
std::u16string result;
result = EncodeUtf16(0x24);
EXPECT_EQ(result.size(), 1);
EXPECT_EQ(result[0], 0x24);
result = EncodeUtf16(0x20AC);
EXPECT_EQ(result.size(), 1);
EXPECT_EQ(result[0], 0x20AC);
result = EncodeUtf16(0x10437);
EXPECT_EQ(result.size(), 2);
EXPECT_EQ(result[0], 0xD801);
EXPECT_EQ(result[1], 0xDC37);
result = EncodeUtf16(0x24B62);
EXPECT_EQ(result.size(), 2);
EXPECT_EQ(result[0], 0xD852);
EXPECT_EQ(result[1], 0xDF62);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/keyboard_utils_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/keyboard_utils_unittests.cc",
"repo_id": "engine",
"token_count": 348
} | 383 |
// 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.
// This file contains utilities for system-level information/settings.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_SYSTEM_UTILS_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_SYSTEM_UTILS_H_
#include <string>
#include <vector>
#include "flutter/shell/platform/windows/windows_proc_table.h"
namespace flutter {
// Registry key for user-preferred languages.
constexpr const wchar_t kGetPreferredLanguageRegKey[] =
L"Control panel\\International\\User Profile";
constexpr const wchar_t kGetPreferredLanguageRegValue[] = L"Languages";
// Components of a system language/locale.
struct LanguageInfo {
std::string language;
std::string region;
std::string script;
};
// Returns the list of user-preferred languages, in preference order,
// parsed into LanguageInfo structures.
std::vector<LanguageInfo> GetPreferredLanguageInfo(
const WindowsProcTable& windows_proc_table);
// Retrieve the preferred languages from the MUI API.
std::wstring GetPreferredLanguagesFromMUI(
const WindowsProcTable& windows_proc_table);
// Returns the list of user-preferred languages, in preference order.
// The language names are as described at:
// https://docs.microsoft.com/en-us/windows/win32/intl/language-names
std::vector<std::wstring> GetPreferredLanguages(
const WindowsProcTable& windows_proc_table);
// Parses a Windows language name into its components.
LanguageInfo ParseLanguageName(std::wstring language_name);
// Returns the user's system time format string.
std::wstring GetUserTimeFormat();
// Returns true if the time_format is set to use 24 hour time.
bool Prefer24HourTime(std::wstring time_format);
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_SYSTEM_UTILS_H_
| engine/shell/platform/windows/system_utils.h/0 | {
"file_path": "engine/shell/platform/windows/system_utils.h",
"repo_id": "engine",
"token_count": 557
} | 384 |
// 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 "flutter/shell/platform/windows/testing/mock_text_input_manager.h"
namespace flutter {
namespace testing {
MockTextInputManager::MockTextInputManager() : TextInputManager(){};
MockTextInputManager::~MockTextInputManager() = default;
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/testing/mock_text_input_manager.cc/0 | {
"file_path": "engine/shell/platform/windows/testing/mock_text_input_manager.cc",
"repo_id": "engine",
"token_count": 132
} | 385 |
// 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_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONFIG_BUILDER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONFIG_BUILDER_H_
#include <string>
#include <string_view>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/unique_object.h"
#include "flutter/shell/platform/windows/public/flutter_windows.h"
#include "flutter/shell/platform/windows/testing/windows_test_context.h"
namespace flutter {
namespace testing {
// Deleter for FlutterDesktopEngineRef objects.
struct EngineDeleter {
typedef FlutterDesktopEngineRef pointer;
void operator()(FlutterDesktopEngineRef engine) {
FML_CHECK(FlutterDesktopEngineDestroy(engine));
}
};
// Unique pointer wrapper for FlutterDesktopEngineRef.
using EnginePtr = std::unique_ptr<FlutterDesktopEngine, EngineDeleter>;
// Deleter for FlutterViewControllerRef objects.
struct ViewControllerDeleter {
typedef FlutterDesktopViewControllerRef pointer;
void operator()(FlutterDesktopViewControllerRef controller) {
FlutterDesktopViewControllerDestroy(controller);
}
};
// Unique pointer wrapper for FlutterDesktopViewControllerRef.
using ViewControllerPtr =
std::unique_ptr<FlutterDesktopViewController, ViewControllerDeleter>;
// Test configuration builder for WindowsTests.
//
// Utility class for configuring engine and view controller launch arguments,
// and launching the engine to run a test fixture.
class WindowsConfigBuilder {
public:
explicit WindowsConfigBuilder(WindowsTestContext& context);
~WindowsConfigBuilder();
// Returns the desktop engine properties configured for this test.
FlutterDesktopEngineProperties GetEngineProperties() const;
// Sets the Dart entrypoint to the specified value.
//
// If not set, the default entrypoint (main) is used. Custom Dart entrypoints
// must be decorated with `@pragma('vm:entry-point')`.
void SetDartEntrypoint(std::string_view entrypoint);
// Adds an argument to the Dart entrypoint arguments List<String>.
void AddDartEntrypointArgument(std::string_view arg);
// Returns a configured and initialized engine.
EnginePtr InitializeEngine() const;
// Returns a configured and initialized engine that runs the configured Dart
// entrypoint.
//
// Returns null on failure.
EnginePtr RunHeadless() const;
// Returns a configured and initialized view controller that runs the
// configured Dart entrypoint.
//
// Returns null on failure.
ViewControllerPtr Run() const;
private:
// Initialize COM, so that it is available for use in the library and/or
// plugins.
void InitializeCOM() const;
WindowsTestContext& context_;
std::string dart_entrypoint_;
std::vector<std::string> dart_entrypoint_arguments_;
FML_DISALLOW_COPY_AND_ASSIGN(WindowsConfigBuilder);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_CONFIG_BUILDER_H_
| engine/shell/platform/windows/testing/windows_test_config_builder.h/0 | {
"file_path": "engine/shell/platform/windows/testing/windows_test_config_builder.h",
"repo_id": "engine",
"token_count": 886
} | 386 |
// 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 <array>
#include "flutter/shell/platform/windows/testing/mock_direct_manipulation.h"
#include "flutter/shell/platform/windows/testing/mock_text_input_manager.h"
#include "flutter/shell/platform/windows/testing/mock_window.h"
#include "flutter/shell/platform/windows/testing/mock_windows_proc_table.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::Eq;
using testing::InSequence;
using testing::Invoke;
using testing::Return;
namespace flutter {
namespace testing {
TEST(MockWindow, CreateDestroy) {
MockWindow window;
ASSERT_TRUE(TRUE);
}
TEST(MockWindow, GetDpiAfterCreate) {
MockWindow window;
ASSERT_TRUE(window.GetDpi() > 0);
}
TEST(MockWindow, VerticalScroll) {
MockWindow window;
const int scroll_amount = 10;
// Vertical scroll should be passed along, adjusted for scroll tick size
// and direction.
EXPECT_CALL(window, OnScroll(0, -scroll_amount / 120.0,
kFlutterPointerDeviceKindMouse, 0))
.Times(1);
window.InjectWindowMessage(WM_MOUSEWHEEL, MAKEWPARAM(0, scroll_amount), 0);
}
TEST(MockWindow, OnImeCompositionCompose) {
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto* text_input_manager = new MockTextInputManager();
std::unique_ptr<TextInputManager> text_input_manager_ptr(text_input_manager);
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager_ptr));
EXPECT_CALL(*text_input_manager, GetComposingString())
.WillRepeatedly(
Return(std::optional<std::u16string>(std::u16string(u"nihao"))));
EXPECT_CALL(*text_input_manager, GetResultString())
.WillRepeatedly(
Return(std::optional<std::u16string>(std::u16string(u"`}"))));
EXPECT_CALL(*text_input_manager, GetComposingCursorPosition())
.WillRepeatedly(Return((int)0));
EXPECT_CALL(window, OnComposeChange(std::u16string(u"nihao"), 0)).Times(1);
EXPECT_CALL(window, OnComposeChange(std::u16string(u"`}"), 0)).Times(0);
EXPECT_CALL(window, OnComposeCommit()).Times(0);
ON_CALL(window, OnImeComposition)
.WillByDefault(Invoke(&window, &MockWindow::CallOnImeComposition));
EXPECT_CALL(window, OnImeComposition(_, _, _)).Times(1);
// Send an IME_COMPOSITION event that contains just the composition string.
window.InjectWindowMessage(WM_IME_COMPOSITION, 0, GCS_COMPSTR);
}
TEST(MockWindow, OnImeCompositionResult) {
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto* text_input_manager = new MockTextInputManager();
std::unique_ptr<TextInputManager> text_input_manager_ptr(text_input_manager);
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager_ptr));
EXPECT_CALL(*text_input_manager, GetComposingString())
.WillRepeatedly(
Return(std::optional<std::u16string>(std::u16string(u"nihao"))));
EXPECT_CALL(*text_input_manager, GetResultString())
.WillRepeatedly(
Return(std::optional<std::u16string>(std::u16string(u"`}"))));
EXPECT_CALL(*text_input_manager, GetComposingCursorPosition())
.WillRepeatedly(Return((int)0));
EXPECT_CALL(window, OnComposeChange(std::u16string(u"nihao"), 0)).Times(0);
EXPECT_CALL(window, OnComposeChange(std::u16string(u"`}"), 0)).Times(1);
EXPECT_CALL(window, OnComposeCommit()).Times(1);
ON_CALL(window, OnImeComposition)
.WillByDefault(Invoke(&window, &MockWindow::CallOnImeComposition));
EXPECT_CALL(window, OnImeComposition(_, _, _)).Times(1);
// Send an IME_COMPOSITION event that contains just the result string.
window.InjectWindowMessage(WM_IME_COMPOSITION, 0, GCS_RESULTSTR);
}
TEST(MockWindow, OnImeCompositionResultAndCompose) {
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto* text_input_manager = new MockTextInputManager();
std::unique_ptr<TextInputManager> text_input_manager_ptr(text_input_manager);
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager_ptr));
// This situation is that Google Japanese Input finished composing "今日" in
// "今日は" but is still composing "は".
{
InSequence dummy;
EXPECT_CALL(*text_input_manager, GetResultString())
.WillRepeatedly(
Return(std::optional<std::u16string>(std::u16string(u"今日"))));
EXPECT_CALL(*text_input_manager, GetComposingString())
.WillRepeatedly(
Return(std::optional<std::u16string>(std::u16string(u"は"))));
}
{
InSequence dummy;
EXPECT_CALL(window, OnComposeChange(std::u16string(u"今日"), 0)).Times(1);
EXPECT_CALL(window, OnComposeCommit()).Times(1);
EXPECT_CALL(window, OnComposeChange(std::u16string(u"は"), 0)).Times(1);
}
EXPECT_CALL(*text_input_manager, GetComposingCursorPosition())
.WillRepeatedly(Return((int)0));
ON_CALL(window, OnImeComposition)
.WillByDefault(Invoke(&window, &MockWindow::CallOnImeComposition));
EXPECT_CALL(window, OnImeComposition(_, _, _)).Times(1);
// send an IME_COMPOSITION event that contains both the result string and the
// composition string.
window.InjectWindowMessage(WM_IME_COMPOSITION, 0,
GCS_COMPSTR | GCS_RESULTSTR);
}
TEST(MockWindow, OnImeCompositionClearChange) {
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto* text_input_manager = new MockTextInputManager();
std::unique_ptr<TextInputManager> text_input_manager_ptr(text_input_manager);
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager_ptr));
EXPECT_CALL(window, OnComposeChange(std::u16string(u""), 0)).Times(1);
EXPECT_CALL(window, OnComposeCommit()).Times(1);
ON_CALL(window, OnImeComposition)
.WillByDefault(Invoke(&window, &MockWindow::CallOnImeComposition));
EXPECT_CALL(window, OnImeComposition(_, _, _)).Times(1);
// send an IME_COMPOSITION event that contains both the result string and the
// composition string.
window.InjectWindowMessage(WM_IME_COMPOSITION, 0, 0);
}
TEST(MockWindow, HorizontalScroll) {
MockWindow window;
const int scroll_amount = 10;
// Vertical scroll should be passed along, adjusted for scroll tick size.
EXPECT_CALL(window, OnScroll(scroll_amount / 120.0, 0,
kFlutterPointerDeviceKindMouse, 0))
.Times(1);
window.InjectWindowMessage(WM_MOUSEHWHEEL, MAKEWPARAM(0, scroll_amount), 0);
}
TEST(MockWindow, MouseLeave) {
MockWindow window;
const double mouse_x = 10.0;
const double mouse_y = 20.0;
EXPECT_CALL(window, OnPointerMove(mouse_x, mouse_y,
kFlutterPointerDeviceKindMouse, 0, 0))
.Times(1);
EXPECT_CALL(window, OnPointerLeave(mouse_x, mouse_y,
kFlutterPointerDeviceKindMouse, 0))
.Times(1);
window.InjectWindowMessage(WM_MOUSEMOVE, 0, MAKELPARAM(mouse_x, mouse_y));
window.InjectWindowMessage(WM_MOUSELEAVE, 0, 0);
}
TEST(MockWindow, KeyDown) {
MockWindow window;
EXPECT_CALL(window, OnKey(_, _, _, _, _, _, _)).Times(1);
LPARAM lparam = CreateKeyEventLparam(42, false, false);
// send a "Shift" key down event.
window.InjectWindowMessage(WM_KEYDOWN, 16, lparam);
}
TEST(MockWindow, KeyUp) {
MockWindow window;
EXPECT_CALL(window, OnKey(_, _, _, _, _, _, _)).Times(1);
LPARAM lparam = CreateKeyEventLparam(42, false, true);
// send a "Shift" key up event.
window.InjectWindowMessage(WM_KEYUP, 16, lparam);
}
TEST(MockWindow, SysKeyDown) {
MockWindow window;
EXPECT_CALL(window, OnKey(_, _, _, _, _, _, _)).Times(1);
LPARAM lparam = CreateKeyEventLparam(42, false, false);
// send a "Shift" key down event.
window.InjectWindowMessage(WM_SYSKEYDOWN, 16, lparam);
}
TEST(MockWindow, SysKeyUp) {
MockWindow window;
EXPECT_CALL(window, OnKey(_, _, _, _, _, _, _)).Times(1);
LPARAM lparam = CreateKeyEventLparam(42, false, true);
// send a "Shift" key up event.
window.InjectWindowMessage(WM_SYSKEYUP, 16, lparam);
}
TEST(MockWindow, KeyDownPrintable) {
MockWindow window;
LPARAM lparam = CreateKeyEventLparam(30, false, false);
auto respond_false = [](int key, int scancode, int action, char32_t character,
bool extended, bool was_down,
std::function<void(bool)> callback) {
callback(false);
};
EXPECT_CALL(window, OnKey(65, 30, WM_KEYDOWN, 0, false, false, _))
.Times(1)
.WillOnce(respond_false);
EXPECT_CALL(window, OnText(_)).Times(1);
std::array<Win32Message, 2> messages = {
Win32Message{WM_KEYDOWN, 65, lparam, kWmResultDontCheck},
Win32Message{WM_CHAR, 65, lparam, kWmResultDontCheck}};
window.InjectMessageList(2, messages.data());
}
TEST(MockWindow, KeyDownWithCtrl) {
MockWindow window;
// Simulate CONTROL pressed
std::array<BYTE, 256> keyboard_state;
keyboard_state[VK_CONTROL] = -1;
SetKeyboardState(keyboard_state.data());
LPARAM lparam = CreateKeyEventLparam(30, false, false);
// Expect OnKey, but not OnText, because Control + Key is not followed by
// WM_CHAR
EXPECT_CALL(window, OnKey(65, 30, WM_KEYDOWN, 0, false, false, _)).Times(1);
EXPECT_CALL(window, OnText(_)).Times(0);
window.InjectWindowMessage(WM_KEYDOWN, 65, lparam);
keyboard_state.fill(0);
SetKeyboardState(keyboard_state.data());
}
TEST(MockWindow, KeyDownWithCtrlToggled) {
MockWindow window;
auto respond_false = [](int key, int scancode, int action, char32_t character,
bool extended, bool was_down,
std::function<void(bool)> callback) {
callback(false);
};
// Simulate CONTROL toggled
std::array<BYTE, 256> keyboard_state;
keyboard_state[VK_CONTROL] = 1;
SetKeyboardState(keyboard_state.data());
LPARAM lparam = CreateKeyEventLparam(30, false, false);
EXPECT_CALL(window, OnKey(65, 30, WM_KEYDOWN, 0, false, false, _))
.Times(1)
.WillOnce(respond_false);
EXPECT_CALL(window, OnText(_)).Times(1);
// send a "A" key down event.
Win32Message messages[] = {{WM_KEYDOWN, 65, lparam, kWmResultDontCheck},
{WM_CHAR, 65, lparam, kWmResultDontCheck}};
window.InjectMessageList(2, messages);
keyboard_state.fill(0);
SetKeyboardState(keyboard_state.data());
}
TEST(MockWindow, Paint) {
MockWindow window;
EXPECT_CALL(window, OnPaint()).Times(1);
window.InjectWindowMessage(WM_PAINT, 0, 0);
}
// Verify direct manipulation isn't notified of pointer hit tests.
TEST(MockWindow, PointerHitTest) {
UINT32 pointer_id = 123;
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto text_input_manager = std::make_unique<MockTextInputManager>();
EXPECT_CALL(*windows_proc_table, GetPointerType(Eq(pointer_id), _))
.Times(1)
.WillOnce([](UINT32 pointer_id, POINTER_INPUT_TYPE* type) {
*type = PT_POINTER;
return TRUE;
});
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager));
auto direct_manipulation =
std::make_unique<MockDirectManipulationOwner>(&window);
EXPECT_CALL(*direct_manipulation, SetContact).Times(0);
window.SetDirectManipulationOwner(std::move(direct_manipulation));
window.InjectWindowMessage(DM_POINTERHITTEST, MAKEWPARAM(pointer_id, 0), 0);
}
// Verify direct manipulation is notified of touchpad hit tests.
TEST(MockWindow, TouchPadHitTest) {
UINT32 pointer_id = 123;
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto text_input_manager = std::make_unique<MockTextInputManager>();
EXPECT_CALL(*windows_proc_table, GetPointerType(Eq(pointer_id), _))
.Times(1)
.WillOnce([](UINT32 pointer_id, POINTER_INPUT_TYPE* type) {
*type = PT_TOUCHPAD;
return TRUE;
});
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager));
auto direct_manipulation =
std::make_unique<MockDirectManipulationOwner>(&window);
EXPECT_CALL(*direct_manipulation, SetContact(Eq(pointer_id))).Times(1);
window.SetDirectManipulationOwner(std::move(direct_manipulation));
window.InjectWindowMessage(DM_POINTERHITTEST, MAKEWPARAM(pointer_id, 0), 0);
}
// Verify direct manipulation isn't notified of unknown hit tests.
// This can happen if determining the pointer type fails, for example,
// if GetPointerType is unsupported by the current Windows version.
// See: https://github.com/flutter/flutter/issues/109412
TEST(MockWindow, UnknownPointerTypeSkipsDirectManipulation) {
UINT32 pointer_id = 123;
auto windows_proc_table = std::make_unique<MockWindowsProcTable>();
auto text_input_manager = std::make_unique<MockTextInputManager>();
EXPECT_CALL(*windows_proc_table, GetPointerType(Eq(pointer_id), _))
.Times(1)
.WillOnce(
[](UINT32 pointer_id, POINTER_INPUT_TYPE* type) { return FALSE; });
MockWindow window(std::move(windows_proc_table),
std::move(text_input_manager));
auto direct_manipulation =
std::make_unique<MockDirectManipulationOwner>(&window);
EXPECT_CALL(*direct_manipulation, SetContact).Times(0);
window.SetDirectManipulationOwner(std::move(direct_manipulation));
window.InjectWindowMessage(DM_POINTERHITTEST, MAKEWPARAM(pointer_id, 0), 0);
}
// Test that the root UIA object is queried by WM_GETOBJECT.
TEST(MockWindow, DISABLED_GetObjectUia) {
MockWindow window;
bool uia_called = false;
ON_CALL(window, OnGetObject)
.WillByDefault(Invoke([&uia_called](UINT msg, WPARAM wpar, LPARAM lpar) {
#ifdef FLUTTER_ENGINE_USE_UIA
uia_called = true;
#endif // FLUTTER_ENGINE_USE_UIA
return static_cast<LRESULT>(0);
}));
EXPECT_CALL(window, OnGetObject).Times(1);
window.InjectWindowMessage(WM_GETOBJECT, 0, UiaRootObjectId);
EXPECT_TRUE(uia_called);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/window_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/window_unittests.cc",
"repo_id": "engine",
"token_count": 5516
} | 387 |
// 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.
#define FML_USED_ON_EMBEDDER
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "flutter/assets/asset_manager.h"
#include "flutter/assets/directory_asset_bundle.h"
#include "flutter/flow/embedded_views.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/file.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/task_runner.h"
#include "flutter/shell/common/platform_view.h"
#include "flutter/shell/common/rasterizer.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/switches.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/gpu/gpu_surface_software.h"
#include "flutter/third_party/abseil-cpp/absl/base/no_destructor.h"
#include "third_party/dart/runtime/include/bin/dart_io_api.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/skia/include/core/SkSurface.h"
// Impeller should only be enabled if the Vulkan backend is enabled.
#define ALLOW_IMPELLER (IMPELLER_SUPPORTS_RENDERING && IMPELLER_ENABLE_VULKAN)
#if ALLOW_IMPELLER
#include <vulkan/vulkan.h> // nogncheck
#include "impeller/entity/vk/entity_shaders_vk.h" // nogncheck
#include "impeller/entity/vk/framebuffer_blend_shaders_vk.h" // nogncheck
#include "impeller/entity/vk/modern_shaders_vk.h" // nogncheck
#include "impeller/renderer/backend/vulkan/context_vk.h" // nogncheck
#include "impeller/renderer/backend/vulkan/surface_context_vk.h" // nogncheck
#include "impeller/renderer/context.h" // nogncheck
#include "impeller/renderer/vk/compute_shaders_vk.h" // nogncheck
#include "shell/gpu/gpu_surface_vulkan_impeller.h" // nogncheck
#if IMPELLER_ENABLE_3D
#include "impeller/scene/shaders/vk/scene_shaders_vk.h" // nogncheck
#endif // IMPELLER_ENABLE_3D
static std::vector<std::shared_ptr<fml::Mapping>> ShaderLibraryMappings() {
return {
std::make_shared<fml::NonOwnedMapping>(impeller_entity_shaders_vk_data,
impeller_entity_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(impeller_modern_shaders_vk_data,
impeller_modern_shaders_vk_length),
std::make_shared<fml::NonOwnedMapping>(
impeller_framebuffer_blend_shaders_vk_data,
impeller_framebuffer_blend_shaders_vk_length),
#if IMPELLER_ENABLE_3D
std::make_shared<fml::NonOwnedMapping>(impeller_scene_shaders_vk_data,
impeller_scene_shaders_vk_length),
#endif // IMPELLER_ENABLE_3D
std::make_shared<fml::NonOwnedMapping>(
impeller_compute_shaders_vk_data, impeller_compute_shaders_vk_length),
};
}
struct ImpellerVulkanContextHolder {
ImpellerVulkanContextHolder() = default;
ImpellerVulkanContextHolder(ImpellerVulkanContextHolder&&) = default;
std::shared_ptr<impeller::ContextVK> context;
std::shared_ptr<impeller::SurfaceContextVK> surface_context;
bool Initialize(bool enable_validation);
};
bool ImpellerVulkanContextHolder::Initialize(bool enable_validation) {
impeller::ContextVK::Settings context_settings;
context_settings.proc_address_callback = &vkGetInstanceProcAddr;
context_settings.shader_libraries_data = ShaderLibraryMappings();
context_settings.cache_directory = fml::paths::GetCachesDirectory();
context_settings.enable_validation = enable_validation;
context = impeller::ContextVK::Create(std::move(context_settings));
if (!context || !context->IsValid()) {
VALIDATION_LOG << "Could not create Vulkan context.";
return false;
}
impeller::vk::SurfaceKHR vk_surface;
impeller::vk::HeadlessSurfaceCreateInfoEXT surface_create_info;
auto res = context->GetInstance().createHeadlessSurfaceEXT(
&surface_create_info, // surface create info
nullptr, // allocator
&vk_surface // surface
);
if (res != impeller::vk::Result::eSuccess) {
VALIDATION_LOG << "Could not create surface for tester "
<< impeller::vk::to_string(res);
return false;
}
impeller::vk::UniqueSurfaceKHR surface{vk_surface, context->GetInstance()};
surface_context = context->CreateSurfaceContext();
if (!surface_context->SetWindowSurface(std::move(surface),
impeller::ISize{1, 1})) {
VALIDATION_LOG << "Could not set up surface for context.";
return false;
}
return true;
}
#else
struct ImpellerVulkanContextHolder {};
#endif // IMPELLER_SUPPORTS_RENDERING
#if defined(FML_OS_WIN)
#include <combaseapi.h>
#endif // defined(FML_OS_WIN)
#if defined(FML_OS_POSIX)
#include <signal.h>
#endif // defined(FML_OS_POSIX)
namespace flutter {
static absl::NoDestructor<std::unique_ptr<Shell>> g_shell;
static constexpr int64_t kImplicitViewId = 0ll;
static void ConfigureShell(Shell* shell) {
auto device_pixel_ratio = 3.0;
auto physical_width = 2400.0; // 800 at 3x resolution.
auto physical_height = 1800.0; // 600 at 3x resolution.
std::vector<std::unique_ptr<Display>> displays;
displays.push_back(std::make_unique<Display>(
0, 60, physical_width, physical_height, device_pixel_ratio));
shell->OnDisplayUpdates(std::move(displays));
flutter::ViewportMetrics metrics{};
metrics.device_pixel_ratio = device_pixel_ratio;
metrics.physical_width = physical_width;
metrics.physical_height = physical_height;
metrics.display_id = 0;
shell->GetPlatformView()->SetViewportMetrics(kImplicitViewId, metrics);
}
class TesterExternalViewEmbedder : public ExternalViewEmbedder {
// |ExternalViewEmbedder|
DlCanvas* GetRootCanvas() override { return nullptr; }
// |ExternalViewEmbedder|
void CancelFrame() override {}
// |ExternalViewEmbedder|
void BeginFrame(GrDirectContext* context,
const fml::RefPtr<fml::RasterThreadMerger>&
raster_thread_merger) override {}
// |ExternalViewEmbedder|
void PrepareFlutterView(int64_t flutter_view_id,
SkISize frame_size,
double device_pixel_ratio) override {}
// |ExternalViewEmbedder|
void PrerollCompositeEmbeddedView(
int64_t view_id,
std::unique_ptr<EmbeddedViewParams> params) override {}
// |ExternalViewEmbedder|
DlCanvas* CompositeEmbeddedView(int64_t view_id) override {
return &builder_;
}
private:
DisplayListBuilder builder_;
};
class TesterGPUSurfaceSoftware : public GPUSurfaceSoftware {
public:
TesterGPUSurfaceSoftware(GPUSurfaceSoftwareDelegate* delegate,
bool render_to_surface)
: GPUSurfaceSoftware(delegate, render_to_surface) {}
bool EnableRasterCache() const override { return false; }
};
class TesterPlatformView : public PlatformView,
public GPUSurfaceSoftwareDelegate {
public:
TesterPlatformView(Delegate& delegate,
const TaskRunners& task_runners,
ImpellerVulkanContextHolder&& impeller_context_holder)
: PlatformView(delegate, task_runners),
impeller_context_holder_(std::move(impeller_context_holder)) {}
~TesterPlatformView() {
#if ALLOW_IMPELLER
if (impeller_context_holder_.context) {
impeller_context_holder_.context->Shutdown();
}
#endif
}
// |PlatformView|
std::shared_ptr<impeller::Context> GetImpellerContext() const override {
#if ALLOW_IMPELLER
return std::static_pointer_cast<impeller::Context>(
impeller_context_holder_.context);
#else
return nullptr;
#endif // ALLOW_IMPELLER
}
// |PlatformView|
std::unique_ptr<Surface> CreateRenderingSurface() override {
#if ALLOW_IMPELLER
if (delegate_.OnPlatformViewGetSettings().enable_impeller) {
FML_DCHECK(impeller_context_holder_.context);
auto surface = std::make_unique<GPUSurfaceVulkanImpeller>(
impeller_context_holder_.surface_context);
FML_DCHECK(surface->IsValid());
return surface;
}
#endif // ALLOW_IMPELLER
auto surface = std::make_unique<TesterGPUSurfaceSoftware>(
this, true /* render to surface */);
FML_DCHECK(surface->IsValid());
return surface;
}
// |GPUSurfaceSoftwareDelegate|
sk_sp<SkSurface> AcquireBackingStore(const SkISize& size) override {
if (sk_surface_ != nullptr &&
SkISize::Make(sk_surface_->width(), sk_surface_->height()) == size) {
// The old and new surface sizes are the same. Nothing to do here.
return sk_surface_;
}
SkImageInfo info =
SkImageInfo::MakeN32(size.fWidth, size.fHeight, kPremul_SkAlphaType,
SkColorSpace::MakeSRGB());
sk_surface_ = SkSurfaces::Raster(info, nullptr);
if (sk_surface_ == nullptr) {
FML_LOG(ERROR)
<< "Could not create backing store for software rendering.";
return nullptr;
}
return sk_surface_;
}
// |GPUSurfaceSoftwareDelegate|
bool PresentBackingStore(sk_sp<SkSurface> backing_store) override {
return true;
}
// |PlatformView|
std::shared_ptr<ExternalViewEmbedder> CreateExternalViewEmbedder() override {
return external_view_embedder_;
}
private:
sk_sp<SkSurface> sk_surface_ = nullptr;
[[maybe_unused]] ImpellerVulkanContextHolder impeller_context_holder_;
std::shared_ptr<TesterExternalViewEmbedder> external_view_embedder_ =
std::make_shared<TesterExternalViewEmbedder>();
};
// Checks whether the engine's main Dart isolate has no pending work. If so,
// then exit the given message loop.
class ScriptCompletionTaskObserver {
public:
ScriptCompletionTaskObserver(Shell& shell,
fml::RefPtr<fml::TaskRunner> main_task_runner,
bool run_forever)
: shell_(shell),
main_task_runner_(std::move(main_task_runner)),
run_forever_(run_forever) {}
int GetExitCodeForLastError() const {
return static_cast<int>(last_error_.value_or(DartErrorCode::NoError));
}
void DidProcessTask() {
last_error_ = shell_.GetUIIsolateLastError();
if (shell_.EngineHasLivePorts()) {
// The UI isolate still has live ports and is running. Nothing to do
// just yet.
return;
}
if (run_forever_) {
// We need this script to run forever. We have already recorded the last
// error. Keep going.
return;
}
if (!has_terminated_) {
// Only try to terminate the loop once.
has_terminated_ = true;
fml::TaskRunner::RunNowOrPostTask(main_task_runner_, []() {
fml::MessageLoop::GetCurrent().Terminate();
});
}
}
private:
Shell& shell_;
fml::RefPtr<fml::TaskRunner> main_task_runner_;
bool run_forever_ = false;
std::optional<DartErrorCode> last_error_;
bool has_terminated_ = false;
FML_DISALLOW_COPY_AND_ASSIGN(ScriptCompletionTaskObserver);
};
// Processes spawned via dart:io inherit their signal handling from the parent
// process. As part of spawning, the spawner blocks signals temporarily, so we
// need to explicitly unblock the signals we care about in the new process. In
// particular, we need to unblock SIGPROF for CPU profiling to work on the
// mutator thread in the main isolate in this process (threads spawned by the VM
// know about this limitation and automatically have this signal unblocked).
static void UnblockSIGPROF() {
#if defined(FML_OS_POSIX)
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGPROF);
pthread_sigmask(SIG_UNBLOCK, &set, NULL);
#endif // defined(FML_OS_POSIX)
}
int RunTester(const flutter::Settings& settings,
bool run_forever,
bool multithreaded) {
const auto thread_label = "io.flutter.test.";
// Necessary if we want to use the CPU profiler on the main isolate's mutator
// thread.
//
// OSX WARNING: avoid spawning additional threads before this call due to a
// kernel bug that may enable SIGPROF on an unintended thread in the process.
UnblockSIGPROF();
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto current_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
std::unique_ptr<ThreadHost> threadhost;
fml::RefPtr<fml::TaskRunner> platform_task_runner;
fml::RefPtr<fml::TaskRunner> raster_task_runner;
fml::RefPtr<fml::TaskRunner> ui_task_runner;
fml::RefPtr<fml::TaskRunner> io_task_runner;
if (multithreaded) {
threadhost = std::make_unique<ThreadHost>(
thread_label, ThreadHost::Type::kPlatform | ThreadHost::Type::kIo |
ThreadHost::Type::kUi | ThreadHost::Type::kRaster);
platform_task_runner = current_task_runner;
raster_task_runner = threadhost->raster_thread->GetTaskRunner();
ui_task_runner = threadhost->ui_thread->GetTaskRunner();
io_task_runner = threadhost->io_thread->GetTaskRunner();
} else {
platform_task_runner = raster_task_runner = ui_task_runner =
io_task_runner = current_task_runner;
}
const flutter::TaskRunners task_runners(thread_label, // dart thread label
platform_task_runner, // platform
raster_task_runner, // raster
ui_task_runner, // ui
io_task_runner // io
);
ImpellerVulkanContextHolder impeller_context_holder;
#if ALLOW_IMPELLER
if (settings.enable_impeller) {
if (!impeller_context_holder.Initialize(
settings.enable_vulkan_validation)) {
return EXIT_FAILURE;
}
}
#endif // ALLOW_IMPELLER
Shell::CreateCallback<PlatformView> on_create_platform_view =
fml::MakeCopyable([impeller_context_holder = std::move(
impeller_context_holder)](Shell& shell) mutable {
return std::make_unique<TesterPlatformView>(
shell, shell.GetTaskRunners(), std::move(impeller_context_holder));
});
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(
shell, Rasterizer::MakeGpuImageBehavior::kBitmap);
};
g_shell->reset(Shell::Create(flutter::PlatformData(), //
task_runners, //
settings, //
on_create_platform_view, //
on_create_rasterizer //
)
.release());
auto shell = g_shell->get();
if (!shell || !shell->IsSetup()) {
FML_LOG(ERROR) << "Could not set up the shell.";
return EXIT_FAILURE;
}
if (settings.application_kernel_asset.empty()) {
FML_LOG(ERROR) << "Dart kernel file not specified.";
return EXIT_FAILURE;
}
shell->GetPlatformView()->NotifyCreated();
// Initialize default testing locales. There is no platform to
// pass locales on the tester, so to retain expected locale behavior,
// we emulate it in here by passing in 'en_US' and 'zh_CN' as test locales.
const char* locale_json =
"{\"method\":\"setLocale\",\"args\":[\"en\",\"US\",\"\",\"\",\"zh\","
"\"CN\",\"\",\"\"]}";
auto locale_bytes = fml::MallocMapping::Copy(
locale_json, locale_json + std::strlen(locale_json));
fml::RefPtr<flutter::PlatformMessageResponse> response;
shell->GetPlatformView()->DispatchPlatformMessage(
std::make_unique<flutter::PlatformMessage>(
"flutter/localization", std::move(locale_bytes), response));
std::initializer_list<fml::FileMapping::Protection> protection = {
fml::FileMapping::Protection::kRead};
auto main_dart_file_mapping = std::make_unique<fml::FileMapping>(
fml::OpenFile(
fml::paths::AbsolutePath(settings.application_kernel_asset).c_str(),
false, fml::FilePermission::kRead),
protection);
auto isolate_configuration =
IsolateConfiguration::CreateForKernel(std::move(main_dart_file_mapping));
if (!isolate_configuration) {
FML_LOG(ERROR) << "Could create isolate configuration.";
return EXIT_FAILURE;
}
auto asset_manager = std::make_shared<flutter::AssetManager>();
asset_manager->PushBack(std::make_unique<flutter::DirectoryAssetBundle>(
fml::Duplicate(settings.assets_dir), true));
asset_manager->PushBack(std::make_unique<flutter::DirectoryAssetBundle>(
fml::OpenDirectory(settings.assets_path.c_str(), false,
fml::FilePermission::kRead),
true));
RunConfiguration run_configuration(std::move(isolate_configuration),
std::move(asset_manager));
// The script completion task observer that will be installed on the UI thread
// that watched if the engine has any live ports.
ScriptCompletionTaskObserver completion_observer(
*shell, // a valid shell
fml::MessageLoop::GetCurrent()
.GetTaskRunner(), // the message loop to terminate
run_forever // should the exit be ignored
);
bool engine_did_run = false;
fml::AutoResetWaitableEvent latch;
auto task_observer_add = [&completion_observer]() {
fml::MessageLoop::GetCurrent().AddTaskObserver(
reinterpret_cast<intptr_t>(&completion_observer),
[&completion_observer]() { completion_observer.DidProcessTask(); });
};
auto task_observer_remove = [&completion_observer, &latch]() {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(
reinterpret_cast<intptr_t>(&completion_observer));
latch.Signal();
};
shell->RunEngine(std::move(run_configuration),
[&engine_did_run, &ui_task_runner,
&task_observer_add](Engine::RunStatus run_status) mutable {
if (run_status != flutter::Engine::RunStatus::Failure) {
engine_did_run = true;
// Now that our engine is initialized we can install the
// ScriptCompletionTaskObserver
fml::TaskRunner::RunNowOrPostTask(ui_task_runner,
task_observer_add);
}
});
ConfigureShell(shell);
// Run the message loop and wait for the script to do its thing.
fml::MessageLoop::GetCurrent().Run();
// Cleanup the completion observer synchronously as it is living on the
// stack.
fml::TaskRunner::RunNowOrPostTask(ui_task_runner, task_observer_remove);
latch.Wait();
delete g_shell->release();
if (!engine_did_run) {
// If the engine itself didn't have a chance to run, there is no point in
// asking it if there was an error. Signal a failure unconditionally.
return EXIT_FAILURE;
}
return completion_observer.GetExitCodeForLastError();
}
#ifdef _WIN32
#define EXPORTED __declspec(dllexport)
#else
#define EXPORTED __attribute__((visibility("default")))
#endif
extern "C" {
EXPORTED Dart_Handle LoadLibraryFromKernel(const char* path) {
std::shared_ptr<fml::FileMapping> mapping =
fml::FileMapping::CreateReadOnly(path);
if (!mapping) {
return Dart_Null();
}
return DartIsolate::LoadLibraryFromKernel(mapping);
}
EXPORTED Dart_Handle LookupEntryPoint(const char* uri, const char* name) {
if (!uri || !name) {
return Dart_Null();
}
Dart_Handle lib = Dart_LookupLibrary(Dart_NewStringFromCString(uri));
if (Dart_IsError(lib)) {
return lib;
}
return Dart_GetField(lib, Dart_NewStringFromCString(name));
}
EXPORTED void Spawn(const char* entrypoint, const char* route) {
auto shell = g_shell->get();
auto isolate = Dart_CurrentIsolate();
auto spawn_task = [shell, entrypoint = std::string(entrypoint),
route = std::string(route)]() {
auto configuration = RunConfiguration::InferFromSettings(
shell->GetSettings(), /*io_worker=*/nullptr,
/*launch_type=*/IsolateLaunchType::kExistingGroup);
configuration.SetEntrypoint(entrypoint);
Shell::CreateCallback<PlatformView> on_create_platform_view =
fml::MakeCopyable([](Shell& shell) mutable {
ImpellerVulkanContextHolder impeller_context_holder;
return std::make_unique<TesterPlatformView>(
shell, shell.GetTaskRunners(),
std::move(impeller_context_holder));
});
Shell::CreateCallback<Rasterizer> on_create_rasterizer = [](Shell& shell) {
return std::make_unique<Rasterizer>(
shell, Rasterizer::MakeGpuImageBehavior::kBitmap);
};
// Spawn a shell, and keep it running until it has no live ports, then
// delete it on the platform thread.
auto spawned_shell =
shell
->Spawn(std::move(configuration), route, on_create_platform_view,
on_create_rasterizer)
.release();
ConfigureShell(spawned_shell);
fml::TaskRunner::RunNowOrPostTask(
spawned_shell->GetTaskRunners().GetUITaskRunner(), [spawned_shell]() {
fml::MessageLoop::GetCurrent().AddTaskObserver(
reinterpret_cast<intptr_t>(spawned_shell), [spawned_shell]() {
if (spawned_shell->EngineHasLivePorts()) {
return;
}
fml::MessageLoop::GetCurrent().RemoveTaskObserver(
reinterpret_cast<intptr_t>(spawned_shell));
// Shell must be deleted on the platform task runner.
fml::TaskRunner::RunNowOrPostTask(
spawned_shell->GetTaskRunners().GetPlatformTaskRunner(),
[spawned_shell]() { delete spawned_shell; });
});
});
};
Dart_ExitIsolate();
// The global shell pointer is never deleted, short of application exit.
// This UI task runner cannot be latched because it will block spawning a new
// shell in the case where flutter_tester is running multithreaded.
fml::TaskRunner::RunNowOrPostTask(
shell->GetTaskRunners().GetPlatformTaskRunner(), spawn_task);
Dart_EnterIsolate(isolate);
}
EXPORTED void ForceShutdownIsolate() {
// Enable Isolate.exit().
FML_DCHECK(Dart_CurrentIsolate() != nullptr);
Dart_Handle isolate_lib = Dart_LookupLibrary(tonic::ToDart("dart:isolate"));
FML_CHECK(!tonic::CheckAndHandleError(isolate_lib));
Dart_Handle isolate_type = Dart_GetNonNullableType(
isolate_lib, tonic::ToDart("Isolate"), 0, nullptr);
FML_CHECK(!tonic::CheckAndHandleError(isolate_type));
Dart_Handle result =
Dart_SetField(isolate_type, tonic::ToDart("_mayExit"), Dart_True());
FML_CHECK(!tonic::CheckAndHandleError(result));
}
}
} // namespace flutter
int main(int argc, char* argv[]) {
dart::bin::SetExecutableName(argv[0]);
dart::bin::SetExecutableArguments(argc - 1, argv);
auto command_line = fml::CommandLineFromPlatformOrArgcArgv(argc, argv);
if (command_line.HasOption(flutter::FlagForSwitch(flutter::Switch::Help))) {
flutter::PrintUsage("flutter_tester");
return EXIT_SUCCESS;
}
auto settings = flutter::SettingsFromCommandLine(command_line);
if (!command_line.positional_args().empty()) {
// The tester may not use the switch for the main dart file path. Specifying
// it as a positional argument instead.
settings.application_kernel_asset = command_line.positional_args()[0];
}
if (settings.application_kernel_asset.empty()) {
FML_LOG(ERROR) << "Dart kernel file not specified.";
return EXIT_FAILURE;
}
settings.leak_vm = false;
if (settings.icu_data_path.empty()) {
settings.icu_data_path = "icudtl.dat";
}
// The tools that read logs get confused if there is a log tag specified.
settings.log_tag = "";
settings.log_message_callback = [](const std::string& tag,
const std::string& message) {
if (!tag.empty()) {
std::cout << tag << ": ";
}
std::cout << message << std::endl;
};
settings.task_observer_add = [](intptr_t key, const fml::closure& callback) {
fml::MessageLoop::GetCurrent().AddTaskObserver(key, callback);
};
settings.task_observer_remove = [](intptr_t key) {
fml::MessageLoop::GetCurrent().RemoveTaskObserver(key);
};
settings.unhandled_exception_callback = [](const std::string& error,
const std::string& stack_trace) {
FML_LOG(ERROR) << "Unhandled exception" << std::endl
<< "Exception: " << error << std::endl
<< "Stack trace: " << stack_trace;
::exit(1);
return true;
};
#if defined(FML_OS_WIN)
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#endif // defined(FML_OS_WIN)
return flutter::RunTester(settings,
command_line.HasOption(flutter::FlagForSwitch(
flutter::Switch::RunForever)),
command_line.HasOption(flutter::FlagForSwitch(
flutter::Switch::ForceMultithreading)));
}
| engine/shell/testing/tester_main.cc/0 | {
"file_path": "engine/shell/testing/tester_main.cc",
"repo_id": "engine",
"token_count": 10270
} | 388 |
# 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.
import("//flutter/build/zip_bundle.gni")
if (is_android) {
action("sky_engine") {
script = "//flutter/sky/tools/dist_dart_pkg.py"
source = "$root_gen_dir/dart-pkg/sky_engine"
dest = "$root_build_dir/dist/packages/sky_engine"
inputs = [ source ]
outputs = [ dest ]
args = [
"--source",
rebase_path(source),
"--dest",
rebase_path(dest),
]
deps = [ "//flutter/sky/packages/sky_engine" ]
}
zip_bundle("zip") {
output = "$android_zip_archive_dir/sky_engine.zip"
files = [
{
source = "$root_build_dir/dist/packages/sky_engine"
destination = "sky_engine"
},
]
deps = [ ":sky_engine" ]
}
zip_bundle("zip_old_location") {
# TODO godofredoc: remove after we migrate the tool to use the new location.
# Bug: https://github.com/flutter/flutter/issues/105351
output = "sky_engine.zip"
files = [
{
source = "$root_build_dir/dist/packages/sky_engine"
destination = "sky_engine"
},
]
deps = [ ":sky_engine" ]
}
}
group("dist") {
if (is_android) {
deps = [ ":zip" ]
}
}
| engine/sky/dist/BUILD.gn/0 | {
"file_path": "engine/sky/dist/BUILD.gn",
"repo_id": "engine",
"token_count": 554
} | 389 |
#!/usr/bin/env python3
#
# 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.
"""Copy a Dart package into a directory suitable for release."""
import argparse
import os
import shutil
import sys
def main():
parser = argparse.ArgumentParser(description='Copy a Dart package')
parser.add_argument('--source', type=str, help='Source directory assembled by dart_pkg.py')
parser.add_argument('--dest', type=str, help='Destination directory for the package')
args = parser.parse_args()
if os.path.exists(args.dest):
shutil.rmtree(args.dest)
# dart_pkg.py will create a packages directory within the package.
# Do not copy this into the release output.
shutil.copytree(args.source, args.dest, ignore=shutil.ignore_patterns('packages'))
if __name__ == '__main__':
sys.exit(main())
| engine/sky/tools/dist_dart_pkg.py/0 | {
"file_path": "engine/sky/tools/dist_dart_pkg.py",
"repo_id": "engine",
"token_count": 274
} | 390 |
# 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.
import("//build/config/android/config.gni")
import("//flutter/tools/templater/templater.gni")
android_buildtools = "//third_party/android_tools/sdk/build-tools/34.0.0"
aapt2 = "$android_buildtools/aapt2"
zipalign = "$android_buildtools/zipalign"
apksigner = "$android_buildtools/apksigner"
android_jar = "//third_party/android_tools/sdk/platforms/android-34/android.jar"
src_root = "//flutter/testing/android/native_activity"
# A drop in replacement for an executable or shared library target. Providing a
# (required) apk_name packages that native code into an APK suitable for
# debugging.
template("native_activity_apk") {
assert(defined(invoker.apk_name), "The name of the APK must be specified.")
invoker_apk_name = invoker.apk_name
apk_dylib_name = "lib$invoker_apk_name.so"
android_manifest_template = "$src_root/AndroidManifest.xml.template"
android_manifest = "$target_gen_dir/AndroidManifest.xml"
android_manifest_target_name = "android_manifest_$target_name"
templater(android_manifest_target_name) {
input = android_manifest_template
output = android_manifest
values = [ "--apk-library-name=$invoker_apk_name" ]
}
shared_library_target_name = "shared_library_$target_name"
shared_library(shared_library_target_name) {
forward_variables_from(invoker, "*", [ "output_name" ])
output_name = invoker_apk_name
}
apk_target_name = "apk_$target_name"
action(apk_target_name) {
forward_variables_from(invoker, [ "testonly" ])
script = "$src_root/native_activity_apk.py"
apk_path = "$root_build_dir/$invoker_apk_name.apk"
sources = [
"$root_build_dir/$apk_dylib_name",
aapt2,
android_jar,
android_manifest_template,
apksigner,
zipalign,
]
outputs = [ apk_path ]
args = [
"--aapt2-bin",
rebase_path(aapt2, root_build_dir),
"--zipalign-bin",
rebase_path(zipalign, root_build_dir),
"--android-manifest",
rebase_path(android_manifest, root_build_dir),
"--android-jar",
rebase_path(android_jar, root_build_dir),
"--output-path",
rebase_path(apk_path, root_build_dir),
"--library",
rebase_path("$root_build_dir/$apk_dylib_name", root_build_dir),
"--apksigner-bin",
rebase_path(apksigner, root_build_dir),
"--keystore",
rebase_path("$src_root/debug.keystore", root_build_dir),
"--gen-dir",
rebase_path(target_gen_dir, root_build_dir),
"--android-abi",
android_app_abi,
]
deps = [
":$android_manifest_target_name",
":$shared_library_target_name",
]
}
group(target_name) {
forward_variables_from(invoker, [ "testonly" ])
deps = [ ":$apk_target_name" ]
}
}
| engine/testing/android/native_activity/native_activity.gni/0 | {
"file_path": "engine/testing/android/native_activity/native_activity.gni",
"repo_id": "engine",
"token_count": 1182
} | 391 |
// 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.
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
final Completer<bool> _completer = Completer<bool>();
Future<void> main() async {
channelBuffers.setListener('flutter/lifecycle', _lifecycle);
final bool success = await _completer.future;
final Uint8List? message = success ? null : Uint8List.fromList(const <int>[1]);
PlatformDispatcher.instance.sendPlatformMessage('finish', message?.buffer.asByteData(), null);
}
Future<void> _lifecycle(ByteData? data, PlatformMessageResponseCallback? callback) async {
final String lifecycleState = String.fromCharCodes(data!.buffer.asUint8List());
if (lifecycleState == AppLifecycleState.paused.toString()) {
await _testImage();
}
}
Future<void> _testImage() async {
// A single pixel image.
final Uint8List pixels = Uint8List.fromList(const <int>[0, 1, 2, 3]);
// As long as we're using the GL backend, this will go down a path that uses
// a cross context image.
final Completer<Image> imageCompleter = Completer<Image>();
decodeImageFromPixels(
pixels,
1,
1,
PixelFormat.rgba8888,
(Image image) {
imageCompleter.complete(image);
},
);
final Image image = await imageCompleter.future;
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawImage(image, Offset.zero, Paint());
final Picture picture = recorder.endRecording();
final Image newImage = await picture.toImage(1, 1);
final ByteData imageData = (await newImage.toByteData())!;
final Uint32List newPixels = imageData.buffer.asUint32List();
if (pixels.buffer.asUint32List()[0] != newPixels[0]) {
print('Pixels do not match');
print('original pixels: $pixels');
print('new pixels: ${newPixels.buffer.asUint8List()}');
_completer.complete(false);
} else {
print('Images are identical!');
_completer.complete(true);
}
}
| engine/testing/android_background_image/lib/main.dart/0 | {
"file_path": "engine/testing/android_background_image/lib/main.dart",
"repo_id": "engine",
"token_count": 697
} | 392 |
#!/bin/bash
#
# 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.
# This script is currently used only by automation to collect and upload
# metrics and expects $ENGINE_PATH to be set.
set -ex
# Needed because if it is set, cd may print the path it changed to.
unset CDPATH
# On Mac OS, readlink -f doesn't work, so follow_links traverses the path one
# link at a time, and then cds into the link destination and find out where it
# ends up.
#
# The function is enclosed in a subshell to avoid changing the working directory
# of the caller.
function follow_links() (
cd -P "$(dirname -- "$1")"
file="$PWD/$(basename -- "$1")"
while [[ -h "$file" ]]; do
cd -P "$(dirname -- "$file")"
file="$(readlink -- "$file")"
cd -P "$(dirname -- "$file")"
file="$PWD/$(basename -- "$file")"
done
echo "$file"
)
function dart_bin() {
dart_path="$1/flutter/third_party/dart/tools/sdks/dart-sdk/bin"
if [[ ! -e "$dart_path" ]]; then
dart_path="$1/third_party/dart/tools/sdks/dart-sdk/bin"
fi
echo "$dart_path"
}
SCRIPT_DIR=$(follow_links "$(dirname -- "${BASH_SOURCE[0]}")")
SRC_DIR="$(cd "$SCRIPT_DIR/../../.."; pwd -P)"
DART_BIN=$(dart_bin "$SRC_DIR")
DART="${DART_BIN}/dart"
cd "$SCRIPT_DIR"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/txt_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/fml_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/shell_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/ui_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/display_list_builder_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/display_list_region_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/display_list_transform_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/geometry_benchmarks.json "$@"
"$DART" --disable-dart-dev bin/parse_and_send.dart \
--json $ENGINE_PATH/src/out/host_release/canvas_benchmarks.json "$@"
| engine/testing/benchmark/upload_metrics.sh/0 | {
"file_path": "engine/testing/benchmark/upload_metrics.sh",
"repo_id": "engine",
"token_count": 974
} | 393 |
// 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.
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:path/path.dart' as path;
import 'package:skia_gold_client/skia_gold_client.dart';
import 'impeller_enabled.dart';
const String _kSkiaGoldWorkDirectoryKey = 'kSkiaGoldWorkDirectory';
/// A helper for doing image comparison (golden) tests.
///
/// Contains utilities for comparing two images in memory that are expected to
/// be identical, or for adding images to Skia gold for comparison.
class ImageComparer {
ImageComparer._({
required SkiaGoldClient client,
}) : _client = client;
// Avoid talking to Skia gold for the force-multithreading variants.
static bool get _useSkiaGold =>
!Platform.executableArguments.contains('--force-multithreading');
/// Creates an image comparer and authorizes.
static Future<ImageComparer> create({
bool verbose = false,
}) async {
const String workDirectoryPath =
String.fromEnvironment(_kSkiaGoldWorkDirectoryKey);
if (workDirectoryPath.isEmpty) {
throw UnsupportedError(
'Using ImageComparer requries defining kSkiaGoldWorkDirectoryKey.');
}
final Directory workDirectory = Directory(
impellerEnabled ? '${workDirectoryPath}_iplr' : workDirectoryPath,
)..createSync();
final Map<String, String> dimensions = <String, String>{
'impeller_enabled': impellerEnabled.toString(),
};
final SkiaGoldClient client = SkiaGoldClient.isAvailable() && _useSkiaGold
? SkiaGoldClient(workDirectory,
dimensions: dimensions, verbose: verbose)
: _FakeSkiaGoldClient(workDirectory, dimensions, verbose: verbose);
await client.auth();
return ImageComparer._(client: client);
}
final SkiaGoldClient _client;
/// Adds an [Image] to Skia Gold for comparison.
///
/// The [fileName] must be unique.
Future<void> addGoldenImage(Image image, String fileName) async {
final ByteData data =
(await image.toByteData(format: ImageByteFormat.png))!;
final File file = File(path.join(_client.workDirectory.path, fileName))
..writeAsBytesSync(data.buffer.asUint8List());
await _client.addImg(
fileName,
file,
screenshotSize: image.width * image.height,
).catchError((dynamic error) {
print('Skia gold comparison failed: $error');
throw Exception('Failed comparison: $fileName');
});
}
Future<bool> fuzzyCompareImages(Image golden, Image testImage) async {
if (golden.width != testImage.width || golden.height != testImage.height) {
return false;
}
int getPixel(ByteData data, int x, int y) =>
data.getUint32((x + y * golden.width) * 4);
final ByteData goldenData = (await golden.toByteData())!;
final ByteData testImageData = (await testImage.toByteData())!;
for (int y = 0; y < golden.height; y++) {
for (int x = 0; x < golden.width; x++) {
if (getPixel(goldenData, x, y) != getPixel(testImageData, x, y)) {
return false;
}
}
}
return true;
}
}
// TODO(dnfield): add local comparison against baseline,
// https://github.com/flutter/flutter/issues/136831
class _FakeSkiaGoldClient implements SkiaGoldClient {
_FakeSkiaGoldClient(
this.workDirectory,
this.dimensions, {
this.verbose = false,
});
@override
final Directory workDirectory;
@override
final Map<String, String> dimensions;
@override
final bool verbose;
@override
Future<void> auth() async {}
@override
Future<void> addImg(
String testName,
File goldenFile, {
double differentPixelsRate = 0.01,
int pixelColorDelta = 0,
required int screenshotSize,
}) async {}
@override
dynamic noSuchMethod(Invocation invocation) {
throw UnimplementedError(invocation.memberName.toString().split('"')[1]);
}
}
| engine/testing/dart/goldens.dart/0 | {
"file_path": "engine/testing/dart/goldens.dart",
"repo_id": "engine",
"token_count": 1384
} | 394 |
// 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.
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Locale', () {
expect(const Locale('en').toLanguageTag(), 'en');
expect(const Locale('en'), const Locale('en'));
expect(const Locale('en').hashCode, const Locale('en').hashCode);
expect(const Locale('en', 'US').toLanguageTag(), 'en-US');
expect(const Locale('en', 'US').toString(), 'en_US');
expect(const Locale('iw').toLanguageTag(), 'he');
expect(const Locale('iw', 'DD').toLanguageTag(), 'he-DE');
expect(const Locale('iw', 'DD').toString(), 'he_DE');
expect(const Locale('iw', 'DD'), const Locale('he', 'DE'));
});
test('Locale.fromSubtags', () {
expect(const Locale.fromSubtags().languageCode, 'und');
expect(const Locale.fromSubtags().scriptCode, null);
expect(const Locale.fromSubtags().countryCode, null);
expect(const Locale.fromSubtags(languageCode: 'en').toLanguageTag(), 'en');
expect(const Locale.fromSubtags(languageCode: 'en').languageCode, 'en');
expect(const Locale.fromSubtags(scriptCode: 'Latn').toLanguageTag(), 'und-Latn');
expect(const Locale.fromSubtags(scriptCode: 'Latn').toString(), 'und_Latn');
expect(const Locale.fromSubtags(scriptCode: 'Latn').scriptCode, 'Latn');
expect(const Locale.fromSubtags(countryCode: 'US').toLanguageTag(), 'und-US');
expect(const Locale.fromSubtags(countryCode: 'US').toString(), 'und_US');
expect(const Locale.fromSubtags(countryCode: 'US').countryCode, 'US');
expect(const Locale.fromSubtags(languageCode: 'es', countryCode: '419').toLanguageTag(), 'es-419');
expect(const Locale.fromSubtags(languageCode: 'es', countryCode: '419').toString(), 'es_419');
expect(const Locale.fromSubtags(languageCode: 'es', countryCode: '419').languageCode, 'es');
expect(const Locale.fromSubtags(languageCode: 'es', countryCode: '419').scriptCode, null);
expect(const Locale.fromSubtags(languageCode: 'es', countryCode: '419').countryCode, '419');
expect(const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN').toLanguageTag(), 'zh-Hans-CN');
expect(const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN').toString(), 'zh_Hans_CN');
});
test('Locale equality', () {
expect(const Locale.fromSubtags(languageCode: 'en'),
notEquals(const Locale.fromSubtags(languageCode: 'en', scriptCode: 'Latn')));
expect(const Locale.fromSubtags(languageCode: 'en').hashCode,
notEquals(const Locale.fromSubtags(languageCode: 'en', scriptCode: 'Latn').hashCode));
expect(const Locale('en', ''), const Locale('en'));
expect(const Locale('en'), const Locale('en', ''));
expect(const Locale('en'), const Locale('en'));
expect(const Locale('en', ''), const Locale('en', ''));
expect(const Locale('en', ''), notEquals(const Locale('en', 'GB')));
expect(const Locale('en'), notEquals(const Locale('en', 'GB')));
expect(const Locale('en', 'GB'), notEquals(const Locale('en', '')));
expect(const Locale('en', 'GB'), notEquals(const Locale('en')));
});
test("Locale toString does not include separator for ''", () {
expect(const Locale('en').toString(), 'en');
expect(const Locale('en', '').toString(), 'en');
expect(const Locale('en', 'US').toString(), 'en_US');
});
}
| engine/testing/dart/locale_test.dart/0 | {
"file_path": "engine/testing/dart/locale_test.dart",
"repo_id": "engine",
"token_count": 1247
} | 395 |
// 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.
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('PlatformView layers do not emit errors from tester', () async {
final SceneBuilder builder = SceneBuilder();
builder.addPlatformView(1);
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Scene scene = builder.build();
PlatformDispatcher.instance.implicitView!.render(scene);
scene.dispose();
};
PlatformDispatcher.instance.scheduleFrame();
// Test harness asserts that this does not emit an error from the shell logs.
});
}
| engine/testing/dart/platform_view_test.dart/0 | {
"file_path": "engine/testing/dart/platform_view_test.dart",
"repo_id": "engine",
"token_count": 226
} | 396 |
// 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 "flutter/testing/debugger_detection.h"
#include "flutter/fml/build_config.h"
#include "flutter/fml/logging.h"
#if FML_OS_MACOSX
#include <assert.h>
#include <stdbool.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#endif // FML_OS_MACOSX
#if FML_OS_WIN
#include <windows.h>
#endif // FML_OS_WIN
namespace flutter {
namespace testing {
DebuggerStatus GetDebuggerStatus() {
#if FML_OS_MACOSX
// From Technical Q&A QA1361 Detecting the Debugger
// https://developer.apple.com/library/archive/qa/qa1361/_index.html
int management_info_base[4];
struct kinfo_proc info;
size_t size;
// Initialize the flags so that, if sysctl fails for some bizarre
// reason, we get a predictable result.
info.kp_proc.p_flag = 0;
// Initialize management_info_base, which tells sysctl the info we want, in
// this case we're looking for information about a specific process ID.
management_info_base[0] = CTL_KERN;
management_info_base[1] = KERN_PROC;
management_info_base[2] = KERN_PROC_PID;
management_info_base[3] = getpid();
// Call sysctl.
size = sizeof(info);
auto status =
::sysctl(management_info_base,
sizeof(management_info_base) / sizeof(*management_info_base),
&info, &size, NULL, 0);
FML_CHECK(status == 0);
// We're being debugged if the P_TRACED flag is set.
return ((info.kp_proc.p_flag & P_TRACED) != 0) ? DebuggerStatus::kAttached
: DebuggerStatus::kDontKnow;
#elif FML_OS_WIN
return ::IsDebuggerPresent() ? DebuggerStatus::kAttached
: DebuggerStatus::kDontKnow;
#else
return DebuggerStatus::kDontKnow;
#endif
} // namespace testing
} // namespace testing
} // namespace flutter
| engine/testing/debugger_detection.cc/0 | {
"file_path": "engine/testing/debugger_detection.cc",
"repo_id": "engine",
"token_count": 758
} | 397 |
// 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_TESTING_LOGGER_LISTENER_H_
#define FLUTTER_TESTING_LOGGER_LISTENER_H_
#include "flutter/fml/logging.h"
#include "flutter/testing/testing.h"
namespace flutter::testing {
class LoggerListener : public ::testing::EmptyTestEventListener {
public:
LoggerListener();
~LoggerListener();
LoggerListener(const LoggerListener&) = delete;
LoggerListener& operator=(const LoggerListener&) = delete;
// |testing::EmptyTestEventListener|
void OnTestStart(const ::testing::TestInfo& test_info) override;
// |testing::EmptyTestEventListener|
void OnTestEnd(const ::testing::TestInfo& test_info) override;
// |testing::EmptyTestEventListener|
void OnTestDisabled(const ::testing::TestInfo& test_info) override;
};
} // namespace flutter::testing
#endif // FLUTTER_TESTING_LOGGER_LISTENER_H_
| engine/testing/logger_listener.h/0 | {
"file_path": "engine/testing/logger_listener.h",
"repo_id": "engine",
"token_count": 314
} | 398 |
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
lintOptions {
abortOnError true
checkAllWarnings true
showAll true
warningsAsErrors true
checkTestSources true
textOutput 'stdout'
htmlReport false
xmlReport true
xmlOutput file("${rootProject.buildDir}/reports/lint-results.xml")
// UnpackedNativeCode can break stack unwinding - see b/193408481
// NewerVersionAvailable and GradleDependency need to be taken care of
// by a roller rather than as part of CI.
// The others are irrelevant for a test application.
disable 'UnpackedNativeCode','MissingApplicationIcon','GoogleAppIndexingApiWarning','GoogleAppIndexingWarning','GradleDependency','NewerVersionAvailable','Registered'
}
buildToolsVersion = '34.0.0'
compileSdkVersion 34
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
defaultConfig {
applicationId 'dev.flutter.scenarios'
minSdkVersion 21
targetSdkVersion 34
versionCode 1
versionName '1.0'
testInstrumentationRunner 'dev.flutter.TestRunner'
testInstrumentationRunnerArgument 'listener', 'leakcanary.FailTestOnLeakRunListener'
testInstrumentationRunnerArguments clearPackageData: 'true'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets.main {
assets.srcDirs += "${project.buildDir}/assets"
if (project.hasProperty('libapp')) {
jni.srcDirs = []
jniLibs.srcDirs = [project.property('libapp')]
}
}
}
dependencies {
// Please *don't* add embedding dependencies to this file.
// The embedding dependencies are configured in tools/androidx/files.json.
// Only add test dependencies.
if (project.hasProperty('flutter_jar')) {
implementation files(project.property('flutter_jar'))
}
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
androidTestImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'com.google.guava:guava:30.1-android'
def leakcanary_version = '2.7'
androidTestImplementation "com.squareup.leakcanary:leakcanary-android:$leakcanary_version"
androidTestImplementation "com.squareup.leakcanary:leakcanary-android-instrumentation:$leakcanary_version"
}
// Configure the embedding dependencies.
apply from: new File(rootDir, '../../../tools/androidx/configure.gradle').absolutePath;
configureDependencies(new File(rootDir, '../../..')) { dependency ->
dependencies {
implementation "$dependency"
}
}
tasks.register('generateLockfiles') {
rootProject.subprojects.each { subproject ->
def gradle = "${rootProject.projectDir}/../../../../third_party/gradle/bin/gradle"
rootProject.exec {
workingDir rootProject.projectDir
executable gradle
args ":${subproject.name}:dependencies", "--write-locks"
}
}
}
// Override the kotlin language/api version to avoid warnings from
// usages in leakcanaary.
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
kotlinOptions {
jvmTarget = '1.8'
apiVersion = '1.4'
languageVersion = '1.4'
}
}
| engine/testing/scenario_app/android/app/build.gradle/0 | {
"file_path": "engine/testing/scenario_app/android/app/build.gradle",
"repo_id": "engine",
"token_count": 1488
} | 399 |
// 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.
package dev.flutter.scenariosui;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.test.InstrumentationRegistry;
import dev.flutter.scenarios.TestableFlutterActivity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* Allows to capture screenshots, and transfers the screenshots to the host where they can be
* further proccessed. On a LUCI environment, the screenshots are sent to Skia Gold.
*/
public class ScreenshotUtil {
private static final String HOST = "localhost";
private static final int PORT = 3000;
private static Connection conn;
private static Executor executor;
private static class Connection {
final Socket clientSocket;
final OutputStream out;
Connection(Socket socket) throws IOException {
clientSocket = socket;
out = socket.getOutputStream();
}
synchronized void writeFile(String name, byte[] fileContent, int pixelCount)
throws IOException {
final ByteBuffer buffer = ByteBuffer.allocate(name.length() + fileContent.length + 12);
// See ScreenshotBlobTransformer#bind in screenshot_transformer.dart for consumer side.
buffer.putInt(name.length());
buffer.putInt(fileContent.length);
buffer.putInt(pixelCount);
buffer.put(name.getBytes());
buffer.put(fileContent);
final byte[] bytes = buffer.array();
out.write(bytes, 0, bytes.length);
out.flush();
}
synchronized void close() throws IOException {
clientSocket.close();
}
}
/** Starts the connection with the host. */
public static synchronized void onCreate() {
if (executor == null) {
executor = Executors.newSingleThreadExecutor();
}
if (conn == null) {
executor.execute(
() -> {
try {
final Socket socket = new Socket(HOST, PORT);
conn = new Connection(socket);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
/** Closes the connection with the host. */
public static synchronized void finish() {
if (executor != null && conn != null) {
executor.execute(
() -> {
try {
conn.close();
conn = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
/**
* Sends the file to the host.
*
* @param filename The file name.
* @param fileContent The file content.
*/
public static synchronized void writeFile(
@NonNull String filename, @NonNull byte[] fileContent, int pixelCount) {
if (executor != null && conn != null) {
executor.execute(
() -> {
try {
conn.writeFile(filename, fileContent, pixelCount);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
}
/**
* Captures a screenshot of the activity, and sends the screenshot bytes to the host where it is
* further processed.
*
* <p>The activity must be already launched.
*
* @param activity The target activity.
* @param fileName The name of the file.
*/
public static void capture(@NonNull TestableFlutterActivity activity, @NonNull String captureName)
throws Exception {
activity.waitUntilFlutterRendered();
final Bitmap bitmap =
InstrumentationRegistry.getInstrumentation().getUiAutomation().takeScreenshot();
if (bitmap == null) {
throw new RuntimeException("failed to capture screenshot");
}
int pixelCount = bitmap.getWidth() * bitmap.getHeight();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
ScreenshotUtil.writeFile(captureName, out.toByteArray(), pixelCount);
}
}
| engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ScreenshotUtil.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ScreenshotUtil.java",
"repo_id": "engine",
"token_count": 1518
} | 400 |
// 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.
#import "SceneDelegate.h"
@interface SceneDelegate ()
@end
@implementation SceneDelegate
- (void)scene:(UIScene*)scene
willConnectToSession:(UISceneSession*)session
options:(UISceneConnectionOptions*)connectionOptions {
// Use this method to optionally configure and attach the UIWindow `window` to the provided
// UIWindowScene `scene`. If using a storyboard, the `window` property will automatically be
// initialized and attached to the scene. This delegate does not imply the connecting scene or
// session are new (see `application:configurationForConnectingSceneSession` instead).
}
- (void)sceneDidDisconnect:(UIScene*)scene {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene
// connects. The scene may re-connect later, as its session was not necessarily discarded (see
// `application:didDiscardSceneSessions` instead).
}
- (void)sceneDidBecomeActive:(UIScene*)scene {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was
// inactive.
}
- (void)sceneWillResignActive:(UIScene*)scene {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
- (void)sceneWillEnterForeground:(UIScene*)scene {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
- (void)sceneDidEnterBackground:(UIScene*)scene {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state
// information to restore the scene back to its current state.
}
@end
| engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/SceneDelegate.m/0 | {
"file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/SceneDelegate.m",
"repo_id": "engine",
"token_count": 579
} | 401 |
// 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.
#import "GoldenPlatformViewTests.h"
#include <sys/sysctl.h>
#import "GoldenTestManager.h"
static const NSInteger kSecondsToWaitForPlatformView = 30;
@interface GoldenPlatformViewTests ()
@property(nonatomic, copy) NSString* goldenName;
@property(nonatomic, strong) GoldenTestManager* manager;
@end
@implementation GoldenPlatformViewTests
- (instancetype)initWithManager:(GoldenTestManager*)manager invocation:(NSInvocation*)invocation {
self = [super initWithInvocation:invocation];
_manager = manager;
_rmseThreadhold = kDefaultRmseThreshold;
return self;
}
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
self.application = [[XCUIApplication alloc] init];
self.application.launchArguments = @[ self.manager.launchArg, @"--enable-software-rendering" ];
[self.application launch];
}
// Note: don't prefix with "test" or GoldenPlatformViewTests will run instead of the subclasses.
- (void)checkPlatformViewGolden {
XCUIElement* element = self.application.textViews.firstMatch;
BOOL exists = [element waitForExistenceWithTimeout:kSecondsToWaitForPlatformView];
if (!exists) {
XCTFail(@"It took longer than %@ second to find the platform view."
@"There might be issues with the platform view's construction,"
@"or with how the scenario is built.",
@(kSecondsToWaitForPlatformView));
}
[self.manager checkGoldenForTest:self rmesThreshold:self.rmseThreadhold];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenPlatformViewTests.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenPlatformViewTests.m",
"repo_id": "engine",
"token_count": 515
} | 402 |
// 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.
import 'dart:ui';
import 'scenario.dart';
/// A scenario with red on top and blue on the bottom.
class GetBitmapScenario extends Scenario {
/// Creates the GetBitmap scenario.
GetBitmapScenario(super.view);
@override
void onBeginFrame(Duration duration) {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawRect(Rect.fromLTWH(0, 0, view.physicalSize.width, 300),
Paint()..color = const Color(0xFFFF0000));
canvas.drawRect(
Rect.fromLTWH(0, view.physicalSize.height - 300,
view.physicalSize.width, 300),
Paint()..color = const Color(0xFF0000FF));
final Picture picture = recorder.endRecording();
final SceneBuilder builder = SceneBuilder();
builder.addPicture(Offset.zero, picture);
final Scene scene = builder.build();
view.render(scene);
picture.dispose();
scene.dispose();
}
}
| engine/testing/scenario_app/lib/src/get_bitmap_scenario.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/get_bitmap_scenario.dart",
"repo_id": "engine",
"token_count": 366
} | 403 |
// 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.
import 'dart:convert';
import 'dart:io' as io;
import 'package:crypto/crypto.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:process/process.dart';
import 'src/errors.dart';
export 'src/errors.dart' show SkiaGoldProcessError;
const String _kGoldctlKey = 'GOLDCTL';
const String _kPresubmitEnvName = 'GOLD_TRYJOB';
const String _kLuciEnvName = 'LUCI_CONTEXT';
const String _skiaGoldHost = 'https://flutter-engine-gold.skia.org';
const String _instance = 'flutter-engine';
/// A client for uploading image tests and making baseline requests to the
/// Flutter Gold Dashboard.
interface class SkiaGoldClient {
/// Creates a [SkiaGoldClient] with the given [workDirectory].
///
/// [dimensions] allows to add attributes about the environment
/// used to generate the screenshots.
SkiaGoldClient(
this.workDirectory, {
this.dimensions,
this.verbose = false,
io.HttpClient? httpClient,
ProcessManager? processManager,
StringSink? stderr,
Map<String, String>? environment,
}) : httpClient = httpClient ?? io.HttpClient(),
process = processManager ?? const LocalProcessManager(),
_stderr = stderr ?? io.stderr,
_environment = environment ?? io.Platform.environment;
/// Whether the client is available and can be used in this environment.
static bool isAvailable({
Map<String, String>? environment,
}) {
final String? result = (environment ?? io.Platform.environment)[_kGoldctlKey];
return result != null && result.isNotEmpty;
}
/// Returns true if the current environment is a LUCI builder.
static bool isLuciEnv({
Map<String, String>? environment,
}) {
return (environment ?? io.Platform.environment).containsKey(_kLuciEnvName);
}
/// Whether the current environment is a presubmit job.
bool get _isPresubmit {
return
isLuciEnv(environment: _environment) &&
isAvailable(environment: _environment) &&
_environment.containsKey(_kPresubmitEnvName);
}
/// Whether the current environment is a postsubmit job.
bool get _isPostsubmit {
return
isLuciEnv(environment: _environment) &&
isAvailable(environment: _environment) &&
!_environment.containsKey(_kPresubmitEnvName);
}
/// Whether to print verbose output from goldctl.
///
/// This flag is intended for use in debugging CI issues, and should not
/// ordinarily be set to true.
final bool verbose;
/// Environment variables for the currently running process.
final Map<String, String> _environment;
/// Where output is written for diagnostics.
final StringSink _stderr;
/// Allows to add attributes about the environment used to generate the screenshots.
final Map<String, String>? dimensions;
/// A controller for launching sub-processes.
final ProcessManager process;
/// A client for making Http requests to the Flutter Gold dashboard.
final io.HttpClient httpClient;
/// The local [Directory] for the current test context. In this directory, the
/// client will create image and JSON files for the `goldctl` tool to use.
final io.Directory workDirectory;
String get _tempPath => path.join(workDirectory.path, 'temp');
String get _keysPath => path.join(workDirectory.path, 'keys.json');
String get _failuresPath => path.join(workDirectory.path, 'failures.json');
Future<void>? _initResult;
Future<void> _initOnce(Future<void> Function() callback) {
// If a call has already been made, return the result of that call.
_initResult ??= callback();
return _initResult!;
}
/// Indicates whether the client has already been authorized to communicate
/// with the Skia Gold backend.
bool get _isAuthorized {
final io.File authFile = io.File(path.join(_tempPath, 'auth_opt.json'));
if (authFile.existsSync()) {
final String contents = authFile.readAsStringSync();
final Map<String, dynamic> decoded = json.decode(contents) as Map<String, dynamic>;
return !(decoded['GSUtil'] as bool);
}
return false;
}
/// The path to the local [Directory] where the `goldctl` tool is hosted.
String get _goldctl {
assert(
isAvailable(environment: _environment),
'Trying to use `goldctl` in an environment where it is not available',
);
final String? result = _environment[_kGoldctlKey];
if (result == null || result.isEmpty) {
throw StateError('The environment variable $_kGoldctlKey is not set.');
}
return result;
}
/// Prepares the local work space for golden file testing and calls the
/// `goldctl auth` command.
///
/// This ensures that the `goldctl` tool is authorized and ready for testing.
Future<void> auth() async {
if (_isAuthorized) {
return;
}
final List<String> authCommand = <String>[
_goldctl,
'auth',
if (verbose) '--verbose',
'--work-dir', _tempPath,
'--luci',
];
final io.ProcessResult result = await _runCommand(authCommand);
if (result.exitCode != 0) {
final StringBuffer buf = StringBuffer()
..writeln('Skia Gold authorization failed.')
..writeln('Luci environments authenticate using the file provided '
'by LUCI_CONTEXT. There may be an error with this file or Gold '
'authentication.');
throw SkiaGoldProcessError(
command: authCommand,
stdout: result.stdout.toString(),
stderr: result.stderr.toString(),
message: buf.toString(),
);
} else if (verbose) {
_stderr.writeln('stdout:\n${result.stdout}');
_stderr.writeln('stderr:\n${result.stderr}');
}
}
Future<io.ProcessResult> _runCommand(List<String> command) {
return process.run(command);
}
/// Executes the `imgtest init` command in the `goldctl` tool.
///
/// The `imgtest` command collects and uploads test results to the Skia Gold
/// backend, the `init` argument initializes the current test.
Future<void> _imgtestInit() async {
final io.File keys = io.File(_keysPath);
final io.File failures = io.File(_failuresPath);
await keys.writeAsString(_getKeysJSON());
await failures.create();
final String commitHash = await _getCurrentCommit();
final List<String> imgtestInitCommand = <String>[
_goldctl,
'imgtest', 'init',
if (verbose) '--verbose',
'--instance', _instance,
'--work-dir', _tempPath,
'--commit', commitHash,
'--keys-file', keys.path,
'--failure-file', failures.path,
'--passfail',
];
final io.ProcessResult result = await _runCommand(imgtestInitCommand);
if (result.exitCode != 0) {
final StringBuffer buf = StringBuffer()
..writeln('Skia Gold imgtest init failed.')
..writeln('An error occurred when initializing golden file test with ')
..writeln('goldctl.');
throw SkiaGoldProcessError(
command: imgtestInitCommand,
stdout: result.stdout.toString(),
stderr: result.stderr.toString(),
message: buf.toString(),
);
} else if (verbose) {
_stderr.writeln('stdout:\n${result.stdout}');
_stderr.writeln('stderr:\n${result.stderr}');
}
}
/// Executes the `imgtest add` command in the `goldctl` tool.
///
/// The `imgtest` command collects and uploads test results to the Skia Gold
/// backend, the `add` argument uploads the current image test.
///
/// Throws an exception for try jobs that failed to pass the pixel comparison.
///
/// The [testName] and [goldenFile] parameters reference the current
/// comparison being evaluated.
///
/// [pixelColorDelta] defines maximum acceptable difference in RGB channels of
/// each pixel, such that:
///
/// ```
/// bool isSame(Color image, Color golden, int pixelDeltaThreshold) {
/// return abs(image.r - golden.r)
/// + abs(image.g - golden.g)
/// + abs(image.b - golden.b) <= pixelDeltaThreshold;
/// }
/// ```
///
/// [differentPixelsRate] is the fraction of pixels that can differ, as
/// determined by the [pixelColorDelta] parameter. It's in the range [0.0,
/// 1.0] and defaults to 0.01. A value of 0.01 means that 1% of the pixels are
/// allowed to be different.
Future<void> addImg(
String testName,
io.File goldenFile, {
double differentPixelsRate = 0.01,
int pixelColorDelta = 0,
required int screenshotSize,
}) async {
assert(_isPresubmit || _isPostsubmit);
if (_isPresubmit) {
await _tryjobAdd(testName, goldenFile, screenshotSize, pixelColorDelta, differentPixelsRate);
}
if (_isPostsubmit) {
await _imgtestAdd(testName, goldenFile, screenshotSize, pixelColorDelta, differentPixelsRate);
}
}
/// Executes the `imgtest add` command in the `goldctl` tool.
///
/// The `imgtest` command collects and uploads test results to the Skia Gold
/// backend, the `add` argument uploads the current image test. A response is
/// returned from the invocation of this command that indicates a pass or fail
/// result.
///
/// The [testName] and [goldenFile] parameters reference the current
/// comparison being evaluated.
Future<void> _imgtestAdd(
String testName,
io.File goldenFile,
int screenshotSize,
int pixelDeltaThreshold,
double maxDifferentPixelsRate,
) async {
await _initOnce(_imgtestInit);
final List<String> imgtestCommand = <String>[
_goldctl,
'imgtest',
'add',
if (verbose)
'--verbose',
'--work-dir',
_tempPath,
'--test-name',
_cleanTestName(testName),
'--png-file',
goldenFile.path,
// Otherwise post submit will not fail.
'--passfail',
..._getMatchingArguments(testName, screenshotSize, pixelDeltaThreshold, maxDifferentPixelsRate),
];
final io.ProcessResult result = await _runCommand(imgtestCommand);
if (result.exitCode != 0) {
final StringBuffer buf = StringBuffer()
..writeln('Skia Gold received an unapproved image in post-submit ')
..writeln('testing. Golden file images in flutter/engine are triaged ')
..writeln('in pre-submit during code review for the given PR.')
..writeln()
..writeln('Visit https://flutter-engine-gold.skia.org/ to view and approve ')
..writeln('the image(s), or revert the associated change. For more ')
..writeln('information, visit the wiki: ')
..writeln('https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter');
throw SkiaGoldProcessError(
command: imgtestCommand,
stdout: result.stdout.toString(),
stderr: result.stderr.toString(),
message: buf.toString(),
);
} else if (verbose) {
_stderr.writeln('stdout:\n${result.stdout}');
_stderr.writeln('stderr:\n${result.stderr}');
}
}
/// Executes the `imgtest init` command in the `goldctl` tool for tryjobs.
///
/// The `imgtest` command collects and uploads test results to the Skia Gold
/// backend, the `init` argument initializes the current tryjob.
Future<void> _tryjobInit() async {
final io.File keys = io.File(_keysPath);
final io.File failures = io.File(_failuresPath);
await keys.writeAsString(_getKeysJSON());
await failures.create();
final String commitHash = await _getCurrentCommit();
final List<String> tryjobInitCommand = <String>[
_goldctl,
'imgtest', 'init',
if (verbose) '--verbose',
'--instance', _instance,
'--work-dir', _tempPath,
'--commit', commitHash,
'--keys-file', keys.path,
'--failure-file', failures.path,
'--passfail',
'--crs', 'github',
'--patchset_id', commitHash,
..._getCIArguments(),
];
final io.ProcessResult result = await _runCommand(tryjobInitCommand);
if (result.exitCode != 0) {
final StringBuffer buf = StringBuffer()
..writeln('Skia Gold tryjobInit failure.')
..writeln('An error occurred when initializing golden file tryjob with ')
..writeln('goldctl.');
throw SkiaGoldProcessError(
command: tryjobInitCommand,
stdout: result.stdout.toString(),
stderr: result.stderr.toString(),
message: buf.toString(),
);
} else if (verbose) {
_stderr.writeln('stdout:\n${result.stdout}');
_stderr.writeln('stderr:\n${result.stderr}');
}
}
/// Executes the `imgtest add` command in the `goldctl` tool for tryjobs.
///
/// The `imgtest` command collects and uploads test results to the Skia Gold
/// backend, the `add` argument uploads the current image test. A response is
/// returned from the invocation of this command that indicates a pass or fail
/// result for the tryjob.
///
/// The [testName] and [goldenFile] parameters reference the current
/// comparison being evaluated.
Future<void> _tryjobAdd(
String testName,
io.File goldenFile,
int screenshotSize,
int pixelDeltaThreshold,
double differentPixelsRate,
) async {
await _initOnce(_tryjobInit);
final List<String> tryjobCommand = <String>[
_goldctl,
'imgtest',
'add',
if (verbose) '--verbose',
'--work-dir',
_tempPath,
'--test-name',
_cleanTestName(testName),
'--png-file',
goldenFile.path,
..._getMatchingArguments(testName, screenshotSize, pixelDeltaThreshold, differentPixelsRate),
];
final io.ProcessResult result = await _runCommand(tryjobCommand);
final String resultStdout = result.stdout.toString();
if (result.exitCode == 0) {
// In "verbose" (debugging) mode, print the output of the tryjob anyway.
if (verbose) {
_stderr.writeln('stdout:\n${result.stdout}');
_stderr.writeln('stderr:\n${result.stderr}');
}
} else {
// Neither of these conditions are considered failures during tryjobs.
final bool isUntriaged = resultStdout.contains('Untriaged');
final bool isNegative = resultStdout.contains('negative image');
if (!isUntriaged && !isNegative) {
final StringBuffer buf = StringBuffer()
..writeln('Unexpected Gold tryjobAdd failure.')
..writeln('Tryjob execution for golden file test $testName failed for')
..writeln('a reason unrelated to pixel comparison.');
throw SkiaGoldProcessError(
command: tryjobCommand,
stdout: resultStdout,
stderr: result.stderr.toString(),
message: buf.toString(),
);
}
// ... but we want to know about them anyway.
// See https://github.com/flutter/flutter/issues/145219.
// TODO(matanlurey): Update the documentation to reflect the new behavior.
if (isUntriaged) {
_stderr
..writeln('NOTE: Untriaged image detected in tryjob.')
..writeln('Triage should be required by the "Flutter Gold" check')
..writeln('stdout:\n$resultStdout');
}
}
}
List<String> _getMatchingArguments(
String testName,
int screenshotSize,
int pixelDeltaThreshold,
double differentPixelsRate,
) {
// The algorithm to be used when matching images. The available options are:
// - "fuzzy": Allows for customizing the thresholds of pixel differences.
// - "sobel": Same as "fuzzy" but performs edge detection before performing
// a fuzzy match.
const String algorithm = 'fuzzy';
// The number of pixels in this image that are allowed to differ from the
// baseline. It's okay for this to be a slightly high number like 10% of the
// image size because those wrong pixels are constrained by
// `pixelDeltaThreshold` below.
final int maxDifferentPixels = (screenshotSize * differentPixelsRate).toInt();
return <String>[
'--add-test-optional-key', 'image_matching_algorithm:$algorithm',
'--add-test-optional-key', 'fuzzy_max_different_pixels:$maxDifferentPixels',
'--add-test-optional-key', 'fuzzy_pixel_delta_threshold:$pixelDeltaThreshold',
];
}
/// Returns the latest positive digest for the given test known to Skia Gold
/// at head.
Future<String?> getExpectationForTest(String testName) async {
late String? expectation;
final String traceID = getTraceID(testName);
final Uri requestForExpectations = Uri.parse(
'$_skiaGoldHost/json/v2/latestpositivedigest/$traceID'
);
late String rawResponse;
try {
final io.HttpClientRequest request = await httpClient.getUrl(requestForExpectations);
final io.HttpClientResponse response = await request.close();
rawResponse = await utf8.decodeStream(response);
final dynamic jsonResponse = json.decode(rawResponse);
if (jsonResponse is! Map<String, dynamic>) {
throw const FormatException('Skia gold expectations do not match expected format.');
}
expectation = jsonResponse['digest'] as String?;
} on FormatException catch (error) {
_stderr.writeln(
'Formatting error detected requesting expectations from Flutter Gold.\n'
'error: $error\n'
'url: $requestForExpectations\n'
'response: $rawResponse'
);
rethrow;
}
return expectation;
}
/// Returns the current commit hash of the engine repository.
Future<String> _getCurrentCommit() async {
final String engineCheckout = Engine.findWithin().flutterDir.path;
final io.ProcessResult revParse = await process.run(
<String>['git', 'rev-parse', 'HEAD'],
workingDirectory: engineCheckout,
);
if (revParse.exitCode != 0) {
throw StateError('Current commit of the engine can not be found from path $engineCheckout.');
}
return (revParse.stdout as String).trim();
}
/// Returns a Map of key value pairs used to uniquely identify the
/// configuration that generated the given golden file.
///
/// Currently, the only key value pairs being tracked are the platform and
/// browser the image was rendered on.
Map<String, dynamic> _getKeys() {
final Map<String, dynamic> initialKeys = <String, dynamic>{
'CI': 'luci',
'Platform': io.Platform.operatingSystem,
};
if (dimensions != null) {
initialKeys.addAll(dimensions!);
}
return initialKeys;
}
/// Same as [_getKeys] but encodes it in a JSON string.
String _getKeysJSON() {
return json.encode(_getKeys());
}
/// Removes the file extension from the [fileName] to represent the test name
/// properly.
static String _cleanTestName(String fileName) {
return path.basenameWithoutExtension(fileName);
}
/// Returns a list of arguments for initializing a tryjob based on the testing
/// environment.
List<String> _getCIArguments() {
final String jobId = _environment['LOGDOG_STREAM_PREFIX']!.split('/').last;
final List<String> refs = _environment['GOLD_TRYJOB']!.split('/');
final String pullRequest = refs[refs.length - 2];
return <String>[
'--changelist', pullRequest,
'--cis', 'buildbucket',
'--jobid', jobId,
];
}
/// Returns a trace id based on the current testing environment to lookup
/// the latest positive digest on Skia Gold with a hex-encoded md5 hash of
/// the image keys.
@visibleForTesting
String getTraceID(String testName) {
final Map<String, dynamic> keys = <String, dynamic>{
..._getKeys(),
'name': testName,
'source_type': _instance,
};
final String jsonTrace = json.encode(keys);
final String md5Sum = md5.convert(utf8.encode(jsonTrace)).toString();
return md5Sum;
}
}
| engine/testing/skia_gold_client/lib/skia_gold_client.dart/0 | {
"file_path": "engine/testing/skia_gold_client/lib/skia_gold_client.dart",
"repo_id": "engine",
"token_count": 7030
} | 404 |
// 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_TESTING_STREAM_CAPTURE_H_
#define FLUTTER_TESTING_STREAM_CAPTURE_H_
#include <ostream>
#include <sstream>
#include <string>
namespace flutter {
namespace testing {
// Temporarily replaces the specified stream's output buffer to capture output.
//
// Example:
// StreamCapture captured_stdout(&std::cout);
// ... code that writest to std::cout ...
// std::string output = captured_stdout.GetCapturedOutput();
class StreamCapture {
public:
// Begins capturing output to the specified stream.
explicit StreamCapture(std::ostream* ostream);
// Stops capturing output to the specified stream, and restores the original
// output buffer, if |Stop| has not already been called.
~StreamCapture();
// Stops capturing output to the specified stream, and restores the original
// output buffer.
void Stop();
// Returns any output written to the captured stream between construction and
// the first call to |Stop|, if any, or now.
std::string GetOutput() const;
private:
std::ostream* ostream_;
std::stringstream buffer_;
std::streambuf* old_buffer_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_STREAM_CAPTURE_H_
| engine/testing/stream_capture.h/0 | {
"file_path": "engine/testing/stream_capture.h",
"repo_id": "engine",
"token_count": 397
} | 405 |
// 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 "flutter/testing/test_timeout_listener.h"
#include <map>
#include <sstream>
namespace flutter {
namespace testing {
class PendingTests : public std::enable_shared_from_this<PendingTests> {
public:
static std::shared_ptr<PendingTests> Create(
fml::RefPtr<fml::TaskRunner> host_task_runner,
fml::TimeDelta timeout) {
return std::shared_ptr<PendingTests>(
new PendingTests(std::move(host_task_runner), timeout));
}
~PendingTests() = default;
void OnTestBegin(const std::string& test_name, fml::TimePoint test_time) {
FML_CHECK(tests_.find(test_name) == tests_.end())
<< "Attempting to start a test that is already pending.";
tests_[test_name] = test_time;
host_task_runner_->PostDelayedTask(
[weak = weak_from_this()] {
if (auto strong = weak.lock()) {
strong->CheckTimedOutTests();
}
},
timeout_);
}
void OnTestEnd(const std::string& test_name) { tests_.erase(test_name); }
void CheckTimedOutTests() const {
const auto now = fml::TimePoint::Now();
for (const auto& test : tests_) {
auto delay = now - test.second;
FML_CHECK(delay < timeout_)
<< "Test " << test.first << " did not complete in "
<< timeout_.ToSeconds()
<< " seconds and is assumed to be hung. Killing the test harness.";
}
}
private:
using TestData = std::map<std::string, fml::TimePoint>;
fml::RefPtr<fml::TaskRunner> host_task_runner_;
TestData tests_;
const fml::TimeDelta timeout_;
PendingTests(fml::RefPtr<fml::TaskRunner> host_task_runner,
fml::TimeDelta timeout)
: host_task_runner_(std::move(host_task_runner)), timeout_(timeout) {}
FML_DISALLOW_COPY_AND_ASSIGN(PendingTests);
};
template <class T>
auto WeakPtr(std::shared_ptr<T> pointer) {
return std::weak_ptr<T>{pointer};
}
TestTimeoutListener::TestTimeoutListener(fml::TimeDelta timeout)
: timeout_(timeout),
listener_thread_("test_timeout_listener"),
listener_thread_runner_(listener_thread_.GetTaskRunner()),
pending_tests_(PendingTests::Create(listener_thread_runner_, timeout_)) {
FML_LOG(INFO) << "Test timeout of " << timeout_.ToSeconds()
<< " seconds per test case will be enforced.";
}
TestTimeoutListener::~TestTimeoutListener() {
listener_thread_runner_->PostTask(
[tests = std::move(pending_tests_)]() mutable { tests.reset(); });
FML_CHECK(pending_tests_ == nullptr);
}
static std::string GetTestNameFromTestInfo(
const ::testing::TestInfo& test_info) {
std::stringstream stream;
stream << test_info.test_suite_name();
stream << ".";
stream << test_info.name();
if (auto type_param = test_info.type_param()) {
stream << "/" << type_param;
}
if (auto value_param = test_info.value_param()) {
stream << "/" << value_param;
}
return stream.str();
}
// |testing::EmptyTestEventListener|
void TestTimeoutListener::OnTestStart(const ::testing::TestInfo& test_info) {
listener_thread_runner_->PostTask([weak_tests = WeakPtr(pending_tests_),
name = GetTestNameFromTestInfo(test_info),
now = fml::TimePoint::Now()]() {
if (auto tests = weak_tests.lock()) {
tests->OnTestBegin(name, now);
}
});
}
// |testing::EmptyTestEventListener|
void TestTimeoutListener::OnTestEnd(const ::testing::TestInfo& test_info) {
listener_thread_runner_->PostTask(
[weak_tests = WeakPtr(pending_tests_),
name = GetTestNameFromTestInfo(test_info)]() {
if (auto tests = weak_tests.lock()) {
tests->OnTestEnd(name);
}
});
}
} // namespace testing
} // namespace flutter
| engine/testing/test_timeout_listener.cc/0 | {
"file_path": "engine/testing/test_timeout_listener.cc",
"repo_id": "engine",
"token_count": 1508
} | 406 |
# Disable all checks in this folder.
#
# We cannot ask third_party code to conform to our lints.
Checks: "-*"
| engine/third_party/.clang-tidy/0 | {
"file_path": "engine/third_party/.clang-tidy",
"repo_id": "engine",
"token_count": 34
} | 407 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_CLIPPING_BEHAVIOR_H_
#define UI_ACCESSIBILITY_AX_CLIPPING_BEHAVIOR_H_
namespace ui {
// The clipping behavior to perform on bounds. Clipping limits a node's bounding
// box to the visible sizes of it's ancestors - which may be hidden or scrolled
// out of view. For a longer discussion on clipping behavior see the link below.
// https://chromium.googlesource.com/chromium/src/+/lkgr/docs/accessibility/offscreen.md
// kUnclipped: Do not apply clipping to bound results
// kClipped: Apply clipping to bound results
enum class AXClippingBehavior { kUnclipped, kClipped };
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_CLIPPING_BEHAVIOR_H_
| engine/third_party/accessibility/ax/ax_clipping_behavior.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_clipping_behavior.h",
"repo_id": "engine",
"token_count": 268
} | 408 |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_node.h"
#include <algorithm>
#include <utility>
#include "ax_enums.h"
#include "ax_role_properties.h"
#include "ax_table_info.h"
#include "ax_tree.h"
#include "ax_tree_manager.h"
#include "ax_tree_manager_map.h"
#include "base/color_utils.h"
#include "base/string_utils.h"
namespace ui {
constexpr AXNode::AXID AXNode::kInvalidAXID;
AXNode::AXNode(AXNode::OwnerTree* tree,
AXNode* parent,
int32_t id,
size_t index_in_parent,
size_t unignored_index_in_parent)
: tree_(tree),
index_in_parent_(index_in_parent),
unignored_index_in_parent_(unignored_index_in_parent),
parent_(parent) {
data_.id = id;
}
AXNode::~AXNode() = default;
size_t AXNode::GetUnignoredChildCount() const {
// TODO(nektar): Should BASE_DCHECK if the node is not ignored.
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return unignored_child_count_;
}
AXNodeData&& AXNode::TakeData() {
return std::move(data_);
}
AXNode* AXNode::GetUnignoredChildAtIndex(size_t index) const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
size_t count = 0;
for (auto it = UnignoredChildrenBegin(); it != UnignoredChildrenEnd(); ++it) {
if (count == index)
return it.get();
++count;
}
return nullptr;
}
AXNode* AXNode::GetUnignoredParent() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
AXNode* result = parent();
while (result && result->IsIgnored())
result = result->parent();
return result;
}
size_t AXNode::GetUnignoredIndexInParent() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return unignored_index_in_parent_;
}
size_t AXNode::GetIndexInParent() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return index_in_parent_;
}
AXNode* AXNode::GetFirstUnignoredChild() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return ComputeFirstUnignoredChildRecursive();
}
AXNode* AXNode::GetLastUnignoredChild() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return ComputeLastUnignoredChildRecursive();
}
AXNode* AXNode::GetDeepestFirstUnignoredChild() const {
if (!GetUnignoredChildCount())
return nullptr;
AXNode* deepest_child = GetFirstUnignoredChild();
while (deepest_child->GetUnignoredChildCount()) {
deepest_child = deepest_child->GetFirstUnignoredChild();
}
return deepest_child;
}
AXNode* AXNode::GetDeepestLastUnignoredChild() const {
if (!GetUnignoredChildCount())
return nullptr;
AXNode* deepest_child = GetLastUnignoredChild();
while (deepest_child->GetUnignoredChildCount()) {
deepest_child = deepest_child->GetLastUnignoredChild();
}
return deepest_child;
}
// Search for the next sibling of this node, skipping over any ignored nodes
// encountered.
//
// In our search:
// If we find an ignored sibling, we consider its children as our siblings.
// If we run out of siblings, we consider an ignored parent's siblings as our
// own siblings.
//
// Note: this behaviour of 'skipping over' an ignored node makes this subtly
// different to finding the next (direct) sibling which is unignored.
//
// Consider a tree, where (i) marks a node as ignored:
//
// 1
// ├── 2
// ├── 3(i)
// │ └── 5
// └── 4
//
// The next sibling of node 2 is node 3, which is ignored.
// The next unignored sibling of node 2 could be either:
// 1) node 4 - next unignored sibling in the literal tree, or
// 2) node 5 - next unignored sibling in the logical document.
//
// There is no next sibling of node 5.
// The next unignored sibling of node 5 could be either:
// 1) null - no next sibling in the literal tree, or
// 2) node 4 - next unignored sibling in the logical document.
//
// In both cases, this method implements approach (2).
//
// TODO(chrishall): Can we remove this non-reflexive case by forbidding
// GetNextUnignoredSibling calls on an ignored started node?
// Note: this means that Next/Previous-UnignoredSibling are not reflexive if
// either of the nodes in question are ignored. From above we get an example:
// NextUnignoredSibling(3) is 4, but
// PreviousUnignoredSibling(4) is 5.
//
// The view of unignored siblings for node 3 includes both node 2 and node 4:
// 2 <-- [3(i)] --> 4
//
// Whereas nodes 2, 5, and 4 do not consider node 3 to be an unignored sibling:
// null <-- [2] --> 5
// 2 <-- [5] --> 4
// 5 <-- [4] --> null
AXNode* AXNode::GetNextUnignoredSibling() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
const AXNode* current = this;
// If there are children of the |current| node still to consider.
bool considerChildren = false;
while (current) {
// A |candidate| sibling to consider.
// If it is unignored then we have found our result.
// Otherwise promote it to |current| and consider its children.
AXNode* candidate;
if (considerChildren && (candidate = current->GetFirstChild())) {
if (!candidate->IsIgnored())
return candidate;
current = candidate;
} else if ((candidate = current->GetNextSibling())) {
if (!candidate->IsIgnored())
return candidate;
current = candidate;
// Look through the ignored candidate node to consider their children as
// though they were siblings.
considerChildren = true;
} else {
// Continue our search through a parent iff they are ignored.
//
// If |current| has an ignored parent, then we consider the parent's
// siblings as though they were siblings of |current|.
//
// Given a tree:
// 1
// ├── 2(?)
// │ └── [4]
// └── 3
//
// Node 4's view of siblings:
// literal tree: null <-- [4] --> null
//
// If node 2 is not ignored, then node 4's view doesn't change, and we
// have no more nodes to consider:
// unignored tree: null <-- [4] --> null
//
// If instead node 2 is ignored, then node 4's view of siblings grows to
// include node 3, and we have more nodes to consider:
// unignored tree: null <-- [4] --> 3
current = current->parent();
if (!current || !current->IsIgnored())
return nullptr;
// We have already considered all relevant descendants of |current|.
considerChildren = false;
}
}
return nullptr;
}
// Search for the previous sibling of this node, skipping over any ignored nodes
// encountered.
//
// In our search for a sibling:
// If we find an ignored sibling, we may consider its children as siblings.
// If we run out of siblings, we may consider an ignored parent's siblings as
// our own.
//
// See the documentation for |GetNextUnignoredSibling| for more details.
AXNode* AXNode::GetPreviousUnignoredSibling() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
const AXNode* current = this;
// If there are children of the |current| node still to consider.
bool considerChildren = false;
while (current) {
// A |candidate| sibling to consider.
// If it is unignored then we have found our result.
// Otherwise promote it to |current| and consider its children.
AXNode* candidate;
if (considerChildren && (candidate = current->GetLastChild())) {
if (!candidate->IsIgnored())
return candidate;
current = candidate;
} else if ((candidate = current->GetPreviousSibling())) {
if (!candidate->IsIgnored())
return candidate;
current = candidate;
// Look through the ignored candidate node to consider their children as
// though they were siblings.
considerChildren = true;
} else {
// Continue our search through a parent iff they are ignored.
//
// If |current| has an ignored parent, then we consider the parent's
// siblings as though they were siblings of |current|.
//
// Given a tree:
// 1
// ├── 2
// └── 3(?)
// └── [4]
//
// Node 4's view of siblings:
// literal tree: null <-- [4] --> null
//
// If node 3 is not ignored, then node 4's view doesn't change, and we
// have no more nodes to consider:
// unignored tree: null <-- [4] --> null
//
// If instead node 3 is ignored, then node 4's view of siblings grows to
// include node 2, and we have more nodes to consider:
// unignored tree: 2 <-- [4] --> null
current = current->parent();
if (!current || !current->IsIgnored())
return nullptr;
// We have already considered all relevant descendants of |current|.
considerChildren = false;
}
}
return nullptr;
}
AXNode* AXNode::GetNextUnignoredInTreeOrder() const {
if (GetUnignoredChildCount())
return GetFirstUnignoredChild();
const AXNode* node = this;
while (node) {
AXNode* sibling = node->GetNextUnignoredSibling();
if (sibling)
return sibling;
node = node->GetUnignoredParent();
}
return nullptr;
}
AXNode* AXNode::GetPreviousUnignoredInTreeOrder() const {
AXNode* sibling = GetPreviousUnignoredSibling();
if (!sibling)
return GetUnignoredParent();
if (sibling->GetUnignoredChildCount())
return sibling->GetDeepestLastUnignoredChild();
return sibling;
}
AXNode::UnignoredChildIterator AXNode::UnignoredChildrenBegin() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return UnignoredChildIterator(this, GetFirstUnignoredChild());
}
AXNode::UnignoredChildIterator AXNode::UnignoredChildrenEnd() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
return UnignoredChildIterator(this, nullptr);
}
// The first (direct) child, ignored or unignored.
AXNode* AXNode::GetFirstChild() const {
if (children().empty())
return nullptr;
return children()[0];
}
// The last (direct) child, ignored or unignored.
AXNode* AXNode::GetLastChild() const {
size_t n = children().size();
if (n == 0)
return nullptr;
return children()[n - 1];
}
// The previous (direct) sibling, ignored or unignored.
AXNode* AXNode::GetPreviousSibling() const {
// Root nodes lack a parent, their index_in_parent should be 0.
BASE_DCHECK(!parent() ? index_in_parent() == 0 : true);
size_t index = index_in_parent();
if (index == 0)
return nullptr;
return parent()->children()[index - 1];
}
// The next (direct) sibling, ignored or unignored.
AXNode* AXNode::GetNextSibling() const {
if (!parent())
return nullptr;
size_t nextIndex = index_in_parent() + 1;
if (nextIndex >= parent()->children().size())
return nullptr;
return parent()->children()[nextIndex];
}
bool AXNode::IsText() const {
// In Legacy Layout, a list marker has no children and is thus represented on
// all platforms as a leaf node that exposes the marker itself, i.e., it forms
// part of the AX tree's text representation. In contrast, in Layout NG, a
// list marker has a static text child.
if (data().role == ax::mojom::Role::kListMarker)
return !children().size();
return ui::IsText(data().role);
}
bool AXNode::IsLineBreak() const {
return data().role == ax::mojom::Role::kLineBreak ||
(data().role == ax::mojom::Role::kInlineTextBox &&
data().GetBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject));
}
void AXNode::SetData(const AXNodeData& src) {
data_ = src;
}
void AXNode::SetLocation(int32_t offset_container_id,
const gfx::RectF& location,
gfx::Transform* transform) {
data_.relative_bounds.offset_container_id = offset_container_id;
data_.relative_bounds.bounds = location;
if (transform) {
data_.relative_bounds.transform =
std::make_unique<gfx::Transform>(*transform);
} else {
data_.relative_bounds.transform.reset();
}
}
void AXNode::SetIndexInParent(size_t index_in_parent) {
index_in_parent_ = index_in_parent;
}
void AXNode::UpdateUnignoredCachedValues() {
if (!IsIgnored())
UpdateUnignoredCachedValuesRecursive(0);
}
void AXNode::SwapChildren(std::vector<AXNode*>* children) {
children->swap(children_);
}
void AXNode::Destroy() {
delete this;
}
bool AXNode::IsDescendantOf(const AXNode* ancestor) const {
if (this == ancestor)
return true;
if (parent())
return parent()->IsDescendantOf(ancestor);
return false;
}
std::vector<int> AXNode::GetOrComputeLineStartOffsets() {
std::vector<int> line_offsets;
if (data().GetIntListAttribute(ax::mojom::IntListAttribute::kCachedLineStarts,
&line_offsets)) {
return line_offsets;
}
int start_offset = 0;
ComputeLineStartOffsets(&line_offsets, &start_offset);
data_.AddIntListAttribute(ax::mojom::IntListAttribute::kCachedLineStarts,
line_offsets);
return line_offsets;
}
void AXNode::ComputeLineStartOffsets(std::vector<int>* line_offsets,
int* start_offset) const {
BASE_DCHECK(line_offsets);
BASE_DCHECK(start_offset);
for (const AXNode* child : children()) {
BASE_DCHECK(child);
if (!child->children().empty()) {
child->ComputeLineStartOffsets(line_offsets, start_offset);
continue;
}
// Don't report if the first piece of text starts a new line or not.
if (*start_offset && !child->data().HasIntAttribute(
ax::mojom::IntAttribute::kPreviousOnLineId)) {
// If there are multiple objects with an empty accessible label at the
// start of a line, only include a single line start offset.
if (line_offsets->empty() || line_offsets->back() != *start_offset)
line_offsets->push_back(*start_offset);
}
std::u16string text =
child->data().GetString16Attribute(ax::mojom::StringAttribute::kName);
*start_offset += static_cast<int>(text.length());
}
}
const std::string& AXNode::GetInheritedStringAttribute(
ax::mojom::StringAttribute attribute) const {
const AXNode* current_node = this;
do {
if (current_node->data().HasStringAttribute(attribute))
return current_node->data().GetStringAttribute(attribute);
current_node = current_node->parent();
} while (current_node);
return base::EmptyString();
}
std::u16string AXNode::GetInheritedString16Attribute(
ax::mojom::StringAttribute attribute) const {
return base::UTF8ToUTF16(GetInheritedStringAttribute(attribute));
}
std::string AXNode::GetInnerText() const {
// If a text field has no descendants, then we compute its inner text from its
// value or its placeholder. Otherwise we prefer to look at its descendant
// text nodes because Blink doesn't always add all trailing white space to the
// value attribute.
const bool is_plain_text_field_without_descendants =
(data().IsTextField() && !GetUnignoredChildCount());
if (is_plain_text_field_without_descendants) {
std::string value =
data().GetStringAttribute(ax::mojom::StringAttribute::kValue);
// If the value is empty, then there might be some placeholder text in the
// text field, or any other name that is derived from visible contents, even
// if the text field has no children.
if (!value.empty())
return value;
}
// Ordinarily, plain text fields are leaves. We need to exclude them from the
// set of leaf nodes when they expose any descendants. This is because we want
// to compute their inner text from their descendant text nodes as we don't
// always trust the "value" attribute provided by Blink.
const bool is_plain_text_field_with_descendants =
(data().IsTextField() && GetUnignoredChildCount());
if (IsLeaf() && !is_plain_text_field_with_descendants) {
switch (data().GetNameFrom()) {
case ax::mojom::NameFrom::kNone:
case ax::mojom::NameFrom::kUninitialized:
// The accessible name is not displayed on screen, e.g. aria-label, or is
// not displayed directly inside the node, e.g. an associated label
// element.
case ax::mojom::NameFrom::kAttribute:
// The node's accessible name is explicitly empty.
case ax::mojom::NameFrom::kAttributeExplicitlyEmpty:
// The accessible name does not represent the entirety of the node's inner
// text, e.g. a table's caption or a figure's figcaption.
case ax::mojom::NameFrom::kCaption:
case ax::mojom::NameFrom::kRelatedElement:
// The accessible name is not displayed directly inside the node but is
// visible via e.g. a tooltip.
case ax::mojom::NameFrom::kTitle:
return std::string();
case ax::mojom::NameFrom::kContents:
// The placeholder text is initially displayed inside the text field and
// takes the place of its value.
case ax::mojom::NameFrom::kPlaceholder:
// The value attribute takes the place of the node's inner text, e.g. the
// value of a submit button is displayed inside the button itself.
case ax::mojom::NameFrom::kValue:
return data().GetStringAttribute(ax::mojom::StringAttribute::kName);
}
}
std::string inner_text;
for (auto it = UnignoredChildrenBegin(); it != UnignoredChildrenEnd(); ++it) {
inner_text += it->GetInnerText();
}
return inner_text;
}
std::string AXNode::GetLanguage() const {
return std::string();
}
std::ostream& operator<<(std::ostream& stream, const AXNode& node) {
return stream << node.data().ToString();
}
bool AXNode::IsTable() const {
return IsTableLike(data().role);
}
std::optional<int> AXNode::GetTableColCount() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
return static_cast<int>(table_info->col_count);
}
std::optional<int> AXNode::GetTableRowCount() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
return static_cast<int>(table_info->row_count);
}
std::optional<int> AXNode::GetTableAriaColCount() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
return std::make_optional(table_info->aria_col_count);
}
std::optional<int> AXNode::GetTableAriaRowCount() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
return std::make_optional(table_info->aria_row_count);
}
std::optional<int> AXNode::GetTableCellCount() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
return static_cast<int>(table_info->unique_cell_ids.size());
}
std::optional<bool> AXNode::GetTableHasColumnOrRowHeaderNode() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
return !table_info->all_headers.empty();
}
AXNode* AXNode::GetTableCellFromIndex(int index) const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return nullptr;
// There is a table but there is no cell with the given index.
if (index < 0 ||
static_cast<size_t>(index) >= table_info->unique_cell_ids.size()) {
return nullptr;
}
return tree_->GetFromId(
table_info->unique_cell_ids[static_cast<size_t>(index)]);
}
AXNode* AXNode::GetTableCaption() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return nullptr;
return tree_->GetFromId(table_info->caption_id);
}
AXNode* AXNode::GetTableCellFromCoords(int row_index, int col_index) const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return nullptr;
// There is a table but the given coordinates are outside the table.
if (row_index < 0 ||
static_cast<size_t>(row_index) >= table_info->row_count ||
col_index < 0 ||
static_cast<size_t>(col_index) >= table_info->col_count) {
return nullptr;
}
return tree_->GetFromId(table_info->cell_ids[static_cast<size_t>(row_index)]
[static_cast<size_t>(col_index)]);
}
std::vector<AXNode::AXID> AXNode::GetTableColHeaderNodeIds() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::vector<AXNode::AXID>();
std::vector<AXNode::AXID> col_header_ids;
// Flatten and add column header ids of each column to |col_header_ids|.
for (std::vector<AXNode::AXID> col_headers_at_index :
table_info->col_headers) {
col_header_ids.insert(col_header_ids.end(), col_headers_at_index.begin(),
col_headers_at_index.end());
}
return col_header_ids;
}
std::vector<AXNode::AXID> AXNode::GetTableColHeaderNodeIds(
int col_index) const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::vector<AXNode::AXID>();
if (col_index < 0 || static_cast<size_t>(col_index) >= table_info->col_count)
return std::vector<AXNode::AXID>();
return std::vector<AXNode::AXID>(
table_info->col_headers[static_cast<size_t>(col_index)]);
}
std::vector<AXNode::AXID> AXNode::GetTableRowHeaderNodeIds(
int row_index) const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::vector<AXNode::AXID>();
if (row_index < 0 || static_cast<size_t>(row_index) >= table_info->row_count)
return std::vector<AXNode::AXID>();
return std::vector<AXNode::AXID>(
table_info->row_headers[static_cast<size_t>(row_index)]);
}
std::vector<AXNode::AXID> AXNode::GetTableUniqueCellIds() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::vector<AXNode::AXID>();
return std::vector<AXNode::AXID>(table_info->unique_cell_ids);
}
const std::vector<AXNode*>* AXNode::GetExtraMacNodes() const {
// Should only be available on the table node itself, not any of its children.
const AXTableInfo* table_info = tree_->GetTableInfo(this);
if (!table_info)
return nullptr;
return &table_info->extra_mac_nodes;
}
//
// Table row-like nodes.
//
bool AXNode::IsTableRow() const {
return ui::IsTableRow(data().role);
}
std::optional<int> AXNode::GetTableRowRowIndex() const {
if (!IsTableRow())
return std::nullopt;
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
const auto& iter = table_info->row_id_to_index.find(id());
if (iter == table_info->row_id_to_index.end())
return std::nullopt;
return static_cast<int>(iter->second);
}
std::vector<AXNode::AXID> AXNode::GetTableRowNodeIds() const {
std::vector<AXNode::AXID> row_node_ids;
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return row_node_ids;
for (AXNode* node : table_info->row_nodes)
row_node_ids.push_back(node->data().id);
return row_node_ids;
}
#if defined(OS_APPLE)
//
// Table column-like nodes. These nodes are only present on macOS.
//
bool AXNode::IsTableColumn() const {
return ui::IsTableColumn(data().role);
}
std::optional<int> AXNode::GetTableColColIndex() const {
if (!IsTableColumn())
return std::nullopt;
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
int index = 0;
for (const AXNode* node : table_info->extra_mac_nodes) {
if (node == this)
break;
index++;
}
return index;
}
#endif // defined(OS_APPLE)
//
// Table cell-like nodes.
//
bool AXNode::IsTableCellOrHeader() const {
return IsCellOrTableHeader(data().role);
}
std::optional<int> AXNode::GetTableCellIndex() const {
if (!IsTableCellOrHeader())
return std::nullopt;
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
const auto& iter = table_info->cell_id_to_index.find(id());
if (iter != table_info->cell_id_to_index.end())
return static_cast<int>(iter->second);
return std::nullopt;
}
std::optional<int> AXNode::GetTableCellColIndex() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
std::optional<int> index = GetTableCellIndex();
if (!index)
return std::nullopt;
return static_cast<int>(table_info->cell_data_vector[*index].col_index);
}
std::optional<int> AXNode::GetTableCellRowIndex() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
std::optional<int> index = GetTableCellIndex();
if (!index)
return std::nullopt;
return static_cast<int>(table_info->cell_data_vector[*index].row_index);
}
std::optional<int> AXNode::GetTableCellColSpan() const {
// If it's not a table cell, don't return a col span.
if (!IsTableCellOrHeader())
return std::nullopt;
// Otherwise, try to return a colspan, with 1 as the default if it's not
// specified.
int col_span;
if (GetIntAttribute(ax::mojom::IntAttribute::kTableCellColumnSpan, &col_span))
return col_span;
return 1;
}
std::optional<int> AXNode::GetTableCellRowSpan() const {
// If it's not a table cell, don't return a row span.
if (!IsTableCellOrHeader())
return std::nullopt;
// Otherwise, try to return a row span, with 1 as the default if it's not
// specified.
int row_span;
if (GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowSpan, &row_span))
return row_span;
return 1;
}
std::optional<int> AXNode::GetTableCellAriaColIndex() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
std::optional<int> index = GetTableCellIndex();
if (!index)
return std::nullopt;
return static_cast<int>(table_info->cell_data_vector[*index].aria_col_index);
}
std::optional<int> AXNode::GetTableCellAriaRowIndex() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info)
return std::nullopt;
std::optional<int> index = GetTableCellIndex();
if (!index)
return std::nullopt;
return static_cast<int>(table_info->cell_data_vector[*index].aria_row_index);
}
std::vector<AXNode::AXID> AXNode::GetTableCellColHeaderNodeIds() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info || table_info->col_count <= 0)
return std::vector<AXNode::AXID>();
// If this node is not a cell, then return the headers for the first column.
int col_index = GetTableCellColIndex().value_or(0);
return std::vector<AXNode::AXID>(table_info->col_headers[col_index]);
}
void AXNode::GetTableCellColHeaders(std::vector<AXNode*>* col_headers) const {
BASE_DCHECK(col_headers);
std::vector<int32_t> col_header_ids = GetTableCellColHeaderNodeIds();
IdVectorToNodeVector(col_header_ids, col_headers);
}
std::vector<AXNode::AXID> AXNode::GetTableCellRowHeaderNodeIds() const {
const AXTableInfo* table_info = GetAncestorTableInfo();
if (!table_info || table_info->row_count <= 0)
return std::vector<AXNode::AXID>();
// If this node is not a cell, then return the headers for the first row.
int row_index = GetTableCellRowIndex().value_or(0);
return std::vector<AXNode::AXID>(table_info->row_headers[row_index]);
}
void AXNode::GetTableCellRowHeaders(std::vector<AXNode*>* row_headers) const {
BASE_DCHECK(row_headers);
std::vector<int32_t> row_header_ids = GetTableCellRowHeaderNodeIds();
IdVectorToNodeVector(row_header_ids, row_headers);
}
bool AXNode::IsCellOrHeaderOfARIATable() const {
if (!IsTableCellOrHeader())
return false;
const AXNode* node = this;
while (node && !node->IsTable())
node = node->parent();
if (!node)
return false;
return node->data().role == ax::mojom::Role::kTable;
}
bool AXNode::IsCellOrHeaderOfARIAGrid() const {
if (!IsTableCellOrHeader())
return false;
const AXNode* node = this;
while (node && !node->IsTable())
node = node->parent();
if (!node)
return false;
return node->data().role == ax::mojom::Role::kGrid ||
node->data().role == ax::mojom::Role::kTreeGrid;
}
AXTableInfo* AXNode::GetAncestorTableInfo() const {
const AXNode* node = this;
while (node && !node->IsTable())
node = node->parent();
if (node)
return tree_->GetTableInfo(node);
return nullptr;
}
void AXNode::IdVectorToNodeVector(const std::vector<int32_t>& ids,
std::vector<AXNode*>* nodes) const {
for (int32_t id : ids) {
AXNode* node = tree_->GetFromId(id);
if (node)
nodes->push_back(node);
}
}
std::optional<int> AXNode::GetHierarchicalLevel() const {
int hierarchical_level =
GetIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel);
// According to the WAI_ARIA spec, a defined hierarchical level value is
// greater than 0.
// https://www.w3.org/TR/wai-aria-1.1/#aria-level
if (hierarchical_level > 0)
return hierarchical_level;
return std::nullopt;
}
bool AXNode::IsOrderedSetItem() const {
return ui::IsItemLike(data().role);
}
bool AXNode::IsOrderedSet() const {
return ui::IsSetLike(data().role);
}
// Uses AXTree's cache to calculate node's PosInSet.
std::optional<int> AXNode::GetPosInSet() {
return tree_->GetPosInSet(*this);
}
// Uses AXTree's cache to calculate node's SetSize.
std::optional<int> AXNode::GetSetSize() {
return tree_->GetSetSize(*this);
}
// Returns true if the role of ordered set matches the role of item.
// Returns false otherwise.
bool AXNode::SetRoleMatchesItemRole(const AXNode* ordered_set) const {
ax::mojom::Role item_role = data().role;
// Switch on role of ordered set
switch (ordered_set->data().role) {
case ax::mojom::Role::kFeed:
return item_role == ax::mojom::Role::kArticle;
case ax::mojom::Role::kList:
return item_role == ax::mojom::Role::kListItem;
case ax::mojom::Role::kGroup:
return item_role == ax::mojom::Role::kComment ||
item_role == ax::mojom::Role::kListItem ||
item_role == ax::mojom::Role::kMenuItem ||
item_role == ax::mojom::Role::kMenuItemRadio ||
item_role == ax::mojom::Role::kListBoxOption ||
item_role == ax::mojom::Role::kTreeItem;
case ax::mojom::Role::kMenu:
return item_role == ax::mojom::Role::kMenuItem ||
item_role == ax::mojom::Role::kMenuItemRadio ||
item_role == ax::mojom::Role::kMenuItemCheckBox;
case ax::mojom::Role::kMenuBar:
return item_role == ax::mojom::Role::kMenuItem ||
item_role == ax::mojom::Role::kMenuItemRadio ||
item_role == ax::mojom::Role::kMenuItemCheckBox;
case ax::mojom::Role::kTabList:
return item_role == ax::mojom::Role::kTab;
case ax::mojom::Role::kTree:
return item_role == ax::mojom::Role::kTreeItem;
case ax::mojom::Role::kListBox:
return item_role == ax::mojom::Role::kListBoxOption;
case ax::mojom::Role::kMenuListPopup:
return item_role == ax::mojom::Role::kMenuListOption ||
item_role == ax::mojom::Role::kMenuItem ||
item_role == ax::mojom::Role::kMenuItemRadio ||
item_role == ax::mojom::Role::kMenuItemCheckBox;
case ax::mojom::Role::kRadioGroup:
return item_role == ax::mojom::Role::kRadioButton;
case ax::mojom::Role::kDescriptionList:
// Only the term for each description list entry should receive posinset
// and setsize.
return item_role == ax::mojom::Role::kDescriptionListTerm ||
item_role == ax::mojom::Role::kTerm;
case ax::mojom::Role::kPopUpButton:
// kPopUpButtons can wrap a kMenuListPopUp.
return item_role == ax::mojom::Role::kMenuListPopup;
default:
return false;
}
}
bool AXNode::IsIgnoredContainerForOrderedSet() const {
return IsIgnored() || IsEmbeddedGroup() ||
data().role == ax::mojom::Role::kListItem ||
data().role == ax::mojom::Role::kGenericContainer ||
data().role == ax::mojom::Role::kUnknown;
}
int AXNode::UpdateUnignoredCachedValuesRecursive(int startIndex) {
int count = 0;
for (AXNode* child : children_) {
if (child->IsIgnored()) {
child->unignored_index_in_parent_ = 0;
count += child->UpdateUnignoredCachedValuesRecursive(startIndex + count);
} else {
child->unignored_index_in_parent_ = startIndex + count++;
}
}
unignored_child_count_ = count;
return count;
}
// Finds ordered set that contains node.
// Is not required for set's role to match node's role.
AXNode* AXNode::GetOrderedSet() const {
AXNode* result = parent();
// Continue walking up while parent is invalid, ignored, a generic container,
// unknown, or embedded group.
while (result && result->IsIgnoredContainerForOrderedSet()) {
result = result->parent();
}
return result;
}
AXNode* AXNode::ComputeLastUnignoredChildRecursive() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
if (children().empty())
return nullptr;
for (int i = static_cast<int>(children().size()) - 1; i >= 0; --i) {
AXNode* child = children_[i];
if (!child->IsIgnored())
return child;
AXNode* descendant = child->ComputeLastUnignoredChildRecursive();
if (descendant)
return descendant;
}
return nullptr;
}
AXNode* AXNode::ComputeFirstUnignoredChildRecursive() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
for (size_t i = 0; i < children().size(); i++) {
AXNode* child = children_[i];
if (!child->IsIgnored())
return child;
AXNode* descendant = child->ComputeFirstUnignoredChildRecursive();
if (descendant)
return descendant;
}
return nullptr;
}
bool AXNode::IsIgnored() const {
return data().IsIgnored();
}
bool AXNode::IsChildOfLeaf() const {
const AXNode* ancestor = GetUnignoredParent();
while (ancestor) {
if (ancestor->IsLeaf())
return true;
ancestor = ancestor->GetUnignoredParent();
}
return false;
}
bool AXNode::IsLeaf() const {
// A node is also a leaf if all of it's descendants are ignored.
if (children().empty() || !GetUnignoredChildCount())
return true;
#if defined(OS_WIN)
// On Windows, we want to hide the subtree of a collapsed <select> element.
// Otherwise, ATs are always going to announce its options whether it's
// collapsed or expanded. In the AXTree, this element corresponds to a node
// with role ax::mojom::Role::kPopUpButton that is the parent of a node with
// role ax::mojom::Role::kMenuListPopup.
if (IsCollapsedMenuListPopUpButton())
return true;
#endif // defined(OS_WIN)
// These types of objects may have children that we use as internal
// implementation details, but we want to expose them as leaves to platform
// accessibility APIs because screen readers might be confused if they find
// any children.
if (data().IsPlainTextField() || IsText())
return true;
// Roles whose children are only presentational according to the ARIA and
// HTML5 Specs should be hidden from screen readers.
switch (data().role) {
// According to the ARIA and Core-AAM specs:
// https://w3c.github.io/aria/#button,
// https://www.w3.org/TR/core-aam-1.1/#exclude_elements
// buttons' children are presentational only and should be hidden from
// screen readers. However, we cannot enforce the leafiness of buttons
// because they may contain many rich, interactive descendants such as a day
// in a calendar, and screen readers will need to interact with these
// contents. See https://crbug.com/689204.
// So we decided to not enforce the leafiness of buttons and expose all
// children.
case ax::mojom::Role::kButton:
return false;
case ax::mojom::Role::kDocCover:
case ax::mojom::Role::kGraphicsSymbol:
case ax::mojom::Role::kImage:
case ax::mojom::Role::kMeter:
case ax::mojom::Role::kScrollBar:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kSplitter:
case ax::mojom::Role::kProgressIndicator:
return true;
default:
return false;
}
}
bool AXNode::IsInListMarker() const {
if (data().role == ax::mojom::Role::kListMarker)
return true;
// List marker node's children can only be text elements.
if (!IsText())
return false;
// There is no need to iterate over all the ancestors of the current anchor
// since a list marker node only has children on 2 levels.
// i.e.:
// AXLayoutObject role=kListMarker
// ++StaticText
// ++++InlineTextBox
AXNode* parent_node = GetUnignoredParent();
if (parent_node && parent_node->data().role == ax::mojom::Role::kListMarker)
return true;
AXNode* grandparent_node = parent_node->GetUnignoredParent();
return grandparent_node &&
grandparent_node->data().role == ax::mojom::Role::kListMarker;
}
bool AXNode::IsCollapsedMenuListPopUpButton() const {
if (data().role != ax::mojom::Role::kPopUpButton ||
!data().HasState(ax::mojom::State::kCollapsed)) {
return false;
}
// When a popup button contains a menu list popup, its only child is unignored
// and is a menu list popup.
AXNode* node = GetFirstUnignoredChild();
if (!node)
return false;
return node->data().role == ax::mojom::Role::kMenuListPopup;
}
AXNode* AXNode::GetCollapsedMenuListPopUpButtonAncestor() const {
AXNode* node = GetOrderedSet();
if (!node)
return nullptr;
// The ordered set returned is either the popup element child of the popup
// button (e.g., the AXMenuListPopup) or the popup button itself. We need
// |node| to point to the popup button itself.
if (node->data().role != ax::mojom::Role::kPopUpButton) {
node = node->parent();
if (!node)
return nullptr;
}
return node->IsCollapsedMenuListPopUpButton() ? node : nullptr;
}
bool AXNode::IsEmbeddedGroup() const {
if (data().role != ax::mojom::Role::kGroup || !parent())
return false;
return ui::IsSetLike(parent()->data().role);
}
AXNode* AXNode::GetLowestPlatformAncestor() const {
AXNode* current_node = const_cast<AXNode*>(this);
AXNode* lowest_unignored_node = current_node;
for (; lowest_unignored_node && lowest_unignored_node->IsIgnored();
lowest_unignored_node = lowest_unignored_node->parent()) {
}
// `highest_leaf_node` could be nullptr.
AXNode* highest_leaf_node = lowest_unignored_node;
// For the purposes of this method, a leaf node does not include leaves in the
// internal accessibility tree, only in the platform exposed tree.
for (AXNode* ancestor_node = lowest_unignored_node; ancestor_node;
ancestor_node = ancestor_node->GetUnignoredParent()) {
if (ancestor_node->IsLeaf())
highest_leaf_node = ancestor_node;
}
if (highest_leaf_node)
return highest_leaf_node;
if (lowest_unignored_node)
return lowest_unignored_node;
return current_node;
}
AXNode* AXNode::GetTextFieldAncestor() const {
AXNode* parent = GetUnignoredParent();
while (parent && parent->data().HasState(ax::mojom::State::kEditable)) {
if (parent->data().IsPlainTextField() || parent->data().IsRichTextField())
return parent;
parent = parent->GetUnignoredParent();
}
return nullptr;
}
bool AXNode::IsDescendantOfCrossingTreeBoundary(const AXNode* ancestor) const {
if (!ancestor)
return false;
if (this == ancestor)
return true;
if (const AXNode* parent = GetParentCrossingTreeBoundary())
return parent->IsDescendantOfCrossingTreeBoundary(ancestor);
return false;
}
AXNode* AXNode::GetParentCrossingTreeBoundary() const {
BASE_DCHECK(!tree_->GetTreeUpdateInProgressState());
if (parent_)
return parent_;
const AXTreeManager* manager =
AXTreeManagerMap::GetInstance().GetManager(tree_->GetAXTreeID());
if (manager)
return manager->GetParentNodeFromParentTreeAsAXNode();
return nullptr;
}
AXTree::Selection AXNode::GetUnignoredSelection() const {
BASE_DCHECK(tree())
<< "Cannot retrieve the current selection if the node is not "
"attached to an accessibility tree.\n"
<< *this;
AXTree::Selection selection = tree()->GetUnignoredSelection();
// "selection.anchor_offset" and "selection.focus_ofset" might need to be
// adjusted if the anchor or the focus nodes include ignored children.
//
// TODO(nektar): Move this logic into its own "AXSelection" class and cache
// the result for faster reuse.
const AXNode* anchor = tree()->GetFromId(selection.anchor_object_id);
if (anchor && !anchor->IsLeaf()) {
BASE_DCHECK(selection.anchor_offset >= 0);
if (static_cast<size_t>(selection.anchor_offset) <
anchor->children().size()) {
const AXNode* anchor_child = anchor->children()[selection.anchor_offset];
BASE_DCHECK(anchor_child);
selection.anchor_offset =
static_cast<int>(anchor_child->GetUnignoredIndexInParent());
} else {
selection.anchor_offset =
static_cast<int>(anchor->GetUnignoredChildCount());
}
}
const AXNode* focus = tree()->GetFromId(selection.focus_object_id);
if (focus && !focus->IsLeaf()) {
BASE_DCHECK(selection.focus_offset >= 0);
if (static_cast<size_t>(selection.focus_offset) <
focus->children().size()) {
const AXNode* focus_child = focus->children()[selection.focus_offset];
BASE_DCHECK(focus_child);
selection.focus_offset =
static_cast<int>(focus_child->GetUnignoredIndexInParent());
} else {
selection.focus_offset =
static_cast<int>(focus->GetUnignoredChildCount());
}
}
return selection;
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_node.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_node.cc",
"repo_id": "engine",
"token_count": 14952
} | 409 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ax_role_properties.h"
#include "ax_build/build_config.h"
#include "ax_enums.h"
namespace ui {
namespace {
#if defined(OS_WIN) || defined(OS_CHROMEOS)
constexpr bool kExposeLayoutTableAsDataTable = true;
#else
constexpr bool kExposeLayoutTableAsDataTable = false;
#endif // defined(OS_WIN)
} // namespace
bool HasPresentationalChildren(const ax::mojom::Role role) {
// See http://www.w3.org/TR/core-aam-1.1/#exclude_elements2.
if (IsImage(role))
return true;
switch (role) {
case ax::mojom::Role::kButton:
case ax::mojom::Role::kCheckBox:
case ax::mojom::Role::kMath:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kProgressIndicator:
case ax::mojom::Role::kScrollBar:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kSwitch:
case ax::mojom::Role::kTab:
return true;
default:
return false;
}
}
bool IsAlert(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kAlert:
case ax::mojom::Role::kAlertDialog:
return true;
default:
return false;
}
}
bool IsButton(const ax::mojom::Role role) {
// According to the WAI-ARIA spec, native button or role="button"
// supports |aria-expanded| and |aria-pressed|.
// If the button has |aria-expanded| set, then it takes on
// Role::kPopUpButton.
// If the button has |aria-pressed| set, then it takes on
// Role::kToggleButton.
// https://www.w3.org/TR/wai-aria-1.1/#button
return role == ax::mojom::Role::kButton ||
role == ax::mojom::Role::kPopUpButton ||
role == ax::mojom::Role::kToggleButton;
}
bool IsClickable(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kButton:
case ax::mojom::Role::kCheckBox:
case ax::mojom::Role::kColorWell:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kDate:
case ax::mojom::Role::kDateTime:
case ax::mojom::Role::kDisclosureTriangle:
case ax::mojom::Role::kDocBackLink:
case ax::mojom::Role::kDocBiblioRef:
case ax::mojom::Role::kDocGlossRef:
case ax::mojom::Role::kDocNoteRef:
case ax::mojom::Role::kImeCandidate:
case ax::mojom::Role::kInputTime:
case ax::mojom::Role::kLink:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kMenuItem:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kPdfActionableHighlight:
case ax::mojom::Role::kPopUpButton:
case ax::mojom::Role::kPortal:
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kSearchBox:
case ax::mojom::Role::kSpinButton:
case ax::mojom::Role::kSwitch:
case ax::mojom::Role::kTab:
case ax::mojom::Role::kTextField:
case ax::mojom::Role::kTextFieldWithComboBox:
// kTree and related roles are not included because they are not natively
// supported by HTML and so their "clickable" behavior is uncertain.
case ax::mojom::Role::kToggleButton:
return true;
default:
return false;
}
}
bool IsCellOrTableHeader(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kCell:
case ax::mojom::Role::kColumnHeader:
case ax::mojom::Role::kRowHeader:
return true;
case ax::mojom::Role::kLayoutTableCell:
return kExposeLayoutTableAsDataTable;
default:
return false;
}
}
bool IsContainerWithSelectableChildren(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kComboBoxGrouping:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kGrid:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kListGrid:
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar:
case ax::mojom::Role::kMenuListPopup:
case ax::mojom::Role::kRadioGroup:
case ax::mojom::Role::kTabList:
case ax::mojom::Role::kToolbar:
case ax::mojom::Role::kTree:
case ax::mojom::Role::kTreeGrid:
return true;
default:
return false;
}
}
bool IsControl(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kButton:
case ax::mojom::Role::kCheckBox:
case ax::mojom::Role::kColorWell:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kDisclosureTriangle:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kListGrid:
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar:
case ax::mojom::Role::kMenuItem:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kMenuListPopup:
case ax::mojom::Role::kPdfActionableHighlight:
case ax::mojom::Role::kPopUpButton:
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kScrollBar:
case ax::mojom::Role::kSearchBox:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kSpinButton:
case ax::mojom::Role::kSwitch:
case ax::mojom::Role::kTab:
case ax::mojom::Role::kTextField:
case ax::mojom::Role::kTextFieldWithComboBox:
case ax::mojom::Role::kToggleButton:
case ax::mojom::Role::kTree:
return true;
default:
return false;
}
}
bool IsControlOnAndroid(const ax::mojom::Role role, bool isFocusable) {
switch (role) {
case ax::mojom::Role::kSplitter:
return isFocusable;
case ax::mojom::Role::kTreeItem:
case ax::mojom::Role::kDate:
case ax::mojom::Role::kDateTime:
case ax::mojom::Role::kInputTime:
case ax::mojom::Role::kDocBackLink:
case ax::mojom::Role::kDocBiblioRef:
case ax::mojom::Role::kDocGlossRef:
case ax::mojom::Role::kDocNoteRef:
case ax::mojom::Role::kLink:
return true;
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar:
case ax::mojom::Role::kNone:
case ax::mojom::Role::kUnknown:
case ax::mojom::Role::kTree:
case ax::mojom::Role::kDialog:
case ax::mojom::Role::kAlert:
return false;
default:
return IsControl(role);
}
}
bool IsDocument(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kDocument:
case ax::mojom::Role::kRootWebArea:
case ax::mojom::Role::kWebArea:
return true;
default:
return false;
}
}
bool IsDialog(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kAlertDialog:
case ax::mojom::Role::kDialog:
return true;
default:
return false;
}
}
bool IsForm(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kForm:
return true;
default:
return false;
}
}
bool IsFormatBoundary(const ax::mojom::Role role) {
return IsControl(role) || IsHeading(role) || IsImageOrVideo(role);
}
bool IsHeading(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kHeading:
case ax::mojom::Role::kDocSubtitle:
return true;
default:
return false;
}
}
bool IsHeadingOrTableHeader(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kColumnHeader:
case ax::mojom::Role::kDocSubtitle:
case ax::mojom::Role::kHeading:
case ax::mojom::Role::kRowHeader:
return true;
default:
return false;
}
}
bool IsIframe(ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kIframe:
case ax::mojom::Role::kIframePresentational:
return true;
default:
return false;
}
}
bool IsImageOrVideo(const ax::mojom::Role role) {
return IsImage(role) || role == ax::mojom::Role::kVideo;
}
bool IsImage(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kCanvas:
case ax::mojom::Role::kDocCover:
case ax::mojom::Role::kGraphicsSymbol:
case ax::mojom::Role::kImage:
case ax::mojom::Role::kImageMap:
case ax::mojom::Role::kSvgRoot:
return true;
default:
return false;
}
}
bool IsItemLike(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kArticle:
case ax::mojom::Role::kComment:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kMenuItem:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kTab:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kTreeItem:
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kDescriptionListTerm:
case ax::mojom::Role::kTerm:
return true;
default:
return false;
}
}
bool IsLandmark(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kBanner:
case ax::mojom::Role::kComplementary:
case ax::mojom::Role::kContentInfo:
case ax::mojom::Role::kForm:
case ax::mojom::Role::kMain:
case ax::mojom::Role::kNavigation:
case ax::mojom::Role::kRegion:
case ax::mojom::Role::kSearch:
return true;
default:
return false;
}
}
bool IsLink(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kDocBackLink:
case ax::mojom::Role::kDocBiblioRef:
case ax::mojom::Role::kDocGlossRef:
case ax::mojom::Role::kDocNoteRef:
case ax::mojom::Role::kLink:
return true;
default:
return false;
}
}
bool IsList(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kDescriptionList:
case ax::mojom::Role::kDirectory:
case ax::mojom::Role::kDocBibliography:
case ax::mojom::Role::kList:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kListGrid:
return true;
default:
return false;
}
}
bool IsListItem(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kDescriptionListTerm:
case ax::mojom::Role::kDocBiblioEntry:
case ax::mojom::Role::kDocEndnote:
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kTerm:
return true;
default:
return false;
}
}
bool IsMenuItem(ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kMenuItem:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
return true;
default:
return false;
}
}
bool IsMenuRelated(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar:
case ax::mojom::Role::kMenuItem:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kMenuListPopup:
return true;
default:
return false;
}
}
bool IsPresentational(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kNone:
case ax::mojom::Role::kPresentational:
return true;
default:
return false;
}
}
bool IsRadio(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kMenuItemRadio:
return true;
default:
return false;
}
}
bool IsRangeValueSupported(const ax::mojom::Role role) {
// https://www.w3.org/TR/wai-aria-1.1/#aria-valuenow
// https://www.w3.org/TR/wai-aria-1.1/#aria-valuetext
// Roles that support aria-valuetext / aria-valuenow
switch (role) {
case ax::mojom::Role::kMeter:
case ax::mojom::Role::kProgressIndicator:
case ax::mojom::Role::kScrollBar:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kSpinButton:
case ax::mojom::Role::kSplitter:
return true;
default:
return false;
}
}
bool IsReadOnlySupported(const ax::mojom::Role role) {
// https://www.w3.org/TR/wai-aria-1.1/#aria-readonly
// Roles that support aria-readonly
switch (role) {
case ax::mojom::Role::kCheckBox:
case ax::mojom::Role::kColorWell:
case ax::mojom::Role::kComboBoxGrouping:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kDate:
case ax::mojom::Role::kDateTime:
case ax::mojom::Role::kGrid:
case ax::mojom::Role::kInputTime:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kMenuItemRadio:
case ax::mojom::Role::kMenuListPopup:
case ax::mojom::Role::kPopUpButton:
case ax::mojom::Role::kRadioButton:
case ax::mojom::Role::kRadioGroup:
case ax::mojom::Role::kSearchBox:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kSpinButton:
case ax::mojom::Role::kSwitch:
case ax::mojom::Role::kTextField:
case ax::mojom::Role::kTextFieldWithComboBox:
case ax::mojom::Role::kToggleButton:
case ax::mojom::Role::kTreeGrid:
return true;
// https://www.w3.org/TR/wai-aria-1.1/#aria-readonly
// ARIA-1.1+ 'gridcell', supports aria-readonly, but 'cell' does not.
//
// https://www.w3.org/TR/wai-aria-1.1/#columnheader
// https://www.w3.org/TR/wai-aria-1.1/#rowheader
// While the [columnheader|rowheader] role can be used in both interactive
// grids and non-interactive tables, the use of aria-readonly and
// aria-required is only applicable to interactive elements.
// Therefore, [...] user agents SHOULD NOT expose either property to
// assistive technologies unless the columnheader descends from a grid.
case ax::mojom::Role::kCell:
case ax::mojom::Role::kRowHeader:
case ax::mojom::Role::kColumnHeader:
return false;
default:
return false;
}
}
bool IsRowContainer(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kGrid:
case ax::mojom::Role::kListGrid:
case ax::mojom::Role::kTable:
case ax::mojom::Role::kTree:
case ax::mojom::Role::kTreeGrid:
return true;
case ax::mojom::Role::kLayoutTable:
return kExposeLayoutTableAsDataTable;
default:
return false;
}
}
bool IsSection(const ax::mojom::Role role) {
if (IsLandmark(role) || IsSelect(role))
return true;
switch (role) {
case ax::mojom::Role::kAlert:
case ax::mojom::Role::kAlertDialog: // Subclass of kAlert.
case ax::mojom::Role::kCell:
case ax::mojom::Role::kColumnHeader: // Subclass of kCell.
case ax::mojom::Role::kDefinition:
case ax::mojom::Role::kDirectory: // Subclass of kList.
case ax::mojom::Role::kFeed: // Subclass of kList.
case ax::mojom::Role::kFigure:
case ax::mojom::Role::kGrid: // Subclass of kTable.
case ax::mojom::Role::kGroup:
case ax::mojom::Role::kImage:
case ax::mojom::Role::kList:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kLog:
case ax::mojom::Role::kMarquee:
case ax::mojom::Role::kMath:
case ax::mojom::Role::kNote:
case ax::mojom::Role::kProgressIndicator: // Subclass of kStatus.
case ax::mojom::Role::kRow: // Subclass of kGroup.
case ax::mojom::Role::kRowHeader: // Subclass of kCell.
case ax::mojom::Role::kSection:
case ax::mojom::Role::kStatus:
case ax::mojom::Role::kTable:
case ax::mojom::Role::kTabPanel:
case ax::mojom::Role::kTerm:
case ax::mojom::Role::kTimer: // Subclass of kStatus.
case ax::mojom::Role::kToolbar: // Subclass of kGroup.
case ax::mojom::Role::kTooltip:
case ax::mojom::Role::kTreeItem: // Subclass of kListItem.
return true;
default:
return false;
}
}
bool IsSectionhead(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kColumnHeader:
case ax::mojom::Role::kHeading:
case ax::mojom::Role::kRowHeader:
case ax::mojom::Role::kTab:
return true;
default:
return false;
}
}
bool IsSelect(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kComboBoxGrouping:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar: // Subclass of kMenu.
case ax::mojom::Role::kRadioGroup:
case ax::mojom::Role::kTree:
case ax::mojom::Role::kTreeGrid: // Subclass of kTree.
return true;
default:
return false;
}
}
bool IsSetLike(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kDescriptionList:
case ax::mojom::Role::kDirectory:
case ax::mojom::Role::kDocBibliography:
case ax::mojom::Role::kFeed:
case ax::mojom::Role::kGroup:
case ax::mojom::Role::kList:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kListGrid:
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar:
case ax::mojom::Role::kMenuListPopup:
case ax::mojom::Role::kPopUpButton:
case ax::mojom::Role::kRadioGroup:
case ax::mojom::Role::kTabList:
case ax::mojom::Role::kTree:
return true;
default:
return false;
}
}
bool IsStaticList(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kList:
case ax::mojom::Role::kDescriptionList:
return true;
default:
return false;
}
}
bool IsStructure(const ax::mojom::Role role) {
if (IsSection(role) || IsSectionhead(role))
return true;
switch (role) {
case ax::mojom::Role::kApplication:
case ax::mojom::Role::kDocument:
case ax::mojom::Role::kArticle: // Subclass of kDocument.
case ax::mojom::Role::kPresentational:
case ax::mojom::Role::kRowGroup:
case ax::mojom::Role::kSplitter:
// Dpub roles.
case ax::mojom::Role::kDocAbstract:
case ax::mojom::Role::kDocAcknowledgments:
case ax::mojom::Role::kDocAfterword:
case ax::mojom::Role::kDocAppendix:
case ax::mojom::Role::kDocBiblioEntry:
case ax::mojom::Role::kDocBibliography:
case ax::mojom::Role::kDocChapter:
case ax::mojom::Role::kDocColophon:
case ax::mojom::Role::kDocConclusion:
case ax::mojom::Role::kDocCover:
case ax::mojom::Role::kDocCredit:
case ax::mojom::Role::kDocCredits:
case ax::mojom::Role::kDocDedication:
case ax::mojom::Role::kDocEndnote:
case ax::mojom::Role::kDocEndnotes:
case ax::mojom::Role::kDocEpigraph:
case ax::mojom::Role::kDocEpilogue:
case ax::mojom::Role::kDocErrata:
case ax::mojom::Role::kDocExample:
case ax::mojom::Role::kDocFootnote:
case ax::mojom::Role::kDocForeword:
case ax::mojom::Role::kDocGlossary:
case ax::mojom::Role::kDocIndex:
case ax::mojom::Role::kDocIntroduction:
case ax::mojom::Role::kDocNotice:
case ax::mojom::Role::kDocPageBreak:
case ax::mojom::Role::kDocPageList:
case ax::mojom::Role::kDocPart:
case ax::mojom::Role::kDocPreface:
case ax::mojom::Role::kDocPrologue:
case ax::mojom::Role::kDocQna:
case ax::mojom::Role::kDocSubtitle:
case ax::mojom::Role::kDocTip:
case ax::mojom::Role::kDocToc:
return true;
default:
return false;
}
}
bool IsTableColumn(ax::mojom::Role role) {
return role == ax::mojom::Role::kColumn;
}
bool IsTableHeader(ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kColumnHeader:
case ax::mojom::Role::kRowHeader:
return true;
default:
return false;
}
}
bool IsTableLike(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kGrid:
case ax::mojom::Role::kListGrid:
case ax::mojom::Role::kTable:
case ax::mojom::Role::kTreeGrid:
return true;
case ax::mojom::Role::kLayoutTable:
return kExposeLayoutTableAsDataTable;
default:
return false;
}
}
bool IsTableRow(ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kRow:
return true;
case ax::mojom::Role::kLayoutTableRow:
return kExposeLayoutTableAsDataTable;
default:
return false;
}
}
bool IsText(ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kInlineTextBox:
case ax::mojom::Role::kLineBreak:
case ax::mojom::Role::kStaticText:
case ax::mojom::Role::kTextField:
case ax::mojom::Role::kTextFieldWithComboBox:
case ax::mojom::Role::kLabelText:
return true;
default:
return false;
}
}
bool SupportsExpandCollapse(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kComboBoxGrouping:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kDisclosureTriangle:
case ax::mojom::Role::kTextFieldWithComboBox:
case ax::mojom::Role::kTreeItem:
return true;
default:
return false;
}
}
bool SupportsHierarchicalLevel(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kComment:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kRow:
case ax::mojom::Role::kTabList:
case ax::mojom::Role::kTreeItem:
return true;
default:
return false;
}
}
bool SupportsOrientation(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kComboBoxGrouping:
case ax::mojom::Role::kComboBoxMenuButton:
case ax::mojom::Role::kListBox:
case ax::mojom::Role::kMenu:
case ax::mojom::Role::kMenuBar:
case ax::mojom::Role::kRadioGroup:
case ax::mojom::Role::kScrollBar:
case ax::mojom::Role::kSlider:
case ax::mojom::Role::kSplitter:
case ax::mojom::Role::kTabList:
case ax::mojom::Role::kToolbar:
case ax::mojom::Role::kTreeGrid:
case ax::mojom::Role::kTree:
return true;
default:
return false;
}
}
bool SupportsSelected(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kCell:
case ax::mojom::Role::kColumnHeader:
case ax::mojom::Role::kListBoxOption:
case ax::mojom::Role::kMenuListOption:
case ax::mojom::Role::kRow:
case ax::mojom::Role::kRowHeader:
case ax::mojom::Role::kTab:
case ax::mojom::Role::kTreeItem:
return true;
default:
return false;
}
}
bool SupportsToggle(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kCheckBox:
case ax::mojom::Role::kMenuItemCheckBox:
case ax::mojom::Role::kSwitch:
case ax::mojom::Role::kToggleButton:
return true;
default:
return false;
}
}
bool ShouldHaveReadonlyStateByDefault(const ax::mojom::Role role) {
switch (role) {
case ax::mojom::Role::kArticle:
case ax::mojom::Role::kDefinition:
case ax::mojom::Role::kDescriptionList:
case ax::mojom::Role::kDescriptionListTerm:
case ax::mojom::Role::kDocument:
case ax::mojom::Role::kGraphicsDocument:
case ax::mojom::Role::kImage:
case ax::mojom::Role::kImageMap:
case ax::mojom::Role::kList:
case ax::mojom::Role::kListItem:
case ax::mojom::Role::kProgressIndicator:
case ax::mojom::Role::kRootWebArea:
case ax::mojom::Role::kTerm:
case ax::mojom::Role::kTimer:
case ax::mojom::Role::kToolbar:
case ax::mojom::Role::kTooltip:
case ax::mojom::Role::kWebArea:
return true;
case ax::mojom::Role::kGrid:
// TODO(aleventhal) this changed between ARIA 1.0 and 1.1,
// need to determine whether grids/treegrids should really be readonly
// or editable by default
break;
default:
break;
}
return false;
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_role_properties.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_role_properties.cc",
"repo_id": "engine",
"token_count": 10109
} | 410 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_TREE_MANAGER_MAP_H_
#define UI_ACCESSIBILITY_AX_TREE_MANAGER_MAP_H_
#include <unordered_map>
#include "ax_tree_id.h"
#include "ax_tree_manager.h"
#include "base/no_destructor.h"
namespace ui {
// This class manages AXTreeManager instances. It is a singleton wrapper
// around a std::unordered_map. AXTreeID's are used as the key for the map.
// Since AXTreeID's might refer to AXTreeIDUnknown, callers should not expect
// AXTreeIDUnknown to map to a particular AXTreeManager.
class AX_EXPORT AXTreeManagerMap {
public:
AXTreeManagerMap();
~AXTreeManagerMap();
static AXTreeManagerMap& GetInstance();
void AddTreeManager(AXTreeID tree_id, AXTreeManager* manager);
void RemoveTreeManager(AXTreeID tree_id);
AXTreeManager* GetManager(AXTreeID tree_id);
// If the child of the provided parent node exists in a separate child tree,
// return the tree manager for that child tree. Otherwise, return nullptr.
AXTreeManager* GetManagerForChildTree(const AXNode& parent_node);
private:
std::unordered_map<AXTreeID, AXTreeManager*, AXTreeIDHash> map_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_TREE_MANAGER_MAP_H_
| engine/third_party/accessibility/ax/ax_tree_manager_map.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_manager_map.h",
"repo_id": "engine",
"token_count": 450
} | 411 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_BASE_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_BASE_H_
#include <cstdint>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "ax_platform_node_delegate.h"
namespace ui {
// Base implementation of AXPlatformNodeDelegate where all functions
// return a default value. Useful for classes that want to implement
// AXPlatformNodeDelegate but don't need to override much of its
// behavior.
class AX_EXPORT AXPlatformNodeDelegateBase : public AXPlatformNodeDelegate {
public:
AXPlatformNodeDelegateBase();
~AXPlatformNodeDelegateBase() override;
// Get the accessibility data that should be exposed for this node.
// Virtually all of the information is obtained from this structure
// (role, state, name, cursor position, etc.) - the rest of this interface
// is mostly to implement support for walking the accessibility tree.
const AXNodeData& GetData() const override;
// Get the accessibility tree data for this node.
const AXTreeData& GetTreeData() const override;
std::u16string GetInnerText() const override;
const AXTree::Selection GetUnignoredSelection() const override;
// Creates a text position rooted at this object.
AXNodePosition::AXPositionInstance CreateTextPositionAt(
int offset) const override;
// See comments in AXPlatformNodeDelegate.
gfx::NativeViewAccessible GetNSWindow() override;
// Get the node for this delegate, which may be an AXPlatformNode or it may
// be a native accessible object implemented by another class.
gfx::NativeViewAccessible GetNativeViewAccessible() override;
// Get the parent of the node, which may be an AXPlatformNode or it may
// be a native accessible object implemented by another class.
gfx::NativeViewAccessible GetParent() override;
// If this object is exposed to the platform's accessibility layer, returns
// this object. Otherwise, returns the platform leaf or lowest unignored
// ancestor under which this object is found.
//
// (An ignored node means that the node should not be exposed to platform
// APIs: See `IsIgnored`.)
gfx::NativeViewAccessible GetLowestPlatformAncestor() const override;
// Get the index in parent. Typically this is the AXNode's index_in_parent_.
int GetIndexInParent() override;
// Get the number of children of this node.
int GetChildCount() const override;
// Get the child of a node given a 0-based index.
gfx::NativeViewAccessible ChildAtIndex(int index) override;
// Returns true if it has a modal dialog.
bool HasModalDialog() const override;
gfx::NativeViewAccessible GetFirstChild() override;
gfx::NativeViewAccessible GetLastChild() override;
gfx::NativeViewAccessible GetNextSibling() override;
gfx::NativeViewAccessible GetPreviousSibling() override;
bool IsChildOfLeaf() const override;
bool IsChildOfPlainTextField() const override;
bool IsLeaf() const override;
bool IsToplevelBrowserWindow() override;
gfx::NativeViewAccessible GetClosestPlatformObject() const override;
class ChildIteratorBase : public ChildIterator {
public:
ChildIteratorBase(AXPlatformNodeDelegateBase* parent, int index);
ChildIteratorBase(const ChildIteratorBase& it);
~ChildIteratorBase() override = default;
bool operator==(const ChildIterator& rhs) const override;
bool operator!=(const ChildIterator& rhs) const override;
void operator++() override;
void operator++(int) override;
void operator--() override;
void operator--(int) override;
gfx::NativeViewAccessible GetNativeViewAccessible() const override;
int GetIndexInParent() const override;
AXPlatformNodeDelegate& operator*() const override;
AXPlatformNodeDelegate* operator->() const override;
private:
int index_;
AXPlatformNodeDelegateBase* parent_;
};
std::unique_ptr<AXPlatformNodeDelegate::ChildIterator> ChildrenBegin()
override;
std::unique_ptr<AXPlatformNodeDelegate::ChildIterator> ChildrenEnd() override;
std::string GetName() const override;
std::u16string GetHypertext() const override;
bool SetHypertextSelection(int start_offset, int end_offset) override;
TextAttributeMap ComputeTextAttributeMap(
const TextAttributeList& default_attributes) const override;
std::string GetInheritedFontFamilyName() const override;
gfx::Rect GetBoundsRect(const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const override;
gfx::Rect GetHypertextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const override;
gfx::Rect GetInnerTextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const override;
// Derivative utils for AXPlatformNodeDelegate::GetBoundsRect
gfx::Rect GetClippedScreenBoundsRect(
AXOffscreenResult* offscreen_result = nullptr) const override;
gfx::Rect GetUnclippedScreenBoundsRect(
AXOffscreenResult* offscreen_result = nullptr) const;
// Do a *synchronous* hit test of the given location in global screen physical
// pixel coordinates, and the node within this node's subtree (inclusive)
// that's hit, if any.
//
// If the result is anything other than this object or NULL, it will be
// hit tested again recursively - that allows hit testing to work across
// implementation classes. It's okay to take advantage of this and return
// only an immediate child and not the deepest descendant.
//
// This function is mainly used by accessibility debugging software.
// Platforms with touch accessibility use a different asynchronous interface.
gfx::NativeViewAccessible HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const override;
// Return the node within this node's subtree (inclusive) that currently
// has focus.
gfx::NativeViewAccessible GetFocus() override;
// Get whether this node is offscreen.
bool IsOffscreen() const override;
// Get whether this node is a minimized window.
bool IsMinimized() const override;
bool IsText() const override;
// Get whether this node is in web content.
bool IsWebContent() const override;
// Returns true if the caret or selection is visible on this object.
bool HasVisibleCaretOrSelection() const override;
// Get another node from this same tree.
AXPlatformNode* GetFromNodeID(int32_t id) override;
// Get a node from a different tree using a tree ID and node ID.
// Note that this is only guaranteed to work if the other tree is of the
// same type, i.e. it won't work between web and views or vice-versa.
AXPlatformNode* GetFromTreeIDAndNodeID(const ui::AXTreeID& ax_tree_id,
int32_t id) override;
// Given a node ID attribute (one where IsNodeIdIntAttribute is true), return
// a target nodes for which this delegate's node has that relationship
// attribute or NULL if there is no such relationship.
AXPlatformNode* GetTargetNodeForRelation(
ax::mojom::IntAttribute attr) override;
// Given a node ID attribute (one where IsNodeIdIntListAttribute is true),
// return a vector of all target nodes for which this delegate's node has that
// relationship attribute.
std::vector<AXPlatformNode*> GetTargetNodesForRelation(
ax::mojom::IntListAttribute attr) override;
// Given a node ID attribute (one where IsNodeIdIntAttribute is true), return
// a set of all source nodes that have that relationship attribute between
// them and this delegate's node.
std::set<AXPlatformNode*> GetReverseRelations(
ax::mojom::IntAttribute attr) override;
// Given a node ID list attribute (one where IsNodeIdIntListAttribute is
// true) return a set of all source nodes that have that relationship
// attribute between them and this delegate's node.
std::set<AXPlatformNode*> GetReverseRelations(
ax::mojom::IntListAttribute attr) override;
std::u16string GetAuthorUniqueId() const override;
const AXUniqueId& GetUniqueId() const override;
std::optional<int> FindTextBoundary(
ax::mojom::TextBoundary boundary,
int offset,
ax::mojom::MoveDirection direction,
ax::mojom::TextAffinity affinity) const override;
const std::vector<gfx::NativeViewAccessible> GetUIADescendants()
const override;
std::string GetLanguage() const override;
//
// Tables. All of these should be called on a node that's a table-like
// role, otherwise they return nullopt.
//
bool IsTable() const override;
std::optional<int> GetTableColCount() const override;
std::optional<int> GetTableRowCount() const override;
std::optional<int> GetTableAriaColCount() const override;
std::optional<int> GetTableAriaRowCount() const override;
std::optional<int> GetTableCellCount() const override;
std::optional<bool> GetTableHasColumnOrRowHeaderNode() const override;
std::vector<int32_t> GetColHeaderNodeIds() const override;
std::vector<int32_t> GetColHeaderNodeIds(int col_index) const override;
std::vector<int32_t> GetRowHeaderNodeIds() const override;
std::vector<int32_t> GetRowHeaderNodeIds(int row_index) const override;
AXPlatformNode* GetTableCaption() const override;
// Table row-like nodes.
bool IsTableRow() const override;
std::optional<int> GetTableRowRowIndex() const override;
// Table cell-like nodes.
bool IsTableCellOrHeader() const override;
std::optional<int> GetTableCellIndex() const override;
std::optional<int> GetTableCellColIndex() const override;
std::optional<int> GetTableCellRowIndex() const override;
std::optional<int> GetTableCellColSpan() const override;
std::optional<int> GetTableCellRowSpan() const override;
std::optional<int> GetTableCellAriaColIndex() const override;
std::optional<int> GetTableCellAriaRowIndex() const override;
std::optional<int32_t> GetCellId(int row_index, int col_index) const override;
std::optional<int32_t> CellIndexToId(int cell_index) const override;
// Helper methods to check if a cell is an ARIA-1.1+ 'cell' or 'gridcell'
bool IsCellOrHeaderOfARIATable() const override;
bool IsCellOrHeaderOfARIAGrid() const override;
// Ordered-set-like and item-like nodes.
bool IsOrderedSetItem() const override;
bool IsOrderedSet() const override;
std::optional<int> GetPosInSet() const override;
std::optional<int> GetSetSize() const override;
//
// Events.
//
// Return the platform-native GUI object that should be used as a target
// for accessibility events.
gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override;
//
// Actions.
//
// Perform an accessibility action, switching on the ax::mojom::Action
// provided in |data|.
bool AccessibilityPerformAction(const AXActionData& data) override;
//
// Localized strings.
//
std::u16string GetLocalizedStringForImageAnnotationStatus(
ax::mojom::ImageAnnotationStatus status) const override;
std::u16string GetLocalizedRoleDescriptionForUnlabeledImage() const override;
std::u16string GetLocalizedStringForLandmarkType() const override;
std::u16string GetLocalizedStringForRoleDescription() const override;
std::u16string GetStyleNameAttributeAsLocalizedString() const override;
//
// Testing.
//
// Accessibility objects can have the "hot tracked" state set when
// the mouse is hovering over them, but this makes tests flaky because
// the test behaves differently when the mouse happens to be over an
// element. The default value should be falses if not in testing mode.
bool ShouldIgnoreHoveredStateForTesting() override;
protected:
std::string SubtreeToStringHelper(size_t level) override;
// Given a list of node ids, return the nodes in this delegate's tree to
// which they correspond.
std::set<ui::AXPlatformNode*> GetNodesForNodeIds(
const std::set<int32_t>& ids);
AXPlatformNodeDelegate* GetParentDelegate();
private:
BASE_DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeDelegateBase);
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_BASE_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_base.h",
"repo_id": "engine",
"token_count": 3741
} | 412 |
//
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_WIN_H_
#include <atlbase.h>
#include <atlcom.h>
#include <objbase.h>
#include <oleacc.h>
#include <oleauto.h>
#include <uiautomation.h>
#include <wrl/client.h>
#include <array>
#include <map>
#include <string>
#include <vector>
#include "ax/ax_export.h"
#include "ax/platform/ax_platform_node_base.h"
#include "base/compiler_specific.h"
#include "gfx/range/range.h"
//
// Macros to use at the top of any AXPlatformNodeWin (or derived class) method
// that implements a UIA COM interface. The error code UIA_E_ELEMENTNOTAVAILABLE
// signals to the OS that the object is no longer valid and no further methods
// should be called on it.
//
#define UIA_VALIDATE_CALL() \
if (!AXPlatformNodeBase::GetDelegate()) \
return UIA_E_ELEMENTNOTAVAILABLE;
#define UIA_VALIDATE_CALL_1_ARG(arg) \
if (!AXPlatformNodeBase::GetDelegate()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
if (!arg) \
return E_INVALIDARG; \
*arg = {};
namespace base {
namespace win {
class VariantVector;
} // namespace win
} // namespace base
namespace ui {
class AXPlatformNodeWin;
// TODO(nektar): Remove multithread superclass since we don't support it.
class AX_EXPORT __declspec(uuid("26f5641a-246d-457b-a96d-07f3fae6acf2"))
AXPlatformNodeWin : public CComObjectRootEx<CComMultiThreadModel>,
public IDispatchImpl<IAccessible>,
public IExpandCollapseProvider,
public IGridItemProvider,
public IGridProvider,
public IInvokeProvider,
public IRangeValueProvider,
public IRawElementProviderFragment,
public IRawElementProviderSimple2,
public IScrollItemProvider,
public IScrollProvider,
public ISelectionItemProvider,
public ISelectionProvider,
public IServiceProvider,
public ITableItemProvider,
public ITableProvider,
public IToggleProvider,
public IValueProvider,
public IWindowProvider,
public AXPlatformNodeBase {
using IDispatchImpl::Invoke;
public:
BEGIN_COM_MAP(AXPlatformNodeWin)
// TODO(nektar): Find a way to remove the following entry because it's not
// an interface.
COM_INTERFACE_ENTRY(AXPlatformNodeWin)
COM_INTERFACE_ENTRY(IAccessible)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(IExpandCollapseProvider)
COM_INTERFACE_ENTRY(IGridItemProvider)
COM_INTERFACE_ENTRY(IGridProvider)
COM_INTERFACE_ENTRY(IInvokeProvider)
COM_INTERFACE_ENTRY(IRangeValueProvider)
COM_INTERFACE_ENTRY(IRawElementProviderFragment)
COM_INTERFACE_ENTRY(IRawElementProviderSimple)
COM_INTERFACE_ENTRY(IRawElementProviderSimple2)
COM_INTERFACE_ENTRY(IScrollItemProvider)
COM_INTERFACE_ENTRY(IScrollProvider)
COM_INTERFACE_ENTRY(ISelectionItemProvider)
COM_INTERFACE_ENTRY(ISelectionProvider)
COM_INTERFACE_ENTRY(ITableItemProvider)
COM_INTERFACE_ENTRY(ITableProvider)
COM_INTERFACE_ENTRY(IToggleProvider)
COM_INTERFACE_ENTRY(IValueProvider)
COM_INTERFACE_ENTRY(IWindowProvider)
COM_INTERFACE_ENTRY(IServiceProvider)
END_COM_MAP()
~AXPlatformNodeWin() override;
void Init(AXPlatformNodeDelegate* delegate) override;
// AXPlatformNode overrides.
gfx::NativeViewAccessible GetNativeViewAccessible() override;
void NotifyAccessibilityEvent(ax::mojom::Event event_type) override;
// AXPlatformNodeBase overrides.
void Destroy() override;
std::u16string GetValue() const override;
bool IsPlatformCheckable() const override;
//
// IAccessible methods.
//
// Retrieves the child element or child object at a given point on the screen.
IFACEMETHODIMP accHitTest(LONG screen_physical_pixel_x,
LONG screen_physical_pixel_y,
VARIANT* child) override;
// Performs the object's default action.
IFACEMETHODIMP accDoDefaultAction(VARIANT var_id) override;
// Retrieves the specified object's current screen location.
IFACEMETHODIMP accLocation(LONG* physical_pixel_left,
LONG* physical_pixel_top,
LONG* width,
LONG* height,
VARIANT var_id) override;
// Traverses to another UI element and retrieves the object.
IFACEMETHODIMP accNavigate(LONG nav_dir,
VARIANT start,
VARIANT* end) override;
// Retrieves an IDispatch interface pointer for the specified child.
IFACEMETHODIMP get_accChild(VARIANT var_child,
IDispatch** disp_child) override;
// Retrieves the number of accessible children.
IFACEMETHODIMP get_accChildCount(LONG* child_count) override;
// Retrieves a string that describes the object's default action.
IFACEMETHODIMP get_accDefaultAction(VARIANT var_id,
BSTR* default_action) override;
// Retrieves the tooltip description.
IFACEMETHODIMP get_accDescription(VARIANT var_id, BSTR* desc) override;
// Retrieves the object that has the keyboard focus.
IFACEMETHODIMP get_accFocus(VARIANT* focus_child) override;
// Retrieves the specified object's shortcut.
IFACEMETHODIMP get_accKeyboardShortcut(VARIANT var_id,
BSTR* access_key) override;
// Retrieves the name of the specified object.
IFACEMETHODIMP get_accName(VARIANT var_id, BSTR* name) override;
// Retrieves the IDispatch interface of the object's parent.
IFACEMETHODIMP get_accParent(IDispatch** disp_parent) override;
// Retrieves information describing the role of the specified object.
IFACEMETHODIMP get_accRole(VARIANT var_id, VARIANT* role) override;
// Retrieves the current state of the specified object.
IFACEMETHODIMP get_accState(VARIANT var_id, VARIANT* state) override;
// Gets the help string for the specified object.
IFACEMETHODIMP get_accHelp(VARIANT var_id, BSTR* help) override;
// Retrieve or set the string value associated with the specified object.
// Setting the value is not typically used by screen readers, but it's
// used frequently by automation software.
IFACEMETHODIMP get_accValue(VARIANT var_id, BSTR* value) override;
IFACEMETHODIMP put_accValue(VARIANT var_id, BSTR new_value) override;
// IAccessible methods not implemented.
IFACEMETHODIMP get_accSelection(VARIANT* selected) override;
IFACEMETHODIMP accSelect(LONG flags_sel, VARIANT var_id) override;
IFACEMETHODIMP get_accHelpTopic(BSTR* help_file,
VARIANT var_id,
LONG* topic_id) override;
IFACEMETHODIMP put_accName(VARIANT var_id, BSTR put_name) override;
//
// IExpandCollapseProvider methods.
//
IFACEMETHODIMP Collapse() override;
IFACEMETHODIMP Expand() override;
IFACEMETHODIMP get_ExpandCollapseState(ExpandCollapseState* result) override;
//
// IGridItemProvider methods.
//
IFACEMETHODIMP get_Column(int* result) override;
IFACEMETHODIMP get_ColumnSpan(int* result) override;
IFACEMETHODIMP get_ContainingGrid(
IRawElementProviderSimple** result) override;
IFACEMETHODIMP get_Row(int* result) override;
IFACEMETHODIMP get_RowSpan(int* result) override;
//
// IGridProvider methods.
//
IFACEMETHODIMP GetItem(int row,
int column,
IRawElementProviderSimple** result) override;
IFACEMETHODIMP get_RowCount(int* result) override;
IFACEMETHODIMP get_ColumnCount(int* result) override;
//
// IInvokeProvider methods.
//
IFACEMETHODIMP Invoke() override;
//
// IScrollItemProvider methods.
//
IFACEMETHODIMP ScrollIntoView() override;
//
// IScrollProvider methods.
//
IFACEMETHODIMP Scroll(ScrollAmount horizontal_amount,
ScrollAmount vertical_amount) override;
IFACEMETHODIMP SetScrollPercent(double horizontal_percent,
double vertical_percent) override;
IFACEMETHODIMP get_HorizontallyScrollable(BOOL* result) override;
IFACEMETHODIMP get_HorizontalScrollPercent(double* result) override;
// Horizontal size of the viewable region as a percentage of the total content
// area.
IFACEMETHODIMP get_HorizontalViewSize(double* result) override;
IFACEMETHODIMP get_VerticallyScrollable(BOOL* result) override;
IFACEMETHODIMP get_VerticalScrollPercent(double* result) override;
// Vertical size of the viewable region as a percentage of the total content
// area.
IFACEMETHODIMP get_VerticalViewSize(double* result) override;
//
// ISelectionItemProvider methods.
//
IFACEMETHODIMP AddToSelection() override;
IFACEMETHODIMP RemoveFromSelection() override;
IFACEMETHODIMP Select() override;
IFACEMETHODIMP get_IsSelected(BOOL* result) override;
IFACEMETHODIMP get_SelectionContainer(
IRawElementProviderSimple** result) override;
//
// ISelectionProvider methods.
//
IFACEMETHODIMP GetSelection(SAFEARRAY** result) override;
IFACEMETHODIMP get_CanSelectMultiple(BOOL* result) override;
IFACEMETHODIMP get_IsSelectionRequired(BOOL* result) override;
//
// ITableItemProvider methods.
//
IFACEMETHODIMP GetColumnHeaderItems(SAFEARRAY** result) override;
IFACEMETHODIMP GetRowHeaderItems(SAFEARRAY** result) override;
//
// ITableProvider methods.
//
IFACEMETHODIMP GetColumnHeaders(SAFEARRAY** result) override;
IFACEMETHODIMP GetRowHeaders(SAFEARRAY** result) override;
IFACEMETHODIMP get_RowOrColumnMajor(RowOrColumnMajor* result) override;
//
// IToggleProvider methods.
//
IFACEMETHODIMP Toggle() override;
IFACEMETHODIMP get_ToggleState(ToggleState* result) override;
//
// IValueProvider methods.
//
IFACEMETHODIMP SetValue(LPCWSTR val) override;
IFACEMETHODIMP get_IsReadOnly(BOOL* result) override;
IFACEMETHODIMP get_Value(BSTR* result) override;
//
// IWindowProvider methods.
//
IFACEMETHODIMP SetVisualState(WindowVisualState window_visual_state) override;
IFACEMETHODIMP Close() override;
IFACEMETHODIMP WaitForInputIdle(int milliseconds, BOOL* result) override;
IFACEMETHODIMP get_CanMaximize(BOOL* result) override;
IFACEMETHODIMP get_CanMinimize(BOOL* result) override;
IFACEMETHODIMP get_IsModal(BOOL* result) override;
IFACEMETHODIMP get_WindowVisualState(WindowVisualState* result) override;
IFACEMETHODIMP get_WindowInteractionState(
WindowInteractionState* result) override;
IFACEMETHODIMP get_IsTopmost(BOOL* result) override;
//
// IRangeValueProvider methods.
//
IFACEMETHODIMP SetValue(double val) override;
IFACEMETHODIMP get_LargeChange(double* result) override;
IFACEMETHODIMP get_Maximum(double* result) override;
IFACEMETHODIMP get_Minimum(double* result) override;
IFACEMETHODIMP get_SmallChange(double* result) override;
IFACEMETHODIMP get_Value(double* result) override;
//
// IRawElementProviderFragment methods.
//
IFACEMETHODIMP Navigate(
NavigateDirection direction,
IRawElementProviderFragment** element_provider) override;
IFACEMETHODIMP GetRuntimeId(SAFEARRAY** runtime_id) override;
IFACEMETHODIMP get_BoundingRectangle(
UiaRect* screen_physical_pixel_bounds) override;
IFACEMETHODIMP GetEmbeddedFragmentRoots(
SAFEARRAY** embedded_fragment_roots) override;
IFACEMETHODIMP SetFocus() override;
IFACEMETHODIMP get_FragmentRoot(
IRawElementProviderFragmentRoot** fragment_root) override;
//
// IRawElementProviderSimple methods.
//
IFACEMETHODIMP GetPatternProvider(PATTERNID pattern_id,
IUnknown** result) override;
IFACEMETHODIMP GetPropertyValue(PROPERTYID property_id,
VARIANT* result) override;
IFACEMETHODIMP
get_ProviderOptions(enum ProviderOptions* ret) override;
IFACEMETHODIMP
get_HostRawElementProvider(IRawElementProviderSimple** provider) override;
//
// IRawElementProviderSimple2 methods.
//
IFACEMETHODIMP ShowContextMenu() override;
//
// IServiceProvider methods.
//
IFACEMETHODIMP QueryService(REFGUID guidService,
REFIID riid,
void** object) override;
//
// Methods used by the ATL COM map.
//
// Called by BEGIN_COM_MAP() / END_COM_MAP().
static STDMETHODIMP InternalQueryInterface(void* this_ptr,
const _ATL_INTMAP_ENTRY* entries,
REFIID riid,
void** object);
// Support method for ITextRangeProvider::GetAttributeValue.
// If either |start_offset| or |end_offset| are not provided then the
// endpoint is treated as the start or end of the node respectively.
HRESULT GetTextAttributeValue(TEXTATTRIBUTEID attribute_id,
const std::optional<int>& start_offset,
const std::optional<int>& end_offset,
base::win::VariantVector* result);
// IRawElementProviderSimple support method.
bool IsPatternProviderSupported(PATTERNID pattern_id);
// Prefer GetPatternProviderImpl when calling internally. We should avoid
// calling external APIs internally as it will cause the histograms to become
// innaccurate.
HRESULT GetPatternProviderImpl(PATTERNID pattern_id, IUnknown** result);
// Prefer GetPropertyValueImpl when calling internally. We should avoid
// calling external APIs internally as it will cause the histograms to become
// innaccurate.
HRESULT GetPropertyValueImpl(PROPERTYID property_id, VARIANT* result);
// Helper to return the runtime id (without going through a SAFEARRAY)
using RuntimeIdArray = std::array<int, 2>;
void GetRuntimeIdArray(RuntimeIdArray& runtime_id);
// Updates the active composition range and fires UIA text edit event about
// composition (active or committed)
void OnActiveComposition(const gfx::Range& range,
const std::u16string& active_composition_text,
bool is_composition_committed);
// Returns true if there is an active composition
bool HasActiveComposition() const;
// Returns the start/end offsets of the active composition
gfx::Range GetActiveCompositionOffsets() const;
// Helper to recursively find live-regions and fire a change event on them
void FireLiveRegionChangeRecursive();
// Returns the parent node that makes this node inaccessible.
AXPlatformNodeWin* GetLowestAccessibleElement();
// Returns the first |IsTextOnlyObject| descendant using
// depth-first pre-order traversal.
AXPlatformNodeWin* GetFirstTextOnlyDescendant();
// Convert a mojo event to an MSAA event. Exposed for testing.
static std::optional<DWORD> MojoEventToMSAAEvent(ax::mojom::Event event);
// Convert a mojo event to a UIA event. Exposed for testing.
static std::optional<EVENTID> MojoEventToUIAEvent(ax::mojom::Event event);
// Convert a mojo event to a UIA property id. Exposed for testing.
std::optional<PROPERTYID> MojoEventToUIAProperty(ax::mojom::Event event);
// |AXPlatformNodeBase|
bool IsDescendantOf(AXPlatformNode* ancestor) const override;
protected:
// This is hard-coded; all products based on the Chromium engine will have the
// same framework name, so that assistive technology can detect any
// Chromium-based product.
static constexpr const wchar_t* FRAMEWORK_ID = L"Chrome";
AXPlatformNodeWin();
int MSAAState() const;
int MSAARole();
std::u16string UIAAriaRole();
std::u16string ComputeUIAProperties();
LONG ComputeUIAControlType();
AXPlatformNodeWin* ComputeUIALabeledBy();
bool CanHaveUIALabeledBy();
bool IsNameExposed() const;
bool IsUIAControl() const;
std::optional<LONG> ComputeUIALandmarkType() const;
bool IsInaccessibleDueToAncestor() const;
bool ShouldHideChildrenForUIA() const;
ExpandCollapseState ComputeExpandCollapseState() const;
// AXPlatformNodeBase overrides.
void Dispose() override;
AXHypertext old_hypertext_;
// These protected methods are still used by BrowserAccessibilityComWin. At
// some point post conversion, we can probably move these to be private
// methods.
// A helper to add the given string value to |attributes|.
void AddAttributeToList(const char* name,
const char* value,
PlatformAttributeList* attributes) override;
private:
bool IsWebAreaForPresentationalIframe();
bool ShouldNodeHaveFocusableState(const AXNodeData& data) const;
// Get the value attribute as a Bstr, this means something different depending
// on the type of element being queried. (e.g. kColorWell uses kColorValue).
static BSTR GetValueAttributeAsBstr(AXPlatformNodeWin* target);
HRESULT GetStringAttributeAsBstr(ax::mojom::StringAttribute attribute,
BSTR* value_bstr) const;
HRESULT GetNameAsBstr(BSTR* value_bstr) const;
// Escapes characters in string attributes as required by the UIA Aria
// Property Spec. It's okay for input to be the same as output.
static void SanitizeStringAttributeForUIAAriaProperty(
const std::u16string& input,
std::u16string* output);
// If the string attribute |attribute| is present, add its value as a
// UIA AriaProperties Property with the name |uia_aria_property|.
void StringAttributeToUIAAriaProperty(std::vector<std::u16string>& properties,
ax::mojom::StringAttribute attribute,
const char* uia_aria_property);
// If the bool attribute |attribute| is present, add its value as a
// UIA AriaProperties Property with the name |uia_aria_property|.
void BoolAttributeToUIAAriaProperty(std::vector<std::u16string>& properties,
ax::mojom::BoolAttribute attribute,
const char* uia_aria_property);
// If the int attribute |attribute| is present, add its value as a
// UIA AriaProperties Property with the name |uia_aria_property|.
void IntAttributeToUIAAriaProperty(std::vector<std::u16string>& properties,
ax::mojom::IntAttribute attribute,
const char* uia_aria_property);
// If the float attribute |attribute| is present, add its value as a
// UIA AriaProperties Property with the name |uia_aria_property|.
void FloatAttributeToUIAAriaProperty(std::vector<std::u16string>& properties,
ax::mojom::FloatAttribute attribute,
const char* uia_aria_property);
// If the state |state| exists, set the
// UIA AriaProperties Property with the name |uia_aria_property| to "true".
// Otherwise set the AriaProperties Property to "false".
void StateToUIAAriaProperty(std::vector<std::u16string>& properties,
ax::mojom::State state,
const char* uia_aria_property);
// If the Html attribute |html_attribute_name| is present, add its value as a
// UIA AriaProperties Property with the name |uia_aria_property|.
void HtmlAttributeToUIAAriaProperty(std::vector<std::u16string>& properties,
const char* html_attribute_name,
const char* uia_aria_property);
// If the IntList attribute |attribute| is present, return an array
// of automation elements referenced by the ids in the
// IntList attribute. Otherwise return an empty array.
// The function will skip over any ids that cannot be resolved.
SAFEARRAY* CreateUIAElementsArrayForRelation(
const ax::mojom::IntListAttribute& attribute);
// Return an array of automation elements based on the attribute
// IntList::kControlsIds for web content and IntAttribute::kViewPopupId. These
// two attributes denote the controllees, web content elements and view popup
// element respectively.
// The function will skip over any ids that cannot be resolved.
SAFEARRAY* CreateUIAControllerForArray();
// Return an unordered array of automation elements which reference this node
// for the given attribute.
SAFEARRAY* CreateUIAElementsArrayForReverseRelation(
const ax::mojom::IntListAttribute& attribute);
// Return a vector of AXPlatformNodeWin referenced by the ids in function
// argument. The function will skip over any ids that cannot be resolved as
// valid relation target.
std::vector<AXPlatformNodeWin*> CreatePlatformNodeVectorFromRelationIdVector(
std::vector<int32_t>& relation_id_list);
// Create a safearray of automation elements from a vector of
// AXPlatformNodeWin.
// The caller should validate that all of the given ax platform nodes are
// valid relation targets.
SAFEARRAY* CreateUIAElementsSafeArray(
std::vector<AXPlatformNodeWin*>& platform_node_list);
// Return an array that contains the center x, y coordinates of the
// clickable point.
SAFEARRAY* CreateClickablePointArray();
// Returns the scroll offsets to which UI Automation should scroll an
// accessible object, given the horizontal and vertical scroll amounts.
gfx::Vector2d CalculateUIAScrollPoint(
const ScrollAmount horizontal_amount,
const ScrollAmount vertical_amount) const;
void AddAlertTarget();
void RemoveAlertTarget();
// Enum used to specify whether IAccessibleText is requesting text
// At, Before, or After a specified offset.
enum class TextOffsetType { kAtOffset, kBeforeOffset, kAfterOffset };
// Many MSAA methods take a var_id parameter indicating that the operation
// should be performed on a particular child ID, rather than this object.
// This method tries to figure out the target object from |var_id| and
// returns a pointer to the target object if it exists, otherwise nullptr.
// Does not return a new reference.
AXPlatformNodeWin* GetTargetFromChildID(const VARIANT& var_id);
// Returns true if this node is in a treegrid.
bool IsInTreeGrid();
// Helper method for returning selected indicies. It is expected that the
// caller ensures that the input has been validated.
HRESULT AllocateComArrayFromVector(std::vector<LONG>& results,
LONG max,
LONG** selected,
LONG* n_selected);
// Helper method for mutating the ISelectionItemProvider selected state
HRESULT ISelectionItemProviderSetSelected(bool selected) const;
// Helper method getting the selected status.
bool ISelectionItemProviderIsSelected() const;
//
// Getters for UIA GetTextAttributeValue
//
// Computes the AnnotationTypes Attribute for the current node.
HRESULT GetAnnotationTypesAttribute(const std::optional<int>& start_offset,
const std::optional<int>& end_offset,
base::win::VariantVector* result);
// Lookup the LCID for the language this node is using.
// Returns base::nullopt if there was an error.
std::optional<LCID> GetCultureAttributeAsLCID() const;
// Converts an int attribute to a COLORREF
COLORREF GetIntAttributeAsCOLORREF(ax::mojom::IntAttribute attribute) const;
// Converts the ListStyle to UIA BulletStyle
BulletStyle ComputeUIABulletStyle() const;
// Helper to get the UIA StyleId enumeration for this node
LONG ComputeUIAStyleId() const;
// Convert mojom TextAlign to UIA HorizontalTextAlignment enumeration
static std::optional<HorizontalTextAlignment>
AXTextAlignToUIAHorizontalTextAlignment(ax::mojom::TextAlign text_align);
// Converts IntAttribute::kHierarchicalLevel to UIA StyleId enumeration
static LONG AXHierarchicalLevelToUIAStyleId(int32_t hierarchical_level);
// Converts a ListStyle to UIA StyleId enumeration
static LONG AXListStyleToUIAStyleId(ax::mojom::ListStyle list_style);
// Convert mojom TextDirection to UIA FlowDirections enumeration
static FlowDirections TextDirectionToFlowDirections(
ax::mojom::WritingDirection);
// Helper method for |GetMarkerTypeFromRange| which aggregates all
// of the ranges for |marker_type| attached to |node|.
static void AggregateRangesForMarkerType(
AXPlatformNodeBase* node,
ax::mojom::MarkerType marker_type,
int offset_ranges_amount,
std::vector<std::pair<int, int>>* ranges);
enum class MarkerTypeRangeResult {
// The MarkerType does not overlap the range.
kNone,
// The MarkerType overlaps the entire range.
kMatch,
// The MarkerType partially overlaps the range.
kMixed,
};
// Determine if a text range overlaps a |marker_type|, and whether
// the overlap is a partial or complete match.
MarkerTypeRangeResult GetMarkerTypeFromRange(
const std::optional<int>& start_offset,
const std::optional<int>& end_offset,
ax::mojom::MarkerType marker_type);
bool IsAncestorComboBox();
bool IsPlaceholderText() const;
// Helper method for getting the horizontal scroll percent.
double GetHorizontalScrollPercent();
// Helper method for getting the vertical scroll percent.
double GetVerticalScrollPercent();
// Helper to get the UIA FontName for this node as a BSTR.
BSTR GetFontNameAttributeAsBSTR() const;
// Helper to get the UIA StyleName for this node as a BSTR.
BSTR GetStyleNameAttributeAsBSTR() const;
// Gets the TextDecorationLineStyle based on the provided int attribute.
TextDecorationLineStyle GetUIATextDecorationStyle(
const ax::mojom::IntAttribute int_attribute) const;
// IRawElementProviderSimple support methods.
using PatternProviderFactoryMethod = void (*)(AXPlatformNodeWin*, IUnknown**);
PatternProviderFactoryMethod GetPatternProviderFactoryMethod(
PATTERNID pattern_id);
// Fires UIA text edit event about composition (active or committed)
void FireUiaTextEditTextChangedEvent(
const gfx::Range& range,
const std::u16string& active_composition_text,
bool is_composition_committed);
// Return true if the given element is valid enough to be returned as a value
// for a UIA relation property (e.g. ControllerFor).
static bool IsValidUiaRelationTarget(AXPlatformNode* ax_platform_node);
// Start and end offsets of an active composition
gfx::Range active_composition_range_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_WIN_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node_win.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_win.h",
"repo_id": "engine",
"token_count": 9858
} | 413 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_TEST_AX_NODE_HELPER_H_
#define UI_ACCESSIBILITY_TEST_AX_NODE_HELPER_H_
#include "ax_clipping_behavior.h"
#include "ax_coordinate_system.h"
#include "ax_node.h"
#include "ax_offscreen_result.h"
#include "ax_tree.h"
namespace ui {
// For testing, a TestAXNodeHelper wraps an AXNode. This is a simple
// version of TestAXNodeWrapper.
class TestAXNodeHelper {
public:
// Create TestAXNodeHelper instances on-demand from an AXTree and AXNode.
static TestAXNodeHelper* GetOrCreate(AXTree* tree, AXNode* node);
~TestAXNodeHelper();
gfx::Rect GetBoundsRect(const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const;
gfx::Rect GetInnerTextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const;
private:
TestAXNodeHelper(AXTree* tree, AXNode* node);
int InternalChildCount() const;
TestAXNodeHelper* InternalGetChild(int index) const;
const AXNodeData& GetData() const;
gfx::RectF GetLocation() const;
gfx::RectF GetInlineTextRect(const int start_offset,
const int end_offset) const;
AXOffscreenResult DetermineOffscreenResult(gfx::RectF bounds) const;
AXTree* tree_;
AXNode* node_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_TEST_AX_NODE_HELPER_H_
| engine/third_party/accessibility/ax/test_ax_node_helper.h/0 | {
"file_path": "engine/third_party/accessibility/ax/test_ax_node_helper.h",
"repo_id": "engine",
"token_count": 636
} | 414 |
# Copyright (c) 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This is a dependency-free, header-only, library, and it needs to stay that
# way to facilitate pulling it into various third-party projects. So, this
# file is here to protect against accidentally introducing external
# dependencies or depending on internal implementation details.
source_set("numerics") {
visibility = [ "//flutter/third_party/accessibility/*" ]
include_dirs = [ "//flutter/third_party/accessibility" ]
sources = [
"checked_math_impl.h",
"clamped_math_impl.h",
"safe_conversions_arm_impl.h",
"safe_conversions_impl.h",
"safe_math_arm_impl.h",
"safe_math_clang_gcc_impl.h",
"safe_math_shared_impl.h",
]
public = [
"checked_math.h",
"clamped_math.h",
"math_constants.h",
"ranges.h",
"safe_conversions.h",
"safe_math.h",
]
deps = [ "//flutter/third_party/accessibility/ax_build" ]
}
| engine/third_party/accessibility/base/numerics/BUILD.gn/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/BUILD.gn",
"repo_id": "engine",
"token_count": 369
} | 415 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/win/enum_variant.h"
#include <wrl/client.h>
#include <wrl/implements.h>
#include "base/win/scoped_com_initializer.h"
#include "base/win/scoped_variant.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace win {
TEST(EnumVariantTest, EmptyEnumVariant) {
ScopedCOMInitializer com_initializer;
Microsoft::WRL::ComPtr<EnumVariant> ev = Microsoft::WRL::Make<EnumVariant>(0);
Microsoft::WRL::ComPtr<IEnumVARIANT> ienumvariant;
ASSERT_TRUE(SUCCEEDED(ev->QueryInterface(IID_PPV_ARGS(&ienumvariant))));
{
base::win::ScopedVariant out_element;
ULONG out_received = 0;
EXPECT_EQ(S_FALSE, ev->Next(1, out_element.Receive(), &out_received));
EXPECT_EQ(0u, out_received);
}
EXPECT_EQ(S_FALSE, ev->Skip(1));
EXPECT_EQ(S_OK, ev->Reset());
Microsoft::WRL::ComPtr<IEnumVARIANT> ev2;
EXPECT_EQ(S_OK, ev->Clone(&ev2));
EXPECT_NE(nullptr, ev2);
EXPECT_NE(ev, ev2);
EXPECT_EQ(S_FALSE, ev2->Skip(1));
EXPECT_EQ(S_OK, ev2->Reset());
}
TEST(EnumVariantTest, SimpleEnumVariant) {
ScopedCOMInitializer com_initializer;
Microsoft::WRL::ComPtr<EnumVariant> ev = Microsoft::WRL::Make<EnumVariant>(3);
ev->ItemAt(0)->vt = VT_I4;
ev->ItemAt(0)->lVal = 10;
ev->ItemAt(1)->vt = VT_I4;
ev->ItemAt(1)->lVal = 20;
ev->ItemAt(2)->vt = VT_I4;
ev->ItemAt(2)->lVal = 30;
// Get elements one at a time from index 0 and 2.
base::win::ScopedVariant out_element_0;
ULONG out_received_0 = 0;
EXPECT_EQ(S_OK, ev->Next(1, out_element_0.Receive(), &out_received_0));
EXPECT_EQ(1u, out_received_0);
EXPECT_EQ(VT_I4, out_element_0.ptr()->vt);
EXPECT_EQ(10, out_element_0.ptr()->lVal);
EXPECT_EQ(S_OK, ev->Skip(1));
base::win::ScopedVariant out_element_2;
ULONG out_received_2 = 0;
EXPECT_EQ(S_OK, ev->Next(1, out_element_2.Receive(), &out_received_2));
EXPECT_EQ(1u, out_received_2);
EXPECT_EQ(VT_I4, out_element_2.ptr()->vt);
EXPECT_EQ(30, out_element_2.ptr()->lVal);
base::win::ScopedVariant placeholder_variant;
EXPECT_EQ(S_FALSE, ev->Next(1, placeholder_variant.Receive(), nullptr));
// Verify the reset works for the next step.
ASSERT_EQ(S_OK, ev->Reset());
// Get all elements at once.
VARIANT out_elements[3];
ULONG out_received_multiple;
for (int i = 0; i < 3; ++i)
::VariantInit(&out_elements[i]);
EXPECT_EQ(S_OK, ev->Next(3, out_elements, &out_received_multiple));
EXPECT_EQ(3u, out_received_multiple);
EXPECT_EQ(VT_I4, out_elements[0].vt);
EXPECT_EQ(10, out_elements[0].lVal);
EXPECT_EQ(VT_I4, out_elements[1].vt);
EXPECT_EQ(20, out_elements[1].lVal);
EXPECT_EQ(VT_I4, out_elements[2].vt);
EXPECT_EQ(30, out_elements[2].lVal);
for (int i = 0; i < 3; ++i)
::VariantClear(&out_elements[i]);
base::win::ScopedVariant placeholder_variant_multiple;
EXPECT_EQ(S_FALSE,
ev->Next(1, placeholder_variant_multiple.Receive(), nullptr));
}
TEST(EnumVariantTest, Clone) {
ScopedCOMInitializer com_initializer;
Microsoft::WRL::ComPtr<EnumVariant> ev = Microsoft::WRL::Make<EnumVariant>(3);
ev->ItemAt(0)->vt = VT_I4;
ev->ItemAt(0)->lVal = 10;
ev->ItemAt(1)->vt = VT_I4;
ev->ItemAt(1)->lVal = 20;
ev->ItemAt(2)->vt = VT_I4;
ev->ItemAt(2)->lVal = 30;
// Clone it.
Microsoft::WRL::ComPtr<IEnumVARIANT> ev2;
EXPECT_EQ(S_OK, ev->Clone(&ev2));
EXPECT_TRUE(ev2 != nullptr);
VARIANT out_elements[3];
for (int i = 0; i < 3; ++i)
::VariantInit(&out_elements[i]);
EXPECT_EQ(S_OK, ev2->Next(3, out_elements, nullptr));
EXPECT_EQ(VT_I4, out_elements[0].vt);
EXPECT_EQ(10, out_elements[0].lVal);
EXPECT_EQ(VT_I4, out_elements[1].vt);
EXPECT_EQ(20, out_elements[1].lVal);
EXPECT_EQ(VT_I4, out_elements[2].vt);
EXPECT_EQ(30, out_elements[2].lVal);
for (int i = 0; i < 3; ++i)
::VariantClear(&out_elements[i]);
}
} // namespace win
} // namespace base
| engine/third_party/accessibility/base/win/enum_variant_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/base/win/enum_variant_unittest.cc",
"repo_id": "engine",
"token_count": 1793
} | 416 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GEOMETRY_INSETS_H_
#define UI_GFX_GEOMETRY_INSETS_H_
#include <memory>
#include <string>
#include "gfx/gfx_export.h"
#include "insets_f.h"
#include "size.h"
namespace gfx {
class Vector2d;
// Represents the widths of the four borders or margins of an unspecified
// rectangle. An Insets stores the thickness of the top, left, bottom and right
// edges, without storing the actual size and position of the rectangle itself.
//
// This can be used to represent a space within a rectangle, by "shrinking" the
// rectangle by the inset amount on all four sides. Alternatively, it can
// represent a border that has a different thickness on each side.
class GFX_EXPORT Insets {
public:
constexpr Insets() : top_(0), left_(0), bottom_(0), right_(0) {}
constexpr explicit Insets(int all)
: top_(all),
left_(all),
bottom_(GetClampedValue(all, all)),
right_(GetClampedValue(all, all)) {}
constexpr explicit Insets(int vertical, int horizontal)
: top_(vertical),
left_(horizontal),
bottom_(GetClampedValue(vertical, vertical)),
right_(GetClampedValue(horizontal, horizontal)) {}
constexpr Insets(int top, int left, int bottom, int right)
: top_(top),
left_(left),
bottom_(GetClampedValue(top, bottom)),
right_(GetClampedValue(left, right)) {}
constexpr int top() const { return top_; }
constexpr int left() const { return left_; }
constexpr int bottom() const { return bottom_; }
constexpr int right() const { return right_; }
// Returns the total width taken up by the insets, which is the sum of the
// left and right insets.
constexpr int width() const { return left_ + right_; }
// Returns the total height taken up by the insets, which is the sum of the
// top and bottom insets.
constexpr int height() const { return top_ + bottom_; }
// Returns the sum of the left and right insets as the width, the sum of the
// top and bottom insets as the height.
constexpr Size size() const { return Size(width(), height()); }
// Returns true if the insets are empty.
bool IsEmpty() const { return width() == 0 && height() == 0; }
void set_top(int top) {
top_ = top;
bottom_ = GetClampedValue(top_, bottom_);
}
void set_left(int left) {
left_ = left;
right_ = GetClampedValue(left_, right_);
}
void set_bottom(int bottom) { bottom_ = GetClampedValue(top_, bottom); }
void set_right(int right) { right_ = GetClampedValue(left_, right); }
void Set(int top, int left, int bottom, int right) {
top_ = top;
left_ = left;
bottom_ = GetClampedValue(top_, bottom);
right_ = GetClampedValue(left_, right);
}
bool operator==(const Insets& insets) const {
return top_ == insets.top_ && left_ == insets.left_ &&
bottom_ == insets.bottom_ && right_ == insets.right_;
}
bool operator!=(const Insets& insets) const { return !(*this == insets); }
void operator+=(const Insets& insets) {
top_ = base::ClampAdd(top_, insets.top_);
left_ = base::ClampAdd(left_, insets.left_);
bottom_ = GetClampedValue(top_, base::ClampAdd(bottom_, insets.bottom_));
right_ = GetClampedValue(left_, base::ClampAdd(right_, insets.right_));
}
void operator-=(const Insets& insets) {
top_ = base::ClampSub(top_, insets.top_);
left_ = base::ClampSub(left_, insets.left_);
bottom_ = GetClampedValue(top_, base::ClampSub(bottom_, insets.bottom_));
right_ = GetClampedValue(left_, base::ClampSub(right_, insets.right_));
}
Insets operator-() const {
return Insets(-base::MakeClampedNum(top_), -base::MakeClampedNum(left_),
-base::MakeClampedNum(bottom_),
-base::MakeClampedNum(right_));
}
Insets Scale(float scale) const { return Scale(scale, scale); }
Insets Scale(float x_scale, float y_scale) const {
return Insets(static_cast<int>(base::ClampMul(top(), y_scale)),
static_cast<int>(base::ClampMul(left(), x_scale)),
static_cast<int>(base::ClampMul(bottom(), y_scale)),
static_cast<int>(base::ClampMul(right(), x_scale)));
}
// Adjusts the vertical and horizontal dimensions by the values described in
// |vector|. Offsetting insets before applying to a rectangle would be
// equivalent to offseting the rectangle then applying the insets.
Insets Offset(const gfx::Vector2d& vector) const;
operator InsetsF() const {
return InsetsF(static_cast<float>(top()), static_cast<float>(left()),
static_cast<float>(bottom()), static_cast<float>(right()));
}
// Returns a string representation of the insets.
std::string ToString() const;
private:
int top_;
int left_;
int bottom_;
int right_;
// See rect.h
// Returns true iff a+b would overflow max int.
static constexpr bool AddWouldOverflow(int a, int b) {
// In this function, GCC tries to make optimizations that would only work if
// max - a wouldn't overflow but it isn't smart enough to notice that a > 0.
// So cast everything to unsigned to avoid this. As it is guaranteed that
// max - a and b are both already positive, the cast is a noop.
//
// This is intended to be: a > 0 && max - a < b
return a > 0 && b > 0 &&
static_cast<unsigned>(std::numeric_limits<int>::max() - a) <
static_cast<unsigned>(b);
}
// Returns true iff a+b would underflow min int.
static constexpr bool AddWouldUnderflow(int a, int b) {
return a < 0 && b < 0 && std::numeric_limits<int>::min() - a > b;
}
// Clamp the right/bottom to avoid integer over/underflow in width() and
// height(). This returns the right/bottom given a top_or_left and a
// bottom_or_right.
// TODO(enne): this should probably use base::ClampAdd, but that
// function is not a constexpr.
static constexpr int GetClampedValue(int top_or_left, int bottom_or_right) {
if (AddWouldOverflow(top_or_left, bottom_or_right)) {
return std::numeric_limits<int>::max() - top_or_left;
} else if (AddWouldUnderflow(top_or_left, bottom_or_right)) {
// If |top_or_left| and |bottom_or_right| are both negative,
// adds |top_or_left| to prevent underflow by subtracting it.
return std::numeric_limits<int>::min() - top_or_left;
} else {
return bottom_or_right;
}
}
};
inline Insets operator+(Insets lhs, const Insets& rhs) {
lhs += rhs;
return lhs;
}
inline Insets operator-(Insets lhs, const Insets& rhs) {
lhs -= rhs;
return lhs;
}
} // namespace gfx
#endif // UI_GFX_GEOMETRY_INSETS_H_
| engine/third_party/accessibility/gfx/geometry/insets.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/insets.h",
"repo_id": "engine",
"token_count": 2440
} | 417 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GEOMETRY_RECT_F_H_
#define UI_GFX_GEOMETRY_RECT_F_H_
#include <iosfwd>
#include <string>
#include "ax_build/build_config.h"
#include "point_f.h"
#include "rect.h"
#include "size_f.h"
#include "vector2d_f.h"
#if defined(OS_APPLE)
typedef struct CGRect CGRect;
#endif
namespace gfx {
class InsetsF;
// A floating version of gfx::Rect.
class GFX_EXPORT RectF {
public:
constexpr RectF() = default;
constexpr RectF(float width, float height) : size_(width, height) {}
constexpr RectF(float x, float y, float width, float height)
: origin_(x, y), size_(width, height) {}
constexpr explicit RectF(const SizeF& size) : size_(size) {}
constexpr RectF(const PointF& origin, const SizeF& size) : origin_(origin), size_(size) {}
constexpr explicit RectF(const Rect& r)
: RectF(static_cast<float>(r.x()),
static_cast<float>(r.y()),
static_cast<float>(r.width()),
static_cast<float>(r.height())) {}
#if defined(OS_APPLE)
explicit RectF(const CGRect& r);
// Construct an equivalent CoreGraphics object.
CGRect ToCGRect() const;
#endif
constexpr float x() const { return origin_.x(); }
void set_x(float x) { origin_.set_x(x); }
constexpr float y() const { return origin_.y(); }
void set_y(float y) { origin_.set_y(y); }
constexpr float width() const { return size_.width(); }
void set_width(float width) { size_.set_width(width); }
constexpr float height() const { return size_.height(); }
void set_height(float height) { size_.set_height(height); }
constexpr const PointF& origin() const { return origin_; }
void set_origin(const PointF& origin) { origin_ = origin; }
constexpr const SizeF& size() const { return size_; }
void set_size(const SizeF& size) { size_ = size; }
constexpr float right() const { return x() + width(); }
constexpr float bottom() const { return y() + height(); }
constexpr PointF top_right() const { return PointF(right(), y()); }
constexpr PointF bottom_left() const { return PointF(x(), bottom()); }
constexpr PointF bottom_right() const { return PointF(right(), bottom()); }
constexpr PointF left_center() const { return PointF(x(), y() + height() / 2); }
constexpr PointF top_center() const { return PointF(x() + width() / 2, y()); }
constexpr PointF right_center() const { return PointF(right(), y() + height() / 2); }
constexpr PointF bottom_center() const { return PointF(x() + width() / 2, bottom()); }
Vector2dF OffsetFromOrigin() const { return Vector2dF(x(), y()); }
void SetRect(float x, float y, float width, float height) {
origin_.SetPoint(x, y);
size_.SetSize(width, height);
}
// Shrink the rectangle by a horizontal and vertical distance on all sides.
void Inset(float horizontal, float vertical) {
Inset(horizontal, vertical, horizontal, vertical);
}
// Shrink the rectangle by the given insets.
void Inset(const InsetsF& insets);
// Shrink the rectangle by the specified amount on each side.
void Inset(float left, float top, float right, float bottom);
// Move the rectangle by a horizontal and vertical distance.
void Offset(float horizontal, float vertical);
void Offset(const Vector2dF& distance) { Offset(distance.x(), distance.y()); }
void operator+=(const Vector2dF& offset);
void operator-=(const Vector2dF& offset);
InsetsF InsetsFrom(const RectF& inner) const;
// Returns true if the area of the rectangle is zero.
bool IsEmpty() const { return size_.IsEmpty(); }
// A rect is less than another rect if its origin is less than
// the other rect's origin. If the origins are equal, then the
// shortest rect is less than the other. If the origin and the
// height are equal, then the narrowest rect is less than.
// This comparison is required to use Rects in sets, or sorted
// vectors.
bool operator<(const RectF& other) const;
// Returns true if the point identified by point_x and point_y falls inside
// this rectangle. The point (x, y) is inside the rectangle, but the
// point (x + width, y + height) is not.
bool Contains(float point_x, float point_y) const;
// Returns true if the specified point is contained by this rectangle.
bool Contains(const PointF& point) const { return Contains(point.x(), point.y()); }
// Returns true if this rectangle contains the specified rectangle.
bool Contains(const RectF& rect) const;
// Returns true if this rectangle intersects the specified rectangle.
// An empty rectangle doesn't intersect any rectangle.
bool Intersects(const RectF& rect) const;
// Computes the intersection of this rectangle with the given rectangle.
void Intersect(const RectF& rect);
// Computes the union of this rectangle with the given rectangle. The union
// is the smallest rectangle containing both rectangles.
void Union(const RectF& rect);
// Computes the rectangle resulting from subtracting |rect| from |*this|,
// i.e. the bounding rect of |Region(*this) - Region(rect)|.
void Subtract(const RectF& rect);
// Fits as much of the receiving rectangle into the supplied rectangle as
// possible, becoming the result. For example, if the receiver had
// a x-location of 2 and a width of 4, and the supplied rectangle had
// an x-location of 0 with a width of 5, the returned rectangle would have
// an x-location of 1 with a width of 4.
void AdjustToFit(const RectF& rect);
// Returns the center of this rectangle.
PointF CenterPoint() const;
// Becomes a rectangle that has the same center point but with a size capped
// at given |size|.
void ClampToCenteredSize(const SizeF& size);
// Transpose x and y axis.
void Transpose();
// Splits |this| in two halves, |left_half| and |right_half|.
void SplitVertically(RectF* left_half, RectF* right_half) const;
// Returns true if this rectangle shares an entire edge (i.e., same width or
// same height) with the given rectangle, and the rectangles do not overlap.
bool SharesEdgeWith(const RectF& rect) const;
// Returns the manhattan distance from the rect to the point. If the point is
// inside the rect, returns 0.
float ManhattanDistanceToPoint(const PointF& point) const;
// Returns the manhattan distance between the contents of this rect and the
// contents of the given rect. That is, if the intersection of the two rects
// is non-empty then the function returns 0. If the rects share a side, it
// returns the smallest non-zero value appropriate for float.
float ManhattanInternalDistance(const RectF& rect) const;
// Scales the rectangle by |scale|.
void Scale(float scale) { Scale(scale, scale); }
void Scale(float x_scale, float y_scale) {
set_origin(ScalePoint(origin(), x_scale, y_scale));
set_size(ScaleSize(size(), x_scale, y_scale));
}
// This method reports if the RectF can be safely converted to an integer
// Rect. When it is false, some dimension of the RectF is outside the bounds
// of what an integer can represent, and converting it to a Rect will require
// clamping.
bool IsExpressibleAsRect() const;
std::string ToString() const;
private:
PointF origin_;
SizeF size_;
};
inline bool operator==(const RectF& lhs, const RectF& rhs) {
return lhs.origin() == rhs.origin() && lhs.size() == rhs.size();
}
inline bool operator!=(const RectF& lhs, const RectF& rhs) {
return !(lhs == rhs);
}
inline RectF operator+(const RectF& lhs, const Vector2dF& rhs) {
return RectF(lhs.x() + rhs.x(), lhs.y() + rhs.y(), lhs.width(), lhs.height());
}
inline RectF operator-(const RectF& lhs, const Vector2dF& rhs) {
return RectF(lhs.x() - rhs.x(), lhs.y() - rhs.y(), lhs.width(), lhs.height());
}
inline RectF operator+(const Vector2dF& lhs, const RectF& rhs) {
return rhs + lhs;
}
GFX_EXPORT RectF IntersectRects(const RectF& a, const RectF& b);
GFX_EXPORT RectF UnionRects(const RectF& a, const RectF& b);
GFX_EXPORT RectF SubtractRects(const RectF& a, const RectF& b);
inline RectF ScaleRect(const RectF& r, float x_scale, float y_scale) {
return RectF(r.x() * x_scale, r.y() * y_scale, r.width() * x_scale, r.height() * y_scale);
}
inline RectF ScaleRect(const RectF& r, float scale) {
return ScaleRect(r, scale, scale);
}
// Constructs a rectangle with |p1| and |p2| as opposite corners.
//
// This could also be thought of as "the smallest rect that contains both
// points", except that we consider points on the right/bottom edges of the
// rect to be outside the rect. So technically one or both points will not be
// contained within the rect, because they will appear on one of these edges.
GFX_EXPORT RectF BoundingRect(const PointF& p1, const PointF& p2);
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const RectF& rect, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_RECT_F_H_
| engine/third_party/accessibility/gfx/geometry/rect_f.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/rect_f.h",
"repo_id": "engine",
"token_count": 2884
} | 418 |
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GFX_EXPORT_H_
#define UI_GFX_GFX_EXPORT_H_
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(GFX_IMPLEMENTATION)
#define GFX_EXPORT __declspec(dllexport)
#else
#define GFX_EXPORT __declspec(dllimport)
#endif // defined(GFX_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(GFX_IMPLEMENTATION)
#define GFX_EXPORT __attribute__((visibility("default")))
#else
#define GFX_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define GFX_EXPORT
#endif
#endif // UI_GFX_GFX_EXPORT_H_
| engine/third_party/accessibility/gfx/gfx_export.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/gfx_export.h",
"repo_id": "engine",
"token_count": 269
} | 419 |
# 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.
if (is_ios || is_mac) {
import("//flutter/common/config.gni")
import("//flutter/testing/testing.gni")
source_set("spring_animation") {
sources = [
"spring_animation.h",
"spring_animation.mm",
]
public_configs = [ "//flutter:config" ]
}
if (enable_unittests) {
test_fixtures("spring_animation_fixtures") {
fixtures = []
}
executable("spring_animation_unittests") {
testonly = true
sources = [ "SpringAnimationTest.mm" ]
deps = [
":spring_animation",
":spring_animation_fixtures",
"//flutter/testing",
]
public_configs = [ "//flutter:config" ]
}
}
}
| engine/third_party/spring_animation/BUILD.gn/0 | {
"file_path": "engine/third_party/spring_animation/BUILD.gn",
"repo_id": "engine",
"token_count": 338
} | 420 |
// 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 TONIC_COMMON_LOG_H_
#define TONIC_COMMON_LOG_H_
#include <functional>
namespace tonic {
void Log(const char* format, ...);
void SetLogHandler(std::function<void(const char*)> handler);
} // namespace tonic
#endif // TONIC_COMMON_LOG_H_
| engine/third_party/tonic/common/log.h/0 | {
"file_path": "engine/third_party/tonic/common/log.h",
"repo_id": "engine",
"token_count": 142
} | 421 |
// 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 "tonic/dart_microtask_queue.h"
#include "tonic/common/build_config.h"
#include "tonic/dart_state.h"
#include "tonic/logging/dart_invoke.h"
#ifdef OS_IOS
#include <pthread.h>
#endif // OS_IOS
namespace tonic {
namespace {
#ifdef OS_IOS
// iOS doesn't support the thread_local keyword.
pthread_key_t g_queue_key;
pthread_once_t g_queue_key_once = PTHREAD_ONCE_INIT;
void MakeKey() {
pthread_key_create(&g_queue_key, nullptr);
}
void SetQueue(DartMicrotaskQueue* queue) {
pthread_once(&g_queue_key_once, MakeKey);
pthread_setspecific(g_queue_key, queue);
}
DartMicrotaskQueue* GetQueue() {
return static_cast<tonic::DartMicrotaskQueue*>(
pthread_getspecific(g_queue_key));
}
#else
thread_local DartMicrotaskQueue* g_queue = nullptr;
void SetQueue(DartMicrotaskQueue* queue) {
g_queue = queue;
}
DartMicrotaskQueue* GetQueue() {
return g_queue;
}
#endif
} // namespace
DartMicrotaskQueue::DartMicrotaskQueue() : last_error_(kNoError) {}
DartMicrotaskQueue::~DartMicrotaskQueue() = default;
void DartMicrotaskQueue::StartForCurrentThread() {
SetQueue(new DartMicrotaskQueue());
}
DartMicrotaskQueue* DartMicrotaskQueue::GetForCurrentThread() {
return GetQueue();
}
void DartMicrotaskQueue::ScheduleMicrotask(Dart_Handle callback) {
queue_.emplace_back(DartState::Current(), callback);
}
void DartMicrotaskQueue::RunMicrotasks() {
while (!queue_.empty()) {
MicrotaskQueue local;
std::swap(queue_, local);
for (const auto& callback : local) {
if (auto dart_state = callback.dart_state().lock()) {
DartState::Scope dart_scope(dart_state.get());
Dart_Handle result = Dart_InvokeClosure(callback.value(), 0, nullptr);
// If the Dart program has set a return code, then it is intending to
// shut down by way of a fatal error, and so there is no need to emit a
// log message.
if (!dart_state->has_set_return_code() || !Dart_IsError(result) ||
!Dart_IsFatalError(result)) {
CheckAndHandleError(result);
}
DartErrorHandleType error = GetErrorHandleType(result);
if (error != kNoError) {
last_error_ = error;
}
dart_state->MessageEpilogue(result);
if (!Dart_CurrentIsolate())
return;
}
}
}
}
void DartMicrotaskQueue::Destroy() {
TONIC_DCHECK(this == GetForCurrentThread());
SetQueue(nullptr);
delete this;
}
DartErrorHandleType DartMicrotaskQueue::GetLastError() {
return last_error_;
}
} // namespace tonic
| engine/third_party/tonic/dart_microtask_queue.cc/0 | {
"file_path": "engine/third_party/tonic/dart_microtask_queue.cc",
"repo_id": "engine",
"token_count": 1032
} | 422 |
// 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 "tonic/file_loader/file_loader.h"
#include <iostream>
#include <memory>
#include <utility>
#include "tonic/common/macros.h"
#include "tonic/filesystem/filesystem/file.h"
#include "tonic/filesystem/filesystem/path.h"
#include "tonic/parsers/packages_map.h"
namespace tonic {
namespace {
void FindAndReplaceInPlace(std::string& str,
const std::string& findStr,
const std::string& replaceStr) {
size_t pos = 0;
while ((pos = str.find(findStr, pos)) != std::string::npos) {
str.replace(pos, findStr.length(), replaceStr);
pos += replaceStr.length();
}
}
} // namespace
const char FileLoader::kFileURLPrefix[] = "file:///";
const size_t FileLoader::kFileURLPrefixLength =
sizeof(FileLoader::kFileURLPrefix) - 1;
const std::string FileLoader::kPathSeparator = "\\";
std::string FileLoader::SanitizePath(const std::string& url) {
std::string sanitized = url;
FindAndReplaceInPlace(sanitized, "/", FileLoader::kPathSeparator);
return SanitizeURIEscapedCharacters(sanitized);
}
bool FileLoader::ReadFileToString(const std::string& path,
std::string* result) {
TONIC_DCHECK(dirfd_ == -1);
return filesystem::ReadFileToString(path, result);
}
std::pair<uint8_t*, intptr_t> FileLoader::ReadFileToBytes(
const std::string& path) {
TONIC_DCHECK(dirfd_ == -1);
return filesystem::ReadFileToBytes(path);
}
} // namespace tonic
| engine/third_party/tonic/file_loader/file_loader_win.cc/0 | {
"file_path": "engine/third_party/tonic/file_loader/file_loader_win.cc",
"repo_id": "engine",
"token_count": 626
} | 423 |
// 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 "filesystem/scoped_temp_dir.h"
#include "filesystem/directory.h"
#include "filesystem/path.h"
#include "gtest/gtest.h"
namespace filesystem {
TEST(ScopedTempDir, Creation) {
ScopedTempDir dir;
EXPECT_TRUE(IsDirectory(dir.path()));
}
TEST(ScopedTempDir, Deletion) {
std::string path;
{
ScopedTempDir dir;
path = dir.path();
}
EXPECT_FALSE(IsDirectory(path));
}
TEST(ScopedTempDir, NewTempFile) {
ScopedTempDir dir;
std::string path;
EXPECT_TRUE(dir.NewTempFile(&path));
EXPECT_FALSE(path.empty());
}
TEST(ScopedTempDir, CustomParent) {
ScopedTempDir root_dir;
std::string parent = root_dir.path() + "/a/b/c";
std::string path;
{
ScopedTempDir dir(parent);
path = dir.path();
EXPECT_TRUE(IsDirectory(path));
EXPECT_EQ(path.substr(0, parent.size()), parent);
EXPECT_NE("temp_dir_XXXXXX", GetBaseName(path));
// Regression test - don't create temp_dir_XXXXXX dir next to the temp one.
EXPECT_FALSE(
files::IsDirectory(GetDirectoryName(path) + "/temp_dir_XXXXXX"));
}
// Verify that the tmp directory itself was deleted, but not the parent.
EXPECT_FALSE(IsDirectory(path));
EXPECT_TRUE(IsDirectory(parent));
}
} // namespace filesystem
| engine/third_party/tonic/filesystem/tests/scoped_temp_dir_unittest.cc/0 | {
"file_path": "engine/third_party/tonic/filesystem/tests/scoped_temp_dir_unittest.cc",
"repo_id": "engine",
"token_count": 517
} | 424 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.