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. #include "flutter/shell/platform/common/client_wrapper/testing/stub_flutter_api.h" #include <cassert> static flutter::testing::StubFlutterApi* s_stub_implementation; namespace flutter { namespace testing { // static void StubFlutterApi::SetTestStub(StubFlutterApi* stub) { s_stub_implementation = stub; } // static StubFlutterApi* StubFlutterApi::GetTestStub() { return s_stub_implementation; } ScopedStubFlutterApi::ScopedStubFlutterApi(std::unique_ptr<StubFlutterApi> stub) : stub_(std::move(stub)) { previous_stub_ = StubFlutterApi::GetTestStub(); StubFlutterApi::SetTestStub(stub_.get()); } ScopedStubFlutterApi::~ScopedStubFlutterApi() { StubFlutterApi::SetTestStub(previous_stub_); } } // namespace testing } // namespace flutter // Forwarding dummy implementations of the C API. FlutterDesktopMessengerRef FlutterDesktopPluginRegistrarGetMessenger( FlutterDesktopPluginRegistrarRef registrar) { // The stub ignores this, so just return an arbitrary non-zero value. return reinterpret_cast<FlutterDesktopMessengerRef>(1); } void FlutterDesktopPluginRegistrarSetDestructionHandler( FlutterDesktopPluginRegistrarRef registrar, FlutterDesktopOnPluginRegistrarDestroyed callback) { if (s_stub_implementation) { s_stub_implementation->PluginRegistrarSetDestructionHandler(callback); } } bool FlutterDesktopMessengerSend(FlutterDesktopMessengerRef messenger, const char* channel, const uint8_t* message, const size_t message_size) { bool result = false; if (s_stub_implementation) { result = s_stub_implementation->MessengerSend(channel, message, message_size); } return result; } bool FlutterDesktopMessengerSendWithReply(FlutterDesktopMessengerRef messenger, const char* channel, const uint8_t* message, const size_t message_size, const FlutterDesktopBinaryReply reply, void* user_data) { bool result = false; if (s_stub_implementation) { result = s_stub_implementation->MessengerSendWithReply( channel, message, message_size, reply, user_data); } return result; } void FlutterDesktopMessengerSendResponse( FlutterDesktopMessengerRef messenger, const FlutterDesktopMessageResponseHandle* handle, const uint8_t* data, size_t data_length) { if (s_stub_implementation) { s_stub_implementation->MessengerSendResponse(handle, data, data_length); } } void FlutterDesktopMessengerSetCallback(FlutterDesktopMessengerRef messenger, const char* channel, FlutterDesktopMessageCallback callback, void* user_data) { if (s_stub_implementation) { s_stub_implementation->MessengerSetCallback(channel, callback, user_data); } } FlutterDesktopMessengerRef FlutterDesktopMessengerAddRef( FlutterDesktopMessengerRef messenger) { assert(false); // not implemented return nullptr; } void FlutterDesktopMessengerRelease(FlutterDesktopMessengerRef messenger) { assert(false); // not implemented } bool FlutterDesktopMessengerIsAvailable(FlutterDesktopMessengerRef messenger) { assert(false); // not implemented return false; } FlutterDesktopMessengerRef FlutterDesktopMessengerLock( FlutterDesktopMessengerRef messenger) { assert(false); // not implemented return nullptr; } void FlutterDesktopMessengerUnlock(FlutterDesktopMessengerRef messenger) { assert(false); // not implemented } FlutterDesktopTextureRegistrarRef FlutterDesktopRegistrarGetTextureRegistrar( FlutterDesktopPluginRegistrarRef registrar) { return reinterpret_cast<FlutterDesktopTextureRegistrarRef>(1); } int64_t FlutterDesktopTextureRegistrarRegisterExternalTexture( FlutterDesktopTextureRegistrarRef texture_registrar, const FlutterDesktopTextureInfo* info) { uint64_t result = -1; if (s_stub_implementation) { result = s_stub_implementation->TextureRegistrarRegisterExternalTexture(info); } return result; } void FlutterDesktopTextureRegistrarUnregisterExternalTexture( FlutterDesktopTextureRegistrarRef texture_registrar, int64_t texture_id, void (*callback)(void* user_data), void* user_data) { if (s_stub_implementation) { s_stub_implementation->TextureRegistrarUnregisterExternalTexture( texture_id, callback, user_data); } else if (callback) { callback(user_data); } } bool FlutterDesktopTextureRegistrarMarkExternalTextureFrameAvailable( FlutterDesktopTextureRegistrarRef texture_registrar, int64_t texture_id) { bool result = false; if (s_stub_implementation) { result = s_stub_implementation->TextureRegistrarMarkTextureFrameAvailable( texture_id); } return result; }
engine/shell/platform/common/client_wrapper/testing/stub_flutter_api.cc/0
{ "file_path": "engine/shell/platform/common/client_wrapper/testing/stub_flutter_api.cc", "repo_id": "engine", "token_count": 1983 }
312
// 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/common/incoming_message_dispatcher.h" #include "gtest/gtest.h" namespace flutter { TEST(IncomingMessageDispatcher, SetHandle) { FlutterDesktopMessengerRef messenger = reinterpret_cast<FlutterDesktopMessengerRef>(0xfeedface); const uint8_t* message_data = reinterpret_cast<const uint8_t*>(0xcafebabe); auto dispatcher = std::make_unique<IncomingMessageDispatcher>(messenger); bool did_call = false; dispatcher->SetMessageCallback( "hello", [](FlutterDesktopMessengerRef messenger, const FlutterDesktopMessage* message, void* user_data) { EXPECT_EQ(messenger, reinterpret_cast<FlutterDesktopMessengerRef>(0xfeedface)); EXPECT_EQ(message->message, reinterpret_cast<const uint8_t*>(0xcafebabe)); EXPECT_EQ(message->message_size, 123u); *reinterpret_cast<bool*>(user_data) = true; }, &did_call); FlutterDesktopMessage message = { .struct_size = sizeof(FlutterDesktopMessage), .channel = "hello", .message = message_data, .message_size = 123, .response_handle = nullptr, }; dispatcher->HandleMessage(message); EXPECT_TRUE(did_call); } TEST(IncomingMessageDispatcher, BlockInputFalse) { FlutterDesktopMessengerRef messenger = nullptr; auto dispatcher = std::make_unique<IncomingMessageDispatcher>(messenger); bool did_call[3] = {false, false, false}; dispatcher->SetMessageCallback( "hello", [](FlutterDesktopMessengerRef messenger, const FlutterDesktopMessage* message, void* user_data) { reinterpret_cast<bool*>(user_data)[0] = true; }, &did_call); FlutterDesktopMessage message = { .struct_size = sizeof(FlutterDesktopMessage), .channel = "hello", .message = nullptr, .message_size = 0, .response_handle = nullptr, }; dispatcher->HandleMessage( message, [&did_call] { did_call[1] = true; }, [&did_call] { did_call[2] = true; }); EXPECT_TRUE(did_call[0]); EXPECT_FALSE(did_call[1]); EXPECT_FALSE(did_call[2]); } TEST(IncomingMessageDispatcher, BlockInputTrue) { FlutterDesktopMessengerRef messenger = nullptr; auto dispatcher = std::make_unique<IncomingMessageDispatcher>(messenger); static int counter = 0; int did_call[3] = {-1, -1, -1}; dispatcher->EnableInputBlockingForChannel("hello"); dispatcher->SetMessageCallback( "hello", [](FlutterDesktopMessengerRef messenger, const FlutterDesktopMessage* message, void* user_data) { reinterpret_cast<int*>(user_data)[counter++] = 1; }, &did_call); FlutterDesktopMessage message = { .struct_size = sizeof(FlutterDesktopMessage), .channel = "hello", .message = nullptr, .message_size = 0, .response_handle = nullptr, }; dispatcher->HandleMessage( message, [&did_call] { did_call[counter++] = 0; }, [&did_call] { did_call[counter++] = 2; }); EXPECT_EQ(did_call[0], 0); EXPECT_EQ(did_call[1], 1); EXPECT_EQ(did_call[2], 2); } } // namespace flutter
engine/shell/platform/common/incoming_message_dispatcher_unittests.cc/0
{ "file_path": "engine/shell/platform/common/incoming_message_dispatcher_unittests.cc", "repo_id": "engine", "token_count": 1250 }
313
// 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 "test_accessibility_bridge.h" namespace flutter { std::shared_ptr<FlutterPlatformNodeDelegate> TestAccessibilityBridge::CreateFlutterPlatformNodeDelegate() { return std::make_unique<FlutterPlatformNodeDelegate>(); }; void TestAccessibilityBridge::OnAccessibilityEvent( ui::AXEventGenerator::TargetedEvent targeted_event) { accessibility_events.push_back(targeted_event.event_params.event); } void TestAccessibilityBridge::DispatchAccessibilityAction( AccessibilityNodeId target, FlutterSemanticsAction action, fml::MallocMapping data) { performed_actions.push_back(action); } } // namespace flutter
engine/shell/platform/common/test_accessibility_bridge.cc/0
{ "file_path": "engine/shell/platform/common/test_accessibility_bridge.cc", "repo_id": "engine", "token_count": 237 }
314
// 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 <tuple> #include "flutter/shell/platform/darwin/common/availability_version_check.h" #include "gtest/gtest.h" TEST(AvailabilityVersionCheck, CanDecodeSystemPlist) { auto maybe_product_version = flutter::ProductVersionFromSystemVersionPList(); ASSERT_TRUE(maybe_product_version.has_value()); if (maybe_product_version.has_value()) { auto product_version = maybe_product_version.value(); ASSERT_GT(product_version, std::make_tuple(0, 0, 0)); } } static inline uint32_t ConstructVersion(uint32_t major, uint32_t minor, uint32_t subminor) { return ((major & 0xffff) << 16) | ((minor & 0xff) << 8) | (subminor & 0xff); } TEST(AvailabilityVersionCheck, CanParseAndCompareVersions) { auto rhs_version = std::make_tuple(17, 2, 0); uint32_t encoded_lower_version = ConstructVersion(12, 3, 7); ASSERT_TRUE(flutter::IsEncodedVersionLessThanOrSame(encoded_lower_version, rhs_version)); uint32_t encoded_higher_version = ConstructVersion(42, 0, 1); ASSERT_FALSE(flutter::IsEncodedVersionLessThanOrSame(encoded_higher_version, rhs_version)); }
engine/shell/platform/darwin/common/availability_version_check_unittests.cc/0
{ "file_path": "engine/shell/platform/darwin/common/availability_version_check_unittests.cc", "repo_id": "engine", "token_count": 609 }
315
// 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 <cstring> FLUTTER_ASSERT_ARC @implementation FlutterBinaryCodec + (instancetype)sharedInstance { static id _sharedInstance = nil; if (!_sharedInstance) { _sharedInstance = [[FlutterBinaryCodec alloc] init]; } return _sharedInstance; } - (NSData*)encode:(id)message { NSAssert(!message || [message isKindOfClass:[NSData class]], @""); return message; } - (NSData*)decode:(NSData*)message { return message; } @end @implementation FlutterStringCodec + (instancetype)sharedInstance { static id _sharedInstance = nil; if (!_sharedInstance) { _sharedInstance = [[FlutterStringCodec alloc] init]; } return _sharedInstance; } - (NSData*)encode:(id)message { if (message == nil) { return nil; } NSAssert([message isKindOfClass:[NSString class]], @""); NSString* stringMessage = message; const char* utf8 = stringMessage.UTF8String; return [NSData dataWithBytes:utf8 length:strlen(utf8)]; } - (NSString*)decode:(NSData*)message { if (message == nil) { return nil; } return [[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding]; } @end @implementation FlutterJSONMessageCodec + (instancetype)sharedInstance { static id _sharedInstance = nil; if (!_sharedInstance) { _sharedInstance = [[FlutterJSONMessageCodec alloc] init]; } return _sharedInstance; } - (NSData*)encode:(id)message { if (message == nil) { return nil; } NSData* encoding; NSError* error; if ([message isKindOfClass:[NSArray class]] || [message isKindOfClass:[NSDictionary class]]) { encoding = [NSJSONSerialization dataWithJSONObject:message options:0 error:&error]; } else { // NSJSONSerialization does not support top-level simple values. // We encode as singleton array, then extract the relevant bytes. encoding = [NSJSONSerialization dataWithJSONObject:@[ message ] options:0 error:&error]; if (encoding) { encoding = [encoding subdataWithRange:NSMakeRange(1, encoding.length - 2)]; } } NSAssert(encoding, @"Invalid JSON message, encoding failed: %@", error); return encoding; } - (id)decode:(NSData*)message { if ([message length] == 0) { return nil; } BOOL isSimpleValue = NO; id decoded = nil; NSError* error; if (0 < message.length) { UInt8 first; [message getBytes:&first length:1]; isSimpleValue = first != '{' && first != '['; if (isSimpleValue) { // NSJSONSerialization does not support top-level simple values. // We expand encoding to singleton array, then decode that and extract // the single entry. UInt8 begin = '['; UInt8 end = ']'; NSMutableData* expandedMessage = [NSMutableData dataWithLength:message.length + 2]; [expandedMessage replaceBytesInRange:NSMakeRange(0, 1) withBytes:&begin]; [expandedMessage replaceBytesInRange:NSMakeRange(1, message.length) withBytes:message.bytes]; [expandedMessage replaceBytesInRange:NSMakeRange(message.length + 1, 1) withBytes:&end]; message = expandedMessage; } decoded = [NSJSONSerialization JSONObjectWithData:message options:0 error:&error]; } NSAssert(decoded, @"Invalid JSON message, decoding failed: %@", error); return isSimpleValue ? ((NSArray*)decoded)[0] : decoded; } @end @implementation FlutterJSONMethodCodec + (instancetype)sharedInstance { static id _sharedInstance = nil; if (!_sharedInstance) { _sharedInstance = [[FlutterJSONMethodCodec alloc] init]; } return _sharedInstance; } - (NSData*)encodeMethodCall:(FlutterMethodCall*)call { return [[FlutterJSONMessageCodec sharedInstance] encode:@{ @"method" : call.method, @"args" : [self wrapNil:call.arguments], }]; } - (NSData*)encodeSuccessEnvelope:(id)result { return [[FlutterJSONMessageCodec sharedInstance] encode:@[ [self wrapNil:result] ]]; } - (NSData*)encodeErrorEnvelope:(FlutterError*)error { return [[FlutterJSONMessageCodec sharedInstance] encode:@[ error.code, [self wrapNil:error.message], [self wrapNil:error.details], ]]; } - (FlutterMethodCall*)decodeMethodCall:(NSData*)message { NSDictionary* dictionary = [[FlutterJSONMessageCodec sharedInstance] decode:message]; id method = dictionary[@"method"]; id arguments = [self unwrapNil:dictionary[@"args"]]; NSAssert([method isKindOfClass:[NSString class]], @"Invalid JSON method call"); return [FlutterMethodCall methodCallWithMethodName:method arguments:arguments]; } - (id)decodeEnvelope:(NSData*)envelope { NSArray* array = [[FlutterJSONMessageCodec sharedInstance] decode:envelope]; if (array.count == 1) { return [self unwrapNil:array[0]]; } NSAssert(array.count == 3, @"Invalid JSON envelope"); id code = array[0]; id message = [self unwrapNil:array[1]]; id details = [self unwrapNil:array[2]]; NSAssert([code isKindOfClass:[NSString class]], @"Invalid JSON envelope"); NSAssert(message == nil || [message isKindOfClass:[NSString class]], @"Invalid JSON envelope"); return [FlutterError errorWithCode:code message:message details:details]; } - (id)wrapNil:(id)value { return value == nil ? [NSNull null] : value; } - (id)unwrapNil:(id)value { return value == [NSNull null] ? nil : value; } @end
engine/shell/platform/darwin/common/framework/Source/FlutterCodecs.mm/0
{ "file_path": "engine/shell/platform/darwin/common/framework/Source/FlutterCodecs.mm", "repo_id": "engine", "token_count": 1868 }
316
// 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_GRAPHICS_FLUTTERDARWINCONTEXTMETALSKIA_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALSKIA_H_ #import <CoreVideo/CVMetalTextureCache.h> #import <Foundation/Foundation.h> #import <Metal/Metal.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterTexture.h" #import "flutter/shell/platform/darwin/graphics/FlutterDarwinExternalTextureMetal.h" #include "third_party/skia/include/gpu/GrDirectContext.h" NS_ASSUME_NONNULL_BEGIN /** * Provides skia GrContexts that are shared between iOS and macOS embeddings. */ @interface FlutterDarwinContextMetalSkia : NSObject /** * Initializes a FlutterDarwinContextMetalSkia with the system default MTLDevice and a new * MTLCommandQueue. */ - (instancetype)initWithDefaultMTLDevice; /** * Initializes a FlutterDarwinContextMetalSkia with provided MTLDevice and MTLCommandQueue. */ - (instancetype)initWithMTLDevice:(id<MTLDevice>)device commandQueue:(id<MTLCommandQueue>)commandQueue; /** * Creates an external texture with the specified ID and contents. */ - (FlutterDarwinExternalTextureMetal*) createExternalTextureWithIdentifier:(int64_t)textureID texture:(NSObject<FlutterTexture>*)texture; /** * Creates a GrDirectContext with the provided `MTLDevice` and `MTLCommandQueue`. */ + (sk_sp<GrDirectContext>)createGrContext:(id<MTLDevice>)device commandQueue:(id<MTLCommandQueue>)commandQueue; /** * MTLDevice that is backing this context.s */ @property(nonatomic, readonly) id<MTLDevice> device; /** * MTLCommandQueue that is acquired from the `device`. This queue is used both for rendering and * resource related commands. */ @property(nonatomic, readonly) id<MTLCommandQueue> commandQueue; /** * Skia GrContext that is used for rendering. */ @property(nonatomic, readonly) sk_sp<GrDirectContext> mainContext; /** * Skia GrContext that is used for resources (uploading textures etc). */ @property(nonatomic, readonly) sk_sp<GrDirectContext> resourceContext; /* * Texture cache for external textures. */ @property(nonatomic, readonly) CVMetalTextureCacheRef textureCache; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_SHELL_PLATFORM_DARWIN_GRAPHICS_FLUTTERDARWINCONTEXTMETALSKIA_H_
engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h/0
{ "file_path": "engine/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h", "repo_id": "engine", "token_count": 872 }
317
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>Flutter</string> <key>CFBundleIdentifier</key> <string>io.flutter.flutter</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>Flutter</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.0</string> <key>MinimumOSVersion</key> <string>{min_version}</string> <key>FlutterEngine</key> <string>{revision}</string> <key>ClangVersion</key> <string>{clang_version}</string> </dict> </plist>
engine/shell/platform/darwin/ios/framework/Info.plist/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Info.plist", "repo_id": "engine", "token_count": 373 }
318
// 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/FlutterEmbedderKeyResponder.h" #include <objc/NSObjCRuntime.h> #import <objc/message.h> #include <map> #include "fml/memory/weak_ptr.h" #import "KeyCodeMap_Internal.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterCodecs.h" namespace { /** * Isolate the least significant 1-bit. * * For example, * * * lowestSetBit(0x1010) returns 0x10. * * lowestSetBit(0) returns 0. */ static NSUInteger lowestSetBit(NSUInteger bitmask) { // This utilizes property of two's complement (negation), which propagates a // carry bit from LSB to the lowest set bit. return bitmask & -bitmask; } /** * Whether a string represents a control character. */ static bool IsControlCharacter(NSUInteger length, NSString* label) { if (length > 1) { return false; } unichar codeUnit = [label characterAtIndex:0]; return (codeUnit <= 0x1f && codeUnit >= 0x00) || (codeUnit >= 0x7f && codeUnit <= 0x9f); } /** * Whether a string represents an unprintable key. */ static bool IsUnprintableKey(NSUInteger length, NSString* label) { if (length > 1) { return false; } unichar codeUnit = [label characterAtIndex:0]; return codeUnit >= 0xF700 && codeUnit <= 0xF8FF; } /** * Returns a key code composed with a base key and a plane. * * Examples of unprintable keys are "NSUpArrowFunctionKey = 0xF700" or * "NSHomeFunctionKey = 0xF729". * * See * https://developer.apple.com/documentation/appkit/1535851-function-key_unicodes?language=objc * for more information. */ static uint64_t KeyOfPlane(uint64_t baseKey, uint64_t plane) { return plane | (baseKey & kValueMask); } /** * Returns the physical key for a key code. */ static uint64_t GetPhysicalKeyForKeyCode(UInt32 keyCode) { auto physicalKey = keyCodeToPhysicalKey.find(keyCode); if (physicalKey == keyCodeToPhysicalKey.end()) { return KeyOfPlane(keyCode, kIosPlane); } return physicalKey->second; } /** * Returns the logical key for a modifier physical key. */ static uint64_t GetLogicalKeyForModifier(UInt32 keyCode, uint64_t hidCode) { auto fromKeyCode = keyCodeToLogicalKey.find(keyCode); if (fromKeyCode != keyCodeToLogicalKey.end()) { return fromKeyCode->second; } return KeyOfPlane(hidCode, kIosPlane); } /** * Converts upper letters to lower letters in ASCII and extended ASCII, and * returns as-is otherwise. * * Independent of locale. */ static uint64_t toLower(uint64_t n) { constexpr uint64_t lower_a = 0x61; constexpr uint64_t upper_a = 0x41; constexpr uint64_t upper_z = 0x5a; constexpr uint64_t lower_a_grave = 0xe0; constexpr uint64_t upper_a_grave = 0xc0; constexpr uint64_t upper_thorn = 0xde; constexpr uint64_t division = 0xf7; // ASCII range. if (n >= upper_a && n <= upper_z) { return n - upper_a + lower_a; } // EASCII range. if (n >= upper_a_grave && n <= upper_thorn && n != division) { return n - upper_a_grave + lower_a_grave; } return n; } /** * Filters out some special cases in the characters field on UIKey. */ static const char* getEventCharacters(NSString* characters, UIKeyboardHIDUsage keyCode) API_AVAILABLE(ios(13.4)) { if (characters == nil) { return nullptr; } if ([characters length] == 0) { return nullptr; } if (@available(iOS 13.4, *)) { // On iOS, function keys return the UTF8 string "\^P" (with a literal '/', // '^' and a 'P', not escaped ctrl-P) as their "characters" field. This // isn't a valid (single) UTF8 character. Looking at the only UTF16 // character for a function key yields a value of "16", which is a Unicode // "SHIFT IN" character, which is just odd. UTF8 conversion of that string // is what generates the three characters "\^P". // // Anyhow, we strip them all out and replace them with empty strings, since // function keys shouldn't be printable. if (functionKeyCodes.find(keyCode) != functionKeyCodes.end()) { return nullptr; } } return [characters UTF8String]; } /** * Returns the logical key of a KeyUp or KeyDown event. * * The `maybeSpecialKey` is a nullable integer, and if not nil, indicates * that the event key is a special key as defined by `specialKeyMapping`, * and is the corresponding logical key. * * For modifier keys, use GetLogicalKeyForModifier. */ static uint64_t GetLogicalKeyForEvent(FlutterUIPressProxy* press, NSNumber* maybeSpecialKey) API_AVAILABLE(ios(13.4)) { if (maybeSpecialKey != nil) { return [maybeSpecialKey unsignedLongLongValue]; } // Look to see if the keyCode can be mapped from keycode. auto fromKeyCode = keyCodeToLogicalKey.find(press.key.keyCode); if (fromKeyCode != keyCodeToLogicalKey.end()) { return fromKeyCode->second; } const char* characters = getEventCharacters(press.key.charactersIgnoringModifiers, press.key.keyCode); NSString* keyLabel = characters == nullptr ? nil : [[[NSString alloc] initWithUTF8String:characters] autorelease]; NSUInteger keyLabelLength = [keyLabel length]; // If this key is printable, generate the logical key from its Unicode // value. Control keys such as ESC, CTRL, and SHIFT are not printable. HOME, // DEL, arrow keys, and function keys are considered modifier function keys, // which generate invalid Unicode scalar values. if (keyLabelLength != 0 && !IsControlCharacter(keyLabelLength, keyLabel) && !IsUnprintableKey(keyLabelLength, keyLabel)) { // Given that charactersIgnoringModifiers can contain a string of arbitrary // length, limit to a maximum of two Unicode scalar values. It is unlikely // that a keyboard would produce a code point bigger than 32 bits, but it is // still worth defending against this case. NSCAssert((keyLabelLength < 2), @"Unexpected long key label: |%@|.", keyLabel); uint64_t codeUnit = (uint64_t)[keyLabel characterAtIndex:0]; if (keyLabelLength == 2) { uint64_t secondCode = (uint64_t)[keyLabel characterAtIndex:1]; codeUnit = (codeUnit << 16) | secondCode; } return KeyOfPlane(toLower(codeUnit), kUnicodePlane); } // This is a non-printable key that is unrecognized, so a new code is minted // with the autogenerated bit set. return KeyOfPlane(press.key.keyCode, kIosPlane); } /** * Converts NSEvent.timestamp to the timestamp for Flutter. */ static double GetFlutterTimestampFrom(NSTimeInterval timestamp) { // Timestamp in microseconds. The event.timestamp is in seconds with sub-ms precision. return timestamp * 1000000.0; } /** * Compute |modifierFlagOfInterestMask| out of |keyCodeToModifierFlag|. * * This is equal to the bitwise-or of all values of |keyCodeToModifierFlag|. */ static NSUInteger computeModifierFlagOfInterestMask() { NSUInteger modifierFlagOfInterestMask = kModifierFlagCapsLock | kModifierFlagShiftAny | kModifierFlagControlAny | kModifierFlagAltAny | kModifierFlagMetaAny; for (std::pair<UInt32, ModifierFlag> entry : keyCodeToModifierFlag) { modifierFlagOfInterestMask = modifierFlagOfInterestMask | entry.second; } return modifierFlagOfInterestMask; } static bool isKeyDown(FlutterUIPressProxy* press) API_AVAILABLE(ios(13.4)) { switch (press.phase) { case UIPressPhaseStationary: case UIPressPhaseChanged: // Not sure if this is the right thing to do for these two, but true seems // more correct than false. return true; case UIPressPhaseBegan: return true; case UIPressPhaseCancelled: case UIPressPhaseEnded: return false; } return false; } /** * The C-function sent to the engine's |sendKeyEvent|, wrapping * |FlutterEmbedderKeyResponder.handleResponse|. * * For the reason of this wrap, see |FlutterKeyPendingResponse|. */ void HandleResponse(bool handled, void* user_data); } // namespace /** * The invocation context for |HandleResponse|, wrapping * |FlutterEmbedderKeyResponder.handleResponse|. * * The key responder's functions only accept C-functions as callbacks, as well * as arbitrary user_data. In order to send an instance method of * |FlutterEmbedderKeyResponder.handleResponse| to the engine's |SendKeyEvent|, * we wrap the invocation into a C-function |HandleResponse| and invocation * context |FlutterKeyPendingResponse|. */ @interface FlutterKeyPendingResponse : NSObject @property(readonly) FlutterEmbedderKeyResponder* responder; @property(nonatomic) uint64_t responseId; - (nonnull instancetype)initWithHandler:(nonnull FlutterEmbedderKeyResponder*)responder responseId:(uint64_t)responseId; @end @implementation FlutterKeyPendingResponse - (instancetype)initWithHandler:(FlutterEmbedderKeyResponder*)responder responseId:(uint64_t)responseId { self = [super init]; if (self != nil) { _responder = responder; _responseId = responseId; } return self; } @end /** * Guards a |FlutterAsyncKeyCallback| to make sure it's handled exactly once * throughout the process of handling an event in |FlutterEmbedderKeyResponder|. * * A callback can either be handled with |pendTo:withId:|, or with |resolveTo:|. * Either way, the callback cannot be handled again, or an assertion will be * thrown. */ @interface FlutterKeyCallbackGuard : NSObject - (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback; /** * Handle the callback by storing it to pending responses. */ - (void)pendTo:(nonnull NSMutableDictionary<NSNumber*, FlutterAsyncKeyCallback>*)pendingResponses withId:(uint64_t)responseId; /** * Handle the callback by calling it with a result. */ - (void)resolveTo:(BOOL)handled; @property(nonatomic) BOOL handled; /** * A string indicating how the callback is handled. * * Only set in debug mode. Nil in release mode, or if the callback has not been * handled. */ @property(readonly) NSString* debugHandleSource; @end @implementation FlutterKeyCallbackGuard { // The callback is declared in the implementation block to avoid being // accessed directly. FlutterAsyncKeyCallback _callback; } - (nonnull instancetype)initWithCallback:(FlutterAsyncKeyCallback)callback { self = [super init]; if (self != nil) { _callback = [callback copy]; _handled = FALSE; } return self; } - (void)dealloc { [_callback release]; [super dealloc]; } - (void)pendTo:(nonnull NSMutableDictionary<NSNumber*, FlutterAsyncKeyCallback>*)pendingResponses withId:(uint64_t)responseId { NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); if (_handled) { return; } pendingResponses[@(responseId)] = _callback; _handled = TRUE; NSAssert( ((_debugHandleSource = [NSString stringWithFormat:@"pending event %llu", responseId]), TRUE), @""); } - (void)resolveTo:(BOOL)handled { NSAssert(!_handled, @"This callback has been handled by %@.", _debugHandleSource); if (_handled) { return; } _callback(handled); _handled = TRUE; NSAssert(((_debugHandleSource = [NSString stringWithFormat:@"resolved with %d", _handled]), TRUE), @""); } @end @interface FlutterEmbedderKeyResponder () /** * The function to send converted events to. * * Set by the initializer. */ @property(nonatomic, copy, readonly) FlutterSendKeyEvent sendEvent; /** * A map of pressed keys. * * The keys of the dictionary are physical keys, while the values are the logical keys * of the key down event. */ @property(nonatomic, retain, readonly) NSMutableDictionary<NSNumber*, NSNumber*>* pressingRecords; /** * A constant mask for NSEvent.modifierFlags that Flutter synchronizes with. * * Flutter keeps track of the last |modifierFlags| and compares it with the * incoming one. Any bit within |modifierFlagOfInterestMask| that is different * (except for the one that corresponds to the event key) indicates that an * event for this modifier was missed, and Flutter synthesizes an event to make * up for the state difference. * * It is computed by computeModifierFlagOfInterestMask. */ @property(nonatomic) NSUInteger modifierFlagOfInterestMask; /** * The modifier flags of the last received key event, excluding uninterested * bits. * * This should be kept synchronized with the last |NSEvent.modifierFlags| * after masking with |modifierFlagOfInterestMask|. This should also be kept * synchronized with the corresponding keys of |pressingRecords|. * * This is used by |synchronizeModifiers| to quickly find out modifier keys that * are desynchronized. */ @property(nonatomic) NSUInteger lastModifierFlagsOfInterest; /** * A self-incrementing ID used to label key events sent to the framework. */ @property(nonatomic) uint64_t responseId; /** * A map of unresponded key events sent to the framework. * * Its values are |responseId|s, and keys are the callback that was received * along with the event. */ @property(nonatomic, retain, readonly) NSMutableDictionary<NSNumber*, FlutterAsyncKeyCallback>* pendingResponses; /** * Compare the last modifier flags and the current, and dispatch synthesized * key events for each different modifier flag bit. * * The flags compared are all flags after masking with * |modifierFlagOfInterestMask| and excluding |ignoringFlags|. */ - (void)synchronizeModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); /** * Update the pressing state. * * If `logicalKey` is not 0, `physicalKey` is pressed as `logicalKey`. * Otherwise, `physicalKey` is released. */ - (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey; /** * Synthesize a CapsLock down event, then a CapsLock up event. */ - (void)synthesizeCapsLockTapWithTimestamp:(NSTimeInterval)timestamp; /** * Send an event to the framework, expecting its response. */ - (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event callback:(nonnull FlutterKeyCallbackGuard*)callback; /** * Send an empty key event. * * The event is never synthesized, and never expects an event result. An empty * event is sent when no other events should be sent, such as upon back-to-back * keydown events of the same key. */ - (void)sendEmptyEvent; /** * Send a key event for a modifier key. */ - (void)synthesizeModifierEventOfType:(BOOL)isDownEvent timestamp:(NSTimeInterval)timestamp keyCode:(UInt32)keyCode; /** * Processes a down event from the system. */ - (void)handlePressBegin:(nonnull FlutterUIPressProxy*)press callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)); /** * Processes an up event from the system. */ - (void)handlePressEnd:(nonnull FlutterUIPressProxy*)press callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)); /** * Processes the response from the framework. */ - (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId; /** * Fix up the modifiers for a particular type of modifier key. */ - (UInt32)fixSidedFlags:(ModifierFlag)anyFlag withLeftFlag:(ModifierFlag)leftSide withRightFlag:(ModifierFlag)rightSide withLeftKey:(UInt16)leftKeyCode withRightKey:(UInt16)rightKeyCode withKeyCode:(UInt16)keyCode keyDown:(BOOL)isKeyDown forFlags:(UInt32)modifiersPressed API_AVAILABLE(ios(13.4)); /** * Because iOS differs from other platforms in that the modifier flags still * contain the flag for the key that is being released on the keyup event, we * adjust the modifiers when the released key is a matching modifier key. */ - (UInt32)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)); @end @implementation FlutterEmbedderKeyResponder - (nonnull instancetype)initWithSendEvent:(FlutterSendKeyEvent)sendEvent { self = [super init]; if (self != nil) { _sendEvent = [sendEvent copy]; _pressingRecords = [[NSMutableDictionary alloc] init]; _pendingResponses = [[NSMutableDictionary alloc] init]; _responseId = 1; _lastModifierFlagsOfInterest = 0; _modifierFlagOfInterestMask = computeModifierFlagOfInterestMask(); } return self; } - (void)dealloc { [_sendEvent release]; [_pressingRecords release]; [_pendingResponses release]; [super dealloc]; } - (void)handlePress:(nonnull FlutterUIPressProxy*)press callback:(FlutterAsyncKeyCallback)callback API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { } else { return; } // The conversion algorithm relies on a non-nil callback to properly compute // `synthesized`. NSAssert(callback != nil, @"The callback must not be nil."); FlutterKeyCallbackGuard* guardedCallback = nil; switch (press.phase) { case UIPressPhaseBegan: guardedCallback = [[[FlutterKeyCallbackGuard alloc] initWithCallback:callback] autorelease]; [self handlePressBegin:press callback:guardedCallback]; break; case UIPressPhaseEnded: guardedCallback = [[[FlutterKeyCallbackGuard alloc] initWithCallback:callback] autorelease]; [self handlePressEnd:press callback:guardedCallback]; break; case UIPressPhaseChanged: case UIPressPhaseCancelled: // TODO(gspencergoog): Handle cancelled events as synthesized up events. case UIPressPhaseStationary: NSAssert(false, @"Unexpected press phase receieved in handlePress"); return; } NSAssert(guardedCallback.handled, @"The callback returned without being handled."); NSAssert( (_lastModifierFlagsOfInterest & ~kModifierFlagCapsLock) == ([self adjustModifiers:press] & (_modifierFlagOfInterestMask & ~kModifierFlagCapsLock)), @"The modifier flags are not properly updated: recorded 0x%lx, event with mask 0x%lx", static_cast<unsigned long>(_lastModifierFlagsOfInterest & ~kModifierFlagCapsLock), static_cast<unsigned long>([self adjustModifiers:press] & (_modifierFlagOfInterestMask & ~kModifierFlagCapsLock))); } #pragma mark - Private - (void)synchronizeModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { } else { return; } const UInt32 lastFlagsOfInterest = _lastModifierFlagsOfInterest & _modifierFlagOfInterestMask; const UInt32 pressedModifiers = [self adjustModifiers:press]; const UInt32 currentFlagsOfInterest = pressedModifiers & _modifierFlagOfInterestMask; UInt32 flagDifference = currentFlagsOfInterest ^ lastFlagsOfInterest; if (flagDifference & kModifierFlagCapsLock) { // If the caps lock changed, and we didn't expect that, then send a // synthesized down and an up to simulate a toggle of the state. if (press.key.keyCode != UIKeyboardHIDUsageKeyboardCapsLock) { [self synthesizeCapsLockTapWithTimestamp:press.timestamp]; } flagDifference &= ~kModifierFlagCapsLock; } while (true) { const UInt32 currentFlag = lowestSetBit(flagDifference); if (currentFlag == 0) { break; } flagDifference &= ~currentFlag; if (currentFlag & kModifierFlagAnyMask) { // Skip synthesizing keys for the "any" flags, since their synthesis will // be handled when we do the sided flags. We still want them in the flags // of interest, though, so we can keep their state. continue; } auto keyCode = modifierFlagToKeyCode.find(static_cast<ModifierFlag>(currentFlag)); NSAssert(keyCode != modifierFlagToKeyCode.end(), @"Invalid modifier flag of interest 0x%lx", static_cast<unsigned long>(currentFlag)); if (keyCode == modifierFlagToKeyCode.end()) { continue; } // If this press matches the modifier key in question, then don't synthesize // it, because it's already a "real" keypress. if (keyCode->second == static_cast<UInt32>(press.key.keyCode)) { continue; } BOOL isDownEvent = currentFlagsOfInterest & currentFlag; [self synthesizeModifierEventOfType:isDownEvent timestamp:press.timestamp keyCode:keyCode->second]; } _lastModifierFlagsOfInterest = (_lastModifierFlagsOfInterest & ~_modifierFlagOfInterestMask) | currentFlagsOfInterest; } - (void)synthesizeCapsLockTapWithTimestamp:(NSTimeInterval)timestamp { // The assumption when the app starts is that caps lock is off, but if that // turns out to be untrue (according to the modifier flags), then this is used // to simulate a key down and a key up of the caps lock key, to simulate // toggling of that state in the framework. FlutterKeyEvent flutterEvent = { .struct_size = sizeof(FlutterKeyEvent), .timestamp = GetFlutterTimestampFrom(timestamp), .type = kFlutterKeyEventTypeDown, .physical = kCapsLockPhysicalKey, .logical = kCapsLockLogicalKey, .character = nil, .synthesized = true, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; _sendEvent(flutterEvent, nullptr, nullptr); flutterEvent.type = kFlutterKeyEventTypeUp; _sendEvent(flutterEvent, nullptr, nullptr); } - (void)updateKey:(uint64_t)physicalKey asPressed:(uint64_t)logicalKey { if (logicalKey == 0) { [_pressingRecords removeObjectForKey:@(physicalKey)]; } else { _pressingRecords[@(physicalKey)] = @(logicalKey); } } - (void)sendPrimaryFlutterEvent:(const FlutterKeyEvent&)event callback:(FlutterKeyCallbackGuard*)callback { _responseId += 1; uint64_t responseId = _responseId; FlutterKeyPendingResponse* pending = [[[FlutterKeyPendingResponse alloc] initWithHandler:self responseId:responseId] autorelease]; [callback pendTo:_pendingResponses withId:responseId]; _sendEvent(event, HandleResponse, pending); } - (void)sendEmptyEvent { FlutterKeyEvent event = { .struct_size = sizeof(FlutterKeyEvent), .timestamp = 0, .type = kFlutterKeyEventTypeDown, .physical = 0, .logical = 0, .character = nil, .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; _sendEvent(event, nil, nil); } - (void)synthesizeModifierEventOfType:(BOOL)isDownEvent timestamp:(NSTimeInterval)timestamp keyCode:(UInt32)keyCode { uint64_t physicalKey = GetPhysicalKeyForKeyCode(keyCode); uint64_t logicalKey = GetLogicalKeyForModifier(keyCode, physicalKey); if (physicalKey == 0 || logicalKey == 0) { return; } FlutterKeyEvent flutterEvent = { .struct_size = sizeof(FlutterKeyEvent), .timestamp = GetFlutterTimestampFrom(timestamp), .type = isDownEvent ? kFlutterKeyEventTypeDown : kFlutterKeyEventTypeUp, .physical = physicalKey, .logical = logicalKey, .character = nil, .synthesized = true, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; [self updateKey:physicalKey asPressed:isDownEvent ? logicalKey : 0]; _sendEvent(flutterEvent, nullptr, nullptr); } - (void)handlePressBegin:(nonnull FlutterUIPressProxy*)press callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { } else { return; } uint64_t physicalKey = GetPhysicalKeyForKeyCode(press.key.keyCode); // Some unprintable keys on iOS have literal names on their key label, such as // @"UIKeyInputEscape". They are called the "special keys" and have predefined // logical keys and empty characters. NSNumber* specialKey = [specialKeyMapping objectForKey:press.key.charactersIgnoringModifiers]; uint64_t logicalKey = GetLogicalKeyForEvent(press, specialKey); [self synchronizeModifiers:press]; NSNumber* pressedLogicalKey = nil; if ([_pressingRecords count] > 0) { pressedLogicalKey = _pressingRecords[@(physicalKey)]; if (pressedLogicalKey != nil) { // Normally the key up events won't be missed since iOS always sends the // key up event to the view where the corresponding key down occurred. // However this might happen in add-to-app scenarios if the focus is changed // from the native view to the Flutter view amid the key tap. [callback resolveTo:TRUE]; [self sendEmptyEvent]; return; } } if (pressedLogicalKey == nil) { [self updateKey:physicalKey asPressed:logicalKey]; } FlutterKeyEvent flutterEvent = { .struct_size = sizeof(FlutterKeyEvent), .timestamp = GetFlutterTimestampFrom(press.timestamp), .type = kFlutterKeyEventTypeDown, .physical = physicalKey, .logical = pressedLogicalKey == nil ? logicalKey : [pressedLogicalKey unsignedLongLongValue], .character = specialKey != nil ? nil : getEventCharacters(press.key.characters, press.key.keyCode), .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; } - (void)handlePressEnd:(nonnull FlutterUIPressProxy*)press callback:(nonnull FlutterKeyCallbackGuard*)callback API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { } else { return; } [self synchronizeModifiers:press]; uint64_t physicalKey = GetPhysicalKeyForKeyCode(press.key.keyCode); NSNumber* pressedLogicalKey = _pressingRecords[@(physicalKey)]; if (pressedLogicalKey == nil) { // Normally the key up events won't be missed since iOS always sends the // key up event to the view where the corresponding key down occurred. // However this might happen in add-to-app scenarios if the focus is changed // from the native view to the Flutter view amid the key tap. [callback resolveTo:TRUE]; [self sendEmptyEvent]; return; } [self updateKey:physicalKey asPressed:0]; FlutterKeyEvent flutterEvent = { .struct_size = sizeof(FlutterKeyEvent), .timestamp = GetFlutterTimestampFrom(press.timestamp), .type = kFlutterKeyEventTypeUp, .physical = physicalKey, .logical = [pressedLogicalKey unsignedLongLongValue], .character = nil, .synthesized = false, .device_type = kFlutterKeyEventDeviceTypeKeyboard, }; [self sendPrimaryFlutterEvent:flutterEvent callback:callback]; } - (void)handleResponse:(BOOL)handled forId:(uint64_t)responseId { FlutterAsyncKeyCallback callback = _pendingResponses[@(responseId)]; callback(handled); [_pendingResponses removeObjectForKey:@(responseId)]; } - (UInt32)fixSidedFlags:(ModifierFlag)anyFlag withLeftFlag:(ModifierFlag)leftSide withRightFlag:(ModifierFlag)rightSide withLeftKey:(UInt16)leftKeyCode withRightKey:(UInt16)rightKeyCode withKeyCode:(UInt16)keyCode keyDown:(BOOL)isKeyDown forFlags:(UInt32)modifiersPressed API_AVAILABLE(ios(13.4)) { UInt32 newModifiers = modifiersPressed; if (isKeyDown) { // Add in the modifier flags that correspond to this key code, if any. if (keyCode == leftKeyCode) { newModifiers |= leftSide | anyFlag; } else if (keyCode == rightKeyCode) { newModifiers |= rightSide | anyFlag; } } else { // If this is a key up, then remove any modifier that matches the keycode in // the event from the flags, and the anyFlag if the other side isn't also // pressed. if (keyCode == leftKeyCode) { newModifiers &= ~leftSide; if (!(newModifiers & rightSide)) { newModifiers &= ~anyFlag; } } else if (keyCode == rightKeyCode) { newModifiers &= ~rightSide; if (!(newModifiers & leftSide)) { newModifiers &= ~anyFlag; } } } if (!(newModifiers & anyFlag)) { // Turn off any sided flags, since the "any" flag is gone. newModifiers &= ~(leftSide | rightSide); } return newModifiers; } // This fixes a few cases where iOS provides modifier flags differently from how // the framework would like to receive them. // // 1) iOS turns off the flag associated with a modifier key AFTER the modifier // key up event, so when the key up event arrives, the flags must be modified // before synchronizing so they do not include the modifier that arrived in // the key up event. // 2) Modifier flags can be set even when that modifier is not being pressed. // One example of this is when a special character is produced with the Alt // (Option) key, and the Alt key is released before the letter key: the // letter key's key up event still contains the Alt key flag. // 3) iOS doesn't provide information about which side modifier was pressed, // except through the keycode of the pressed key, so we look at the pressed // key code to decide which side to indicate in the flags. If we can't know // (in the case of a non-modifier key event having an "any" modifier set, but // we don't know already that the modifier is down), then we just pick the // left one arbitrarily. - (UInt32)adjustModifiers:(nonnull FlutterUIPressProxy*)press API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // no-op } else { return press.key.modifierFlags; } bool keyDown = isKeyDown(press); // Start with the current modifier flags, along with any sided flags that we // already know are down. UInt32 pressedModifiers = press.key.modifierFlags | (_lastModifierFlagsOfInterest & kModifierFlagSidedMask); pressedModifiers = [self fixSidedFlags:kModifierFlagShiftAny withLeftFlag:kModifierFlagShiftLeft withRightFlag:kModifierFlagShiftRight withLeftKey:UIKeyboardHIDUsageKeyboardLeftShift withRightKey:UIKeyboardHIDUsageKeyboardRightShift withKeyCode:press.key.keyCode keyDown:keyDown forFlags:pressedModifiers]; pressedModifiers = [self fixSidedFlags:kModifierFlagControlAny withLeftFlag:kModifierFlagControlLeft withRightFlag:kModifierFlagControlRight withLeftKey:UIKeyboardHIDUsageKeyboardLeftControl withRightKey:UIKeyboardHIDUsageKeyboardRightControl withKeyCode:press.key.keyCode keyDown:keyDown forFlags:pressedModifiers]; pressedModifiers = [self fixSidedFlags:kModifierFlagAltAny withLeftFlag:kModifierFlagAltLeft withRightFlag:kModifierFlagAltRight withLeftKey:UIKeyboardHIDUsageKeyboardLeftAlt withRightKey:UIKeyboardHIDUsageKeyboardRightAlt withKeyCode:press.key.keyCode keyDown:keyDown forFlags:pressedModifiers]; pressedModifiers = [self fixSidedFlags:kModifierFlagMetaAny withLeftFlag:kModifierFlagMetaLeft withRightFlag:kModifierFlagMetaRight withLeftKey:UIKeyboardHIDUsageKeyboardLeftGUI withRightKey:UIKeyboardHIDUsageKeyboardRightGUI withKeyCode:press.key.keyCode keyDown:keyDown forFlags:pressedModifiers]; if (press.key.keyCode == UIKeyboardHIDUsageKeyboardCapsLock) { // The caps lock modifier needs to be unset only if it was already on // and this is a key up. This is because it indicates the lock state, and // not the key press state. The caps lock state should be on between the // first down, and the second up (i.e. while the lock in effect), and // this code turns it off at the second up event. The OS leaves it on still // because of iOS's weird late processing of modifier states. Synthesis of // the appropriate synthesized key events happens in synchronizeModifiers. if (!keyDown && _lastModifierFlagsOfInterest & kModifierFlagCapsLock) { pressedModifiers &= ~kModifierFlagCapsLock; } } return pressedModifiers; } @end namespace { void HandleResponse(bool handled, void* user_data) { FlutterKeyPendingResponse* pending = reinterpret_cast<FlutterKeyPendingResponse*>(user_data); [pending.responder handleResponse:handled forId:pending.responseId]; } } // namespace
engine/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterEmbedderKeyResponder.mm", "repo_id": "engine", "token_count": 11668 }
319
// 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/FlutterKeyboardManager.h" #include "flutter/fml/platform/darwin/message_loop_darwin.h" #include "flutter/fml/platform/darwin/weak_nsobject.h" static constexpr CFTimeInterval kDistantFuture = 1.0e10; @interface FlutterKeyboardManager () /** * The primary responders added by addPrimaryResponder. */ @property(nonatomic, retain, readonly) NSMutableArray<id<FlutterKeyPrimaryResponder>>* primaryResponders; /** * The secondary responders added by addSecondaryResponder. */ @property(nonatomic, retain, readonly) NSMutableArray<id<FlutterKeySecondaryResponder>>* secondaryResponders; - (void)dispatchToSecondaryResponders:(nonnull FlutterUIPressProxy*)press complete:(nonnull KeyEventCompleteCallback)callback API_AVAILABLE(ios(13.4)); @end @implementation FlutterKeyboardManager { std::unique_ptr<fml::WeakNSObjectFactory<FlutterKeyboardManager>> _weakFactory; } - (nonnull instancetype)init { self = [super init]; if (self != nil) { _primaryResponders = [[NSMutableArray alloc] init]; _secondaryResponders = [[NSMutableArray alloc] init]; _weakFactory = std::make_unique<fml::WeakNSObjectFactory<FlutterKeyboardManager>>(self); } return self; } - (void)addPrimaryResponder:(nonnull id<FlutterKeyPrimaryResponder>)responder { [_primaryResponders addObject:responder]; } - (void)addSecondaryResponder:(nonnull id<FlutterKeySecondaryResponder>)responder { [_secondaryResponders addObject:responder]; } - (void)dealloc { // It will be destroyed and invalidate its weak pointers // before any other members are destroyed. _weakFactory.reset(); [_primaryResponders removeAllObjects]; [_secondaryResponders removeAllObjects]; [_primaryResponders release]; [_secondaryResponders release]; _primaryResponders = nil; _secondaryResponders = nil; [super dealloc]; } - (fml::WeakNSObject<FlutterKeyboardManager>)getWeakNSObject { return _weakFactory->GetWeakNSObject(); } - (void)handlePress:(nonnull FlutterUIPressProxy*)press nextAction:(nonnull void (^)())next API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // no-op } else { return; } bool __block wasHandled = false; KeyEventCompleteCallback completeCallback = ^void(bool handled, FlutterUIPressProxy* press) { wasHandled = handled; CFRunLoopStop(CFRunLoopGetCurrent()); }; switch (press.phase) { case UIPressPhaseBegan: case UIPressPhaseEnded: { // Having no primary responders requires extra logic, but Flutter hard-codes // all primary responders, so this is a situation that Flutter will never // encounter. NSAssert([_primaryResponders count] >= 0, @"At least one primary responder must be added."); __block auto weakSelf = [self getWeakNSObject]; __block NSUInteger unreplied = [self.primaryResponders count]; __block BOOL anyHandled = false; FlutterAsyncKeyCallback replyCallback = ^(BOOL handled) { unreplied--; NSAssert(unreplied >= 0, @"More primary responders replied than expected."); anyHandled = anyHandled || handled; if (unreplied == 0) { if (!anyHandled && weakSelf) { [weakSelf.get() dispatchToSecondaryResponders:press complete:completeCallback]; } else { completeCallback(true, press); } } }; for (id<FlutterKeyPrimaryResponder> responder in _primaryResponders) { [responder handlePress:press callback:replyCallback]; } // Create a nested run loop while we wait for a response from the // framework. Once the completeCallback is called, this run loop will exit // and the main one will resume. The completeCallback MUST be called, or // the app will get stuck in this run loop indefinitely. // // We need to run in this mode so that UIKit doesn't give us new // events until we are done processing this one. CFRunLoopRunInMode(fml::MessageLoopDarwin::kMessageLoopCFRunLoopMode, kDistantFuture, NO); break; } case UIPressPhaseChanged: case UIPressPhaseCancelled: case UIPressPhaseStationary: break; } if (!wasHandled) { next(); } } #pragma mark - Private - (void)dispatchToSecondaryResponders:(nonnull FlutterUIPressProxy*)press complete:(nonnull KeyEventCompleteCallback)callback API_AVAILABLE(ios(13.4)) { if (@available(iOS 13.4, *)) { // no-op } else { callback(false, press); return; } for (id<FlutterKeySecondaryResponder> responder in _secondaryResponders) { if ([responder handlePress:press]) { callback(true, press); return; } } callback(false, press); } @end
engine/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterKeyboardManager.mm", "repo_id": "engine", "token_count": 1772 }
320
// 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_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_INTERNAL_H_ #define FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_INTERNAL_H_ @interface FlutterPluginAppLifeCycleDelegate () /** * Check whether the selector should be handled dynamically. */ - (BOOL)isSelectorAddedDynamically:(SEL)selector; /** * Check whether there is at least one plugin responds to the selector. */ - (BOOL)hasPluginThatRespondsToSelector:(SEL)selector; @end ; #endif // FLUTTER_SHELL_PLATFORM_DARWIN_IOS_FRAMEWORK_SOURCE_FLUTTERPLUGINAPPLIFECYCLEDELEGATE_INTERNAL_H_
engine/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/FlutterPluginAppLifeCycleDelegate_internal.h", "repo_id": "engine", "token_count": 300 }
321
// 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 <map> #include <set> #include "flutter/shell/platform/darwin/ios/framework/Source/KeyCodeMap_Internal.h" // DO NOT EDIT -- DO NOT EDIT -- DO NOT EDIT // This file is generated by // flutter/flutter:dev/tools/gen_keycodes/bin/gen_keycodes.dart and should not // be edited directly. // // Edit the template // flutter/flutter:dev/tools/gen_keycodes/data/ios_key_code_map_mm.tmpl instead. // // See flutter/flutter:dev/tools/gen_keycodes/README.md for more information. /** * Mask for the 32-bit value portion of the key code. */ const uint64_t kValueMask = 0x000ffffffff; /** * The plane value for keys which have a Unicode representation. */ const uint64_t kUnicodePlane = 0x00000000000; /** * The plane value for the private keys defined by the iOS embedding. */ const uint64_t kIosPlane = 0x01300000000; // Maps iOS-specific key code values representing PhysicalKeyboardKey. // // iOS doesn't provide a scan code, but a virtual keycode to represent a physical key. const std::map<uint32_t, uint64_t> keyCodeToPhysicalKey = { {0x00000000, 0x00070000}, // usbReserved {0x00000001, 0x00070001}, // usbErrorRollOver {0x00000002, 0x00070002}, // usbPostFail {0x00000003, 0x00070003}, // usbErrorUndefined {0x00000004, 0x00070004}, // keyA {0x00000005, 0x00070005}, // keyB {0x00000006, 0x00070006}, // keyC {0x00000007, 0x00070007}, // keyD {0x00000008, 0x00070008}, // keyE {0x00000009, 0x00070009}, // keyF {0x0000000a, 0x0007000a}, // keyG {0x0000000b, 0x0007000b}, // keyH {0x0000000c, 0x0007000c}, // keyI {0x0000000d, 0x0007000d}, // keyJ {0x0000000e, 0x0007000e}, // keyK {0x0000000f, 0x0007000f}, // keyL {0x00000010, 0x00070010}, // keyM {0x00000011, 0x00070011}, // keyN {0x00000012, 0x00070012}, // keyO {0x00000013, 0x00070013}, // keyP {0x00000014, 0x00070014}, // keyQ {0x00000015, 0x00070015}, // keyR {0x00000016, 0x00070016}, // keyS {0x00000017, 0x00070017}, // keyT {0x00000018, 0x00070018}, // keyU {0x00000019, 0x00070019}, // keyV {0x0000001a, 0x0007001a}, // keyW {0x0000001b, 0x0007001b}, // keyX {0x0000001c, 0x0007001c}, // keyY {0x0000001d, 0x0007001d}, // keyZ {0x0000001e, 0x0007001e}, // digit1 {0x0000001f, 0x0007001f}, // digit2 {0x00000020, 0x00070020}, // digit3 {0x00000021, 0x00070021}, // digit4 {0x00000022, 0x00070022}, // digit5 {0x00000023, 0x00070023}, // digit6 {0x00000024, 0x00070024}, // digit7 {0x00000025, 0x00070025}, // digit8 {0x00000026, 0x00070026}, // digit9 {0x00000027, 0x00070027}, // digit0 {0x00000028, 0x00070028}, // enter {0x00000029, 0x00070029}, // escape {0x0000002a, 0x0007002a}, // backspace {0x0000002b, 0x0007002b}, // tab {0x0000002c, 0x0007002c}, // space {0x0000002d, 0x0007002d}, // minus {0x0000002e, 0x0007002e}, // equal {0x0000002f, 0x0007002f}, // bracketLeft {0x00000030, 0x00070030}, // bracketRight {0x00000031, 0x00070031}, // backslash {0x00000033, 0x00070033}, // semicolon {0x00000034, 0x00070034}, // quote {0x00000035, 0x00070035}, // backquote {0x00000036, 0x00070036}, // comma {0x00000037, 0x00070037}, // period {0x00000038, 0x00070038}, // slash {0x00000039, 0x00070039}, // capsLock {0x0000003a, 0x0007003a}, // f1 {0x0000003b, 0x0007003b}, // f2 {0x0000003c, 0x0007003c}, // f3 {0x0000003d, 0x0007003d}, // f4 {0x0000003e, 0x0007003e}, // f5 {0x0000003f, 0x0007003f}, // f6 {0x00000040, 0x00070040}, // f7 {0x00000041, 0x00070041}, // f8 {0x00000042, 0x00070042}, // f9 {0x00000043, 0x00070043}, // f10 {0x00000044, 0x00070044}, // f11 {0x00000045, 0x00070045}, // f12 {0x00000046, 0x00070046}, // printScreen {0x00000047, 0x00070047}, // scrollLock {0x00000048, 0x00070048}, // pause {0x00000049, 0x00070049}, // insert {0x0000004a, 0x0007004a}, // home {0x0000004b, 0x0007004b}, // pageUp {0x0000004c, 0x0007004c}, // delete {0x0000004d, 0x0007004d}, // end {0x0000004e, 0x0007004e}, // pageDown {0x0000004f, 0x0007004f}, // arrowRight {0x00000050, 0x00070050}, // arrowLeft {0x00000051, 0x00070051}, // arrowDown {0x00000052, 0x00070052}, // arrowUp {0x00000053, 0x00070053}, // numLock {0x00000054, 0x00070054}, // numpadDivide {0x00000055, 0x00070055}, // numpadMultiply {0x00000056, 0x00070056}, // numpadSubtract {0x00000057, 0x00070057}, // numpadAdd {0x00000058, 0x00070058}, // numpadEnter {0x00000059, 0x00070059}, // numpad1 {0x0000005a, 0x0007005a}, // numpad2 {0x0000005b, 0x0007005b}, // numpad3 {0x0000005c, 0x0007005c}, // numpad4 {0x0000005d, 0x0007005d}, // numpad5 {0x0000005e, 0x0007005e}, // numpad6 {0x0000005f, 0x0007005f}, // numpad7 {0x00000060, 0x00070060}, // numpad8 {0x00000061, 0x00070061}, // numpad9 {0x00000062, 0x00070062}, // numpad0 {0x00000063, 0x00070063}, // numpadDecimal {0x00000064, 0x00070064}, // intlBackslash {0x00000065, 0x00070065}, // contextMenu {0x00000066, 0x00070066}, // power {0x00000067, 0x00070067}, // numpadEqual {0x00000068, 0x00070068}, // f13 {0x00000069, 0x00070069}, // f14 {0x0000006a, 0x0007006a}, // f15 {0x0000006b, 0x0007006b}, // f16 {0x0000006c, 0x0007006c}, // f17 {0x0000006d, 0x0007006d}, // f18 {0x0000006e, 0x0007006e}, // f19 {0x0000006f, 0x0007006f}, // f20 {0x00000070, 0x00070070}, // f21 {0x00000071, 0x00070071}, // f22 {0x00000072, 0x00070072}, // f23 {0x00000073, 0x00070073}, // f24 {0x00000074, 0x00070074}, // open {0x00000075, 0x00070075}, // help {0x00000077, 0x00070077}, // select {0x00000079, 0x00070079}, // again {0x0000007a, 0x0007007a}, // undo {0x0000007b, 0x0007007b}, // cut {0x0000007c, 0x0007007c}, // copy {0x0000007d, 0x0007007d}, // paste {0x0000007e, 0x0007007e}, // find {0x0000007f, 0x0007007f}, // audioVolumeMute {0x00000080, 0x00070080}, // audioVolumeUp {0x00000081, 0x00070081}, // audioVolumeDown {0x00000085, 0x00070085}, // numpadComma {0x00000087, 0x00070087}, // intlRo {0x00000088, 0x00070088}, // kanaMode {0x00000089, 0x00070089}, // intlYen {0x0000008a, 0x0007008a}, // convert {0x0000008b, 0x0007008b}, // nonConvert {0x00000090, 0x00070090}, // lang1 {0x00000091, 0x00070091}, // lang2 {0x00000092, 0x00070092}, // lang3 {0x00000093, 0x00070093}, // lang4 {0x00000094, 0x00070094}, // lang5 {0x0000009b, 0x0007009b}, // abort {0x000000a3, 0x000700a3}, // props {0x000000b6, 0x000700b6}, // numpadParenLeft {0x000000b7, 0x000700b7}, // numpadParenRight {0x000000bb, 0x000700bb}, // numpadBackspace {0x000000d0, 0x000700d0}, // numpadMemoryStore {0x000000d1, 0x000700d1}, // numpadMemoryRecall {0x000000d2, 0x000700d2}, // numpadMemoryClear {0x000000d3, 0x000700d3}, // numpadMemoryAdd {0x000000d4, 0x000700d4}, // numpadMemorySubtract {0x000000d7, 0x000700d7}, // numpadSignChange {0x000000d8, 0x000700d8}, // numpadClear {0x000000d9, 0x000700d9}, // numpadClearEntry {0x000000e0, 0x000700e0}, // controlLeft {0x000000e1, 0x000700e1}, // shiftLeft {0x000000e2, 0x000700e2}, // altLeft {0x000000e3, 0x000700e3}, // metaLeft {0x000000e4, 0x000700e4}, // controlRight {0x000000e5, 0x000700e5}, // shiftRight {0x000000e6, 0x000700e6}, // altRight {0x000000e7, 0x000700e7}, // metaRight }; // Maps iOS-specific virtual key code values to logical keys representing // LogicalKeyboardKey const std::map<uint32_t, uint64_t> keyCodeToLogicalKey = { {0x00000028, 0x0010000000d}, // Enter {0x00000029, 0x0010000001b}, // Escape {0x0000002a, 0x00100000008}, // Backspace {0x0000002b, 0x00100000009}, // Tab {0x00000039, 0x00100000104}, // CapsLock {0x0000003a, 0x00100000801}, // F1 {0x0000003b, 0x00100000802}, // F2 {0x0000003c, 0x00100000803}, // F3 {0x0000003d, 0x00100000804}, // F4 {0x0000003e, 0x00100000805}, // F5 {0x0000003f, 0x00100000806}, // F6 {0x00000040, 0x00100000807}, // F7 {0x00000041, 0x00100000808}, // F8 {0x00000042, 0x00100000809}, // F9 {0x00000043, 0x0010000080a}, // F10 {0x00000044, 0x0010000080b}, // F11 {0x00000045, 0x0010000080c}, // F12 {0x00000049, 0x00100000407}, // Insert {0x0000004a, 0x00100000306}, // Home {0x0000004b, 0x00100000308}, // PageUp {0x0000004c, 0x0010000007f}, // Delete {0x0000004d, 0x00100000305}, // End {0x0000004e, 0x00100000307}, // PageDown {0x0000004f, 0x00100000303}, // ArrowRight {0x00000050, 0x00100000302}, // ArrowLeft {0x00000051, 0x00100000301}, // ArrowDown {0x00000052, 0x00100000304}, // ArrowUp {0x00000053, 0x0010000010a}, // NumLock {0x00000054, 0x0020000022f}, // NumpadDivide {0x00000055, 0x0020000022a}, // NumpadMultiply {0x00000056, 0x0020000022d}, // NumpadSubtract {0x00000057, 0x0020000022b}, // NumpadAdd {0x00000058, 0x0020000020d}, // NumpadEnter {0x00000059, 0x00200000231}, // Numpad1 {0x0000005a, 0x00200000232}, // Numpad2 {0x0000005b, 0x00200000233}, // Numpad3 {0x0000005c, 0x00200000234}, // Numpad4 {0x0000005d, 0x00200000235}, // Numpad5 {0x0000005e, 0x00200000236}, // Numpad6 {0x0000005f, 0x00200000237}, // Numpad7 {0x00000060, 0x00200000238}, // Numpad8 {0x00000061, 0x00200000239}, // Numpad9 {0x00000062, 0x00200000230}, // Numpad0 {0x00000063, 0x0020000022e}, // NumpadDecimal {0x00000065, 0x00100000505}, // ContextMenu {0x00000067, 0x0020000023d}, // NumpadEqual {0x00000068, 0x0010000080d}, // F13 {0x00000069, 0x0010000080e}, // F14 {0x0000006a, 0x0010000080f}, // F15 {0x0000006b, 0x00100000810}, // F16 {0x0000006c, 0x00100000811}, // F17 {0x0000006d, 0x00100000812}, // F18 {0x0000006e, 0x00100000813}, // F19 {0x0000006f, 0x00100000814}, // F20 {0x0000007f, 0x00100000a11}, // AudioVolumeMute {0x00000080, 0x00100000a10}, // AudioVolumeUp {0x00000081, 0x00100000a0f}, // AudioVolumeDown {0x00000085, 0x0020000022c}, // NumpadComma {0x00000087, 0x00200000021}, // IntlRo {0x00000089, 0x00200000022}, // IntlYen {0x00000090, 0x00200000010}, // Lang1 {0x00000091, 0x00200000011}, // Lang2 {0x00000092, 0x00200000012}, // Lang3 {0x00000093, 0x00200000013}, // Lang4 {0x00000094, 0x00200000014}, // Lang5 {0x000000e0, 0x00200000100}, // ControlLeft {0x000000e1, 0x00200000102}, // ShiftLeft {0x000000e2, 0x00200000104}, // AltLeft {0x000000e3, 0x00200000106}, // MetaLeft {0x000000e4, 0x00200000101}, // ControlRight {0x000000e5, 0x00200000103}, // ShiftRight {0x000000e6, 0x00200000105}, // AltRight {0x000000e7, 0x00200000107}, // MetaRight }; // Maps iOS-specific virtual key codes to an equivalent modifier flag enum // value. const std::map<uint32_t, ModifierFlag> keyCodeToModifierFlag = { {0x000000e1, kModifierFlagShiftLeft}, // ShiftLeft {0x000000e5, kModifierFlagShiftRight}, // ShiftRight {0x000000e0, kModifierFlagControlLeft}, // ControlLeft {0x000000e4, kModifierFlagControlRight}, // ControlRight {0x000000e2, kModifierFlagAltLeft}, // AltLeft {0x000000e6, kModifierFlagAltRight}, // AltRight {0x000000e3, kModifierFlagMetaLeft}, // MetaLeft {0x000000e7, kModifierFlagMetaRight}, // MetaRight }; // Maps modifier flag enum values to an iOS-specific virtual key code. const std::map<ModifierFlag, uint32_t> modifierFlagToKeyCode = { {kModifierFlagShiftLeft, 0x000000e1}, // ShiftLeft {kModifierFlagShiftRight, 0x000000e5}, // ShiftRight {kModifierFlagControlLeft, 0x000000e0}, // ControlLeft {kModifierFlagControlRight, 0x000000e4}, // ControlRight {kModifierFlagAltLeft, 0x000000e2}, // AltLeft {kModifierFlagAltRight, 0x000000e6}, // AltRight {kModifierFlagMetaLeft, 0x000000e3}, // MetaLeft {kModifierFlagMetaRight, 0x000000e7}, // MetaRight }; // A set of virtual key codes mapping to function keys, so that may be // identified as such. const std::set<uint32_t> functionKeyCodes = { 0x0000003a, // f1 0x0000003b, // f2 0x0000003c, // f3 0x0000003d, // f4 0x0000003e, // f5 0x0000003f, // f6 0x00000040, // f7 0x00000041, // f8 0x00000042, // f9 0x00000043, // f10 0x00000044, // f11 0x00000045, // f12 0x00000068, // f13 0x00000069, // f14 0x0000006a, // f15 0x0000006b, // f16 0x0000006c, // f17 0x0000006d, // f18 0x0000006e, // f19 0x0000006f, // f20 0x00000070, // f21 0x00000071, // f22 0x00000072, // f23 0x00000073, // f24 }; API_AVAILABLE(ios(13.4)) NSDictionary<NSString*, NSNumber*>* specialKeyMapping = [[NSDictionary alloc] initWithDictionary:@{ @"UIKeyInputEscape" : @(0x10000001b), @"UIKeyInputF1" : @(0x100000801), @"UIKeyInputF2" : @(0x100000802), @"UIKeyInputF3" : @(0x100000803), @"UIKeyInputF4" : @(0x100000804), @"UIKeyInputF5" : @(0x100000805), @"UIKeyInputF6" : @(0x100000806), @"UIKeyInputF7" : @(0x100000807), @"UIKeyInputF8" : @(0x100000808), @"UIKeyInputF9" : @(0x100000809), @"UIKeyInputF10" : @(0x10000080a), @"UIKeyInputF11" : @(0x10000080b), @"UIKeyInputF12" : @(0x10000080c), @"UIKeyInputUpArrow" : @(0x100000304), @"UIKeyInputDownArrow" : @(0x100000301), @"UIKeyInputLeftArrow" : @(0x100000302), @"UIKeyInputRightArrow" : @(0x100000303), @"UIKeyInputHome" : @(0x100000306), @"UIKeyInputEnd" : @(0x10000000d), @"UIKeyInputPageUp" : @(0x100000308), @"UIKeyInputPageDown" : @(0x100000307), }]; const uint64_t kCapsLockPhysicalKey = 0x00070039; const uint64_t kCapsLockLogicalKey = 0x100000104;
engine/shell/platform/darwin/ios/framework/Source/KeyCodeMap.g.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/KeyCodeMap.g.mm", "repo_id": "engine", "token_count": 6758 }
322
// 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 <tuple> #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "flutter/shell/platform/darwin/common/availability_version_check.h" @interface AvailabilityVersionCheckTest : XCTestCase @end @implementation AvailabilityVersionCheckTest - (void)testSimple { auto maybe_product_version = flutter::ProductVersionFromSystemVersionPList(); XCTAssertTrue(maybe_product_version.has_value()); if (maybe_product_version.has_value()) { auto product_version = maybe_product_version.value(); XCTAssertTrue(product_version > std::make_tuple(0, 0, 0)); } } @end
engine/shell/platform/darwin/ios/framework/Source/availability_version_check_test.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/framework/Source/availability_version_check_test.mm", "repo_id": "engine", "token_count": 243 }
323
// 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_context_metal_skia.h" #include "flutter/common/graphics/persistent_cache.h" #include "flutter/fml/logging.h" #import "flutter/shell/platform/darwin/graphics/FlutterDarwinContextMetalSkia.h" #import "flutter/shell/platform/darwin/ios/ios_external_texture_metal.h" #include "third_party/skia/include/gpu/GrContextOptions.h" namespace flutter { IOSContextMetalSkia::IOSContextMetalSkia(MsaaSampleCount msaa_samples) : IOSContext(msaa_samples) { darwin_context_metal_ = fml::scoped_nsobject<FlutterDarwinContextMetalSkia>{ [[FlutterDarwinContextMetalSkia alloc] initWithDefaultMTLDevice]}; } IOSContextMetalSkia::~IOSContextMetalSkia() = default; fml::scoped_nsobject<FlutterDarwinContextMetalSkia> IOSContextMetalSkia::GetDarwinContext() const { return darwin_context_metal_; } IOSRenderingBackend IOSContextMetalSkia::GetBackend() const { return IOSRenderingBackend::kSkia; } sk_sp<GrDirectContext> IOSContextMetalSkia::GetMainContext() const { return darwin_context_metal_.get().mainContext; } sk_sp<GrDirectContext> IOSContextMetalSkia::GetResourceContext() const { return darwin_context_metal_.get().resourceContext; } // |IOSContext| sk_sp<GrDirectContext> IOSContextMetalSkia::CreateResourceContext() { return darwin_context_metal_.get().resourceContext; } // |IOSContext| std::unique_ptr<GLContextResult> IOSContextMetalSkia::MakeCurrent() { // This only makes sense for context that need to be bound to a specific thread. return std::make_unique<GLContextDefaultResult>(true); } // |IOSContext| std::unique_ptr<Texture> IOSContextMetalSkia::CreateExternalTexture( int64_t texture_id, fml::scoped_nsobject<NSObject<FlutterTexture>> texture) { return std::make_unique<IOSExternalTextureMetal>( fml::scoped_nsobject<FlutterDarwinExternalTextureMetal>{ [[darwin_context_metal_ createExternalTextureWithIdentifier:texture_id texture:texture] retain]}); } } // namespace flutter
engine/shell/platform/darwin/ios/ios_context_metal_skia.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/ios_context_metal_skia.mm", "repo_id": "engine", "token_count": 800 }
324
// 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/platform_message_handler_ios.h" #import "flutter/fml/trace_event.h" #import "flutter/lib/ui/window/platform_message.h" #import "flutter/shell/platform/darwin/common/buffer_conversions.h" #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" static uint64_t platform_message_counter = 1; @interface FLTSerialTaskQueue : NSObject <FlutterTaskQueueDispatch> @property(nonatomic, strong) dispatch_queue_t queue; @end @implementation FLTSerialTaskQueue - (instancetype)init { self = [super init]; if (self) { _queue = dispatch_queue_create("FLTSerialTaskQueue", DISPATCH_QUEUE_SERIAL); } return self; } - (void)dealloc { dispatch_release(_queue); [super dealloc]; } - (void)dispatch:(dispatch_block_t)block { dispatch_async(self.queue, block); } @end namespace flutter { NSObject<FlutterTaskQueue>* PlatformMessageHandlerIos::MakeBackgroundTaskQueue() { return [[[FLTSerialTaskQueue alloc] init] autorelease]; } PlatformMessageHandlerIos::PlatformMessageHandlerIos( fml::RefPtr<fml::TaskRunner> platform_task_runner) : platform_task_runner_(std::move(platform_task_runner)) {} void PlatformMessageHandlerIos::HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) { // This can be called from any isolate's thread. @autoreleasepool { fml::RefPtr<flutter::PlatformMessageResponse> completer = message->response(); HandlerInfo handler_info; { // TODO(gaaclarke): This mutex is a bottleneck for multiple isolates sending // messages at the same time. This could be potentially changed to a // read-write lock. std::lock_guard lock(message_handlers_mutex_); auto it = message_handlers_.find(message->channel()); if (it != message_handlers_.end()) { handler_info = it->second; } } if (handler_info.handler) { FlutterBinaryMessageHandler handler = handler_info.handler; NSData* data = nil; if (message->hasData()) { data = ConvertMappingToNSData(message->releaseData()); } uint64_t platform_message_id = platform_message_counter++; TRACE_EVENT_ASYNC_BEGIN1("flutter", "PlatformChannel ScheduleHandler", platform_message_id, "channel", message->channel().c_str()); dispatch_block_t run_handler = ^{ handler(data, ^(NSData* reply) { TRACE_EVENT_ASYNC_END0("flutter", "PlatformChannel ScheduleHandler", platform_message_id); // Called from any thread. if (completer) { if (reply) { completer->Complete(ConvertNSDataToMappingPtr(reply)); } else { completer->CompleteEmpty(); } } }); }; if (handler_info.task_queue.get()) { [handler_info.task_queue.get() dispatch:run_handler]; } else { dispatch_async(dispatch_get_main_queue(), run_handler); } } else { if (completer) { completer->CompleteEmpty(); } } } } bool PlatformMessageHandlerIos::DoesHandlePlatformMessageOnPlatformThread() const { return false; } void PlatformMessageHandlerIos::InvokePlatformMessageResponseCallback( int response_id, std::unique_ptr<fml::Mapping> mapping) { // Called from any thread. // TODO(gaaclarke): This vestigal from the Android implementation, find a way // to migrate this to PlatformMessageHandlerAndroid. } void PlatformMessageHandlerIos::InvokePlatformMessageEmptyResponseCallback(int response_id) { // Called from any thread. // TODO(gaaclarke): This vestigal from the Android implementation, find a way // to migrate this to PlatformMessageHandlerAndroid. } void PlatformMessageHandlerIos::SetMessageHandler(const std::string& channel, FlutterBinaryMessageHandler handler, NSObject<FlutterTaskQueue>* task_queue) { FML_CHECK(platform_task_runner_->RunsTasksOnCurrentThread()); // Use `respondsToSelector` instead of `conformsToProtocol` to accomodate // injecting your own `FlutterTaskQueue`. This is not a supported usage but // not one worth breaking. FML_CHECK(!task_queue || [task_queue respondsToSelector:@selector(dispatch:)]); /// TODO(gaaclarke): This should be migrated to a lockfree datastructure. std::lock_guard lock(message_handlers_mutex_); message_handlers_.erase(channel); if (handler) { message_handlers_[channel] = { .task_queue = fml::scoped_nsprotocol( [static_cast<NSObject<FlutterTaskQueueDispatch>*>(task_queue) retain]), .handler = fml::ScopedBlock<FlutterBinaryMessageHandler>{ handler, fml::scoped_policy::OwnershipPolicy::kRetain}, }; } } } // namespace flutter
engine/shell/platform/darwin/ios/platform_message_handler_ios.mm/0
{ "file_path": "engine/shell/platform/darwin/ios/platform_message_handler_ios.mm", "repo_id": "engine", "token_count": 1885 }
325
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleExecutable</key> <string>FlutterMacOS</string> <key>CFBundleIdentifier</key> <string>io.flutter.flutter-macos</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>FlutterMacOS</string> <key>CFBundlePackageType</key> <string>FMWK</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1.0</string> <key>NSPrincipalClass</key> <string></string> </dict> </plist>
engine/shell/platform/darwin/macos/framework/Info.plist/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Info.plist", "repo_id": "engine", "token_count": 307 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterCompositor.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMutatorView.h" #include "flutter/fml/logging.h" namespace flutter { namespace { std::vector<PlatformViewLayerWithIndex> CopyPlatformViewLayers(const FlutterLayer** layers, size_t layer_count) { std::vector<PlatformViewLayerWithIndex> platform_views; for (size_t i = 0; i < layer_count; i++) { if (layers[i]->type == kFlutterLayerContentTypePlatformView) { platform_views.push_back(std::make_pair(PlatformViewLayer(layers[i]), i)); } } return platform_views; } } // namespace FlutterCompositor::FlutterCompositor(id<FlutterViewProvider> view_provider, FlutterTimeConverter* time_converter, FlutterPlatformViewController* platform_view_controller) : view_provider_(view_provider), time_converter_(time_converter), platform_view_controller_(platform_view_controller), mutator_views_([NSMapTable strongToStrongObjectsMapTable]) { FML_CHECK(view_provider != nullptr) << "view_provider cannot be nullptr"; } bool FlutterCompositor::CreateBackingStore(const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out) { // TODO(dkwingsmt): This class only supports single-view for now. As more // classes are gradually converted to multi-view, it should get the view ID // from somewhere. FlutterView* view = [view_provider_ viewForId:kFlutterImplicitViewId]; if (!view) { return false; } CGSize size = CGSizeMake(config->size.width, config->size.height); FlutterSurface* surface = [view.surfaceManager surfaceForSize:size]; memset(backing_store_out, 0, sizeof(FlutterBackingStore)); backing_store_out->struct_size = sizeof(FlutterBackingStore); backing_store_out->type = kFlutterBackingStoreTypeMetal; backing_store_out->metal.struct_size = sizeof(FlutterMetalBackingStore); backing_store_out->metal.texture = surface.asFlutterMetalTexture; return true; } bool FlutterCompositor::Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) { FlutterView* view = [view_provider_ viewForId:view_id]; if (!view) { return false; } NSMutableArray* surfaces = [NSMutableArray array]; for (size_t i = 0; i < layers_count; i++) { const FlutterLayer* layer = layers[i]; if (layer->type == kFlutterLayerContentTypeBackingStore) { FlutterSurface* surface = [FlutterSurface fromFlutterMetalTexture:&layer->backing_store->metal.texture]; if (surface) { FlutterSurfacePresentInfo* info = [[FlutterSurfacePresentInfo alloc] init]; info.surface = surface; info.offset = CGPointMake(layer->offset.x, layer->offset.y); info.zIndex = i; FlutterBackingStorePresentInfo* present_info = layer->backing_store_present_info; if (present_info != nullptr && present_info->paint_region != nullptr) { auto paint_region = present_info->paint_region; // Safe because the size of FlutterRect is not expected to change. info.paintRegion = std::vector<FlutterRect>( paint_region->rects, paint_region->rects + paint_region->rects_count); } [surfaces addObject:info]; } } } CFTimeInterval presentation_time = 0; if (layers_count > 0 && layers[0]->presentation_time != 0) { presentation_time = [time_converter_ engineTimeToCAMediaTime:layers[0]->presentation_time]; } // Notify block below may be called asynchronously, hence the need to copy // the layer information instead of passing the original pointers from embedder. auto platform_views_layers = std::make_shared<std::vector<PlatformViewLayerWithIndex>>( CopyPlatformViewLayers(layers, layers_count)); [view.surfaceManager presentSurfaces:surfaces atTime:presentation_time notify:^{ PresentPlatformViews(view, *platform_views_layers); }]; return true; } void FlutterCompositor::PresentPlatformViews( FlutterView* default_base_view, const std::vector<PlatformViewLayerWithIndex>& platform_views) { FML_DCHECK([[NSThread currentThread] isMainThread]) << "Must be on the main thread to present platform views"; // Active mutator views for this frame. NSMutableArray<FlutterMutatorView*>* present_mutators = [NSMutableArray array]; for (const auto& platform_view : platform_views) { [present_mutators addObject:PresentPlatformView(default_base_view, platform_view.first, platform_view.second)]; } NSMutableArray<FlutterMutatorView*>* obsolete_mutators = [NSMutableArray arrayWithArray:[mutator_views_ objectEnumerator].allObjects]; [obsolete_mutators removeObjectsInArray:present_mutators]; for (FlutterMutatorView* mutator in obsolete_mutators) { [mutator_views_ removeObjectForKey:mutator.platformView]; [mutator removeFromSuperview]; } [platform_view_controller_ disposePlatformViews]; } FlutterMutatorView* FlutterCompositor::PresentPlatformView(FlutterView* default_base_view, const PlatformViewLayer& layer, size_t index) { FML_DCHECK([[NSThread currentThread] isMainThread]) << "Must be on the main thread to present platform views"; int64_t platform_view_id = layer.identifier(); NSView* platform_view = [platform_view_controller_ platformViewWithID:platform_view_id]; FML_DCHECK(platform_view) << "Platform view not found for id: " << platform_view_id; FlutterMutatorView* container = [mutator_views_ objectForKey:platform_view]; if (!container) { container = [[FlutterMutatorView alloc] initWithPlatformView:platform_view]; [mutator_views_ setObject:container forKey:platform_view]; [default_base_view addSubview:container]; } container.layer.zPosition = index; [container applyFlutterLayer:&layer]; return container; } } // namespace flutter
engine/shell/platform/darwin/macos/framework/Source/FlutterCompositor.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterCompositor.mm", "repo_id": "engine", "token_count": 2544 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h" #include "flutter/fml/platform/darwin/cf_utils.h" @implementation FlutterExternalTexture { FlutterDarwinContextMetalSkia* _darwinMetalContext; int64_t _textureID; id<FlutterTexture> _texture; std::vector<FlutterMetalTextureHandle> _textures; } - (instancetype)initWithFlutterTexture:(id<FlutterTexture>)texture darwinMetalContext:(FlutterDarwinContextMetalSkia*)context { self = [super init]; if (self) { _texture = texture; _textureID = reinterpret_cast<int64_t>(_texture); _darwinMetalContext = context; } return self; } - (int64_t)textureID { return _textureID; } - (BOOL)populateTexture:(FlutterMetalExternalTexture*)textureOut { // Copy the pixel buffer from the FlutterTexture instance implemented on the user side. fml::CFRef<CVPixelBufferRef> pixelBuffer([_texture copyPixelBuffer]); if (!pixelBuffer) { return NO; } OSType pixel_format = CVPixelBufferGetPixelFormatType(pixelBuffer); if (pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange || pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) { return [self populateTextureFromYUVAPixelBuffer:pixelBuffer textureOut:textureOut]; } else { return [self populateTextureFromRGBAPixelBuffer:pixelBuffer textureOut:textureOut]; } } - (BOOL)populateTextureFromYUVAPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer textureOut:(nonnull FlutterMetalExternalTexture*)textureOut { CVMetalTextureRef yCVMetalTexture = nullptr; CVMetalTextureRef uvCVMetalTextureRef = nullptr; SkISize textureSize = SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); CVReturn yCVReturn = CVMetalTextureCacheCreateTextureFromImage( /*allocator=*/kCFAllocatorDefault, /*textureCache=*/_darwinMetalContext.textureCache, /*sourceImage=*/pixelBuffer, /*textureAttributes=*/nullptr, /*pixelFormat=*/MTLPixelFormatR8Unorm, /*width=*/CVPixelBufferGetWidthOfPlane(pixelBuffer, 0u), /*height=*/CVPixelBufferGetHeightOfPlane(pixelBuffer, 0u), /*planeIndex=*/0u, /*texture=*/&yCVMetalTexture); if (yCVReturn != kCVReturnSuccess) { NSLog(@"Could not create Metal texture from pixel buffer: CVReturn %d", yCVReturn); return NO; } CVReturn uvCVReturn = CVMetalTextureCacheCreateTextureFromImage( /*allocator=*/kCFAllocatorDefault, /*textureCache=*/_darwinMetalContext.textureCache, /*sourceImage=*/pixelBuffer, /*textureAttributes=*/nullptr, /*pixelFormat=*/MTLPixelFormatRG8Unorm, /*width=*/CVPixelBufferGetWidthOfPlane(pixelBuffer, 1u), /*height=*/CVPixelBufferGetHeightOfPlane(pixelBuffer, 1u), /*planeIndex=*/1u, /*texture=*/&uvCVMetalTextureRef); if (uvCVReturn != kCVReturnSuccess) { CVBufferRelease(yCVMetalTexture); NSLog(@"Could not create Metal texture from pixel buffer: CVReturn %d", uvCVReturn); return NO; } _textures = {(__bridge FlutterMetalTextureHandle)CVMetalTextureGetTexture(yCVMetalTexture), (__bridge FlutterMetalTextureHandle)CVMetalTextureGetTexture(uvCVMetalTextureRef)}; CVBufferRelease(yCVMetalTexture); CVBufferRelease(uvCVMetalTextureRef); textureOut->num_textures = 2; textureOut->height = textureSize.height(); textureOut->width = textureSize.width(); textureOut->pixel_format = FlutterMetalExternalTexturePixelFormat::kYUVA; textureOut->textures = _textures.data(); OSType pixel_format = CVPixelBufferGetPixelFormatType(pixelBuffer); textureOut->yuv_color_space = pixel_format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange ? FlutterMetalExternalTextureYUVColorSpace::kBT601LimitedRange : FlutterMetalExternalTextureYUVColorSpace::kBT601FullRange; return YES; } - (BOOL)populateTextureFromRGBAPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer textureOut:(nonnull FlutterMetalExternalTexture*)textureOut { SkISize textureSize = SkISize::Make(CVPixelBufferGetWidth(pixelBuffer), CVPixelBufferGetHeight(pixelBuffer)); CVMetalTextureRef cvMetalTexture = nullptr; CVReturn cvReturn = CVMetalTextureCacheCreateTextureFromImage(/*allocator=*/kCFAllocatorDefault, /*textureCache=*/_darwinMetalContext.textureCache, /*sourceImage=*/pixelBuffer, /*textureAttributes=*/nullptr, /*pixelFormat=*/MTLPixelFormatBGRA8Unorm, /*width=*/textureSize.width(), /*height=*/textureSize.height(), /*planeIndex=*/0u, /*texture=*/&cvMetalTexture); if (cvReturn != kCVReturnSuccess) { NSLog(@"Could not create Metal texture from pixel buffer: CVReturn %d", cvReturn); return NO; } _textures = {(__bridge FlutterMetalTextureHandle)CVMetalTextureGetTexture(cvMetalTexture)}; CVBufferRelease(cvMetalTexture); textureOut->num_textures = 1; textureOut->height = textureSize.height(); textureOut->width = textureSize.width(); textureOut->pixel_format = FlutterMetalExternalTexturePixelFormat::kRGBA; textureOut->textures = _textures.data(); return YES; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.mm", "repo_id": "engine", "token_count": 2276 }
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/macos/framework/Source/FlutterPlatformNodeDelegateMac.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterAppDelegate.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #include "flutter/third_party/accessibility/ax/ax_action_data.h" #include "flutter/third_party/accessibility/ax/ax_node_position.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node.h" #include "flutter/third_party/accessibility/ax/platform/ax_platform_node_base.h" #include "flutter/third_party/accessibility/base/string_utils.h" #include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h" #include "flutter/third_party/accessibility/gfx/mac/coordinate_conversion.h" namespace flutter { // namespace FlutterPlatformNodeDelegateMac::FlutterPlatformNodeDelegateMac( std::weak_ptr<AccessibilityBridge> bridge, __weak FlutterViewController* view_controller) : bridge_(std::move(bridge)), view_controller_(view_controller) {} void FlutterPlatformNodeDelegateMac::Init(std::weak_ptr<OwnerBridge> bridge, ui::AXNode* node) { FlutterPlatformNodeDelegate::Init(bridge, node); if (GetData().IsTextField()) { ax_platform_node_ = new FlutterTextPlatformNode(this, view_controller_); } else { ax_platform_node_ = ui::AXPlatformNode::Create(this); } NSCAssert(ax_platform_node_, @"Failed to create platform node."); } FlutterPlatformNodeDelegateMac::~FlutterPlatformNodeDelegateMac() { // Destroy() also calls delete on itself. ax_platform_node_->Destroy(); } gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetNativeViewAccessible() { NSCAssert(ax_platform_node_, @"Platform node does not exist."); return ax_platform_node_->GetNativeViewAccessible(); } gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetParent() { gfx::NativeViewAccessible parent = FlutterPlatformNodeDelegate::GetParent(); if (!parent) { NSCAssert(view_controller_.viewLoaded, @"Flutter view must be loaded"); return view_controller_.flutterView; } return parent; } gfx::Rect FlutterPlatformNodeDelegateMac::GetBoundsRect( const ui::AXCoordinateSystem coordinate_system, const ui::AXClippingBehavior clipping_behavior, ui::AXOffscreenResult* offscreen_result) const { gfx::Rect local_bounds = FlutterPlatformNodeDelegate::GetBoundsRect( coordinate_system, clipping_behavior, offscreen_result); gfx::RectF local_bounds_f(local_bounds); gfx::RectF screen_bounds = ConvertBoundsFromLocalToScreen(local_bounds_f); return gfx::ToEnclosingRect(ConvertBoundsFromScreenToGlobal(screen_bounds)); } gfx::NativeViewAccessible FlutterPlatformNodeDelegateMac::GetNSWindow() { FlutterAppDelegate* appDelegate = (FlutterAppDelegate*)[NSApp delegate]; return appDelegate.mainFlutterWindow; } std::string FlutterPlatformNodeDelegateMac::GetLiveRegionText() const { if (GetAXNode()->IsIgnored()) { return ""; } std::string text = GetData().GetStringAttribute(ax::mojom::StringAttribute::kName); if (!text.empty()) { return text; }; auto bridge_ptr = bridge_.lock(); NSCAssert(bridge_ptr, @"Accessibility bridge in flutter engine must not be null."); for (int32_t child : GetData().child_ids) { auto delegate_child = bridge_ptr->GetFlutterPlatformNodeDelegateFromID(child).lock(); if (!delegate_child) { continue; } text += std::static_pointer_cast<FlutterPlatformNodeDelegateMac>(delegate_child) ->GetLiveRegionText(); } return text; } gfx::RectF FlutterPlatformNodeDelegateMac::ConvertBoundsFromLocalToScreen( const gfx::RectF& local_bounds) const { // Converts to NSRect to use NSView rect conversion. NSRect ns_local_bounds = NSMakeRect(local_bounds.x(), local_bounds.y(), local_bounds.width(), local_bounds.height()); // The macOS XY coordinates start at bottom-left and increase toward top-right, // which is different from the Flutter's XY coordinates that start at top-left // increasing to bottom-right. Therefore, this method needs to flip the y coordinate when // it converts the bounds from flutter coordinates to macOS coordinates. ns_local_bounds.origin.y = -ns_local_bounds.origin.y - ns_local_bounds.size.height; NSCAssert(view_controller_.viewLoaded, @"Flutter view must be loaded."); NSRect ns_view_bounds = [view_controller_.flutterView convertRectFromBacking:ns_local_bounds]; NSRect ns_window_bounds = [view_controller_.flutterView convertRect:ns_view_bounds toView:nil]; NSRect ns_screen_bounds = [[view_controller_.flutterView window] convertRectToScreen:ns_window_bounds]; gfx::RectF screen_bounds(ns_screen_bounds.origin.x, ns_screen_bounds.origin.y, ns_screen_bounds.size.width, ns_screen_bounds.size.height); return screen_bounds; } gfx::RectF FlutterPlatformNodeDelegateMac::ConvertBoundsFromScreenToGlobal( const gfx::RectF& screen_bounds) const { // The VoiceOver seems to only accept bounds that are relative to primary screen. // Thus, this method uses [[NSScreen screens] firstObject] instead of [NSScreen mainScreen]. NSScreen* screen = [[NSScreen screens] firstObject]; NSRect primary_screen_bounds = [screen frame]; // The screen is flipped against y axis. float flipped_y = primary_screen_bounds.size.height - screen_bounds.y() - screen_bounds.height(); return {screen_bounds.x(), flipped_y, screen_bounds.width(), screen_bounds.height()}; } } // namespace flutter
engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterPlatformNodeDelegateMac.mm", "repo_id": "engine", "token_count": 1959 }
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. #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #include "flutter/third_party/accessibility/ax/ax_action_data.h" #include "flutter/third_party/accessibility/gfx/geometry/rect_conversions.h" #include "flutter/third_party/accessibility/gfx/mac/coordinate_conversion.h" #pragma mark - FlutterTextFieldCell /** * A convenient class that can be used to set a custom field editor for an * NSTextField. * * The FlutterTextField uses this class set the FlutterTextInputPlugin as * its field editor. */ @interface FlutterTextFieldCell : NSTextFieldCell /** * Initializes the NSCell for the input NSTextField. */ - (instancetype)initWithTextField:(NSTextField*)textField fieldEditor:(NSTextView*)editor; @end @implementation FlutterTextFieldCell { NSTextView* _editor; } #pragma mark - Private - (instancetype)initWithTextField:(NSTextField*)textField fieldEditor:(NSTextView*)editor { self = [super initTextCell:textField.stringValue]; if (self) { _editor = editor; [self setControlView:textField]; // Read-only text fields are sent to the mac embedding as static // text. This text field must be editable and selectable at this // point. self.editable = YES; self.selectable = YES; } return self; } #pragma mark - NSCell - (NSTextView*)fieldEditorForView:(NSView*)controlView { return _editor; } @end #pragma mark - FlutterTextField @implementation FlutterTextField { flutter::FlutterTextPlatformNode* _node; FlutterTextInputPlugin* _plugin; } #pragma mark - Public - (instancetype)initWithPlatformNode:(flutter::FlutterTextPlatformNode*)node fieldEditor:(FlutterTextInputPlugin*)plugin { self = [super initWithFrame:NSZeroRect]; if (self) { _node = node; _plugin = plugin; [self setCell:[[FlutterTextFieldCell alloc] initWithTextField:self fieldEditor:plugin]]; } return self; } - (void)updateString:(NSString*)string withSelection:(NSRange)selection { NSAssert(_plugin.client == self, @"Can't update FlutterTextField when it is not the first responder"); if (![[self stringValue] isEqualToString:string]) { [self setStringValue:string]; } if (!NSEqualRanges(_plugin.selectedRange, selection)) { [_plugin setSelectedRange:selection]; } } #pragma mark - NSView - (NSRect)frame { if (!_node) { return NSZeroRect; } return _node->GetFrame(); } #pragma mark - NSAccessibilityProtocol - (void)setAccessibilityFocused:(BOOL)isFocused { if (!_node) { return; } [super setAccessibilityFocused:isFocused]; ui::AXActionData data; data.action = isFocused ? ax::mojom::Action::kFocus : ax::mojom::Action::kBlur; _node->GetDelegate()->AccessibilityPerformAction(data); } - (void)startEditing { if (!_plugin) { return; } if (self.currentEditor == _plugin) { return; } if (!_node) { return; } // Selecting text seems to be the only way to make the field editor // current editor. [self selectText:self]; NSAssert(self.currentEditor == _plugin, @"Failed to set current editor"); _plugin.client = self; // Restore previous selection. NSString* textValue = @(_node->GetStringAttribute(ax::mojom::StringAttribute::kValue).data()); int start = _node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelStart); int end = _node->GetIntAttribute(ax::mojom::IntAttribute::kTextSelEnd); NSAssert((start >= 0 && end >= 0) || (start == -1 && end == -1), @"selection is invalid"); NSRange selection; if (start >= 0 && end >= 0) { selection = NSMakeRange(MIN(start, end), ABS(end - start)); } else { // The native behavior is to place the cursor at the end of the string if // there is no selection. selection = NSMakeRange([self stringValue].length, 0); } [self updateString:textValue withSelection:selection]; } - (void)setPlatformNode:(flutter::FlutterTextPlatformNode*)node { _node = node; } #pragma mark - NSObject - (void)dealloc { if (_plugin.client == self) { _plugin.client = nil; } } @end namespace flutter { FlutterTextPlatformNode::FlutterTextPlatformNode(FlutterPlatformNodeDelegate* delegate, __weak FlutterViewController* view_controller) { Init(delegate); view_controller_ = view_controller; appkit_text_field_ = [[FlutterTextField alloc] initWithPlatformNode:this fieldEditor:view_controller.textInputPlugin]; appkit_text_field_.bezeled = NO; appkit_text_field_.drawsBackground = NO; appkit_text_field_.bordered = NO; appkit_text_field_.focusRingType = NSFocusRingTypeNone; } FlutterTextPlatformNode::~FlutterTextPlatformNode() { [appkit_text_field_ setPlatformNode:nil]; EnsureDetachedFromView(); } gfx::NativeViewAccessible FlutterTextPlatformNode::GetNativeViewAccessible() { if (EnsureAttachedToView()) { return appkit_text_field_; } return nil; } NSRect FlutterTextPlatformNode::GetFrame() { if (!view_controller_.viewLoaded) { return NSZeroRect; } FlutterPlatformNodeDelegate* delegate = static_cast<FlutterPlatformNodeDelegate*>(GetDelegate()); bool offscreen; auto bridge_ptr = delegate->GetOwnerBridge().lock(); gfx::RectF bounds = bridge_ptr->RelativeToGlobalBounds(delegate->GetAXNode(), offscreen, true); // Converts to NSRect to use NSView rect conversion. NSRect ns_local_bounds = NSMakeRect(bounds.x(), bounds.y(), bounds.width(), bounds.height()); // The macOS XY coordinates start at bottom-left and increase toward top-right, // which is different from the Flutter's XY coordinates that start at top-left // increasing to bottom-right. Flip the y coordinate to convert from Flutter // coordinates to macOS coordinates. ns_local_bounds.origin.y = -ns_local_bounds.origin.y - ns_local_bounds.size.height; NSRect ns_view_bounds = [view_controller_.flutterView convertRectFromBacking:ns_local_bounds]; return [view_controller_.flutterView convertRect:ns_view_bounds toView:nil]; } bool FlutterTextPlatformNode::EnsureAttachedToView() { if (!view_controller_.viewLoaded) { return false; } if ([appkit_text_field_ isDescendantOf:view_controller_.view]) { return true; } [view_controller_.view addSubview:appkit_text_field_ positioned:NSWindowBelow relativeTo:view_controller_.flutterView]; return true; } void FlutterTextPlatformNode::EnsureDetachedFromView() { [appkit_text_field_ removeFromSuperview]; } } // namespace flutter
engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.mm", "repo_id": "engine", "token_count": 2441 }
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. #import "KeyCodeMap_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h" #import <OCMock/OCMock.h> #import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h" #import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterEngine.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngineTestUtils.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h" #import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTestUtils.h" #include "flutter/shell/platform/embedder/test_utils/key_codes.g.h" #include "flutter/testing/autoreleasepool_test.h" #include "flutter/testing/testing.h" #pragma mark - Test Helper Classes // A wrap to convert FlutterKeyEvent to a ObjC class. @interface KeyEventWrapper : NSObject @property(nonatomic) FlutterKeyEvent* data; - (nonnull instancetype)initWithEvent:(const FlutterKeyEvent*)event; @end @implementation KeyEventWrapper - (instancetype)initWithEvent:(const FlutterKeyEvent*)event { self = [super init]; _data = new FlutterKeyEvent(*event); return self; } - (void)dealloc { delete _data; } @end /// Responder wrapper that forwards key events to another responder. This is a necessary middle step /// for mocking responder because when setting the responder to controller AppKit will access ivars /// of the objects, which means it must extend NSResponder instead of just implementing the /// selectors. @interface FlutterResponderWrapper : NSResponder { NSResponder* _responder; } @end @implementation FlutterResponderWrapper - (instancetype)initWithResponder:(NSResponder*)responder { if (self = [super init]) { _responder = responder; } return self; } - (void)keyDown:(NSEvent*)event { [_responder keyDown:event]; } - (void)keyUp:(NSEvent*)event { [_responder keyUp:event]; } - (BOOL)performKeyEquivalent:(NSEvent*)event { return [_responder performKeyEquivalent:event]; } - (void)flagsChanged:(NSEvent*)event { [_responder flagsChanged:event]; } @end // A FlutterViewController subclass for testing that mouseDown/mouseUp get called when // mouse events are sent to the associated view. @interface MouseEventFlutterViewController : FlutterViewController @property(nonatomic, assign) BOOL mouseDownCalled; @property(nonatomic, assign) BOOL mouseUpCalled; @end @implementation MouseEventFlutterViewController - (void)mouseDown:(NSEvent*)event { self.mouseDownCalled = YES; } - (void)mouseUp:(NSEvent*)event { self.mouseUpCalled = YES; } @end @interface FlutterViewControllerTestObjC : NSObject - (bool)testKeyEventsAreSentToFramework:(id)mockEngine; - (bool)testKeyEventsArePropagatedIfNotHandled:(id)mockEngine; - (bool)testKeyEventsAreNotPropagatedIfHandled:(id)mockEngine; - (bool)testCtrlTabKeyEventIsPropagated:(id)mockEngine; - (bool)testKeyEquivalentIsPassedToTextInputPlugin:(id)mockEngine; - (bool)testFlagsChangedEventsArePropagatedIfNotHandled:(id)mockEngine; - (bool)testKeyboardIsRestartedOnEngineRestart:(id)mockEngine; - (bool)testTrackpadGesturesAreSentToFramework:(id)mockEngine; - (bool)testMouseDownUpEventsSentToNextResponder:(id)mockEngine; - (bool)testModifierKeysAreSynthesizedOnMouseMove:(id)mockEngine; - (bool)testViewWillAppearCalledMultipleTimes:(id)mockEngine; - (bool)testFlutterViewIsConfigured:(id)mockEngine; - (bool)testLookupKeyAssets; - (bool)testLookupKeyAssetsWithPackage; - (bool)testViewControllerIsReleased; + (void)respondFalseForSendEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData; @end #pragma mark - Static helper functions using namespace ::flutter::testing::keycodes; namespace flutter::testing { namespace { id MockGestureEvent(NSEventType type, NSEventPhase phase, double magnification, double rotation) { id event = [OCMockObject mockForClass:[NSEvent class]]; NSPoint locationInWindow = NSMakePoint(0, 0); CGFloat deltaX = 0; CGFloat deltaY = 0; NSTimeInterval timestamp = 1; NSUInteger modifierFlags = 0; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(type)] type]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(phase)] phase]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(locationInWindow)] locationInWindow]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(deltaX)] deltaX]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(deltaY)] deltaY]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(timestamp)] timestamp]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(modifierFlags)] modifierFlags]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(magnification)] magnification]; [(NSEvent*)[[event stub] andReturnValue:OCMOCK_VALUE(rotation)] rotation]; return event; } // Allocates and returns an engine configured for the test fixture resource configuration. FlutterEngine* CreateTestEngine() { NSString* fixtures = @(testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; return [[FlutterEngine alloc] initWithName:@"test" project:project allowHeadlessExecution:true]; } NSResponder* mockResponder() { NSResponder* mock = OCMStrictClassMock([NSResponder class]); OCMStub([mock keyDown:[OCMArg any]]).andDo(nil); OCMStub([mock keyUp:[OCMArg any]]).andDo(nil); OCMStub([mock flagsChanged:[OCMArg any]]).andDo(nil); return mock; } NSEvent* CreateMouseEvent(NSEventModifierFlags modifierFlags) { return [NSEvent mouseEventWithType:NSEventTypeMouseMoved location:NSZeroPoint modifierFlags:modifierFlags timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:1 pressure:1.0]; } } // namespace #pragma mark - gtest tests // Test-specific names for AutoreleasePoolTest, MockFlutterEngineTest fixtures. using FlutterViewControllerTest = AutoreleasePoolTest; using FlutterViewControllerMockEngineTest = MockFlutterEngineTest; TEST_F(FlutterViewControllerTest, HasViewThatHidesOtherViewsInAccessibility) { FlutterViewController* viewControllerMock = CreateMockViewController(); [viewControllerMock loadView]; auto subViews = [viewControllerMock.view subviews]; EXPECT_EQ([subViews count], 1u); EXPECT_EQ(subViews[0], viewControllerMock.flutterView); NSTextField* textField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 1, 1)]; [viewControllerMock.view addSubview:textField]; subViews = [viewControllerMock.view subviews]; EXPECT_EQ([subViews count], 2u); auto accessibilityChildren = viewControllerMock.view.accessibilityChildren; // The accessibilityChildren should only contains the FlutterView. EXPECT_EQ([accessibilityChildren count], 1u); EXPECT_EQ(accessibilityChildren[0], viewControllerMock.flutterView); } TEST_F(FlutterViewControllerTest, FlutterViewAcceptsFirstMouse) { FlutterViewController* viewControllerMock = CreateMockViewController(); [viewControllerMock loadView]; EXPECT_EQ([viewControllerMock.flutterView acceptsFirstMouse:nil], YES); } TEST_F(FlutterViewControllerTest, ReparentsPluginWhenAccessibilityDisabled) { FlutterEngine* engine = CreateTestEngine(); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; [viewController loadView]; [engine setViewController:viewController]; // Creates a NSWindow so that sub view can be first responder. NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]; window.contentView = viewController.view; NSView* dummyView = [[NSView alloc] initWithFrame:CGRectZero]; [viewController.view addSubview:dummyView]; // Attaches FlutterTextInputPlugin to the view; [dummyView addSubview:viewController.textInputPlugin]; // Makes sure the textInputPlugin can be the first responder. EXPECT_TRUE([window makeFirstResponder:viewController.textInputPlugin]); EXPECT_EQ([window firstResponder], viewController.textInputPlugin); EXPECT_FALSE(viewController.textInputPlugin.superview == viewController.view); [viewController onAccessibilityStatusChanged:NO]; // FlutterView becomes child of view controller EXPECT_TRUE(viewController.textInputPlugin.superview == viewController.view); } TEST_F(FlutterViewControllerTest, CanSetMouseTrackingModeBeforeViewLoaded) { NSString* fixtures = @(testing::GetFixturesPath()); FlutterDartProject* project = [[FlutterDartProject alloc] initWithAssetsPath:fixtures ICUDataPath:[fixtures stringByAppendingString:@"/icudtl.dat"]]; FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:project]; viewController.mouseTrackingMode = kFlutterMouseTrackingModeInActiveApp; ASSERT_EQ(viewController.mouseTrackingMode, kFlutterMouseTrackingModeInActiveApp); } TEST_F(FlutterViewControllerMockEngineTest, TestKeyEventsAreSentToFramework) { id mockEngine = GetMockEngine(); ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testKeyEventsAreSentToFramework:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestKeyEventsArePropagatedIfNotHandled) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testKeyEventsArePropagatedIfNotHandled:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestKeyEventsAreNotPropagatedIfHandled) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testKeyEventsAreNotPropagatedIfHandled:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestCtrlTabKeyEventIsPropagated) { id mockEngine = GetMockEngine(); ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testCtrlTabKeyEventIsPropagated:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestKeyEquivalentIsPassedToTextInputPlugin) { id mockEngine = GetMockEngine(); ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testKeyEquivalentIsPassedToTextInputPlugin:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestFlagsChangedEventsArePropagatedIfNotHandled) { id mockEngine = GetMockEngine(); ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testFlagsChangedEventsArePropagatedIfNotHandled:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestKeyboardIsRestartedOnEngineRestart) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testKeyboardIsRestartedOnEngineRestart:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestTrackpadGesturesAreSentToFramework) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testTrackpadGesturesAreSentToFramework:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestMouseDownUpEventsSentToNextResponder) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testMouseDownUpEventsSentToNextResponder:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, TestModifierKeysAreSynthesizedOnMouseMove) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testModifierKeysAreSynthesizedOnMouseMove:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, testViewWillAppearCalledMultipleTimes) { id mockEngine = GetMockEngine(); ASSERT_TRUE( [[FlutterViewControllerTestObjC alloc] testViewWillAppearCalledMultipleTimes:mockEngine]); } TEST_F(FlutterViewControllerMockEngineTest, testFlutterViewIsConfigured) { id mockEngine = GetMockEngine(); ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testFlutterViewIsConfigured:mockEngine]); } TEST_F(FlutterViewControllerTest, testLookupKeyAssets) { ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testLookupKeyAssets]); } TEST_F(FlutterViewControllerTest, testLookupKeyAssetsWithPackage) { ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testLookupKeyAssetsWithPackage]); } TEST_F(FlutterViewControllerTest, testViewControllerIsReleased) { ASSERT_TRUE([[FlutterViewControllerTestObjC alloc] testViewControllerIsReleased]); } } // namespace flutter::testing #pragma mark - FlutterViewControllerTestObjC @implementation FlutterViewControllerTestObjC - (bool)testKeyEventsAreSentToFramework:(id)engineMock { id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andCall([FlutterViewControllerTestObjC class], @selector(respondFalseForSendEvent:callback:userData:)); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; NSDictionary* expectedEvent = @{ @"keymap" : @"macos", @"type" : @"keydown", @"keyCode" : @(65), @"modifiers" : @(538968064), @"characters" : @".", @"charactersIgnoringModifiers" : @".", }; NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 65, TRUE); NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; [viewController viewWillAppear]; // Initializes the event channel. [viewController keyDown:event]; @try { OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]); } @catch (...) { return false; } return true; } // Regression test for https://github.com/flutter/flutter/issues/122084. - (bool)testCtrlTabKeyEventIsPropagated:(id)engineMock { __block bool called = false; __block FlutterKeyEvent last_event; OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andDo((^(NSInvocation* invocation) { FlutterKeyEvent* event; [invocation getArgument:&event atIndex:2]; called = true; last_event = *event; })); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; // Ctrl+tab NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint modifierFlags:0x40101 timestamp:0 windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:48]; const uint64_t kPhysicalKeyTab = 0x7002b; [viewController viewWillAppear]; // Initializes the event channel. // Creates a NSWindow so that FlutterView view can be first responder. NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]; window.contentView = viewController.view; [window makeFirstResponder:viewController.flutterView]; [viewController.view performKeyEquivalent:event]; EXPECT_TRUE(called); EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); EXPECT_EQ(last_event.physical, kPhysicalKeyTab); return true; } - (bool)testKeyEquivalentIsPassedToTextInputPlugin:(id)engineMock { __block bool called = false; __block FlutterKeyEvent last_event; OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andDo((^(NSInvocation* invocation) { FlutterKeyEvent* event; [invocation getArgument:&event atIndex:2]; called = true; last_event = *event; })); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; // Ctrl+tab NSEvent* event = [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint modifierFlags:0x40101 timestamp:0 windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:48]; const uint64_t kPhysicalKeyTab = 0x7002b; [viewController viewWillAppear]; // Initializes the event channel. NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 800, 600) styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO]; window.contentView = viewController.view; [viewController.view addSubview:viewController.textInputPlugin]; // Make the textInputPlugin first responder. This should still result in // view controller reporting the key event. [window makeFirstResponder:viewController.textInputPlugin]; [viewController.view performKeyEquivalent:event]; EXPECT_TRUE(called); EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); EXPECT_EQ(last_event.physical, kPhysicalKeyTab); return true; } - (bool)testKeyEventsArePropagatedIfNotHandled:(id)engineMock { id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andCall([FlutterViewControllerTestObjC class], @selector(respondFalseForSendEvent:callback:userData:)); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; id responderMock = flutter::testing::mockResponder(); id responderWrapper = [[FlutterResponderWrapper alloc] initWithResponder:responderMock]; viewController.nextResponder = responderWrapper; NSDictionary* expectedEvent = @{ @"keymap" : @"macos", @"type" : @"keydown", @"keyCode" : @(65), @"modifiers" : @(538968064), @"characters" : @".", @"charactersIgnoringModifiers" : @".", }; NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 65, TRUE); NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]) .andDo((^(NSInvocation* invocation) { FlutterBinaryReply handler; [invocation getArgument:&handler atIndex:4]; NSDictionary* reply = @{ @"handled" : @(false), }; NSData* encodedReply = [[FlutterJSONMessageCodec sharedInstance] encode:reply]; handler(encodedReply); })); [viewController viewWillAppear]; // Initializes the event channel. [viewController keyDown:event]; @try { OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) [responderMock keyDown:[OCMArg any]]); OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]); } @catch (...) { return false; } return true; } - (bool)testFlutterViewIsConfigured:(id)engineMock { FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; OCMStub([engineMock renderer]).andReturn(renderer_); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; [viewController loadView]; @try { // Make sure "renderer" was called during "loadView", which means "flutterView" is created OCMVerify([engineMock renderer]); } @catch (...) { return false; } return true; } - (bool)testFlagsChangedEventsArePropagatedIfNotHandled:(id)engineMock { id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andCall([FlutterViewControllerTestObjC class], @selector(respondFalseForSendEvent:callback:userData:)); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; id responderMock = flutter::testing::mockResponder(); id responderWrapper = [[FlutterResponderWrapper alloc] initWithResponder:responderMock]; viewController.nextResponder = responderWrapper; NSDictionary* expectedEvent = @{ @"keymap" : @"macos", @"type" : @"keydown", @"keyCode" : @(56), // SHIFT key @"modifiers" : @(537001986), }; NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 56, TRUE); // SHIFT key CGEventSetType(cgEvent, kCGEventFlagsChanged); NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]) .andDo((^(NSInvocation* invocation) { FlutterBinaryReply handler; [invocation getArgument:&handler atIndex:4]; NSDictionary* reply = @{ @"handled" : @(false), }; NSData* encodedReply = [[FlutterJSONMessageCodec sharedInstance] encode:reply]; handler(encodedReply); })); [viewController viewWillAppear]; // Initializes the event channel. [viewController flagsChanged:event]; @try { OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]); } @catch (NSException* e) { NSLog(@"%@", e.reason); return false; } return true; } - (bool)testKeyEventsAreNotPropagatedIfHandled:(id)engineMock { id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andCall([FlutterViewControllerTestObjC class], @selector(respondFalseForSendEvent:callback:userData:)); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; id responderMock = flutter::testing::mockResponder(); id responderWrapper = [[FlutterResponderWrapper alloc] initWithResponder:responderMock]; viewController.nextResponder = responderWrapper; NSDictionary* expectedEvent = @{ @"keymap" : @"macos", @"type" : @"keydown", @"keyCode" : @(65), @"modifiers" : @(538968064), @"characters" : @".", @"charactersIgnoringModifiers" : @".", }; NSData* encodedKeyEvent = [[FlutterJSONMessageCodec sharedInstance] encode:expectedEvent]; CGEventRef cgEvent = CGEventCreateKeyboardEvent(NULL, 65, TRUE); NSEvent* event = [NSEvent eventWithCGEvent:cgEvent]; OCMExpect( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]) .andDo((^(NSInvocation* invocation) { FlutterBinaryReply handler; [invocation getArgument:&handler atIndex:4]; NSDictionary* reply = @{ @"handled" : @(true), }; NSData* encodedReply = [[FlutterJSONMessageCodec sharedInstance] encode:reply]; handler(encodedReply); })); [viewController viewWillAppear]; // Initializes the event channel. [viewController keyDown:event]; @try { OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) never(), [responderMock keyDown:[OCMArg any]]); OCMVerify( // NOLINT(google-objc-avoid-throwing-exception) [binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:encodedKeyEvent binaryReply:[OCMArg any]]); } @catch (...) { return false; } return true; } - (bool)testKeyboardIsRestartedOnEngineRestart:(id)engineMock { id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); __block bool called = false; __block FlutterKeyEvent last_event; OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andDo((^(NSInvocation* invocation) { FlutterKeyEvent* event; [invocation getArgument:&event atIndex:2]; called = true; last_event = *event; })); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; [viewController viewWillAppear]; NSEvent* keyADown = [NSEvent keyEventWithType:NSEventTypeKeyDown location:NSZeroPoint modifierFlags:0x100 timestamp:0 windowNumber:0 context:nil characters:@"a" charactersIgnoringModifiers:@"a" isARepeat:FALSE keyCode:0]; const uint64_t kPhysicalKeyA = 0x70004; // Send KeyA key down event twice. Without restarting the keyboard during // onPreEngineRestart, the second event received will be an empty event with // physical key 0x0 because duplicate key down events are ignored. called = false; [viewController keyDown:keyADown]; EXPECT_TRUE(called); EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); EXPECT_EQ(last_event.physical, kPhysicalKeyA); [viewController onPreEngineRestart]; called = false; [viewController keyDown:keyADown]; EXPECT_TRUE(called); EXPECT_EQ(last_event.type, kFlutterKeyEventTypeDown); EXPECT_EQ(last_event.physical, kPhysicalKeyA); return true; } + (void)respondFalseForSendEvent:(const FlutterKeyEvent&)event callback:(nullable FlutterKeyEventCallback)callback userData:(nullable void*)userData { if (callback != nullptr) { callback(false, userData); } } - (bool)testTrackpadGesturesAreSentToFramework:(id)engineMock { // Need to return a real renderer to allow view controller to load. FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; OCMStub([engineMock renderer]).andReturn(renderer_); __block bool called = false; __block FlutterPointerEvent last_event; OCMStub([[engineMock ignoringNonObjectArgs] sendPointerEvent:FlutterPointerEvent{}]) .andDo((^(NSInvocation* invocation) { FlutterPointerEvent* event; [invocation getArgument:&event atIndex:2]; called = true; last_event = *event; })); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; [viewController loadView]; // Test for pan events. // Start gesture. CGEventRef cgEventStart = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); CGEventSetType(cgEventStart, kCGEventScrollWheel); CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventScrollPhase, kCGScrollPhaseBegan); CGEventSetIntegerValueField(cgEventStart, kCGScrollWheelEventIsContinuous, 1); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventStart]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomStart); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Update gesture. CGEventRef cgEventUpdate = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventScrollPhase, kCGScrollPhaseChanged); CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis2, 1); // pan_x CGEventSetIntegerValueField(cgEventUpdate, kCGScrollWheelEventDeltaAxis1, 2); // pan_y called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventUpdate]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomUpdate); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.pan_x, 8 * viewController.flutterView.layer.contentsScale); EXPECT_EQ(last_event.pan_y, 16 * viewController.flutterView.layer.contentsScale); // Make sure the pan values accumulate. called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventUpdate]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomUpdate); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.pan_x, 16 * viewController.flutterView.layer.contentsScale); EXPECT_EQ(last_event.pan_y, 32 * viewController.flutterView.layer.contentsScale); // End gesture. CGEventRef cgEventEnd = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventEnd, kCGScrollWheelEventScrollPhase, kCGScrollPhaseEnded); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventEnd]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomEnd); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Start system momentum. CGEventRef cgEventMomentumStart = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventMomentumStart, kCGScrollWheelEventScrollPhase, 0); CGEventSetIntegerValueField(cgEventMomentumStart, kCGScrollWheelEventMomentumPhase, kCGMomentumScrollPhaseBegin); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMomentumStart]]; EXPECT_FALSE(called); // Advance system momentum. CGEventRef cgEventMomentumUpdate = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventMomentumUpdate, kCGScrollWheelEventScrollPhase, 0); CGEventSetIntegerValueField(cgEventMomentumUpdate, kCGScrollWheelEventMomentumPhase, kCGMomentumScrollPhaseContinue); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMomentumUpdate]]; EXPECT_FALSE(called); // Mock a touch on the trackpad. id touchMock = OCMClassMock([NSTouch class]); NSSet* touchSet = [NSSet setWithObject:touchMock]; id touchEventMock1 = OCMClassMock([NSEvent class]); OCMStub([touchEventMock1 allTouches]).andReturn(touchSet); CGPoint touchLocation = {0, 0}; OCMStub([touchEventMock1 locationInWindow]).andReturn(touchLocation); OCMStub([(NSEvent*)touchEventMock1 timestamp]).andReturn(0.150); // 150 milliseconds. // Scroll inertia cancel event should not be issued (timestamp too far in the future). called = false; [viewController touchesBeganWithEvent:touchEventMock1]; EXPECT_FALSE(called); // Mock another touch on the trackpad. id touchEventMock2 = OCMClassMock([NSEvent class]); OCMStub([touchEventMock2 allTouches]).andReturn(touchSet); OCMStub([touchEventMock2 locationInWindow]).andReturn(touchLocation); OCMStub([(NSEvent*)touchEventMock2 timestamp]).andReturn(0.005); // 5 milliseconds. // Scroll inertia cancel event should be issued. called = false; [viewController touchesBeganWithEvent:touchEventMock2]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindScrollInertiaCancel); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); // End system momentum. CGEventRef cgEventMomentumEnd = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventMomentumEnd, kCGScrollWheelEventScrollPhase, 0); CGEventSetIntegerValueField(cgEventMomentumEnd, kCGScrollWheelEventMomentumPhase, kCGMomentumScrollPhaseEnd); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMomentumEnd]]; EXPECT_FALSE(called); // May-begin and cancel are used while macOS determines which type of gesture to choose. CGEventRef cgEventMayBegin = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventMayBegin, kCGScrollWheelEventScrollPhase, kCGScrollPhaseMayBegin); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventMayBegin]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomStart); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Cancel gesture. CGEventRef cgEventCancel = CGEventCreateCopy(cgEventStart); CGEventSetIntegerValueField(cgEventCancel, kCGScrollWheelEventScrollPhase, kCGScrollPhaseCancelled); called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventCancel]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomEnd); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // A discrete scroll event should use the PointerSignal system. CGEventRef cgEventDiscrete = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); CGEventSetType(cgEventDiscrete, kCGEventScrollWheel); CGEventSetIntegerValueField(cgEventDiscrete, kCGScrollWheelEventIsContinuous, 0); CGEventSetIntegerValueField(cgEventDiscrete, kCGScrollWheelEventDeltaAxis2, 1); // scroll_delta_x CGEventSetIntegerValueField(cgEventDiscrete, kCGScrollWheelEventDeltaAxis1, 2); // scroll_delta_y called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventDiscrete]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindScroll); // pixelsPerLine is 40.0 and direction is reversed. EXPECT_EQ(last_event.scroll_delta_x, -40 * viewController.flutterView.layer.contentsScale); EXPECT_EQ(last_event.scroll_delta_y, -80 * viewController.flutterView.layer.contentsScale); // A discrete scroll event should use the PointerSignal system, and flip the // direction when shift is pressed. CGEventRef cgEventDiscreteShift = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 1, 0); CGEventSetType(cgEventDiscreteShift, kCGEventScrollWheel); CGEventSetFlags(cgEventDiscreteShift, kCGEventFlagMaskShift | flutter::kModifierFlagShiftLeft); CGEventSetIntegerValueField(cgEventDiscreteShift, kCGScrollWheelEventIsContinuous, 0); CGEventSetIntegerValueField(cgEventDiscreteShift, kCGScrollWheelEventDeltaAxis2, 0); // scroll_delta_x CGEventSetIntegerValueField(cgEventDiscreteShift, kCGScrollWheelEventDeltaAxis1, 2); // scroll_delta_y called = false; [viewController scrollWheel:[NSEvent eventWithCGEvent:cgEventDiscreteShift]]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindScroll); // pixelsPerLine is 40.0, direction is reversed and axes have been flipped back. EXPECT_FLOAT_EQ(last_event.scroll_delta_x, 0.0 * viewController.flutterView.layer.contentsScale); EXPECT_FLOAT_EQ(last_event.scroll_delta_y, -80.0 * viewController.flutterView.layer.contentsScale); // Test for scale events. // Start gesture. called = false; [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, NSEventPhaseBegan, 1, 0)]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomStart); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Update gesture. called = false; [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, NSEventPhaseChanged, 1, 0)]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomUpdate); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.pan_x, 0); EXPECT_EQ(last_event.pan_y, 0); EXPECT_EQ(last_event.scale, 2); // macOS uses logarithmic scaling values, the linear value for // flutter here should be 2^1 = 2. EXPECT_EQ(last_event.rotation, 0); // Make sure the scale values accumulate. called = false; [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, NSEventPhaseChanged, 1, 0)]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomUpdate); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.pan_x, 0); EXPECT_EQ(last_event.pan_y, 0); EXPECT_EQ(last_event.scale, 4); // macOS uses logarithmic scaling values, the linear value for // flutter here should be 2^(1+1) = 2. EXPECT_EQ(last_event.rotation, 0); // End gesture. called = false; [viewController magnifyWithEvent:flutter::testing::MockGestureEvent(NSEventTypeMagnify, NSEventPhaseEnded, 0, 0)]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomEnd); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Test for rotation events. // Start gesture. called = false; [viewController rotateWithEvent:flutter::testing::MockGestureEvent(NSEventTypeRotate, NSEventPhaseBegan, 1, 0)]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomStart); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Update gesture. called = false; [viewController rotateWithEvent:flutter::testing::MockGestureEvent( NSEventTypeRotate, NSEventPhaseChanged, 0, -180)]; // degrees EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomUpdate); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.pan_x, 0); EXPECT_EQ(last_event.pan_y, 0); EXPECT_EQ(last_event.scale, 1); EXPECT_EQ(last_event.rotation, M_PI); // radians // Make sure the rotation values accumulate. called = false; [viewController rotateWithEvent:flutter::testing::MockGestureEvent( NSEventTypeRotate, NSEventPhaseChanged, 0, -360)]; // degrees EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomUpdate); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.pan_x, 0); EXPECT_EQ(last_event.pan_y, 0); EXPECT_EQ(last_event.scale, 1); EXPECT_EQ(last_event.rotation, 3 * M_PI); // radians // End gesture. called = false; [viewController rotateWithEvent:flutter::testing::MockGestureEvent(NSEventTypeRotate, NSEventPhaseEnded, 0, 0)]; EXPECT_TRUE(called); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(last_event.phase, kPanZoomEnd); EXPECT_EQ(last_event.device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(last_event.signal_kind, kFlutterPointerSignalKindNone); // Test that stray NSEventPhaseCancelled event does not crash called = false; [viewController rotateWithEvent:flutter::testing::MockGestureEvent(NSEventTypeRotate, NSEventPhaseCancelled, 0, 0)]; EXPECT_FALSE(called); return true; } - (bool)testViewWillAppearCalledMultipleTimes:(id)engineMock { FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; [viewController viewWillAppear]; [viewController viewWillAppear]; return true; } - (bool)testLookupKeyAssets { FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:nil]; NSString* key = [viewController lookupKeyForAsset:@"test.png"]; EXPECT_TRUE( [key isEqualToString:@"Contents/Frameworks/App.framework/Resources/flutter_assets/test.png"]); return true; } - (bool)testLookupKeyAssetsWithPackage { FlutterViewController* viewController = [[FlutterViewController alloc] initWithProject:nil]; NSString* packageKey = [viewController lookupKeyForAsset:@"test.png" fromPackage:@"test"]; EXPECT_TRUE([packageKey isEqualToString: @"Contents/Frameworks/App.framework/Resources/flutter_assets/packages/test/test.png"]); return true; } static void SwizzledNoop(id self, SEL _cmd) {} // Verify workaround an AppKit bug where mouseDown/mouseUp are not called on the view controller if // the view is the content view of an NSPopover AND macOS's Reduced Transparency accessibility // setting is enabled. // // See: https://github.com/flutter/flutter/issues/115015 // See: http://www.openradar.me/FB12050037 // See: https://developer.apple.com/documentation/appkit/nsresponder/1524634-mousedown - (bool)testMouseDownUpEventsSentToNextResponder:(id)engineMock { // The root cause of the above bug is NSResponder mouseDown/mouseUp methods that don't correctly // walk the responder chain calling the appropriate method on the next responder under certain // conditions. Simulate this by swizzling out the default implementations and replacing them with // no-ops. Method mouseDown = class_getInstanceMethod([NSResponder class], @selector(mouseDown:)); Method mouseUp = class_getInstanceMethod([NSResponder class], @selector(mouseUp:)); IMP noopImp = (IMP)SwizzledNoop; IMP origMouseDown = method_setImplementation(mouseDown, noopImp); IMP origMouseUp = method_setImplementation(mouseUp, noopImp); // Verify that mouseDown/mouseUp trigger mouseDown/mouseUp calls on FlutterViewController. MouseEventFlutterViewController* viewController = [[MouseEventFlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; FlutterView* view = (FlutterView*)[viewController view]; EXPECT_FALSE(viewController.mouseDownCalled); EXPECT_FALSE(viewController.mouseUpCalled); NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(0x00); [view mouseDown:mouseEvent]; EXPECT_TRUE(viewController.mouseDownCalled); EXPECT_FALSE(viewController.mouseUpCalled); viewController.mouseDownCalled = NO; [view mouseUp:mouseEvent]; EXPECT_FALSE(viewController.mouseDownCalled); EXPECT_TRUE(viewController.mouseUpCalled); // Restore the original NSResponder mouseDown/mouseUp implementations. method_setImplementation(mouseDown, origMouseDown); method_setImplementation(mouseUp, origMouseUp); return true; } - (bool)testModifierKeysAreSynthesizedOnMouseMove:(id)engineMock { id binaryMessengerMock = OCMProtocolMock(@protocol(FlutterBinaryMessenger)); OCMStub( // NOLINT(google-objc-avoid-throwing-exception) [engineMock binaryMessenger]) .andReturn(binaryMessengerMock); // Need to return a real renderer to allow view controller to load. FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; OCMStub([engineMock renderer]).andReturn(renderer_); // Capture calls to sendKeyEvent __block NSMutableArray<KeyEventWrapper*>* events = [NSMutableArray array]; OCMStub([[engineMock ignoringNonObjectArgs] sendKeyEvent:FlutterKeyEvent {} callback:nil userData:nil]) .andDo((^(NSInvocation* invocation) { FlutterKeyEvent* event; [invocation getArgument:&event atIndex:2]; [events addObject:[[KeyEventWrapper alloc] initWithEvent:event]]; })); __block NSMutableArray<NSDictionary*>* channelEvents = [NSMutableArray array]; OCMStub([binaryMessengerMock sendOnChannel:@"flutter/keyevent" message:[OCMArg any] binaryReply:[OCMArg any]]) .andDo((^(NSInvocation* invocation) { NSData* data; [invocation getArgument:&data atIndex:3]; id event = [[FlutterJSONMessageCodec sharedInstance] decode:data]; [channelEvents addObject:event]; })); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; [viewController loadView]; [viewController viewWillAppear]; // Zeroed modifier flag should not synthesize events. NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(0x00); [viewController mouseMoved:mouseEvent]; EXPECT_EQ([events count], 0u); // For each modifier key, check that key events are synthesized. for (NSNumber* keyCode in flutter::keyCodeToModifierFlag) { FlutterKeyEvent* event; NSDictionary* channelEvent; NSNumber* logicalKey; NSNumber* physicalKey; NSEventModifierFlags flag = [flutter::keyCodeToModifierFlag[keyCode] unsignedLongValue]; // Cocoa event always contain combined flags. if (flag & (flutter::kModifierFlagShiftLeft | flutter::kModifierFlagShiftRight)) { flag |= NSEventModifierFlagShift; } if (flag & (flutter::kModifierFlagControlLeft | flutter::kModifierFlagControlRight)) { flag |= NSEventModifierFlagControl; } if (flag & (flutter::kModifierFlagAltLeft | flutter::kModifierFlagAltRight)) { flag |= NSEventModifierFlagOption; } if (flag & (flutter::kModifierFlagMetaLeft | flutter::kModifierFlagMetaRight)) { flag |= NSEventModifierFlagCommand; } // Should synthesize down event. NSEvent* mouseEvent = flutter::testing::CreateMouseEvent(flag); [viewController mouseMoved:mouseEvent]; EXPECT_EQ([events count], 1u); event = events[0].data; logicalKey = [flutter::keyCodeToLogicalKey objectForKey:keyCode]; physicalKey = [flutter::keyCodeToPhysicalKey objectForKey:keyCode]; EXPECT_EQ(event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(event->logical, logicalKey.unsignedLongLongValue); EXPECT_EQ(event->physical, physicalKey.unsignedLongLongValue); EXPECT_EQ(event->synthesized, true); channelEvent = channelEvents[0]; EXPECT_TRUE([channelEvent[@"type"] isEqual:@"keydown"]); EXPECT_TRUE([channelEvent[@"keyCode"] isEqual:keyCode]); EXPECT_TRUE([channelEvent[@"modifiers"] isEqual:@(flag)]); // Should synthesize up event. mouseEvent = flutter::testing::CreateMouseEvent(0x00); [viewController mouseMoved:mouseEvent]; EXPECT_EQ([events count], 2u); event = events[1].data; logicalKey = [flutter::keyCodeToLogicalKey objectForKey:keyCode]; physicalKey = [flutter::keyCodeToPhysicalKey objectForKey:keyCode]; EXPECT_EQ(event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(event->logical, logicalKey.unsignedLongLongValue); EXPECT_EQ(event->physical, physicalKey.unsignedLongLongValue); EXPECT_EQ(event->synthesized, true); channelEvent = channelEvents[1]; EXPECT_TRUE([channelEvent[@"type"] isEqual:@"keyup"]); EXPECT_TRUE([channelEvent[@"keyCode"] isEqual:keyCode]); EXPECT_TRUE([channelEvent[@"modifiers"] isEqual:@(0)]); [events removeAllObjects]; [channelEvents removeAllObjects]; }; return true; } - (bool)testViewControllerIsReleased { __weak FlutterViewController* weakController; @autoreleasepool { id engineMock = flutter::testing::CreateMockFlutterEngine(@""); FlutterRenderer* renderer_ = [[FlutterRenderer alloc] initWithFlutterEngine:engineMock]; OCMStub([engineMock renderer]).andReturn(renderer_); FlutterViewController* viewController = [[FlutterViewController alloc] initWithEngine:engineMock nibName:@"" bundle:nil]; [viewController loadView]; weakController = viewController; [engineMock shutDownEngine]; } EXPECT_EQ(weakController, nil); return true; } @end
engine/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewControllerTest.mm", "repo_id": "engine", "token_count": 22704 }
331
framework module FlutterMacOS { umbrella header "FlutterMacOS.h" export * module * { export * } }
engine/shell/platform/darwin/macos/framework/module.modulemap/0
{ "file_path": "engine/shell/platform/darwin/macos/framework/module.modulemap", "repo_id": "engine", "token_count": 34 }
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. #include "flutter/shell/platform/embedder/embedder_external_view.h" #include "flutter/display_list/dl_builder.h" #include "flutter/fml/trace_event.h" #include "flutter/shell/common/dl_op_spy.h" #ifdef IMPELLER_SUPPORTS_RENDERING #include "impeller/display_list/dl_dispatcher.h" // nogncheck #endif // IMPELLER_SUPPORTS_RENDERING namespace flutter { static SkISize TransformedSurfaceSize(const SkISize& size, const SkMatrix& transformation) { const auto source_rect = SkRect::MakeWH(size.width(), size.height()); const auto transformed_rect = transformation.mapRect(source_rect); return SkISize::Make(transformed_rect.width(), transformed_rect.height()); } EmbedderExternalView::EmbedderExternalView( const SkISize& frame_size, const SkMatrix& surface_transformation) : EmbedderExternalView(frame_size, surface_transformation, {}, nullptr) {} EmbedderExternalView::EmbedderExternalView( const SkISize& frame_size, const SkMatrix& surface_transformation, ViewIdentifier view_identifier, std::unique_ptr<EmbeddedViewParams> params) : render_surface_size_( TransformedSurfaceSize(frame_size, surface_transformation)), surface_transformation_(surface_transformation), view_identifier_(view_identifier), embedded_view_params_(std::move(params)), slice_(std::make_unique<DisplayListEmbedderViewSlice>( SkRect::Make(frame_size))) {} EmbedderExternalView::~EmbedderExternalView() = default; EmbedderExternalView::RenderTargetDescriptor EmbedderExternalView::CreateRenderTargetDescriptor() const { return RenderTargetDescriptor(render_surface_size_); } DlCanvas* EmbedderExternalView::GetCanvas() { return slice_->canvas(); } SkISize EmbedderExternalView::GetRenderSurfaceSize() const { return render_surface_size_; } bool EmbedderExternalView::IsRootView() const { return !HasPlatformView(); } bool EmbedderExternalView::HasPlatformView() const { return view_identifier_.platform_view_id.has_value(); } const DlRegion& EmbedderExternalView::GetDlRegion() const { return slice_->getRegion(); } bool EmbedderExternalView::HasEngineRenderedContents() { if (has_engine_rendered_contents_.has_value()) { return has_engine_rendered_contents_.value(); } TryEndRecording(); DlOpSpy dl_op_spy; slice_->dispatch(dl_op_spy); has_engine_rendered_contents_ = dl_op_spy.did_draw() && !slice_->is_empty(); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) return has_engine_rendered_contents_.value(); } EmbedderExternalView::ViewIdentifier EmbedderExternalView::GetViewIdentifier() const { return view_identifier_; } const EmbeddedViewParams* EmbedderExternalView::GetEmbeddedViewParams() const { return embedded_view_params_.get(); } bool EmbedderExternalView::Render(const EmbedderRenderTarget& render_target, bool clear_surface) { TRACE_EVENT0("flutter", "EmbedderExternalView::Render"); TryEndRecording(); FML_DCHECK(HasEngineRenderedContents()) << "Unnecessarily asked to render into a render target when there was " "nothing to render."; #ifdef IMPELLER_SUPPORTS_RENDERING auto* impeller_target = render_target.GetImpellerRenderTarget(); if (impeller_target) { auto aiks_context = render_target.GetAiksContext(); auto dl_builder = DisplayListBuilder(); dl_builder.SetTransform(&surface_transformation_); slice_->render_into(&dl_builder); auto dispatcher = impeller::DlDispatcher(); dispatcher.drawDisplayList(dl_builder.Build(), 1); return aiks_context->Render(dispatcher.EndRecordingAsPicture(), *impeller_target, /*reset_host_buffer=*/true); } #endif // IMPELLER_SUPPORTS_RENDERING auto skia_surface = render_target.GetSkiaSurface(); if (!skia_surface) { return false; } FML_DCHECK(render_target.GetRenderTargetSize() == render_surface_size_); auto canvas = skia_surface->getCanvas(); if (!canvas) { return false; } DlSkCanvasAdapter dl_canvas(canvas); int restore_count = dl_canvas.GetSaveCount(); dl_canvas.SetTransform(surface_transformation_); if (clear_surface) { dl_canvas.Clear(DlColor::kTransparent()); } slice_->render_into(&dl_canvas); dl_canvas.RestoreToCount(restore_count); dl_canvas.Flush(); return true; } void EmbedderExternalView::TryEndRecording() const { if (slice_->recording_ended()) { return; } slice_->end_recording(); } } // namespace flutter
engine/shell/platform/embedder/embedder_external_view.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_external_view.cc", "repo_id": "engine", "token_count": 1736 }
333
// 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_skia.h" #include "flutter/fml/logging.h" namespace flutter { EmbedderRenderTargetSkia::EmbedderRenderTargetSkia( FlutterBackingStore backing_store, sk_sp<SkSurface> render_surface, fml::closure on_release) : EmbedderRenderTarget(backing_store, std::move(on_release)), render_surface_(std::move(render_surface)) { FML_DCHECK(render_surface_); } EmbedderRenderTargetSkia::~EmbedderRenderTargetSkia() = default; sk_sp<SkSurface> EmbedderRenderTargetSkia::GetSkiaSurface() const { return render_surface_; } impeller::RenderTarget* EmbedderRenderTargetSkia::GetImpellerRenderTarget() const { return nullptr; } std::shared_ptr<impeller::AiksContext> EmbedderRenderTargetSkia::GetAiksContext() const { return nullptr; } SkISize EmbedderRenderTargetSkia::GetRenderTargetSize() const { return SkISize::Make(render_surface_->width(), render_surface_->height()); } } // namespace flutter
engine/shell/platform/embedder/embedder_render_target_skia.cc/0
{ "file_path": "engine/shell/platform/embedder/embedder_render_target_skia.cc", "repo_id": "engine", "token_count": 397 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_SOFTWARE_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_SOFTWARE_H_ #include "flutter/fml/macros.h" #include "flutter/shell/gpu/gpu_surface_software.h" #include "flutter/shell/platform/embedder/embedder_external_view_embedder.h" #include "flutter/shell/platform/embedder/embedder_surface.h" #include "third_party/skia/include/core/SkSurface.h" namespace flutter { class EmbedderSurfaceSoftware final : public EmbedderSurface, public GPUSurfaceSoftwareDelegate { public: struct SoftwareDispatchTable { std::function<bool(const void* allocation, size_t row_bytes, size_t height)> software_present_backing_store; // required }; EmbedderSurfaceSoftware( SoftwareDispatchTable software_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder); ~EmbedderSurfaceSoftware() override; private: bool valid_ = false; SoftwareDispatchTable software_dispatch_table_; sk_sp<SkSurface> sk_surface_; std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_; // |EmbedderSurface| bool IsValid() const override; // |EmbedderSurface| std::unique_ptr<Surface> CreateGPUSurface() override; // |EmbedderSurface| sk_sp<GrDirectContext> CreateResourceContext() const override; // |GPUSurfaceSoftwareDelegate| sk_sp<SkSurface> AcquireBackingStore(const SkISize& size) override; // |GPUSurfaceSoftwareDelegate| bool PresentBackingStore(sk_sp<SkSurface> backing_store) override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurfaceSoftware); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_SOFTWARE_H_
engine/shell/platform/embedder/embedder_surface_software.h/0
{ "file_path": "engine/shell/platform/embedder/embedder_surface_software.h", "repo_id": "engine", "token_count": 691 }
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. #include "flutter/shell/platform/embedder/platform_view_embedder.h" #include <utility> #include "flutter/fml/make_copyable.h" namespace flutter { class PlatformViewEmbedder::EmbedderPlatformMessageHandler : public PlatformMessageHandler { public: EmbedderPlatformMessageHandler( fml::WeakPtr<PlatformView> parent, fml::RefPtr<fml::TaskRunner> platform_task_runner) : parent_(std::move(parent)), platform_task_runner_(std::move(platform_task_runner)) {} virtual void HandlePlatformMessage(std::unique_ptr<PlatformMessage> message) { platform_task_runner_->PostTask(fml::MakeCopyable( [parent = parent_, message = std::move(message)]() mutable { if (parent) { parent->HandlePlatformMessage(std::move(message)); } else { FML_DLOG(WARNING) << "Deleted engine dropping message on channel " << message->channel(); } })); } virtual bool DoesHandlePlatformMessageOnPlatformThread() const { return true; } virtual void InvokePlatformMessageResponseCallback( int response_id, std::unique_ptr<fml::Mapping> mapping) {} virtual void InvokePlatformMessageEmptyResponseCallback(int response_id) {} private: fml::WeakPtr<PlatformView> parent_; fml::RefPtr<fml::TaskRunner> platform_task_runner_; }; PlatformViewEmbedder::PlatformViewEmbedder( PlatformView::Delegate& delegate, const flutter::TaskRunners& task_runners, const EmbedderSurfaceSoftware::SoftwareDispatchTable& software_dispatch_table, PlatformDispatchTable platform_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder) : PlatformView(delegate, task_runners), external_view_embedder_(std::move(external_view_embedder)), embedder_surface_( std::make_unique<EmbedderSurfaceSoftware>(software_dispatch_table, external_view_embedder_)), platform_message_handler_(new EmbedderPlatformMessageHandler( GetWeakPtr(), task_runners.GetPlatformTaskRunner())), platform_dispatch_table_(std::move(platform_dispatch_table)) {} #ifdef SHELL_ENABLE_GL PlatformViewEmbedder::PlatformViewEmbedder( PlatformView::Delegate& delegate, const flutter::TaskRunners& task_runners, std::unique_ptr<EmbedderSurface> embedder_surface, PlatformDispatchTable platform_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder) : PlatformView(delegate, task_runners), external_view_embedder_(std::move(external_view_embedder)), embedder_surface_(std::move(embedder_surface)), platform_message_handler_(new EmbedderPlatformMessageHandler( GetWeakPtr(), task_runners.GetPlatformTaskRunner())), platform_dispatch_table_(std::move(platform_dispatch_table)) {} #endif #ifdef SHELL_ENABLE_METAL PlatformViewEmbedder::PlatformViewEmbedder( PlatformView::Delegate& delegate, const flutter::TaskRunners& task_runners, std::unique_ptr<EmbedderSurface> embedder_surface, PlatformDispatchTable platform_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder) : PlatformView(delegate, task_runners), external_view_embedder_(std::move(external_view_embedder)), embedder_surface_(std::move(embedder_surface)), platform_message_handler_(new EmbedderPlatformMessageHandler( GetWeakPtr(), task_runners.GetPlatformTaskRunner())), platform_dispatch_table_(std::move(platform_dispatch_table)) {} #endif #ifdef SHELL_ENABLE_VULKAN PlatformViewEmbedder::PlatformViewEmbedder( PlatformView::Delegate& delegate, const flutter::TaskRunners& task_runners, std::unique_ptr<EmbedderSurfaceVulkan> embedder_surface, PlatformDispatchTable platform_dispatch_table, std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder) : PlatformView(delegate, task_runners), external_view_embedder_(std::move(external_view_embedder)), embedder_surface_(std::move(embedder_surface)), platform_message_handler_(new EmbedderPlatformMessageHandler( GetWeakPtr(), task_runners.GetPlatformTaskRunner())), platform_dispatch_table_(std::move(platform_dispatch_table)) {} #endif PlatformViewEmbedder::~PlatformViewEmbedder() = default; void PlatformViewEmbedder::UpdateSemantics( flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) { if (platform_dispatch_table_.update_semantics_callback != nullptr) { platform_dispatch_table_.update_semantics_callback(std::move(update), std::move(actions)); } } void PlatformViewEmbedder::HandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { if (!message) { return; } if (platform_dispatch_table_.platform_message_response_callback == nullptr) { if (message->response()) { message->response()->CompleteEmpty(); } return; } platform_dispatch_table_.platform_message_response_callback( std::move(message)); } // |PlatformView| std::unique_ptr<Surface> PlatformViewEmbedder::CreateRenderingSurface() { if (embedder_surface_ == nullptr) { FML_LOG(ERROR) << "Embedder surface was null."; return nullptr; } return embedder_surface_->CreateGPUSurface(); } // |PlatformView| std::shared_ptr<ExternalViewEmbedder> PlatformViewEmbedder::CreateExternalViewEmbedder() { return external_view_embedder_; } std::shared_ptr<impeller::Context> PlatformViewEmbedder::GetImpellerContext() const { return embedder_surface_->CreateImpellerContext(); } // |PlatformView| sk_sp<GrDirectContext> PlatformViewEmbedder::CreateResourceContext() const { if (embedder_surface_ == nullptr) { FML_LOG(ERROR) << "Embedder surface was null."; return nullptr; } return embedder_surface_->CreateResourceContext(); } // |PlatformView| std::unique_ptr<VsyncWaiter> PlatformViewEmbedder::CreateVSyncWaiter() { if (!platform_dispatch_table_.vsync_callback) { // Superclass implementation creates a timer based fallback. return PlatformView::CreateVSyncWaiter(); } return std::make_unique<VsyncWaiterEmbedder>( platform_dispatch_table_.vsync_callback, task_runners_); } // |PlatformView| std::unique_ptr<std::vector<std::string>> PlatformViewEmbedder::ComputePlatformResolvedLocales( const std::vector<std::string>& supported_locale_data) { if (platform_dispatch_table_.compute_platform_resolved_locale_callback != nullptr) { return platform_dispatch_table_.compute_platform_resolved_locale_callback( supported_locale_data); } std::unique_ptr<std::vector<std::string>> out = std::make_unique<std::vector<std::string>>(); return out; } // |PlatformView| void PlatformViewEmbedder::OnPreEngineRestart() const { if (platform_dispatch_table_.on_pre_engine_restart_callback != nullptr) { platform_dispatch_table_.on_pre_engine_restart_callback(); } } // |PlatformView| void PlatformViewEmbedder::SendChannelUpdate(const std::string& name, bool listening) { if (platform_dispatch_table_.on_channel_update != nullptr) { platform_dispatch_table_.on_channel_update(name, listening); } } std::shared_ptr<PlatformMessageHandler> PlatformViewEmbedder::GetPlatformMessageHandler() const { return platform_message_handler_; } } // namespace flutter
engine/shell/platform/embedder/platform_view_embedder.cc/0
{ "file_path": "engine/shell/platform/embedder/platform_view_embedder.cc", "repo_id": "engine", "token_count": 2787 }
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_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/fml/memory/ref_ptr_internal.h" #include "flutter/shell/platform/embedder/embedder.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #ifdef SHELL_ENABLE_METAL #include "flutter/testing/test_metal_context.h" #endif #ifdef SHELL_ENABLE_VULKAN #include "flutter/testing/test_vulkan_context.h" // nogncheck #endif namespace flutter { namespace testing { class EmbedderTestBackingStoreProducer { public: struct UserData { SkSurface* surface; FlutterVulkanImage* image; }; enum class RenderTargetType { kSoftwareBuffer, kSoftwareBuffer2, kOpenGLFramebuffer, kOpenGLTexture, kMetalTexture, kVulkanImage, }; EmbedderTestBackingStoreProducer(sk_sp<GrDirectContext> context, RenderTargetType type, FlutterSoftwarePixelFormat software_pixfmt = kFlutterSoftwarePixelFormatNative32); ~EmbedderTestBackingStoreProducer(); bool Create(const FlutterBackingStoreConfig* config, FlutterBackingStore* renderer_out); private: bool CreateFramebuffer(const FlutterBackingStoreConfig* config, FlutterBackingStore* renderer_out); bool CreateTexture(const FlutterBackingStoreConfig* config, FlutterBackingStore* renderer_out); bool CreateSoftware(const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out); bool CreateSoftware2(const FlutterBackingStoreConfig* config, FlutterBackingStore* backing_store_out); bool CreateMTLTexture(const FlutterBackingStoreConfig* config, FlutterBackingStore* renderer_out); bool CreateVulkanImage(const FlutterBackingStoreConfig* config, FlutterBackingStore* renderer_out); sk_sp<GrDirectContext> context_; RenderTargetType type_; FlutterSoftwarePixelFormat software_pixfmt_; #ifdef SHELL_ENABLE_METAL std::unique_ptr<TestMetalContext> test_metal_context_; #endif #ifdef SHELL_ENABLE_VULKAN fml::RefPtr<TestVulkanContext> test_vulkan_context_; #endif FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestBackingStoreProducer); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_BACKINGSTORE_PRODUCER_H_
engine/shell/platform/embedder/tests/embedder_test_backingstore_producer.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_backingstore_producer.h", "repo_id": "engine", "token_count": 1151 }
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. #ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_METAL_H_ #define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_METAL_H_ #include "flutter/shell/platform/embedder/tests/embedder_test_context.h" #include "flutter/testing/test_metal_context.h" #include "flutter/testing/test_metal_surface.h" namespace flutter { namespace testing { class EmbedderTestContextMetal : public EmbedderTestContext { public: using TestExternalTextureCallback = std::function<bool(int64_t texture_id, size_t w, size_t h, FlutterMetalExternalTexture* output)>; using NextDrawableCallback = std::function<FlutterMetalTexture(const FlutterFrameInfo* frame_info)>; using PresentCallback = std::function<bool(int64_t texture_id)>; explicit EmbedderTestContextMetal(std::string assets_path = ""); ~EmbedderTestContextMetal() override; // |EmbedderTestContext| EmbedderTestContextType GetContextType() const override; // |EmbedderTestContext| size_t GetSurfacePresentCount() const override; // |EmbedderTestContext| void SetupCompositor() override; void SetExternalTextureCallback( TestExternalTextureCallback external_texture_frame_callback); // Override the default handling for Present. void SetPresentCallback(PresentCallback present_callback); bool Present(int64_t texture_id); bool PopulateExternalTexture(int64_t texture_id, size_t w, size_t h, FlutterMetalExternalTexture* output); TestMetalContext* GetTestMetalContext(); TestMetalSurface* GetTestMetalSurface(); // Override the default handling for GetNextDrawable. void SetNextDrawableCallback(NextDrawableCallback next_drawable_callback); FlutterMetalTexture GetNextDrawable(const FlutterFrameInfo* frame_info); private: // This allows the builder to access the hooks. friend class EmbedderConfigBuilder; TestExternalTextureCallback external_texture_frame_callback_ = nullptr; SkISize surface_size_ = SkISize::MakeEmpty(); std::unique_ptr<TestMetalContext> metal_context_; std::unique_ptr<TestMetalSurface> metal_surface_; size_t present_count_ = 0; PresentCallback present_callback_ = nullptr; NextDrawableCallback next_drawable_callback_ = nullptr; void SetupSurface(SkISize surface_size) override; FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestContextMetal); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_CONTEXT_METAL_H_
engine/shell/platform/embedder/tests/embedder_test_context_metal.h/0
{ "file_path": "engine/shell/platform/embedder/tests/embedder_test_context_metal.h", "repo_id": "engine", "token_count": 997 }
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. library fuchsia; import 'dart:io'; import 'dart:isolate'; import 'dart:zircon'; // ignore_for_file: native_function_body_in_non_sdk_code // ignore_for_file: public_member_api_docs // TODO: refactors this incomingServices instead @pragma('vm:entry-point') Handle? _environment; @pragma('vm:entry-point') Handle? _outgoingServices; @pragma('vm:entry-point') Handle? _viewRef; class MxStartupInfo { // TODO: refactor Handle to a Channel // https://github.com/flutter/flutter/issues/49439 static Handle takeEnvironment() { if (_environment == null && Platform.isFuchsia) { throw Exception( 'Attempting to call takeEnvironment more than once per process'); } final handle = _environment; _environment = null; return handle!; } // TODO: refactor Handle to a Channel // https://github.com/flutter/flutter/issues/49439 static Handle takeOutgoingServices() { if (_outgoingServices == null && Platform.isFuchsia) { throw Exception( 'Attempting to call takeOutgoingServices more than once per process'); } final handle = _outgoingServices; _outgoingServices = null; return handle!; } // TODO: refactor Handle to a ViewRef // https://github.com/flutter/flutter/issues/49439 static Handle takeViewRef() { if (_viewRef == null && Platform.isFuchsia) { throw Exception( 'Attempting to call takeViewRef more than once per process'); } final handle = _viewRef; _viewRef = null; return handle!; } } @pragma('vm:external-name', 'SetReturnCode') external void _setReturnCode(int returnCode); void exit(int returnCode) { _setReturnCode(returnCode); Isolate.current.kill(priority: Isolate.immediate); } // ignore: always_declare_return_types, prefer_generic_function_type_aliases typedef _ListStringArgFunction(List<String> args); // This function is used as the entry point for code in the dart runner and is // not meant to be called directly outside of that context. The code will invoke // the given main entry point and pass the args if the function takes args. This // function is needed because without it the snapshot compiler will tree shake // the function away unless the user marks it as being an entry point. // // The code does not catch any exceptions since this is handled in the dart // runner calling code. @pragma('vm:entry-point') void _runUserMainForDartRunner(Function userMainFunction, List<String> args) { if (userMainFunction is _ListStringArgFunction) { (userMainFunction as dynamic)(args); } else { userMainFunction(); } }
engine/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/fuchsia/lib/fuchsia.dart", "repo_id": "engine", "token_count": 902 }
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. #include "handle.h" #include <algorithm> #include "third_party/tonic/dart_binding_macros.h" #include "third_party/tonic/dart_class_library.h" using tonic::ToDart; namespace zircon { namespace dart { IMPLEMENT_WRAPPERTYPEINFO(zircon, Handle); Handle::Handle(zx_handle_t handle) : handle_(handle) {} Handle::~Handle() { if (is_valid()) { zx_status_t status = Close(); FML_DCHECK(status == ZX_OK); } } fml::RefPtr<Handle> Handle::Create(zx_handle_t handle) { return fml::MakeRefCounted<Handle>(handle); } Dart_Handle Handle::CreateInvalid() { return ToDart(Create(ZX_HANDLE_INVALID)); } zx_handle_t Handle::ReleaseHandle() { FML_DCHECK(is_valid()); zx_handle_t handle = handle_; handle_ = ZX_HANDLE_INVALID; cached_koid_ = std::nullopt; while (waiters_.size()) { // HandleWaiter::Cancel calls Handle::ReleaseWaiter which removes the // HandleWaiter from waiters_. FML_DCHECK(waiters_.back()->is_pending()); waiters_.back()->Cancel(); } FML_DCHECK(!is_valid()); return handle; } zx_status_t Handle::Close() { if (is_valid()) { zx_handle_t handle = ReleaseHandle(); return zx_handle_close(handle); } return ZX_ERR_BAD_HANDLE; } fml::RefPtr<HandleWaiter> Handle::AsyncWait(zx_signals_t signals, Dart_Handle callback) { if (!is_valid()) { FML_LOG(WARNING) << "Attempt to wait on an invalid handle."; return nullptr; } fml::RefPtr<HandleWaiter> waiter = HandleWaiter::Create(this, signals, callback); waiters_.push_back(waiter.get()); return waiter; } void Handle::ReleaseWaiter(HandleWaiter* waiter) { FML_DCHECK(waiter); auto iter = std::find(waiters_.cbegin(), waiters_.cend(), waiter); FML_DCHECK(iter != waiters_.cend()); FML_DCHECK(*iter == waiter); waiters_.erase(iter); } Dart_Handle Handle::Duplicate(uint32_t rights) { if (!is_valid()) { return ToDart(Create(ZX_HANDLE_INVALID)); } zx_handle_t out_handle; zx_status_t status = zx_handle_duplicate(handle_, rights, &out_handle); if (status != ZX_OK) { return ToDart(Create(ZX_HANDLE_INVALID)); } return ToDart(Create(out_handle)); } Dart_Handle Handle::Replace(uint32_t rights) { if (!is_valid()) { return ToDart(Create(ZX_HANDLE_INVALID)); } zx_handle_t out_handle; zx_status_t status = zx_handle_replace(ReleaseHandle(), rights, &out_handle); if (status != ZX_OK) { return ToDart(Create(ZX_HANDLE_INVALID)); } return ToDart(Create(out_handle)); } // clang-format: off #define FOR_EACH_STATIC_BINDING(V) V(Handle, CreateInvalid) #define FOR_EACH_BINDING(V) \ V(Handle, handle) \ V(Handle, koid) \ V(Handle, is_valid) \ V(Handle, Close) \ V(Handle, AsyncWait) \ V(Handle, Duplicate) \ V(Handle, Replace) // clang-format: on // Tonic is missing a comma. #define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \ DART_REGISTER_NATIVE_STATIC(CLASS, METHOD), FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC) FOR_EACH_BINDING(DART_NATIVE_NO_UI_CHECK_CALLBACK) void Handle::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_) FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } } // namespace dart } // namespace zircon
engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/handle.cc", "repo_id": "engine", "token_count": 1441 }
340
// 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_DART_PKG_ZIRCON_FFI_CHANNEL_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CHANNEL_H_ #include "basic_types.h" #include "handle.h" #include "macros.h" #include <stdint.h> #ifdef __cplusplus extern "C" { #endif ZIRCON_FFI_EXPORT zircon_dart_handle_pair_t* zircon_dart_channel_create( uint32_t options); ZIRCON_FFI_EXPORT int32_t zircon_dart_channel_write( zircon_dart_handle_t* handle, zircon_dart_byte_array_t* bytes, zircon_dart_handle_list_t* handles); #ifdef __cplusplus } #endif #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_CHANNEL_H_
engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/channel.h", "repo_id": "engine", "token_count": 358 }
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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_BUILTIN_LIBRARIES_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_BUILTIN_LIBRARIES_H_ #include <lib/fdio/namespace.h> #include <lib/zx/channel.h> #include <memory> #include <string> namespace dart_runner { void InitBuiltinLibrariesForIsolate(const std::string& script_uri, fdio_ns_t* namespc, int stdoutfd, int stderrfd, zx::channel directory_request, bool service_isolate); } // namespace dart_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_BUILTIN_LIBRARIES_H_
engine/shell/platform/fuchsia/dart_runner/builtin_libraries.h/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/builtin_libraries.h", "repo_id": "engine", "token_count": 455 }
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. import("//build/compiled_action.gni") import("//flutter/common/config.gni") import("//flutter/tools/fuchsia/dart.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("$dart_src/utils/compile_platform.gni") compile_platform("kernel_platform_files") { single_root_scheme = "org-dartlang-sdk" single_root_base = rebase_path("../../../../../../") libraries_specification_uri = "org-dartlang-sdk:///flutter/shell/platform/fuchsia/dart_runner/kernel/libraries.json" outputs = [ "$root_out_dir/dart_runner_patched_sdk/platform_strong.dill", "$root_out_dir/dart_runner_patched_sdk/vm_outline_strong.dill", ] args = [ "--nnbd-agnostic", "--target=dart_runner", "dart:core", ] } template("create_kernel_core_snapshot") { assert(defined(invoker.product), "The parameter 'product' must be defined") product_suffix = "" if (invoker.product) { product_suffix = "_product" } compiled_action(target_name) { deps = [ ":kernel_platform_files" ] platform_dill = "$root_out_dir/dart_runner_patched_sdk/platform_strong.dill" inputs = [ platform_dill ] vm_snapshot_data = "$target_gen_dir/vm_data${product_suffix}.bin" isolate_snapshot_data = "$target_gen_dir/isolate_data${product_suffix}.bin" snapshot_profile = "$target_gen_dir/snapshot_profile${product_suffix}.json" outputs = [ vm_snapshot_data, isolate_snapshot_data, snapshot_profile, ] gen_snapshot_to_use = gen_snapshot if (invoker.product) { gen_snapshot_to_use = gen_snapshot_product } tool = gen_snapshot_to_use args = [ "--enable_mirrors=false", "--deterministic", "--snapshot_kind=core", "--vm_snapshot_data=" + rebase_path(vm_snapshot_data, root_build_dir), "--isolate_snapshot_data=" + rebase_path(isolate_snapshot_data, root_build_dir), "--write_v8_snapshot_profile_to=" + rebase_path(snapshot_profile, root_build_dir), ] # No asserts in debug or release product. # No asserts in release with flutter_profile=true (non-product) # Yes asserts in non-product debug. if (!invoker.product && (is_debug || flutter_runtime_mode == "debug")) { args += [ "--enable_asserts" ] } args += [ rebase_path(platform_dill) ] } } create_kernel_core_snapshot("kernel_core_snapshot") { product = false } create_kernel_core_snapshot("kernel_core_snapshot_product") { product = true }
engine/shell/platform/fuchsia/dart_runner/kernel/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/kernel/BUILD.gn", "repo_id": "engine", "token_count": 1045 }
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 <dart/test/cpp/fidl.h> #include <fuchsia/tracing/provider/cpp/fidl.h> #include <lib/async-loop/testing/cpp/real_loop.h> #include <lib/sys/component/cpp/testing/realm_builder.h> #include <lib/sys/component/cpp/testing/realm_builder_types.h> #include "flutter/fml/logging.h" #include "gtest/gtest.h" namespace dart_aot_runner_testing::testing { namespace { // Types imported for the realm_builder library using component_testing::ChildOptions; using component_testing::ChildRef; using component_testing::Directory; using component_testing::ParentRef; using component_testing::Protocol; using component_testing::RealmBuilder; using component_testing::RealmRoot; using component_testing::Route; constexpr auto kDartRunnerEnvironment = "dart_runner_env"; constexpr auto kDartAotRunner = "dart_aot_runner"; constexpr auto kDartAotRunnerRef = ChildRef{kDartAotRunner}; constexpr auto kDartAotRunnerUrl = "fuchsia-pkg://fuchsia.com/oot_dart_aot_runner#meta/" "dart_aot_runner.cm"; constexpr auto kDartAotEchoServer = "dart_aot_echo_server"; constexpr auto kDartAotEchoServerRef = ChildRef{kDartAotEchoServer}; constexpr auto kDartAotEchoServerUrl = "fuchsia-pkg://fuchsia.com/dart_aot_echo_server#meta/" "dart_aot_echo_server.cm"; class RealmBuilderTest : public ::loop_fixture::RealLoop, public ::testing::Test { public: RealmBuilderTest() = default; }; TEST_F(RealmBuilderTest, DartRunnerStartsUp) { auto realm_builder = RealmBuilder::Create(); // Add Dart AOT runner as a child of RealmBuilder realm_builder.AddChild(kDartAotRunner, kDartAotRunnerUrl); // Add environment providing the Dart AOT runner fuchsia::component::decl::Environment dart_runner_environment; dart_runner_environment.set_name(kDartRunnerEnvironment); dart_runner_environment.set_extends( fuchsia::component::decl::EnvironmentExtends::REALM); dart_runner_environment.set_runners({}); auto environment_runners = dart_runner_environment.mutable_runners(); fuchsia::component::decl::RunnerRegistration dart_aot_runner_reg; dart_aot_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild( fuchsia::component::decl::ChildRef{.name = kDartAotRunner})); dart_aot_runner_reg.set_source_name(kDartAotRunner); dart_aot_runner_reg.set_target_name(kDartAotRunner); environment_runners->push_back(std::move(dart_aot_runner_reg)); auto realm_decl = realm_builder.GetRealmDecl(); if (!realm_decl.has_environments()) { realm_decl.set_environments({}); } auto realm_environments = realm_decl.mutable_environments(); realm_environments->push_back(std::move(dart_runner_environment)); realm_builder.ReplaceRealmDecl(std::move(realm_decl)); // Add Dart server component as a child of Realm Builder realm_builder.AddChild(kDartAotEchoServer, kDartAotEchoServerUrl, ChildOptions{.environment = kDartRunnerEnvironment}); // Route base capabilities to the Dart AOT runner realm_builder.AddRoute( Route{.capabilities = {Protocol{"fuchsia.logger.LogSink"}, Protocol{"fuchsia.tracing.provider.Registry"}, Protocol{"fuchsia.posix.socket.Provider"}, Protocol{"fuchsia.intl.PropertyProvider"}, Protocol{"fuchsia.vulkan.loader.Loader"}, Protocol{"fuchsia.inspect.InspectSink"}, Directory{"config-data"}}, .source = ParentRef(), .targets = {kDartAotRunnerRef, kDartAotEchoServerRef}}); // Route the Echo FIDL protocol, this allows the Dart echo server to // communicate with the Realm Builder realm_builder.AddRoute(Route{.capabilities = {Protocol{"dart.test.Echo"}}, .source = kDartAotEchoServerRef, .targets = {ParentRef()}}); // Build the Realm with the provided child and protocols auto realm = realm_builder.Build(dispatcher()); FML_LOG(INFO) << "Realm built: " << realm.component().GetChildName(); // Connect to the Dart echo server auto echo = realm.component().ConnectSync<dart::test::Echo>(); fidl::StringPtr response; // Attempt to ping the Dart echo server for a response echo->EchoString("hello", &response); ASSERT_EQ(response, "hello"); } } // namespace } // namespace dart_aot_runner_testing::testing
engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/dart-aot-runner-integration-test.cc/0
{ "file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_aot_runner/dart-aot-runner-integration-test.cc", "repo_id": "engine", "token_count": 1726 }
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. assert(is_fuchsia) import("//flutter/common/config.gni") import("//flutter/shell/config.gni") import("//flutter/shell/gpu/gpu.gni") import("//flutter/testing/testing.gni") import("//flutter/tools/fuchsia/dart.gni") import("//flutter/tools/fuchsia/fuchsia_archive.gni") import("//flutter/tools/fuchsia/fuchsia_libs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/vulkan/config.gni") # Fuchsia uses its own custom Surface implementation. shell_gpu_configuration("fuchsia_gpu_configuration") { enable_software = false enable_gl = false # TODO(dworsham): Enable once Fuchsia supports Vulkan through the embedder. enable_vulkan = false enable_metal = false } config("runner_base_config") { defines = [ "FML_USED_ON_EMBEDDER" ] } config("runner_debug_config") { defines = [ "DEBUG" ] # Needed due to direct dart dependencies. } config("runner_flutter_profile_config") { defines = [ "FLUTTER_PROFILE" ] } config("runner_product_config") { defines = [ "DART_PRODUCT" ] } template("runner_sources") { assert(defined(invoker.product), "runner_sources must define product") runner_configs = [ ":runner_base_config" ] if (is_debug) { runner_configs += [ ":runner_debug_config" ] } if (flutter_runtime_mode == "profile") { runner_configs += [ ":runner_flutter_profile_config" ] } if (invoker.product) { runner_configs += [ ":runner_product_config" ] } source_set(target_name) { sources = [ "accessibility_bridge.cc", "accessibility_bridge.h", "canvas_spy.cc", "canvas_spy.h", "component_v2.cc", "component_v2.h", "engine.cc", "engine.h", "external_view_embedder.cc", "external_view_embedder.h", "file_in_namespace_buffer.cc", "file_in_namespace_buffer.h", "flatland_connection.cc", "flatland_connection.h", "flutter_runner_product_configuration.cc", "flutter_runner_product_configuration.h", "focus_delegate.cc", "focus_delegate.h", "fuchsia_intl.cc", "fuchsia_intl.h", "isolate_configurator.cc", "isolate_configurator.h", "keyboard.cc", "keyboard.h", "logging.h", "platform_view.cc", "platform_view.h", "pointer_delegate.cc", "pointer_delegate.h", "pointer_injector_delegate.cc", "pointer_injector_delegate.h", "program_metadata.h", "rtree.cc", "rtree.h", "runner.cc", "runner.h", "software_surface.cc", "software_surface.h", "software_surface_producer.cc", "software_surface_producer.h", "surface.cc", "surface.h", "surface_producer.h", "task_runner_adapter.cc", "task_runner_adapter.h", "text_delegate.cc", "text_delegate.h", "unique_fdio_ns.h", "vsync_waiter.cc", "vsync_waiter.h", "vulkan_surface.cc", "vulkan_surface.h", "vulkan_surface_pool.cc", "vulkan_surface_pool.h", "vulkan_surface_producer.cc", "vulkan_surface_producer.h", ] public_configs = runner_configs # The use of these dependencies is temporary and will be moved behind the # embedder API. flutter_public_deps = [ "//flutter/common/graphics", "//flutter/flow", "//flutter/lib/ui", "//flutter/runtime", "//flutter/shell/common", "//flutter/shell/platform/common/client_wrapper:client_wrapper", ] flutter_deps = [ ":fuchsia_gpu_configuration", "//flutter/assets", "//flutter/common", "//flutter/flutter_vma:flutter_skia_vma", "//flutter/fml", "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", "//flutter/vulkan", "//flutter/vulkan/procs", ] # TODO(zijiehe): Considering which deps should belong to the public_deps, # multiple dependencies of this target use the following deps without # explicitly claiming the dependencies. public_deps = [ "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", "${fuchsia_sdk}/fidl/fuchsia.component.runner", "${fuchsia_sdk}/fidl/fuchsia.fonts", "${fuchsia_sdk}/fidl/fuchsia.images", "${fuchsia_sdk}/fidl/fuchsia.intl", "${fuchsia_sdk}/fidl/fuchsia.io", "${fuchsia_sdk}/fidl/fuchsia.media", "${fuchsia_sdk}/fidl/fuchsia.memorypressure", "${fuchsia_sdk}/fidl/fuchsia.ui.app", "${fuchsia_sdk}/fidl/fuchsia.ui.composition", "${fuchsia_sdk}/fidl/fuchsia.ui.input", "${fuchsia_sdk}/fidl/fuchsia.ui.input3", "${fuchsia_sdk}/fidl/fuchsia.ui.pointer", "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", "${fuchsia_sdk}/fidl/fuchsia.ui.views", "${fuchsia_sdk}/pkg/inspect", "${fuchsia_sdk}/pkg/inspect_component_cpp", "${fuchsia_sdk}/pkg/sys_cpp", "//flutter/shell/platform/fuchsia/runtime/dart/utils", ] + flutter_public_deps deps = [ "${fuchsia_sdk}/pkg/async-cpp", "${fuchsia_sdk}/pkg/async-default", "${fuchsia_sdk}/pkg/async-loop", "${fuchsia_sdk}/pkg/async-loop-cpp", "${fuchsia_sdk}/pkg/fdio", "${fuchsia_sdk}/pkg/fidl_cpp", "${fuchsia_sdk}/pkg/trace", "${fuchsia_sdk}/pkg/trace-engine", "${fuchsia_sdk}/pkg/trace-provider-so", "${fuchsia_sdk}/pkg/vfs_cpp", "${fuchsia_sdk}/pkg/zx", "//flutter/shell/platform/fuchsia/dart-pkg/fuchsia", "//flutter/shell/platform/fuchsia/dart-pkg/zircon", ] + flutter_deps } } runner_sources("flutter_runner_sources") { product = false } runner_sources("flutter_runner_sources_product") { product = true } # Things that explicitly being excluded: # 1. Kernel snapshot framework mode. # 2. Profiler symbols. # Builds a flutter_runner # # Parameters: # # output_name (required): # The name of the resulting binary. # # extra_deps (required): # Any additional dependencies. # # product (required): # Whether to link against a Product mode Dart VM. # # extra_defines (optional): # Any additional preprocessor defines. template("flutter_runner") { assert(defined(invoker.output_name), "flutter_runner must define output_name") assert(defined(invoker.extra_deps), "flutter_runner must define extra_deps") assert(defined(invoker.product), "flutter_runner must define product") invoker_output_name = invoker.output_name extra_deps = invoker.extra_deps product_suffix = "" if (invoker.product) { product_suffix = "_product" } executable(target_name) { output_name = invoker_output_name sources = [ "main.cc" ] deps = [ ":flutter_runner_sources${product_suffix}", "${fuchsia_sdk}/pkg/async-loop-cpp", "${fuchsia_sdk}/pkg/trace", "${fuchsia_sdk}/pkg/trace-provider-so", ] + extra_deps # The flags below are needed so that Dart's CPU profiler can walk the # C++ stack. cflags = [ "-fno-omit-frame-pointer" ] if (invoker.product) { # Fuchsia's default stack size was resulting in test failures in a # downstream project. Provide some extra room. ldflags = [ "-Wl,-z,stack-size=0x100000" ] } else { # This flag is needed so that the call to dladdr() in Dart's native symbol # resolver can report good symbol information for the CPU profiler. ldflags = [ "-Wl,-z,stack-size=0x100000", "-rdynamic", ] } } } flutter_runner("jit") { output_name = "flutter_jit_runner" product = false extra_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", ] } flutter_runner("jit_product") { output_name = "flutter_jit_product_runner" product = true extra_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", ] } flutter_runner("aot") { output_name = "flutter_aot_runner" product = false extra_deps = [ "$dart_src/runtime:libdart_precompiled_runtime", "$dart_src/runtime/platform:libdart_platform_precompiled_runtime", ] } flutter_runner("aot_product") { output_name = "flutter_aot_product_runner" product = true extra_deps = [ "$dart_src/runtime:libdart_precompiled_runtime", "$dart_src/runtime/platform:libdart_platform_precompiled_runtime", ] } template("jit_runner") { product = defined(invoker.product) && invoker.product product_suffix = "" if (product) { product_suffix = "_product" } fuchsia_archive(target_name) { snapshot_label = "kernel:kernel_core_snapshot${product_suffix}" snapshot_gen_dir = get_label_info(snapshot_label, "target_gen_dir") deps = [ ":jit${product_suffix}", snapshot_label, ] if (!product) { deps += [ "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_jit_runner", observatory_target, ] } binary = "flutter_jit${product_suffix}_runner" cml_file = rebase_path("meta/flutter_jit${product_suffix}_runner.cml") resources = [ { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl.dat" }, ] if (!product) { resources += [ { path = rebase_path(observatory_archive_file) dest = "observatory.tar" }, { path = rebase_path( get_label_info( "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_jit_runner", "target_gen_dir") + "/flutter_jit_runner.dartprofilersymbols") dest = "flutter_jit_runner.dartprofilersymbols" }, ] } resources += [ { path = rebase_path( "$snapshot_gen_dir/vm_isolate_snapshot${product_suffix}.bin") dest = "vm_snapshot_data.bin" }, { path = rebase_path( "$snapshot_gen_dir/isolate_snapshot${product_suffix}.bin") dest = "isolate_core_snapshot_data.bin" }, ] _vulkan_icds = [] _libs = common_libs if (enable_vulkan_validation_layers) { _libs += vulkan_validation_libs _vulkan_icds += vulkan_icds } resources += _vulkan_icds libraries = _libs } } template("aot_runner") { product = defined(invoker.product) && invoker.product product_suffix = "" if (product) { product_suffix = "_product" } fuchsia_archive(target_name) { deps = [ ":aot${product_suffix}" ] if (!product) { deps += [ "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_aot_runner", observatory_target, ] } cml_file = rebase_path("meta/flutter_aot${product_suffix}_runner.cml") binary = "flutter_aot${product_suffix}_runner" resources = [ { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl.dat" }, ] if (!product) { resources += [ { path = rebase_path(observatory_archive_file) dest = "observatory.tar" }, { path = rebase_path( get_label_info( "//flutter/shell/platform/fuchsia/runtime/dart/profiler_symbols:flutter_aot_runner", "target_gen_dir") + "/flutter_aot_runner.dartprofilersymbols") dest = "flutter_aot_runner.dartprofilersymbols" }, ] } _vulkan_icds = [] _libs = common_libs if (enable_vulkan_validation_layers) { _libs += vulkan_validation_libs _vulkan_icds += vulkan_icds } resources += _vulkan_icds libraries = _libs } } aot_runner("flutter_aot_runner") { product = false } aot_runner("flutter_aot_product_runner") { product = true } jit_runner("flutter_jit_runner") { product = false } jit_runner("flutter_jit_product_runner") { product = true } # "OOT" copy of the runner used by tests, to avoid conflicting with the runner # in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. aot_runner("oot_flutter_aot_runner") { product = false } # "OOT" copy of the runner used by tests, to avoid conflicting with the runner # in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. aot_runner("oot_flutter_aot_product_runner") { product = true } # "OOT" copy of the runner used by tests, to avoid conflicting with the runner # in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. jit_runner("oot_flutter_jit_runner") { product = false } # "OOT" copy of the runner used by tests, to avoid conflicting with the runner # in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. jit_runner("oot_flutter_jit_product_runner") { product = true } test_fixtures("flutter_runner_fixtures") { fixtures = [] } if (enable_unittests) { executable("flutter_runner_unittests") { testonly = true output_name = "flutter_runner_tests" sources = [ "accessibility_bridge_unittest.cc", "canvas_spy_unittests.cc", "component_v2_unittest.cc", "flutter_runner_fakes.h", "focus_delegate_unittests.cc", "fuchsia_intl_unittest.cc", "keyboard_unittest.cc", "pointer_delegate_unittests.cc", "pointer_injector_delegate_unittest.cc", "rtree_unittests.cc", "tests/engine_unittests.cc", "tests/external_view_embedder_unittests.cc", "tests/fake_flatland_unittests.cc", "tests/flatland_connection_unittests.cc", "tests/flutter_runner_product_configuration_unittests.cc", "tests/platform_view_unittest.cc", "tests/pointer_event_utility.cc", "tests/pointer_event_utility.h", "text_delegate_unittests.cc", "vsync_waiter_unittest.cc", ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] # The use of these dependencies is temporary and will be moved behind the # embedder API. flutter_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", "//flutter/assets:assets", "//flutter/common/graphics", "//flutter/flow", "//flutter/lib/ui", "//flutter/shell/common", ] deps = [ "tests/fakes", ":flutter_runner_fixtures", ":flutter_runner_sources", "${fuchsia_sdk}/pkg/async-testing", "${fuchsia_sdk}/pkg/sys_cpp_testing", "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", "//flutter/testing", ] + flutter_deps } executable("flutter_runner_tzdata_unittests") { testonly = true output_name = "flutter_runner_tzdata_tests" sources = [ "runner_tzdata_unittest.cc" ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] # The use of these dependencies is temporary and will be moved behind the # embedder API. flutter_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", "//flutter/lib/ui", "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", ] deps = [ ":flutter_runner_fixtures", ":flutter_runner_sources", "//flutter/testing", ] + flutter_deps } executable("flutter_runner_tzdata_missing_unittests") { testonly = true output_name = "flutter_runner_tzdata_missing_tests" sources = [ "runner_tzdata_missing_unittest.cc" ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] # The use of these dependencies is temporary and will be moved behind the # embedder API. flutter_deps = [ "$dart_src/runtime:libdart_jit", "$dart_src/runtime/platform:libdart_platform_jit", "//flutter/lib/ui", "//flutter/shell/platform/common/client_wrapper:client_wrapper_library_stubs", ] deps = [ ":flutter_runner_fixtures", ":flutter_runner_sources", "//flutter/testing", ] + flutter_deps } fuchsia_test_archive("flutter_runner_tests") { deps = [ ":flutter_runner_unittests" ] binary = "$target_name" resources = [ { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl.dat" }, ] } fuchsia_test_archive("flutter_runner_tzdata_tests") { deps = [ ":flutter_runner_tzdata_unittests" ] binary = "$target_name" resources = [ { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl.dat" }, { path = rebase_path( "//flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/metaZones.res") dest = "tzdata/metaZones.res" }, { path = rebase_path( "//flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/timezoneTypes.res") dest = "tzdata/timezoneTypes.res" }, { path = rebase_path( "//flutter/shell/platform/fuchsia/flutter/tests/tzdata/2019a/44/le/zoneinfo64.res") dest = "tzdata/zoneinfo64.res" }, ] } fuchsia_test_archive("flutter_runner_tzdata_missing_tests") { deps = [ ":flutter_runner_tzdata_missing_unittests" ] binary = "$target_name" resources = [ { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl.dat" }, ] } fuchsia_test_archive("fml_tests") { deps = [ "//flutter/fml:fml_unittests" ] binary = "fml_unittests" } fuchsia_test_archive("display_list_tests") { deps = [ "//flutter/display_list:display_list_unittests" ] binary = "display_list_unittests" resources = [ { path = rebase_path( "//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf") dest = "assets/Roboto-Regular.ttf" }, ] } fuchsia_test_archive("display_list_render_tests") { deps = [ "//flutter/display_list:display_list_rendertests" ] binary = "display_list_rendertests" resources = [ { path = rebase_path( "//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf") dest = "assets/Roboto-Regular.ttf" }, ] } fuchsia_test_archive("flow_tests") { deps = [ "//flutter/flow:flow_unittests" ] binary = "flow_unittests" resources = [ { path = rebase_path( "//flutter/testing/resources/performance_overlay_gold_60fps.png") dest = "flutter/testing/resources/performance_overlay_gold_60fps.png" }, { path = rebase_path( "//flutter/testing/resources/performance_overlay_gold_90fps.png") dest = "flutter/testing/resources/performance_overlay_gold_90fps.png" }, { path = rebase_path( "//flutter/testing/resources/performance_overlay_gold_120fps.png") dest = "flutter/testing/resources/performance_overlay_gold_120fps.png" }, { path = rebase_path( "//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf") dest = "assets/Roboto-Regular.ttf" }, ] } fuchsia_test_archive("runtime_tests") { deps = [ "//flutter/runtime:runtime_fixtures", "//flutter/runtime:runtime_unittests", ] binary = "runtime_unittests" # TODO(gw280): https://github.com/flutter/flutter/issues/50294 # Right now we need to manually specify all the fixtures that are # declared in the test_fixtures() call above. resources = [ { path = "$root_gen_dir/flutter/runtime/assets/kernel_blob.bin" dest = "assets/kernel_blob.bin" }, ] } fuchsia_test_archive("shell_tests") { deps = [ "//flutter/shell/common:shell_unittests", "//flutter/shell/common:shell_unittests_fixtures", ] binary = "shell_unittests" # TODO(gw280): https://github.com/flutter/flutter/issues/50294 # Right now we need to manually specify all the fixtures that are # declared in the test_fixtures() call above. resources = [ { path = "$root_gen_dir/flutter/shell/common/assets/kernel_blob.bin" dest = "assets/kernel_blob.bin" }, { path = "$root_gen_dir/flutter/shell/common/assets/shelltest_screenshot.png" dest = "assets/shelltest_screenshot.png" }, { path = rebase_path( "//flutter/third_party/txt/third_party/fonts/Roboto-Regular.ttf") dest = "assets/Roboto-Regular.ttf" }, ] libraries = vulkan_validation_libs resources += vulkan_icds } fuchsia_test_archive("testing_tests") { deps = [ "//flutter/testing:testing_unittests" ] binary = "testing_unittests" } fuchsia_test_archive("txt_tests") { deps = [ "//flutter/third_party/txt:txt_unittests" ] binary = "txt_unittests" resources = [ { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl.dat" }, { path = rebase_path("//flutter/third_party/icu/common/icudtl.dat") dest = "icudtl2.dat" }, ] } fuchsia_test_archive("ui_tests") { deps = [ "//flutter/lib/ui:ui_unittests", "//flutter/lib/ui:ui_unittests_fixtures", ] binary = "ui_unittests" # TODO(gw280): https://github.com/flutter/flutter/issues/50294 # Right now we need to manually specify all the fixtures that are # declared in the test_fixtures() call above. resources = [ { path = "$root_gen_dir/flutter/lib/ui/assets/kernel_blob.bin" dest = "assets/kernel_blob.bin" }, { path = "$root_gen_dir/flutter/lib/ui/assets/DashInNooglerHat.jpg" dest = "assets/DashInNooglerHat.jpg" }, { path = "$root_gen_dir/flutter/lib/ui/assets/Horizontal.jpg" dest = "assets/Horizontal.jpg" }, { path = "$root_gen_dir/flutter/lib/ui/assets/Horizontal.png" dest = "assets/Horizontal.png" }, { path = "$root_gen_dir/flutter/lib/ui/assets/hello_loop_2.gif" dest = "assets/hello_loop_2.gif" }, { path = "$root_gen_dir/flutter/lib/ui/assets/hello_loop_2.webp" dest = "assets/hello_loop_2.webp" }, ] libraries = vulkan_validation_libs resources += vulkan_icds } fuchsia_test_archive("embedder_tests") { deps = [ "//flutter/shell/platform/embedder:embedder_unittests", "//flutter/shell/platform/embedder:fixtures", ] binary = "embedder_unittests" # TODO(gw280): https://github.com/flutter/flutter/issues/50294 # Right now we need to manually specify all the fixtures that are # declared in the test_fixtures() call above. resources = [ { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/kernel_blob.bin" dest = "assets/kernel_blob.bin" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/arc_end_caps.png" dest = "assets/arc_end_caps.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor.png" dest = "assets/compositor.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_root_surface_xformation.png" dest = "assets/compositor_root_surface_xformation.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_software.png" dest = "assets/compositor_software.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_with_platform_layer_on_bottom.png" dest = "assets/compositor_with_platform_layer_on_bottom.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/compositor_with_root_layer_only.png" dest = "assets/compositor_with_root_layer_only.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/dpr_noxform.png" dest = "assets/dpr_noxform.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/dpr_xform.png" dest = "assets/dpr_xform.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/gradient.png" dest = "assets/gradient.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/gradient_xform.png" dest = "assets/gradient_xform.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/scene_without_custom_compositor.png" dest = "assets/scene_without_custom_compositor.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/scene_without_custom_compositor_with_xform.png" dest = "assets/scene_without_custom_compositor_with_xform.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/snapshot_large_scene.png" dest = "assets/snapshot_large_scene.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/verifyb143464703.png" dest = "assets/verifyb143464703.png" }, { path = "$root_gen_dir/flutter/shell/platform/embedder/assets/verifyb143464703_soft_noxform.png" dest = "assets/verifyb143464703_soft_noxform.png" }, ] } fuchsia_test_archive("dart_utils_tests") { deps = [ "//flutter/shell/platform/fuchsia/runtime/dart/utils:dart_utils_unittests" ] binary = "dart_utils_unittests" } # When adding a new dep here, please also ensure the dep is added to # testing/fuchsia/test_suites.yaml. group("tests") { testonly = true deps = [ ":dart_utils_tests", ":display_list_render_tests", ":display_list_tests", ":embedder_tests", ":flow_tests", ":flutter_runner_tests", ":flutter_runner_tzdata_missing_tests", ":flutter_runner_tzdata_tests", ":fml_tests", ":runtime_tests", ":shell_tests", ":testing_tests", ":txt_tests", ":ui_tests", "tests/integration", ] } }
engine/shell/platform/fuchsia/flutter/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/BUILD.gn", "repo_id": "engine", "token_count": 12624 }
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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_EXTERNAL_VIEW_EMBEDDER_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_EXTERNAL_VIEW_EMBEDDER_H_ #include <fuchsia/ui/composition/cpp/fidl.h> #include <fuchsia/ui/views/cpp/fidl.h> #include <lib/fit/function.h> #include <cstdint> // For uint32_t & uint64_t #include <memory> #include <string> #include <unordered_map> #include <vector> #include "flutter/flow/embedded_views.h" #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/fuchsia/flutter/canvas_spy.h" #include "flutter/shell/platform/fuchsia/flutter/rtree.h" #include "third_party/skia/include/core/SkPictureRecorder.h" #include "third_party/skia/include/core/SkPoint.h" #include "third_party/skia/include/core/SkRect.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "flatland_connection.h" #include "surface_producer.h" namespace flutter_runner { using ViewCallback = std::function<void()>; using ViewCreatedCallback = std::function<void( fuchsia::ui::composition::ContentId, fuchsia::ui::composition::ChildViewWatcherHandle child_view_watcher)>; using ViewIdCallback = std::function<void(fuchsia::ui::composition::ContentId)>; // This class orchestrates interaction with the Scenic's compositor on // Fuchsia. It ensures that flutter content and platform view content are both // rendered correctly in a unified scene. class ExternalViewEmbedder final : public flutter::ExternalViewEmbedder { public: constexpr static uint32_t kDefaultViewportSize = 32; ExternalViewEmbedder( fuchsia::ui::views::ViewCreationToken view_creation_token, fuchsia::ui::views::ViewIdentityOnCreation view_identity, fuchsia::ui::composition::ViewBoundProtocols endpoints, fidl::InterfaceRequest<fuchsia::ui::composition::ParentViewportWatcher> parent_viewport_watcher_request, std::shared_ptr<FlatlandConnection> flatland, std::shared_ptr<SurfaceProducer> surface_producer, bool intercept_all_input = false); ~ExternalViewEmbedder(); // |ExternalViewEmbedder| flutter::DlCanvas* GetRootCanvas() override; // |ExternalViewEmbedder| void PrerollCompositeEmbeddedView( int64_t view_id, std::unique_ptr<flutter::EmbeddedViewParams> params) override; // |ExternalViewEmbedder| flutter::DlCanvas* CompositeEmbeddedView(int64_t view_id) override; // |ExternalViewEmbedder| flutter::PostPrerollResult PostPrerollAction( const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) 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 EndFrame(bool should_resubmit_frame, const fml::RefPtr<fml::RasterThreadMerger>& raster_thread_merger) override; // |ExternalViewEmbedder| void SubmitFlutterView( GrDirectContext* context, const std::shared_ptr<impeller::AiksContext>& aiks_context, std::unique_ptr<flutter::SurfaceFrame> frame) override; // |ExternalViewEmbedder| void CancelFrame() override { Reset(); } // |ExternalViewEmbedder| bool SupportsDynamicThreadMerging() override { return false; } // View manipulation. // |SetViewProperties| doesn't manipulate the view directly -- it sets pending // properties for the next |UpdateView| call. void CreateView(int64_t view_id, ViewCallback on_view_created, ViewCreatedCallback on_view_bound); void DestroyView(int64_t view_id, ViewIdCallback on_view_unbound); void SetViewProperties(int64_t view_id, const SkRect& occlusion_hint, bool hit_testable, bool focusable); // Holds the clip transform that may be applied on a View. struct ClipTransform { fuchsia::ui::composition::TransformId transform_id; std::vector<fuchsia::ui::composition::TransformId> children; }; private: void Reset(); // Reset state for a new frame. // This struct represents a transformed clip rect. struct TransformedClip { SkMatrix transform = SkMatrix::I(); SkRect rect = SkRect::MakeEmpty(); bool operator==(const TransformedClip& other) const { return transform == other.transform && rect == other.rect; } }; // This struct represents all the mutators that can be applied to a // PlatformView, unpacked from the `MutatorStack`. struct ViewMutators { std::vector<TransformedClip> clips; SkMatrix total_transform = SkMatrix::I(); SkMatrix transform = SkMatrix::I(); SkScalar opacity = 1.f; bool operator==(const ViewMutators& other) const { return clips == other.clips && total_transform == other.total_transform && transform == other.transform && opacity == other.opacity; } }; ViewMutators ParseMutatorStack(const flutter::MutatorsStack& mutators_stack); struct EmbedderLayer { EmbedderLayer(const SkISize& frame_size, std::optional<flutter::EmbeddedViewParams> view_params, flutter::RTreeFactory rtree_factory) : rtree(rtree_factory.getInstance()), embedded_view_params(std::move(view_params)), recorder(std::make_unique<SkPictureRecorder>()), canvas_spy(std::make_unique<flutter::CanvasSpy>( recorder->beginRecording(SkRect::Make(frame_size), &rtree_factory))), surface_size(frame_size), picture(nullptr) {} // Records paint operations applied to this layer's `SkCanvas`. // These records are used to determine which portions of this layer // contain content. The embedder propagates this information to scenic, so // that scenic can accurately decide which portions of this layer may // interact with input. sk_sp<flutter::RTree> rtree; std::optional<flutter::EmbeddedViewParams> embedded_view_params; std::unique_ptr<SkPictureRecorder> recorder; // TODO(cyanglaz: use DlOpSpy instead. // https://github.com/flutter/flutter/issues/123805 std::unique_ptr<flutter::CanvasSpy> canvas_spy; SkISize surface_size; sk_sp<SkPicture> picture; }; using EmbedderLayerId = std::optional<uint32_t>; constexpr static EmbedderLayerId kRootLayerId = EmbedderLayerId{}; struct View { std::vector<ClipTransform> clip_transforms; fuchsia::ui::composition::TransformId transform_id; fuchsia::ui::composition::ContentId viewport_id; ViewMutators mutators; SkSize size = SkSize::MakeEmpty(); SkRect pending_occlusion_hint = SkRect::MakeEmpty(); SkRect occlusion_hint = SkRect::MakeEmpty(); fit::callback<void(const SkSize&, const SkRect&)> pending_create_viewport_callback; }; struct Layer { // Transform on which Images are set. fuchsia::ui::composition::TransformId transform_id; }; std::shared_ptr<FlatlandConnection> flatland_; std::shared_ptr<SurfaceProducer> surface_producer_; fuchsia::ui::composition::ParentViewportWatcherPtr parent_viewport_watcher_; fuchsia::ui::composition::TransformId root_transform_id_; std::unordered_map<int64_t, View> views_; std::vector<Layer> layers_; std::unordered_map<EmbedderLayerId, EmbedderLayer> frame_layers_; std::vector<EmbedderLayerId> frame_composition_order_; std::vector<fuchsia::ui::composition::TransformId> child_transforms_; SkISize frame_size_ = SkISize::Make(0, 0); float frame_dpr_ = 1.f; // TransformId for the input interceptor node when input shield is turned on, // std::nullptr otherwise. std::optional<fuchsia::ui::composition::TransformId> input_interceptor_transform_; FML_DISALLOW_COPY_AND_ASSIGN(ExternalViewEmbedder); }; } // namespace flutter_runner #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_EXTERNAL_VIEW_EMBEDDER_H_
engine/shell/platform/fuchsia/flutter/external_view_embedder.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/external_view_embedder.h", "repo_id": "engine", "token_count": 3132 }
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. import("//build/compiled_action.gni") import("//flutter/common/config.gni") import("//flutter/tools/fuchsia/dart.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("$dart_src/utils/compile_platform.gni") compile_platform("kernel_platform_files") { single_root_scheme = "org-dartlang-sdk" single_root_base = rebase_path("../../../../../../") libraries_specification_uri = "org-dartlang-sdk:///flutter/shell/platform/fuchsia/flutter/kernel/libraries.json" outputs = [ "$root_out_dir/flutter_runner_patched_sdk/platform_strong.dill", "$root_out_dir/flutter_runner_patched_sdk/vm_outline_strong.dill", ] args = [ "--nnbd-agnostic", "--target=flutter_runner", "dart:core", ] } template("core_snapshot") { assert(defined(invoker.product), "core_snapshot requires 'product' to be defined") suffix = "" if (invoker.product) { suffix = "${suffix}_product" } compiled_action(target_name) { deps = [ ":kernel_platform_files" ] platform_dill = "$root_out_dir/flutter_runner_patched_sdk/platform_strong.dill" inputs = [ platform_dill ] vm_snapshot_data = "$target_gen_dir/vm_isolate_snapshot${suffix}.bin" isolate_snapshot_data = "$target_gen_dir/isolate_snapshot${suffix}.bin" snapshot_profile = "$target_gen_dir/snapshot_profile${suffix}.json" outputs = [ vm_snapshot_data, isolate_snapshot_data, snapshot_profile, ] gen_snapshot_to_use = gen_snapshot if (invoker.product) { gen_snapshot_to_use = gen_snapshot_product } tool = gen_snapshot_to_use args = [ "--enable_mirrors=false", "--deterministic", "--snapshot_kind=core", "--vm_snapshot_data=" + rebase_path(vm_snapshot_data, root_build_dir), "--isolate_snapshot_data=" + rebase_path(isolate_snapshot_data, root_build_dir), "--write_v8_snapshot_profile_to=" + rebase_path(snapshot_profile, root_build_dir), ] # No asserts in debug or release product. # No asserts in release with flutter_profile=true (non-product) # Yes asserts in non-product debug. if (!invoker.product && (is_debug || flutter_runtime_mode == "debug")) { args += [ "--enable_asserts" ] } args += [ rebase_path(platform_dill) ] } } core_snapshot("kernel_core_snapshot") { product = false } core_snapshot("kernel_core_snapshot_product") { product = true }
engine/shell/platform/fuchsia/flutter/kernel/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/kernel/BUILD.gn", "repo_id": "engine", "token_count": 1049 }
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. #define RAPIDJSON_HAS_STDSTRING 1 #include "platform_view.h" #include <fuchsia/ui/app/cpp/fidl.h> #include <zircon/status.h> #include <algorithm> #include <cstring> #include <limits> #include <sstream> #include "flutter/fml/logging.h" #include "flutter/fml/make_copyable.h" #include "flutter/lib/ui/window/pointer_data.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" #include "third_party/rapidjson/include/rapidjson/document.h" #include "third_party/rapidjson/include/rapidjson/stringbuffer.h" #include "third_party/rapidjson/include/rapidjson/writer.h" #include "flutter/fml/make_copyable.h" #include "logging.h" #include "pointer_injector_delegate.h" #include "runtime/dart/utils/inlines.h" #include "text_delegate.h" #include "vsync_waiter.h" namespace { // Helper to extract a given member with a given type from a rapidjson object. template <typename T, typename O, typename F> bool CallWithMember(O obj, const char* member_name, F func) { auto it = obj.FindMember(member_name); if (it == obj.MemberEnd()) { return false; } if (!it->value.template Is<T>()) { return false; } func(it->value.template Get<T>()); return true; } } // namespace namespace flutter_runner { static constexpr char kFlutterPlatformChannel[] = "flutter/platform"; static constexpr char kAccessibilityChannel[] = "flutter/accessibility"; static constexpr char kFlutterPlatformViewsChannel[] = "flutter/platform_views"; static constexpr char kFuchsiaShaderWarmupChannel[] = "fuchsia/shader_warmup"; static constexpr char kFuchsiaInputTestChannel[] = "fuchsia/input_test"; static constexpr char kFuchsiaChildViewChannel[] = "fuchsia/child_view"; static constexpr int64_t kFlutterImplicitViewId = 0ll; PlatformView::PlatformView( flutter::PlatformView::Delegate& delegate, flutter::TaskRunners task_runners, fuchsia::ui::views::ViewRef view_ref, std::shared_ptr<flutter::ExternalViewEmbedder> 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::FocuserHandle focuser, fuchsia::ui::views::ViewRefFocusedHandle view_ref_focused, fuchsia::ui::composition::ParentViewportWatcherHandle parent_viewport_watcher, fuchsia::ui::pointerinjector::RegistryHandle pointerinjector_registry, OnEnableWireframeCallback wireframe_enabled_callback, OnCreateViewCallback on_create_view_callback, OnUpdateViewCallback on_update_view_callback, OnDestroyViewCallback on_destroy_view_callback, OnCreateSurfaceCallback on_create_surface_callback, OnSemanticsNodeUpdateCallback on_semantics_node_update_callback, OnRequestAnnounceCallback on_request_announce_callback, OnShaderWarmupCallback on_shader_warmup_callback, AwaitVsyncCallback await_vsync_callback, AwaitVsyncForSecondaryCallbackCallback await_vsync_for_secondary_callback_callback, std::shared_ptr<sys::ServiceDirectory> dart_application_svc) : flutter::PlatformView(delegate, std::move(task_runners)), external_view_embedder_(external_view_embedder), focus_delegate_( std::make_shared<FocusDelegate>(std::move(view_ref_focused), std::move(focuser))), pointer_delegate_( std::make_shared<PointerDelegate>(std::move(touch_source), std::move(mouse_source))), wireframe_enabled_callback_(std::move(wireframe_enabled_callback)), on_update_view_callback_(std::move(on_update_view_callback)), on_create_surface_callback_(std::move(on_create_surface_callback)), on_semantics_node_update_callback_( std::move(on_semantics_node_update_callback)), on_request_announce_callback_(std::move(on_request_announce_callback)), on_create_view_callback_(std::move(on_create_view_callback)), on_destroy_view_callback_(std::move(on_destroy_view_callback)), on_shader_warmup_callback_(std::move(on_shader_warmup_callback)), await_vsync_callback_(await_vsync_callback), await_vsync_for_secondary_callback_callback_( await_vsync_for_secondary_callback_callback), dart_application_svc_(dart_application_svc), parent_viewport_watcher_(parent_viewport_watcher.Bind()), weak_factory_(this) { fuchsia::ui::views::ViewRef view_ref_clone; fidl::Clone(view_ref, &view_ref_clone); text_delegate_ = std::make_unique<TextDelegate>( std::move(view_ref), std::move(ime_service), std::move(keyboard), [weak = weak_factory_.GetWeakPtr()]( std::unique_ptr<flutter::PlatformMessage> message) { if (!weak) { FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; } weak->delegate_.OnPlatformViewDispatchPlatformMessage( std::move(message)); }); // Begin watching for focus changes. focus_delegate_->WatchLoop([weak = weak_factory_.GetWeakPtr()](bool focused) { if (!weak) { FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; return; } // Ensure last_text_state_ is set to make sure Flutter actually wants // an IME. if (focused && weak->text_delegate_->HasTextState()) { weak->text_delegate_->ActivateIme(); } else if (!focused) { weak->text_delegate_->DeactivateIme(); } }); // Begin watching for pointer events. pointer_delegate_->WatchLoop([weak = weak_factory_.GetWeakPtr()]( std::vector<flutter::PointerData> events) { if (!weak) { FML_LOG(WARNING) << "PlatformView use-after-free attempted. Ignoring."; return; } if (events.empty()) { return; // No work, bounce out. } // If pixel ratio hasn't been set, use a default value of 1. const float pixel_ratio = weak->view_pixel_ratio_.value_or(1.f); auto packet = std::make_unique<flutter::PointerDataPacket>(events.size()); for (size_t i = 0; i < events.size(); ++i) { auto& event = events[i]; // Translate logical to physical coordinates, as per // flutter::PointerData contract. Done here because pixel ratio comes // from the graphics API. event.physical_x = event.physical_x * pixel_ratio; event.physical_y = event.physical_y * pixel_ratio; packet->SetPointerData(i, event); } weak->DispatchPointerDataPacket(std::move(packet)); }); // Configure the pointer injector delegate. pointer_injector_delegate_ = std::make_unique<PointerInjectorDelegate>( std::move(pointerinjector_registry), std::move(view_ref_clone)); // This is only used by the integration tests. if (dart_application_svc) { // Connect to TouchInputListener fuchsia::ui::test::input::TouchInputListenerHandle touch_input_listener; zx_status_t touch_input_listener_status = dart_application_svc ->Connect<fuchsia::ui::test::input::TouchInputListener>( touch_input_listener.NewRequest()); if (touch_input_listener_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::ui::test::input::TouchInputListener connection failed: " << zx_status_get_string(touch_input_listener_status); } else { touch_input_listener_.Bind(std::move(touch_input_listener)); } // Connect to KeyboardInputListener fuchsia::ui::test::input::KeyboardInputListenerHandle keyboard_input_listener; zx_status_t keyboard_input_listener_status = dart_application_svc ->Connect<fuchsia::ui::test::input::KeyboardInputListener>( keyboard_input_listener.NewRequest()); if (keyboard_input_listener_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::ui::test::input::KeyboardInputListener " "connection failed: " << zx_status_get_string(keyboard_input_listener_status); } else { keyboard_input_listener_.Bind(std::move(keyboard_input_listener)); } // Connect to MouseInputListener fuchsia::ui::test::input::MouseInputListenerHandle mouse_input_listener; zx_status_t mouse_input_listener_status = dart_application_svc ->Connect<fuchsia::ui::test::input::MouseInputListener>( mouse_input_listener.NewRequest()); if (mouse_input_listener_status != ZX_OK) { FML_LOG(WARNING) << "fuchsia::ui::test::input::MouseInputListener connection failed: " << zx_status_get_string(mouse_input_listener_status); } else { mouse_input_listener_.Bind(std::move(mouse_input_listener)); } } // Finally! Register the native platform message handlers. RegisterPlatformMessageHandlers(); parent_viewport_watcher_.set_error_handler([](zx_status_t status) { FML_LOG(ERROR) << "Interface error on: ParentViewportWatcher status: " << status; }); parent_viewport_watcher_->GetLayout( fit::bind_member(this, &PlatformView::OnGetLayout)); parent_viewport_watcher_->GetStatus( fit::bind_member(this, &PlatformView::OnParentViewportStatus)); } PlatformView::~PlatformView() = default; void PlatformView::RegisterPlatformMessageHandlers() { platform_message_handlers_[kFlutterPlatformChannel] = std::bind(&PlatformView::HandleFlutterPlatformChannelPlatformMessage, this, std::placeholders::_1); platform_message_handlers_[kTextInputChannel] = std::bind(&TextDelegate::HandleFlutterTextInputChannelPlatformMessage, text_delegate_.get(), std::placeholders::_1); platform_message_handlers_[kAccessibilityChannel] = std::bind(&PlatformView::HandleAccessibilityChannelPlatformMessage, this, std::placeholders::_1); platform_message_handlers_[kFlutterPlatformViewsChannel] = std::bind(&PlatformView::HandleFlutterPlatformViewsChannelPlatformMessage, this, std::placeholders::_1); platform_message_handlers_[kFuchsiaShaderWarmupChannel] = std::bind(&HandleFuchsiaShaderWarmupChannelPlatformMessage, on_shader_warmup_callback_, std::placeholders::_1); platform_message_handlers_[kFuchsiaInputTestChannel] = std::bind(&PlatformView::HandleFuchsiaInputTestChannelPlatformMessage, this, std::placeholders::_1); platform_message_handlers_[kFuchsiaChildViewChannel] = std::bind(&PlatformView::HandleFuchsiaChildViewChannelPlatformMessage, this, std::placeholders::_1); } static flutter::PointerData::Change GetChangeFromPointerEventPhase( fuchsia::ui::input::PointerEventPhase phase) { switch (phase) { case fuchsia::ui::input::PointerEventPhase::ADD: return flutter::PointerData::Change::kAdd; case fuchsia::ui::input::PointerEventPhase::HOVER: return flutter::PointerData::Change::kHover; case fuchsia::ui::input::PointerEventPhase::DOWN: return flutter::PointerData::Change::kDown; case fuchsia::ui::input::PointerEventPhase::MOVE: return flutter::PointerData::Change::kMove; case fuchsia::ui::input::PointerEventPhase::UP: return flutter::PointerData::Change::kUp; case fuchsia::ui::input::PointerEventPhase::REMOVE: return flutter::PointerData::Change::kRemove; case fuchsia::ui::input::PointerEventPhase::CANCEL: return flutter::PointerData::Change::kCancel; default: return flutter::PointerData::Change::kCancel; } } static flutter::PointerData::DeviceKind GetKindFromPointerType( fuchsia::ui::input::PointerEventType type) { switch (type) { case fuchsia::ui::input::PointerEventType::TOUCH: return flutter::PointerData::DeviceKind::kTouch; case fuchsia::ui::input::PointerEventType::MOUSE: return flutter::PointerData::DeviceKind::kMouse; default: return flutter::PointerData::DeviceKind::kTouch; } } // TODO(SCN-1278): Remove this. // Turns two floats (high bits, low bits) into a 64-bit uint. static trace_flow_id_t PointerTraceHACK(float fa, float fb) { uint32_t ia, ib; memcpy(&ia, &fa, sizeof(uint32_t)); memcpy(&ib, &fb, sizeof(uint32_t)); return (((uint64_t)ia) << 32) | ib; } // For certain scenarios that must avoid floating-point drift, compute a // coordinate that falls within the logical view bounding box. std::array<float, 2> PlatformView::ClampToViewSpace(const float x, const float y) const { if (!view_logical_size_.has_value() || !view_logical_origin_.has_value()) { return {x, y}; // If we can't do anything, return the original values. } const auto origin = view_logical_origin_.value(); const auto size = view_logical_size_.value(); const float min_x = origin[0]; const float max_x = origin[0] + size[0]; const float min_y = origin[1]; const float max_y = origin[1] + size[1]; if (min_x <= x && x < max_x && min_y <= y && y < max_y) { return {x, y}; // No clamping to perform. } // View boundary is [min_x, max_x) x [min_y, max_y). Note that min is // inclusive, but max is exclusive - so we subtract epsilon. const float max_x_inclusive = max_x - std::numeric_limits<float>::epsilon(); const float max_y_inclusive = max_y - std::numeric_limits<float>::epsilon(); const float& clamped_x = std::clamp(x, min_x, max_x_inclusive); const float& clamped_y = std::clamp(y, min_y, max_y_inclusive); FML_LOG(INFO) << "Clamped (" << x << ", " << y << ") to (" << clamped_x << ", " << clamped_y << ")."; return {clamped_x, clamped_y}; } void PlatformView::OnGetLayout(fuchsia::ui::composition::LayoutInfo info) { view_logical_size_ = {static_cast<float>(info.logical_size().width), static_cast<float>(info.logical_size().height)}; if (info.has_device_pixel_ratio()) { // Both values should be identical for the Vec2 for DPR. FML_DCHECK(info.device_pixel_ratio().x == info.device_pixel_ratio().y); view_pixel_ratio_ = info.device_pixel_ratio().x; } float pixel_ratio = view_pixel_ratio_ ? *view_pixel_ratio_ : 1.0f; flutter::ViewportMetrics metrics{ pixel_ratio, // device_pixel_ratio std::round(view_logical_size_.value()[0] * pixel_ratio), // physical_width std::round(view_logical_size_.value()[1] * pixel_ratio), // physical_height 0.0f, // physical_padding_top 0.0f, // physical_padding_right 0.0f, // physical_padding_bottom 0.0f, // physical_padding_left 0.0f, // physical_view_inset_top 0.0f, // physical_view_inset_right 0.0f, // physical_view_inset_bottom 0.0f, // physical_view_inset_left 0.0f, // p_physical_system_gesture_inset_top 0.0f, // p_physical_system_gesture_inset_right 0.0f, // p_physical_system_gesture_inset_bottom 0.0f, // p_physical_system_gesture_inset_left, -1.0, // p_physical_touch_slop, {}, // p_physical_display_features_bounds {}, // p_physical_display_features_type {}, // p_physical_display_features_state 0, // p_display_id }; SetViewportMetrics(kFlutterImplicitViewId, metrics); parent_viewport_watcher_->GetLayout( fit::bind_member(this, &PlatformView::OnGetLayout)); } void PlatformView::OnParentViewportStatus( fuchsia::ui::composition::ParentViewportStatus status) { // TODO(fxbug.dev/116001): Investigate if it is useful to send hidden/shown // signals. parent_viewport_status_ = status; parent_viewport_watcher_->GetStatus( fit::bind_member(this, &PlatformView::OnParentViewportStatus)); } void PlatformView::OnChildViewStatus( uint64_t content_id, fuchsia::ui::composition::ChildViewStatus status) { FML_DCHECK(child_view_info_.count(content_id) == 1); std::ostringstream out; out << "{" << "\"method\":\"View.viewStateChanged\"," << "\"args\":{" << " \"viewId\":" << child_view_info_.at(content_id).view_id << "," // ViewId << " \"is_rendering\":true," // IsViewRendering << " \"state\":true" // IsViewRendering << " }" << "}"; auto call = out.str(); std::unique_ptr<flutter::PlatformMessage> message = std::make_unique<flutter::PlatformMessage>( "flutter/platform_views", fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr); DispatchPlatformMessage(std::move(message)); child_view_info_.at(content_id) .child_view_watcher->GetStatus( [this, content_id](fuchsia::ui::composition::ChildViewStatus status) { OnChildViewStatus(content_id, status); }); } void PlatformView::OnChildViewViewRef(uint64_t content_id, uint64_t view_id, fuchsia::ui::views::ViewRef view_ref) { FML_CHECK(child_view_info_.count(content_id) == 1); fuchsia::ui::views::ViewRef view_ref_clone; fidl::Clone(view_ref, &view_ref_clone); focus_delegate_->OnChildViewViewRef(view_id, std::move(view_ref)); pointer_injector_delegate_->OnCreateView(view_id, std::move(view_ref_clone)); OnChildViewConnected(content_id); } void PlatformView::OnCreateView(ViewCallback on_view_created, int64_t view_id_raw, bool hit_testable, bool focusable) { auto on_view_bound = [weak = weak_factory_.GetWeakPtr(), platform_task_runner = task_runners_.GetPlatformTaskRunner(), view_id = view_id_raw]( fuchsia::ui::composition::ContentId content_id, fuchsia::ui::composition::ChildViewWatcherHandle child_view_watcher_handle) { FML_CHECK(weak); FML_CHECK(weak->child_view_info_.count(content_id.value) == 0); platform_task_runner->PostTask(fml::MakeCopyable( [weak, view_id, content_id, watcher_handle = std::move(child_view_watcher_handle)]() mutable { if (!weak) { FML_LOG(WARNING) << "View bound to PlatformView after PlatformView was " "destroyed; ignoring."; return; } // Bind the child view watcher to the platform thread so that the FIDL // calls are handled on the platform thread. fuchsia::ui::composition::ChildViewWatcherPtr child_view_watcher = watcher_handle.Bind(); FML_CHECK(child_view_watcher); child_view_watcher.set_error_handler([weak, view_id, content_id]( zx_status_t status) { FML_LOG(WARNING) << "Child disconnected. ChildViewWatcher status: " << status; if (!weak) { FML_LOG(WARNING) << "View bound to PlatformView after " "PlatformView was " "destroyed; ignoring."; return; } // Disconnected views cannot listen to pointer events. weak->pointer_injector_delegate_->OnDestroyView(view_id); weak->OnChildViewDisconnected(content_id.value); }); weak->child_view_info_.emplace( std::piecewise_construct, std::forward_as_tuple(content_id.value), std::forward_as_tuple(view_id, std::move(child_view_watcher))); weak->child_view_info_.at(content_id.value) .child_view_watcher->GetStatus( [weak, id = content_id.value]( fuchsia::ui::composition::ChildViewStatus status) { weak->OnChildViewStatus(id, status); }); weak->child_view_info_.at(content_id.value) .child_view_watcher->GetViewRef( [weak, content_id = content_id.value, view_id](fuchsia::ui::views::ViewRef view_ref) { weak->OnChildViewViewRef(content_id, view_id, std::move(view_ref)); }); })); }; on_create_view_callback_(view_id_raw, std::move(on_view_created), std::move(on_view_bound), hit_testable, focusable); } void PlatformView::OnDisposeView(int64_t view_id_raw) { auto on_view_unbound = [weak = weak_factory_.GetWeakPtr(), platform_task_runner = task_runners_.GetPlatformTaskRunner(), view_id_raw](fuchsia::ui::composition::ContentId content_id) { platform_task_runner->PostTask([weak, content_id, view_id_raw]() { if (!weak) { FML_LOG(WARNING) << "View unbound from PlatformView after PlatformView" "was destroyed; ignoring."; return; } FML_DCHECK(weak->child_view_info_.count(content_id.value) == 1); weak->OnChildViewDisconnected(content_id.value); weak->child_view_info_.erase(content_id.value); weak->focus_delegate_->OnDisposeChildView(view_id_raw); weak->pointer_injector_delegate_->OnDestroyView(view_id_raw); }); }; on_destroy_view_callback_(view_id_raw, std::move(on_view_unbound)); } void PlatformView::OnChildViewConnected(uint64_t content_id) { FML_CHECK(child_view_info_.count(content_id) == 1); std::ostringstream out; out << "{" << "\"method\":\"View.viewConnected\"," << "\"args\":{" << " \"viewId\":" << child_view_info_.at(content_id).view_id << " }" << "}"; auto call = out.str(); std::unique_ptr<flutter::PlatformMessage> message = std::make_unique<flutter::PlatformMessage>( "flutter/platform_views", fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr); DispatchPlatformMessage(std::move(message)); } void PlatformView::OnChildViewDisconnected(uint64_t content_id) { FML_CHECK(child_view_info_.count(content_id) == 1); std::ostringstream out; out << "{" << "\"method\":\"View.viewDisconnected\"," << "\"args\":{" << " \"viewId\":" << child_view_info_.at(content_id).view_id << " }" << "}"; auto call = out.str(); std::unique_ptr<flutter::PlatformMessage> message = std::make_unique<flutter::PlatformMessage>( "flutter/platform_views", fml::MallocMapping::Copy(call.c_str(), call.size()), nullptr); DispatchPlatformMessage(std::move(message)); } bool PlatformView::OnHandlePointerEvent( const fuchsia::ui::input::PointerEvent& pointer) { TRACE_EVENT0("flutter", "PlatformView::OnHandlePointerEvent"); // TODO(SCN-1278): Use proper trace_id for tracing flow. trace_flow_id_t trace_id = PointerTraceHACK(pointer.radius_major, pointer.radius_minor); TRACE_FLOW_END("input", "dispatch_event_to_client", trace_id); const float pixel_ratio = view_pixel_ratio_.has_value() ? *view_pixel_ratio_ : 0.f; flutter::PointerData pointer_data; pointer_data.Clear(); pointer_data.time_stamp = pointer.event_time / 1000; pointer_data.change = GetChangeFromPointerEventPhase(pointer.phase); pointer_data.kind = GetKindFromPointerType(pointer.type); pointer_data.device = pointer.pointer_id; // Pointer events are in logical pixels, so scale to physical. pointer_data.physical_x = pointer.x * pixel_ratio; pointer_data.physical_y = pointer.y * pixel_ratio; // Buttons are single bit values starting with kMousePrimaryButton = 1. pointer_data.buttons = static_cast<uint64_t>(pointer.buttons); switch (pointer_data.change) { case flutter::PointerData::Change::kDown: { // Make the pointer start in the view space, despite numerical drift. auto clamped_pointer = ClampToViewSpace(pointer.x, pointer.y); pointer_data.physical_x = clamped_pointer[0] * pixel_ratio; pointer_data.physical_y = clamped_pointer[1] * pixel_ratio; down_pointers_.insert(pointer_data.device); break; } case flutter::PointerData::Change::kCancel: case flutter::PointerData::Change::kUp: down_pointers_.erase(pointer_data.device); break; case flutter::PointerData::Change::kMove: if (down_pointers_.count(pointer_data.device) == 0) { pointer_data.change = flutter::PointerData::Change::kHover; } break; case flutter::PointerData::Change::kAdd: if (down_pointers_.count(pointer_data.device) != 0) { FML_LOG(ERROR) << "Received add event for down pointer."; } break; case flutter::PointerData::Change::kRemove: if (down_pointers_.count(pointer_data.device) != 0) { FML_LOG(ERROR) << "Received remove event for down pointer."; } break; case flutter::PointerData::Change::kHover: if (down_pointers_.count(pointer_data.device) != 0) { FML_LOG(ERROR) << "Received hover event for down pointer."; } break; case flutter::PointerData::Change::kPanZoomStart: case flutter::PointerData::Change::kPanZoomUpdate: case flutter::PointerData::Change::kPanZoomEnd: FML_DLOG(ERROR) << "Unexpectedly received pointer pan/zoom event"; break; } auto packet = std::make_unique<flutter::PointerDataPacket>(1); packet->SetPointerData(0, pointer_data); DispatchPointerDataPacket(std::move(packet)); return true; } // |flutter::PlatformView| std::unique_ptr<flutter::VsyncWaiter> PlatformView::CreateVSyncWaiter() { return std::make_unique<flutter_runner::VsyncWaiter>( await_vsync_callback_, await_vsync_for_secondary_callback_callback_, task_runners_); } // |flutter::PlatformView| std::unique_ptr<flutter::Surface> PlatformView::CreateRenderingSurface() { return on_create_surface_callback_ ? on_create_surface_callback_() : nullptr; } // |flutter::PlatformView| std::shared_ptr<flutter::ExternalViewEmbedder> PlatformView::CreateExternalViewEmbedder() { return external_view_embedder_; } // |flutter::PlatformView| void PlatformView::HandlePlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { if (!message) { return; } const std::string channel = message->channel(); auto found = platform_message_handlers_.find(channel); if (found == platform_message_handlers_.end()) { const bool already_errored = unregistered_channels_.count(channel); if (!already_errored) { FML_LOG(INFO) << "Platform view received message on channel '" << message->channel() << "' with no registered handler. An empty response will be " "generated. Please implement the native message handler. This " "message will appear only once per channel."; unregistered_channels_.insert(channel); } flutter::PlatformView::HandlePlatformMessage(std::move(message)); return; } auto response = message->response(); bool response_handled = found->second(std::move(message)); // Ensure all responses are completed. if (response && !response_handled) { // response_handled should be true if the response was completed. FML_DCHECK(!response->is_complete()); response->CompleteEmpty(); } } // |flutter::PlatformView| void PlatformView::SetSemanticsEnabled(bool enabled) { flutter::PlatformView::SetSemanticsEnabled(enabled); if (enabled) { SetAccessibilityFeatures(static_cast<int32_t>( flutter::AccessibilityFeatureFlag::kAccessibleNavigation)); } else { SetAccessibilityFeatures(0); } } // |flutter::PlatformView| void PlatformView::UpdateSemantics( flutter::SemanticsNodeUpdates update, flutter::CustomAccessibilityActionUpdates actions) { const float pixel_ratio = view_pixel_ratio_.has_value() ? *view_pixel_ratio_ : 0.f; on_semantics_node_update_callback_(update, pixel_ratio); } // Channel handler for kAccessibilityChannel bool PlatformView::HandleAccessibilityChannelPlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kAccessibilityChannel); const flutter::StandardMessageCodec& standard_message_codec = flutter::StandardMessageCodec::GetInstance(nullptr); std::unique_ptr<flutter::EncodableValue> decoded = standard_message_codec.DecodeMessage(message->data().GetMapping(), message->data().GetSize()); flutter::EncodableMap map = std::get<flutter::EncodableMap>(*decoded); std::string type = std::get<std::string>(map.at(flutter::EncodableValue("type"))); if (type == "announce") { flutter::EncodableMap data_map = std::get<flutter::EncodableMap>( map.at(flutter::EncodableValue("data"))); std::string text = std::get<std::string>(data_map.at(flutter::EncodableValue("message"))); on_request_announce_callback_(text); } // Complete with an empty response. return false; } // Channel handler for kFlutterPlatformChannel bool PlatformView::HandleFlutterPlatformChannelPlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kFlutterPlatformChannel); // Fuchsia does not handle any platform messages at this time. // Complete with an empty response. return false; } bool PlatformView::HandleFlutterPlatformViewsChannelPlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kFlutterPlatformViewsChannel); const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { FML_LOG(ERROR) << "Could not parse document"; return false; } auto root = document.GetObject(); auto method_member = root.FindMember("method"); if (method_member == root.MemberEnd() || !method_member->value.IsString()) { return false; } std::string method(method_member->value.GetString()); if (method == "View.enableWireframe") { auto args_it = root.FindMember("args"); if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } const auto& args = args_it->value; auto enable = args.FindMember("enable"); if (!enable->value.IsBool()) { FML_LOG(ERROR) << "Argument 'enable' is not a bool"; return false; } wireframe_enabled_callback_(enable->value.GetBool()); } else if (method == "View.create") { auto args_it = root.FindMember("args"); if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } const auto& args = args_it->value; auto view_id = args.FindMember("viewId"); if (!view_id->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewId' is not a int64"; return false; } auto hit_testable = args.FindMember("hitTestable"); if (!hit_testable->value.IsBool()) { FML_LOG(ERROR) << "Argument 'hitTestable' is not a bool"; return false; } auto focusable = args.FindMember("focusable"); if (!focusable->value.IsBool()) { FML_LOG(ERROR) << "Argument 'focusable' is not a bool"; return false; } auto on_view_created = fml::MakeCopyable( [platform_task_runner = task_runners_.GetPlatformTaskRunner(), message = std::move(message)]() { // The client is waiting for view creation. Send an empty response // back to signal the view was created. if (message->response()) { message->response()->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>({'[', '0', ']'}))); } }); OnCreateView(std::move(on_view_created), view_id->value.GetUint64(), hit_testable->value.GetBool(), focusable->value.GetBool()); return true; } else if (method == "View.update") { auto args_it = root.FindMember("args"); if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } const auto& args = args_it->value; auto view_id = args.FindMember("viewId"); if (!view_id->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewId' is not a int64"; return false; } auto hit_testable = args.FindMember("hitTestable"); if (!hit_testable->value.IsBool()) { FML_LOG(ERROR) << "Argument 'hitTestable' is not a bool"; return false; } auto focusable = args.FindMember("focusable"); if (!focusable->value.IsBool()) { FML_LOG(ERROR) << "Argument 'focusable' is not a bool"; return false; } SkRect view_occlusion_hint_raw = SkRect::MakeEmpty(); auto view_occlusion_hint = args.FindMember("viewOcclusionHintLTRB"); if (view_occlusion_hint != args.MemberEnd()) { if (view_occlusion_hint->value.IsArray()) { const auto& view_occlusion_hint_array = view_occlusion_hint->value.GetArray(); if (view_occlusion_hint_array.Size() == 4) { bool parse_error = false; for (int i = 0; i < 4; i++) { auto& array_val = view_occlusion_hint_array[i]; if (!array_val.IsDouble()) { FML_LOG(ERROR) << "Argument 'viewOcclusionHintLTRB' element " << i << " is not a double"; parse_error = true; break; } } if (!parse_error) { view_occlusion_hint_raw = SkRect::MakeLTRB(view_occlusion_hint_array[0].GetDouble(), view_occlusion_hint_array[1].GetDouble(), view_occlusion_hint_array[2].GetDouble(), view_occlusion_hint_array[3].GetDouble()); } } else { FML_LOG(ERROR) << "Argument 'viewOcclusionHintLTRB' expected size 4; got " << view_occlusion_hint_array.Size(); } } else { FML_LOG(ERROR) << "Argument 'viewOcclusionHintLTRB' is not a double array"; } } else { FML_LOG(WARNING) << "Argument 'viewOcclusionHintLTRB' is missing"; } on_update_view_callback_( view_id->value.GetUint64(), view_occlusion_hint_raw, hit_testable->value.GetBool(), focusable->value.GetBool()); if (message->response()) { message->response()->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>({'[', '0', ']'}))); return true; } } else if (method == "View.dispose") { auto args_it = root.FindMember("args"); if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } const auto& args = args_it->value; auto view_id = args.FindMember("viewId"); if (!view_id->value.IsUint64()) { FML_LOG(ERROR) << "Argument 'viewId' is not a int64"; return false; } OnDisposeView(view_id->value.GetUint64()); if (message->response()) { message->response()->Complete(std::make_unique<fml::DataMapping>( std::vector<uint8_t>({'[', '0', ']'}))); return true; } } else if (method.rfind("View.focus", 0) == 0) { return focus_delegate_->HandlePlatformMessage(root, message->response()); } else if (method.rfind(PointerInjectorDelegate::kPointerInjectorMethodPrefix, 0) == 0) { return pointer_injector_delegate_->HandlePlatformMessage( root, message->response()); } else { FML_LOG(ERROR) << "Unknown " << message->channel() << " method " << method; } // Complete with an empty response by default. return false; } bool PlatformView::HandleFuchsiaShaderWarmupChannelPlatformMessage( OnShaderWarmupCallback on_shader_warmup_callback, std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kFuchsiaShaderWarmupChannel); if (!on_shader_warmup_callback) { FML_LOG(ERROR) << "No shader warmup callback set!"; std::string result = "[0]"; message->response()->Complete( std::make_unique<fml::DataMapping>(std::vector<uint8_t>( (const uint8_t*)result.c_str(), (const uint8_t*)result.c_str() + result.length()))); return true; } const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { FML_LOG(ERROR) << "Could not parse document"; return false; } auto root = document.GetObject(); auto method = root.FindMember("method"); if (method == root.MemberEnd() || !method->value.IsString() || method->value != "WarmupSkps") { FML_LOG(ERROR) << "Invalid method name"; return false; } auto args_it = root.FindMember("args"); if (args_it == root.MemberEnd() || !args_it->value.IsObject()) { FML_LOG(ERROR) << "No arguments found."; return false; } auto shaders_it = root["args"].FindMember("shaders"); if (shaders_it == root["args"].MemberEnd() || !shaders_it->value.IsArray()) { FML_LOG(ERROR) << "No shaders found."; return false; } auto width_it = root["args"].FindMember("width"); auto height_it = root["args"].FindMember("height"); if (width_it == root["args"].MemberEnd() || !width_it->value.IsNumber()) { FML_LOG(ERROR) << "Invalid width"; return false; } if (height_it == root["args"].MemberEnd() || !height_it->value.IsNumber()) { FML_LOG(ERROR) << "Invalid height"; return false; } auto width = width_it->value.GetUint64(); auto height = height_it->value.GetUint64(); std::vector<std::string> skp_paths; const auto& shaders = shaders_it->value; for (rapidjson::Value::ConstValueIterator itr = shaders.Begin(); itr != shaders.End(); ++itr) { skp_paths.push_back((*itr).GetString()); } auto completion_callback = [response = message->response()](uint32_t num_successes) { std::ostringstream result_stream; result_stream << "[" << num_successes << "]"; std::string result(result_stream.str()); response->Complete(std::make_unique<fml::DataMapping>(std::vector<uint8_t>( (const uint8_t*)result.c_str(), (const uint8_t*)result.c_str() + result.length()))); }; on_shader_warmup_callback(skp_paths, completion_callback, width, height); // The response has already been completed by us. return true; } // Channel handler for kFuchsiaInputTestChannel bool PlatformView::HandleFuchsiaInputTestChannelPlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kFuchsiaInputTestChannel); const auto& data = message->data(); rapidjson::Document document; document.Parse(reinterpret_cast<const char*>(data.GetMapping()), data.GetSize()); if (document.HasParseError() || !document.IsObject()) { FML_LOG(ERROR) << "Could not parse document"; return false; } auto root = document.GetObject(); auto method = root.FindMember("method"); if (method == root.MemberEnd() || !method->value.IsString()) { FML_LOG(ERROR) << "Missing method"; return false; } FML_LOG(INFO) << "fuchsia/input_test: method=" << method->value.GetString(); if (method->value == "TouchInputListener.ReportTouchInput") { if (!touch_input_listener_) { FML_LOG(ERROR) << "TouchInputListener not found."; return false; } fuchsia::ui::test::input::TouchInputListenerReportTouchInputRequest request; CallWithMember<double>( root, "local_x", [&](double local_x) { request.set_local_x(local_x); }); CallWithMember<double>( root, "local_y", [&](double local_y) { request.set_local_y(local_y); }); CallWithMember<int64_t>(root, "time_received", [&](uint64_t time_received) { request.set_time_received(time_received); }); CallWithMember<std::string>(root, "component_name", [&](std::string component_name) { request.set_component_name(component_name); }); touch_input_listener_->ReportTouchInput(std::move(request)); return true; } if (method->value == "KeyboardInputListener.ReportTextInput") { if (!keyboard_input_listener_) { FML_LOG(ERROR) << "KeyboardInputListener not found."; return false; } fuchsia::ui::test::input::KeyboardInputListenerReportTextInputRequest request; CallWithMember<std::string>( root, "text", [&](std::string text) { request.set_text(text); }); keyboard_input_listener_->ReportTextInput(std::move(request)); return true; } if (method->value == "MouseInputListener.ReportMouseInput") { if (!mouse_input_listener_) { FML_LOG(ERROR) << "MouseInputListener not found."; return false; } fuchsia::ui::test::input::MouseInputListenerReportMouseInputRequest request; CallWithMember<double>( root, "local_x", [&](double local_x) { request.set_local_x(local_x); }); CallWithMember<double>( root, "local_y", [&](double local_y) { request.set_local_y(local_y); }); CallWithMember<int64_t>(root, "time_received", [&](uint64_t time_received) { request.set_time_received(time_received); }); CallWithMember<std::string>(root, "component_name", [&](std::string component_name) { request.set_component_name(component_name); }); CallWithMember<int>(root, "buttons", [&](int button_mask) { std::vector<fuchsia::ui::test::input::MouseButton> buttons; if (button_mask & 1) { buttons.push_back(fuchsia::ui::test::input::MouseButton::FIRST); } if (button_mask & 2) { buttons.push_back(fuchsia::ui::test::input::MouseButton::SECOND); } if (button_mask & 4) { buttons.push_back(fuchsia::ui::test::input::MouseButton::THIRD); } request.set_buttons(buttons); }); CallWithMember<std::string>(root, "phase", [&](std::string phase) { if (phase == "add") { request.set_phase(fuchsia::ui::test::input::MouseEventPhase::ADD); } else if (phase == "hover") { request.set_phase(fuchsia::ui::test::input::MouseEventPhase::HOVER); } else if (phase == "down") { request.set_phase(fuchsia::ui::test::input::MouseEventPhase::DOWN); } else if (phase == "move") { request.set_phase(fuchsia::ui::test::input::MouseEventPhase::MOVE); } else if (phase == "up") { request.set_phase(fuchsia::ui::test::input::MouseEventPhase::UP); } else { FML_LOG(ERROR) << "Unexpected mouse phase: " << phase; } }); CallWithMember<double>( root, "wheel_x_physical_pixel", [&](double wheel_x_physical_pixel) { request.set_wheel_x_physical_pixel(wheel_x_physical_pixel); }); CallWithMember<double>( root, "wheel_y_physical_pixel", [&](double wheel_y_physical_pixel) { request.set_wheel_y_physical_pixel(wheel_y_physical_pixel); }); mouse_input_listener_->ReportMouseInput(std::move(request)); return true; } FML_LOG(ERROR) << "fuchsia/input_test: unrecognized method " << method->value.GetString(); return false; } // Channel handler for kFuchsiaChildViewChannel bool PlatformView::HandleFuchsiaChildViewChannelPlatformMessage( std::unique_ptr<flutter::PlatformMessage> message) { FML_DCHECK(message->channel() == kFuchsiaChildViewChannel); if (message->data().GetSize() != 1 || (message->data().GetMapping()[0] != '1')) { FML_LOG(ERROR) << kFuchsiaChildViewChannel << " data must be singularly '1'."; return false; } FML_DCHECK(message->data().GetMapping()[0] == '1'); if (!message->response()) { FML_LOG(ERROR) << kFuchsiaChildViewChannel << " must have a response callback."; return false; } if (!dart_application_svc_) { FML_LOG(ERROR) << "No service directory."; return false; } fuchsia::ui::app::ViewProviderHandle view_provider_handle; zx_status_t status = dart_application_svc_->Connect(view_provider_handle.NewRequest()); if (status != ZX_OK) { FML_LOG(ERROR) << "Failed to connect to view provider."; return false; } fuchsia::ui::app::ViewProviderPtr view_provider; view_provider.Bind(std::move(view_provider_handle)); zx::handle view_id; zx::channel view_tokens[2]; fuchsia::ui::views::ViewportCreationToken viewport_creation_token; fuchsia::ui::views::ViewCreationToken view_creation_token; status = zx::channel::create(0, &viewport_creation_token.value, &view_creation_token.value); if (status != ZX_OK) { FML_LOG(ERROR) << "Creating view tokens: " << zx_status_get_string(status); return false; } fuchsia::ui::app::CreateView2Args create_view_args; create_view_args.set_view_creation_token(std::move(view_creation_token)); view_provider->CreateView2(std::move(create_view_args)); view_id = std::move(viewport_creation_token.value); if (view_id) { message->response()->Complete( std::make_unique<fml::DataMapping>(std::to_string(view_id.release()) )); return true; } else { return false; } } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/platform_view.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/platform_view.cc", "repo_id": "engine", "token_count": 18951 }
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. #include <gtest/gtest.h> #include <cstdlib> #include "runner.h" #include "third_party/icu/source/i18n/unicode/timezone.h" namespace flutter_runner { TEST(RunnerTZDataTest, LoadsWithTZDataPresent) { // TODO(fxbug.dev/69570): Move to cml file if env_vars gains supported for the // gtest_runner. setenv("ICU_TIMEZONE_FILES_DIR", "/pkg/data/tzdata", true); UErrorCode err = U_ZERO_ERROR; const auto version_before = std::string(icu::TimeZone::getTZDataVersion(err)); ASSERT_EQ(U_ZERO_ERROR, err) << "unicode error: " << u_errorName(err); // This loads the tzdata. In Fuchsia, we force the data from this package // to be version 2019a, so that we can test the resource load. bool success = Runner::SetupICUInternal(); ASSERT_TRUE(success) << "failed to load timezone data"; const auto version_after = std::string(icu::TimeZone::getTZDataVersion(err)); ASSERT_EQ(U_ZERO_ERROR, err) << "unicode error: " << u_errorName(err); EXPECT_EQ("2019a", version_after); } } // namespace flutter_runner
engine/shell/platform/fuchsia/flutter/runner_tzdata_unittest.cc/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/runner_tzdata_unittest.cc", "repo_id": "engine", "token_count": 417 }
349
// 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_TESTS_FAKES_MOUSE_SOURCE_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOUSE_SOURCE_H_ #include <fuchsia/ui/pointer/cpp/fidl.h> #include "flutter/fml/logging.h" namespace flutter_runner::testing { // A test stub to act as the protocol server. A test can control what is sent // back by this server implementation, via the ScheduleCallback call. class FakeMouseSource : public fuchsia::ui::pointer::MouseSource { public: // |fuchsia.ui.pointer.MouseSource| void Watch(MouseSource::WatchCallback callback) override { callback_ = std::move(callback); } // Have the server issue events to the client's hanging-get Watch call. void ScheduleCallback(std::vector<fuchsia::ui::pointer::MouseEvent> events) { FML_CHECK(callback_) << "require a valid WatchCallback"; callback_(std::move(events)); } private: // Client-side logic to invoke on Watch() call's return. A test triggers it // with ScheduleCallback(). MouseSource::WatchCallback callback_; }; } // namespace flutter_runner::testing #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_MOUSE_SOURCE_H_
engine/shell/platform/fuchsia/flutter/tests/fakes/mouse_source.h/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/mouse_source.h", "repo_id": "engine", "token_count": 441 }
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. assert(is_fuchsia) import("//flutter/tools/fuchsia/fuchsia_archive.gni") import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni") import("//flutter/tools/fuchsia/gn-sdk/src/package.gni") group("tests") { testonly = true deps = [ ":text-input-test" ] } executable("text-input-test-bin") { testonly = true output_name = "text-input-test" sources = [ "text-input-test.cc" ] # This is needed for //flutter/third_party/googletest for linking zircon # symbols. libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ] deps = [ "${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics", "${fuchsia_sdk}/fidl/fuchsia.component", "${fuchsia_sdk}/fidl/fuchsia.feedback", "${fuchsia_sdk}/fidl/fuchsia.intl", "${fuchsia_sdk}/fidl/fuchsia.kernel", "${fuchsia_sdk}/fidl/fuchsia.logger", "${fuchsia_sdk}/fidl/fuchsia.tracing.provider", "${fuchsia_sdk}/fidl/fuchsia.ui.app", "${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton", "${fuchsia_sdk}/fidl/fuchsia.ui.input", "${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector", "${fuchsia_sdk}/fidl/fuchsia.ui.test.input", "${fuchsia_sdk}/fidl/fuchsia.ui.test.scene", "${fuchsia_sdk}/pkg/async", "${fuchsia_sdk}/pkg/async-loop-testing", "${fuchsia_sdk}/pkg/fidl_cpp", "${fuchsia_sdk}/pkg/sys_component_cpp_testing", "${fuchsia_sdk}/pkg/zx", "text-input-view:package", "//flutter/fml", "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:check_view", "//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:portable_ui_test", "//flutter/third_party/googletest:gtest", "//flutter/third_party/googletest:gtest_main", ] } fuchsia_test_archive("text-input-test") { deps = [ ":text-input-test-bin", # "OOT" copies of the runners used by tests, to avoid conflicting with the # runners in the base fuchsia image. # TODO(fxbug.dev/106575): Fix this with subpackages. "//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner", ] binary = "$target_name" cml_file = rebase_path("meta/$target_name.cml") }
engine/shell/platform/fuchsia/flutter/tests/integration/text-input/BUILD.gn/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/text-input/BUILD.gn", "repo_id": "engine", "token_count": 1019 }
351
// Copyright 2020 The Fuchsia 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:typed_data'; import 'dart:ui'; import 'dart:zircon'; void main() { print('Launching touch-input-view'); TestApp app = TestApp(); app.run(); } class TestApp { static const _yellow = Color.fromARGB(255, 255, 255, 0); static const _pink = Color.fromARGB(255, 255, 0, 255); Color _backgroundColor = _pink; void run() { // 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 & size * pixelRatio; 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, pixelRatio); // Draw something final paint = Paint()..color = this._backgroundColor; canvas.drawRect(windowBounds, paint); // Build the scene final picture = recorder.endRecording(); final sceneBuilder = SceneBuilder() ..pushClipRect(physicalBounds) ..addPicture(Offset.zero, picture) ..pop(); window.render(sceneBuilder.build()); } void pointerDataPacket(PointerDataPacket packet) async { int nowNanos = System.clockGetMonotonic(); for (PointerData data in packet.data) { print('touch-input-view received tap: ${data.toStringFull()}'); if (data.change == PointerChange.down) { this._backgroundColor = _yellow; } 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('touch-input-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': 'touch-input-view', })).buffer.asByteData(); PlatformDispatcher.instance.sendPlatformMessage('fuchsia/input_test', message, null); } }
engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/lib/touch-input-view.dart/0
{ "file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/lib/touch-input-view.dart", "repo_id": "engine", "token_count": 1050 }
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. #ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_ROOT_INSPECT_NODE_H_ #define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_ROOT_INSPECT_NODE_H_ #include <lib/inspect/component/cpp/component.h> #include <lib/sys/cpp/component_context.h> #include <memory> #include <mutex> namespace dart_utils { // This singleton object offers a way to create a new inspect node under the // root node in a thread safe way. // // Usage notes: // RootInspectNode::Initialize() must be invoked once in the program's // main before trying to obtain a child node. class RootInspectNode { private: RootInspectNode() = default; ~RootInspectNode() = default; public: // Initializes the underlying component inspector. Must be invoked at least // once before calling CreateRootChild(). static void Initialize(sys::ComponentContext* context); // Creates an inspect node which is a child of the component's root inspect // node with the provided |name|. static inspect::Node CreateRootChild(const std::string& name); // Gets an instance to the component's inspector. static inspect::Inspector* GetInspector(); private: static std::unique_ptr<inspect::ComponentInspector> inspector_; static std::mutex mutex_; }; } // namespace dart_utils #endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_ROOT_INSPECT_NODE_H_
engine/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.h/0
{ "file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/root_inspect_node.h", "repo_id": "engine", "token_count": 482 }
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. #ifndef FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ #define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_ #include <flutter_glfw.h> #include <chrono> #include <memory> #include <string> #include <vector> #include "plugin_registrar.h" #include "plugin_registry.h" namespace flutter { // An engine for running a headless Flutter application. class FlutterEngine : public PluginRegistry { public: explicit FlutterEngine(); virtual ~FlutterEngine(); // Prevent copying. FlutterEngine(FlutterEngine const&) = delete; FlutterEngine& operator=(FlutterEngine const&) = delete; // Starts running the engine with the given parameters, returning true if // successful. bool Start(const std::string& icu_data_path, const std::string& assets_path, const std::vector<std::string>& arguments, const std::string& aot_library_path = ""); // Terminates the running engine. void ShutDown(); // Processes the next event for the engine, or returns early if |timeout| is // reached before the next event. void RunEventLoopWithTimeout( std::chrono::milliseconds timeout = std::chrono::milliseconds::max()); // flutter::PluginRegistry: FlutterDesktopPluginRegistrarRef GetRegistrarForPlugin( const std::string& plugin_name) override; private: using UniqueEnginePtr = std::unique_ptr<FlutterDesktopEngineState, bool (*)(FlutterDesktopEngineState*)>; // Handle for interacting with the C API's engine reference. UniqueEnginePtr engine_ = UniqueEnginePtr(nullptr, FlutterDesktopShutDownEngine); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_ENGINE_H_
engine/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h/0
{ "file_path": "engine/shell/platform/glfw/client_wrapper/include/flutter/flutter_engine.h", "repo_id": "engine", "token_count": 687 }
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. #ifndef FLUTTER_SHELL_PLATFORM_GLFW_KEY_EVENT_HANDLER_H_ #define FLUTTER_SHELL_PLATFORM_GLFW_KEY_EVENT_HANDLER_H_ #include <memory> #include "flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" #include "flutter/shell/platform/glfw/keyboard_hook_handler.h" #include "flutter/shell/platform/glfw/public/flutter_glfw.h" #include "rapidjson/document.h" namespace flutter { // Implements a KeyboardHookHandler // // Handles key events and forwards them to the Flutter engine. class KeyEventHandler : public KeyboardHookHandler { public: explicit KeyEventHandler(flutter::BinaryMessenger* messenger); virtual ~KeyEventHandler(); // |KeyboardHookHandler| void KeyboardHook(GLFWwindow* window, int key, int scancode, int action, int mods) override; // |KeyboardHookHandler| void CharHook(GLFWwindow* window, unsigned int code_point) override; private: // The Flutter system channel for key event messages. std::unique_ptr<flutter::BasicMessageChannel<rapidjson::Document>> channel_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_GLFW_KEY_EVENT_HANDLER_H_
engine/shell/platform/glfw/key_event_handler.h/0
{ "file_path": "engine/shell/platform/glfw/key_event_handler.h", "repo_id": "engine", "token_count": 535 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_ACCESSIBLE_TEXT_FIELD_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_ACCESSIBLE_TEXT_FIELD_H_ #include <gtk/gtk.h> #include "flutter/shell/platform/linux/fl_accessible_node.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlAccessibleTextField, fl_accessible_text_field, FL, ACCESSIBLE_TEXT_FIELD, FlAccessibleNode); /** * fl_accessible_text_field_new: * @engine: the #FlEngine this node came from. * @id: the semantics node ID this object represents. * * Creates a new accessibility object that exposes an editable Flutter text * field to ATK. * * Returns: a new #FlAccessibleNode. */ FlAccessibleNode* fl_accessible_text_field_new(FlEngine* engine, int32_t id); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_ACCESSIBLE_TEXT_FIELD_H_
engine/shell/platform/linux/fl_accessible_text_field.h/0
{ "file_path": "engine/shell/platform/linux/fl_accessible_text_field.h", "repo_id": "engine", "token_count": 421 }
356
// 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 "flutter/shell/platform/common/app_lifecycle_state.h" #include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h" #include "flutter/shell/platform/linux/fl_engine_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_string_codec.h" #include "flutter/shell/platform/linux/testing/fl_test.h" // MOCK_ENGINE_PROC is leaky by design // NOLINTBEGIN(clang-analyzer-core.StackAddressEscape) // Checks sending window metrics events works. TEST(FlEngineTest, WindowMetrics) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->SendWindowMetricsEvent = MOCK_ENGINE_PROC( SendWindowMetricsEvent, ([&called](auto engine, const FlutterWindowMetricsEvent* event) { called = true; EXPECT_EQ(event->width, static_cast<size_t>(3840)); EXPECT_EQ(event->height, static_cast<size_t>(2160)); EXPECT_EQ(event->pixel_ratio, 2.0); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); fl_engine_send_window_metrics_event(engine, 3840, 2160, 2.0); EXPECT_TRUE(called); } // Checks sending mouse pointer events works. TEST(FlEngineTest, MousePointer) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->SendPointerEvent = MOCK_ENGINE_PROC( SendPointerEvent, ([&called](auto engine, const FlutterPointerEvent* events, size_t events_count) { called = true; EXPECT_EQ(events_count, static_cast<size_t>(1)); EXPECT_EQ(events[0].phase, kDown); EXPECT_EQ(events[0].timestamp, static_cast<size_t>(1234567890)); EXPECT_EQ(events[0].x, 800); EXPECT_EQ(events[0].y, 600); EXPECT_EQ(events[0].device, static_cast<int32_t>(0)); EXPECT_EQ(events[0].signal_kind, kFlutterPointerSignalKindScroll); EXPECT_EQ(events[0].scroll_delta_x, 1.2); EXPECT_EQ(events[0].scroll_delta_y, -3.4); EXPECT_EQ(events[0].device_kind, kFlutterPointerDeviceKindMouse); EXPECT_EQ(events[0].buttons, kFlutterPointerButtonMouseSecondary); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); fl_engine_send_mouse_pointer_event(engine, kDown, 1234567890, 800, 600, 1.2, -3.4, kFlutterPointerButtonMouseSecondary); EXPECT_TRUE(called); } // Checks sending pan/zoom events works. TEST(FlEngineTest, PointerPanZoom) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->SendPointerEvent = MOCK_ENGINE_PROC( SendPointerEvent, ([&called](auto engine, const FlutterPointerEvent* events, size_t events_count) { called = true; EXPECT_EQ(events_count, static_cast<size_t>(1)); EXPECT_EQ(events[0].phase, kPanZoomUpdate); EXPECT_EQ(events[0].timestamp, static_cast<size_t>(1234567890)); EXPECT_EQ(events[0].x, 800); EXPECT_EQ(events[0].y, 600); EXPECT_EQ(events[0].device, static_cast<int32_t>(1)); EXPECT_EQ(events[0].signal_kind, kFlutterPointerSignalKindNone); EXPECT_EQ(events[0].pan_x, 1.5); EXPECT_EQ(events[0].pan_y, 2.5); EXPECT_EQ(events[0].scale, 3.5); EXPECT_EQ(events[0].rotation, 4.5); EXPECT_EQ(events[0].device_kind, kFlutterPointerDeviceKindTrackpad); EXPECT_EQ(events[0].buttons, 0); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); fl_engine_send_pointer_pan_zoom_event(engine, 1234567890, 800, 600, kPanZoomUpdate, 1.5, 2.5, 3.5, 4.5); EXPECT_TRUE(called); } // Checks dispatching a semantics action works. TEST(FlEngineTest, DispatchSemanticsAction) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->DispatchSemanticsAction = MOCK_ENGINE_PROC( DispatchSemanticsAction, ([&called](auto engine, uint64_t id, FlutterSemanticsAction action, const uint8_t* data, size_t data_length) { EXPECT_EQ(id, static_cast<uint64_t>(42)); EXPECT_EQ(action, kFlutterSemanticsActionTap); EXPECT_EQ(data_length, static_cast<size_t>(4)); EXPECT_EQ(data[0], 't'); EXPECT_EQ(data[1], 'e'); EXPECT_EQ(data[2], 's'); EXPECT_EQ(data[3], 't'); called = true; return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); g_autoptr(GBytes) data = g_bytes_new_static("test", 4); fl_engine_dispatch_semantics_action(engine, 42, kFlutterSemanticsActionTap, data); EXPECT_TRUE(called); } // Checks sending platform messages works. TEST(FlEngineTest, PlatformMessage) { 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) { if (strcmp(message->channel, "test") != 0) { return old_handler(engine, message); } called = true; EXPECT_EQ(message->message_size, static_cast<size_t>(4)); EXPECT_EQ(message->message[0], 't'); EXPECT_EQ(message->message[1], 'e'); EXPECT_EQ(message->message[2], 's'); EXPECT_EQ(message->message[3], 't'); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); g_autoptr(GBytes) message = g_bytes_new_static("test", 4); fl_engine_send_platform_message(engine, "test", message, nullptr, nullptr, nullptr); EXPECT_TRUE(called); } // Checks sending platform message responses works. TEST(FlEngineTest, PlatformMessageResponse) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->SendPlatformMessageResponse = MOCK_ENGINE_PROC( SendPlatformMessageResponse, ([&called](auto engine, const FlutterPlatformMessageResponseHandle* handle, const uint8_t* data, size_t data_length) { called = true; EXPECT_EQ( handle, reinterpret_cast<const FlutterPlatformMessageResponseHandle*>(42)); EXPECT_EQ(data_length, static_cast<size_t>(4)); EXPECT_EQ(data[0], 't'); EXPECT_EQ(data[1], 'e'); EXPECT_EQ(data[2], 's'); EXPECT_EQ(data[3], 't'); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); g_autoptr(GBytes) response = g_bytes_new_static("test", 4); EXPECT_TRUE(fl_engine_send_platform_message_response( engine, reinterpret_cast<const FlutterPlatformMessageResponseHandle*>(42), response, &error)); EXPECT_EQ(error, nullptr); EXPECT_TRUE(called); } // Checks settings plugin sends settings on startup. TEST(FlEngineTest, SettingsPlugin) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC( SendPlatformMessage, ([&called](auto engine, const FlutterPlatformMessage* message) { called = true; EXPECT_STREQ(message->channel, "flutter/settings"); g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new(); g_autoptr(GBytes) data = g_bytes_new(message->message, message->message_size); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) settings = fl_message_codec_decode_message( FL_MESSAGE_CODEC(codec), data, &error); EXPECT_NE(settings, nullptr); EXPECT_EQ(error, nullptr); FlValue* text_scale_factor = fl_value_lookup_string(settings, "textScaleFactor"); EXPECT_NE(text_scale_factor, nullptr); EXPECT_EQ(fl_value_get_type(text_scale_factor), FL_VALUE_TYPE_FLOAT); FlValue* always_use_24hr_format = fl_value_lookup_string(settings, "alwaysUse24HourFormat"); EXPECT_NE(always_use_24hr_format, nullptr); EXPECT_EQ(fl_value_get_type(always_use_24hr_format), FL_VALUE_TYPE_BOOL); FlValue* platform_brightness = fl_value_lookup_string(settings, "platformBrightness"); EXPECT_NE(platform_brightness, nullptr); EXPECT_EQ(fl_value_get_type(platform_brightness), FL_VALUE_TYPE_STRING); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); EXPECT_TRUE(called); } void on_pre_engine_restart_cb(FlEngine* engine, gpointer user_data) { int* count = reinterpret_cast<int*>(user_data); *count += 1; } void on_pre_engine_restart_destroy_notify(gpointer user_data) { int* count = reinterpret_cast<int*>(user_data); *count += 10; } // Checks restarting the engine invokes the correct callback. TEST(FlEngineTest, OnPreEngineRestart) { FlEngine* engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); OnPreEngineRestartCallback callback; void* callback_user_data; bool called = false; embedder_api->Initialize = MOCK_ENGINE_PROC( Initialize, ([&callback, &callback_user_data, &called]( size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { called = true; callback = args->on_pre_engine_restart_callback; callback_user_data = user_data; return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); EXPECT_TRUE(called); EXPECT_NE(callback, nullptr); // The following call has no effect but should not crash. callback(callback_user_data); int count = 0; // Set handler so that: // // * When the engine restarts, count += 1; // * When the engine is freed, count += 10. fl_engine_set_on_pre_engine_restart_handler( engine, on_pre_engine_restart_cb, &count, on_pre_engine_restart_destroy_notify); callback(callback_user_data); EXPECT_EQ(count, 1); // Disposal should call the destroy notify. g_object_unref(engine); EXPECT_EQ(count, 11); } TEST(FlEngineTest, DartEntrypointArgs) { g_autoptr(FlDartProject) project = fl_dart_project_new(); GPtrArray* args_array = g_ptr_array_new(); g_ptr_array_add(args_array, const_cast<char*>("arg_one")); g_ptr_array_add(args_array, const_cast<char*>("arg_two")); g_ptr_array_add(args_array, const_cast<char*>("arg_three")); g_ptr_array_add(args_array, nullptr); gchar** args = reinterpret_cast<gchar**>(g_ptr_array_free(args_array, false)); fl_dart_project_set_dart_entrypoint_arguments(project, args); g_autoptr(FlEngine) engine = make_mock_engine_with_project(project); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->Initialize = MOCK_ENGINE_PROC( Initialize, ([&called, &set_args = args]( size_t version, const FlutterRendererConfig* config, const FlutterProjectArgs* args, void* user_data, FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) { called = true; EXPECT_NE(set_args, args->dart_entrypoint_argv); EXPECT_EQ(args->dart_entrypoint_argc, 3); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); EXPECT_TRUE(called); } TEST(FlEngineTest, Locales) { gchar* initial_language = g_strdup(g_getenv("LANGUAGE")); g_setenv("LANGUAGE", "de:en_US", TRUE); g_autoptr(FlDartProject) project = fl_dart_project_new(); g_autoptr(FlEngine) engine = make_mock_engine_with_project(project); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; embedder_api->UpdateLocales = MOCK_ENGINE_PROC( UpdateLocales, ([&called](auto engine, const FlutterLocale** locales, size_t locales_count) { called = true; EXPECT_EQ(locales_count, static_cast<size_t>(4)); EXPECT_STREQ(locales[0]->language_code, "de"); EXPECT_STREQ(locales[0]->country_code, nullptr); EXPECT_STREQ(locales[0]->script_code, nullptr); EXPECT_STREQ(locales[0]->variant_code, nullptr); EXPECT_STREQ(locales[1]->language_code, "en"); EXPECT_STREQ(locales[1]->country_code, "US"); EXPECT_STREQ(locales[1]->script_code, nullptr); EXPECT_STREQ(locales[1]->variant_code, nullptr); EXPECT_STREQ(locales[2]->language_code, "en"); EXPECT_STREQ(locales[2]->country_code, nullptr); EXPECT_STREQ(locales[2]->script_code, nullptr); EXPECT_STREQ(locales[2]->variant_code, nullptr); EXPECT_STREQ(locales[3]->language_code, "C"); EXPECT_STREQ(locales[3]->country_code, nullptr); EXPECT_STREQ(locales[3]->script_code, nullptr); EXPECT_STREQ(locales[3]->variant_code, nullptr); return kSuccess; })); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_engine_start(engine, &error)); EXPECT_EQ(error, nullptr); EXPECT_TRUE(called); if (initial_language) { g_setenv("LANGUAGE", initial_language, TRUE); } else { g_unsetenv("LANGUAGE"); } g_free(initial_language); } TEST(FlEngineTest, SwitchesEmpty) { g_autoptr(FlEngine) engine = make_mock_engine(); // Clear the main environment variable, since test order is not guaranteed. unsetenv("FLUTTER_ENGINE_SWITCHES"); g_autoptr(GPtrArray) switches = fl_engine_get_switches(engine); EXPECT_EQ(switches->len, 0U); } TEST(FlEngineTest, SendWindowStateEvent) { g_autoptr(FlEngine) engine = make_mock_engine(); FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine); bool called = false; std::string state; embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC( SendPlatformMessage, ([&called, &state](auto engine, const FlutterPlatformMessage* message) { EXPECT_STREQ(message->channel, "flutter/lifecycle"); called = true; g_autoptr(FlStringCodec) codec = fl_string_codec_new(); g_autoptr(GBytes) data = g_bytes_new(message->message, message->message_size); g_autoptr(GError) error = nullptr; g_autoptr(FlValue) parsed_state = fl_message_codec_decode_message( FL_MESSAGE_CODEC(codec), data, &error); state = fl_value_get_string(parsed_state); return kSuccess; })); fl_engine_send_window_state_event(engine, false, false); EXPECT_STREQ(state.c_str(), flutter::AppLifecycleStateToString( flutter::AppLifecycleState::kHidden)); fl_engine_send_window_state_event(engine, false, true); EXPECT_STREQ(state.c_str(), flutter::AppLifecycleStateToString( flutter::AppLifecycleState::kHidden)); fl_engine_send_window_state_event(engine, true, false); EXPECT_STREQ(state.c_str(), flutter::AppLifecycleStateToString( flutter::AppLifecycleState::kInactive)); fl_engine_send_window_state_event(engine, true, true); EXPECT_STREQ(state.c_str(), flutter::AppLifecycleStateToString( flutter::AppLifecycleState::kResumed)); EXPECT_TRUE(called); } #ifndef FLUTTER_RELEASE TEST(FlEngineTest, Switches) { g_autoptr(FlEngine) engine = make_mock_engine(); setenv("FLUTTER_ENGINE_SWITCHES", "2", 1); setenv("FLUTTER_ENGINE_SWITCH_1", "abc", 1); setenv("FLUTTER_ENGINE_SWITCH_2", "foo=\"bar, baz\"", 1); g_autoptr(GPtrArray) switches = fl_engine_get_switches(engine); EXPECT_EQ(switches->len, 2U); EXPECT_STREQ(static_cast<const char*>(g_ptr_array_index(switches, 0)), "--abc"); EXPECT_STREQ(static_cast<const char*>(g_ptr_array_index(switches, 1)), "--foo=\"bar, baz\""); unsetenv("FLUTTER_ENGINE_SWITCHES"); unsetenv("FLUTTER_ENGINE_SWITCH_1"); unsetenv("FLUTTER_ENGINE_SWITCH_2"); } #endif // !FLUTTER_RELEASE // NOLINTEND(clang-analyzer-core.StackAddressEscape)
engine/shell/platform/linux/fl_engine_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_engine_test.cc", "repo_id": "engine", "token_count": 7704 }
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 "flutter/shell/platform/linux/fl_key_embedder_responder.h" #include "gtest/gtest.h" #include "flutter/shell/platform/embedder/test_utils/key_codes.g.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/testing/fl_test.h" namespace { constexpr gboolean kRelease = FALSE; constexpr gboolean kPress = TRUE; constexpr gboolean kIsModifier = TRUE; constexpr gboolean kIsNotModifier = FALSE; constexpr guint16 kKeyCodeDigit1 = 0x0au; constexpr guint16 kKeyCodeKeyA = 0x26u; constexpr guint16 kKeyCodeShiftLeft = 0x32u; constexpr guint16 kKeyCodeShiftRight = 0x3Eu; constexpr guint16 kKeyCodeAltLeft = 0x40u; constexpr guint16 kKeyCodeAltRight = 0x6Cu; constexpr guint16 kKeyCodeNumpad1 = 0x57u; constexpr guint16 kKeyCodeNumLock = 0x4Du; constexpr guint16 kKeyCodeCapsLock = 0x42u; constexpr guint16 kKeyCodeControlLeft = 0x25u; constexpr guint16 kKeyCodeControlRight = 0x69u; using namespace ::flutter::testing::keycodes; } // namespace static void g_ptr_array_clear(GPtrArray* array) { g_ptr_array_remove_range(array, 0, array->len); } G_DECLARE_FINAL_TYPE(FlKeyEmbedderCallRecord, fl_key_embedder_call_record, FL, KEY_EMBEDDER_CALL_RECORD, GObject); struct _FlKeyEmbedderCallRecord { GObject parent_instance; FlutterKeyEvent* event; FlutterKeyEventCallback callback; gpointer user_data; }; G_DEFINE_TYPE(FlKeyEmbedderCallRecord, fl_key_embedder_call_record, G_TYPE_OBJECT) static void fl_key_embedder_call_record_init(FlKeyEmbedderCallRecord* self) {} // Dispose method for FlKeyEmbedderCallRecord. static void fl_key_embedder_call_record_dispose(GObject* object) { g_return_if_fail(FL_IS_KEY_EMBEDDER_CALL_RECORD(object)); FlKeyEmbedderCallRecord* self = FL_KEY_EMBEDDER_CALL_RECORD(object); if (self->event != nullptr) { g_free(const_cast<char*>(self->event->character)); g_free(self->event); } G_OBJECT_CLASS(fl_key_embedder_call_record_parent_class)->dispose(object); } // Class Initialization method for FlKeyEmbedderCallRecord class. static void fl_key_embedder_call_record_class_init( FlKeyEmbedderCallRecordClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_key_embedder_call_record_dispose; } static FlKeyEmbedderCallRecord* fl_key_embedder_call_record_new( const FlutterKeyEvent* event, FlutterKeyEventCallback callback, gpointer user_data) { g_return_val_if_fail(event != nullptr, nullptr); FlKeyEmbedderCallRecord* self = FL_KEY_EMBEDDER_CALL_RECORD( g_object_new(fl_key_embedder_call_record_get_type(), nullptr)); FlutterKeyEvent* clone_event = g_new(FlutterKeyEvent, 1); *clone_event = *event; if (event->character != nullptr) { size_t character_length = strlen(event->character); char* clone_character = g_new(char, character_length + 1); strncpy(clone_character, event->character, character_length + 1); clone_event->character = clone_character; } self->event = clone_event; self->callback = callback; self->user_data = user_data; return self; } namespace { // A global variable to store new event. It is a global variable so that it can // be returned by #fl_key_event_new_by_mock for easy use. FlKeyEvent _g_key_event; } // namespace // Create a new #FlKeyEvent with the given information. // // This event is passed to #fl_key_responder_handle_event, // which assumes that the event is managed by callee. // Therefore #fl_key_event_new_by_mock doesn't need to // dynamically allocate, but reuses the same global object. static FlKeyEvent* fl_key_event_new_by_mock(guint32 time_in_milliseconds, bool is_press, guint keyval, guint16 keycode, GdkModifierType state, gboolean is_modifier) { _g_key_event.is_press = is_press; _g_key_event.time = time_in_milliseconds; _g_key_event.state = state; _g_key_event.keyval = keyval; _g_key_event.keycode = keycode; _g_key_event.origin = nullptr; return &_g_key_event; } static gboolean g_expected_handled; static gpointer g_expected_user_data; static void verify_response_handled(bool handled, gpointer user_data) { EXPECT_EQ(handled, g_expected_handled); } static void invoke_record_callback_and_verify(FlKeyEmbedderCallRecord* record, bool expected_handled, void* expected_user_data) { g_return_if_fail(record->callback != nullptr); g_expected_handled = expected_handled; g_expected_user_data = expected_user_data; record->callback(expected_handled, record->user_data); } namespace { GPtrArray* g_call_records; } static void record_calls(const FlutterKeyEvent* event, FlutterKeyEventCallback callback, void* callback_user_data, void* send_key_event_user_data) { GPtrArray* records_array = reinterpret_cast<GPtrArray*>(send_key_event_user_data); if (records_array != nullptr) { g_ptr_array_add(records_array, fl_key_embedder_call_record_new( event, callback, callback_user_data)); } } static void clear_g_call_records() { g_ptr_array_free(g_call_records, TRUE); g_call_records = nullptr; } // Basic key presses TEST(FlKeyEmbedderResponderTest, SendKeyEvent) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // On a QWERTY keyboard, press key Q (physically key A), and release. // Key down fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12345, kPress, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->struct_size, sizeof(FlutterKeyEvent)); EXPECT_EQ(record->event->timestamp, 12345000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "a"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Key up fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12346, kRelease, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->struct_size, sizeof(FlutterKeyEvent)); EXPECT_EQ(record->event->timestamp, 12346000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, FALSE, &user_data); g_ptr_array_clear(g_call_records); // On an AZERTY keyboard, press key Q (physically key A), and release. // Key down fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12347, kPress, GDK_KEY_q, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->struct_size, sizeof(FlutterKeyEvent)); EXPECT_EQ(record->event->timestamp, 12347000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyQ); EXPECT_STREQ(record->event->character, "q"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Key up fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12348, kRelease, GDK_KEY_q, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->struct_size, sizeof(FlutterKeyEvent)); EXPECT_EQ(record->event->timestamp, 12348000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyQ); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, FALSE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Basic key presses, but uses the specified logical key if it is not 0. TEST(FlKeyEmbedderResponderTest, UsesSpecifiedLogicalKey) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // On an AZERTY keyboard, press physical key 1, and release. // Key down fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(12345, kPress, GDK_KEY_ampersand, kKeyCodeDigit1, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data, kLogicalDigit1); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->struct_size, sizeof(FlutterKeyEvent)); EXPECT_EQ(record->event->timestamp, 12345000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalDigit1); EXPECT_EQ(record->event->logical, kLogicalDigit1); EXPECT_STREQ(record->event->character, "&"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Press Shift, key A, then release Shift, key A. TEST(FlKeyEmbedderResponderTest, PressShiftDuringLetterKeyTap) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Press shift right fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_Shift_R, kKeyCodeShiftRight, static_cast<GdkModifierType>(0), kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalShiftRight); EXPECT_EQ(record->event->logical, kLogicalShiftRight); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press key A fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_A, kKeyCodeKeyA, GDK_SHIFT_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "A"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release shift right fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Shift_R, kKeyCodeShiftRight, GDK_SHIFT_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalShiftRight); EXPECT_EQ(record->event->logical, kLogicalShiftRight); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release key A fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_A, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Press or release Numpad 1 between presses/releases of NumLock. // // This tests interaction between lock keys and non-lock keys in cases that do // not have events missed. // // This also tests the result of Numpad keys across NumLock taps, which is // test-worthy because the keyval for the numpad key will change before and // after the NumLock tap, which should not alter the resulting logical key. TEST(FlKeyEmbedderResponderTest, TapNumPadKeysBetweenNumLockEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Press Numpad 1 (stage 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_KP_End, kKeyCodeNumpad1, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumpad1); EXPECT_EQ(record->event->logical, kLogicalNumpad1); EXPECT_STREQ(record->event->character, nullptr); // TODO(chrome-bot): EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press NumLock (stage 0 -> 1) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_Num_Lock, kKeyCodeNumLock, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release numpad 1 (stage 1) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_KP_1, kKeyCodeNumpad1, GDK_MOD2_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumpad1); EXPECT_EQ(record->event->logical, kLogicalNumpad1); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release NumLock (stage 1 -> 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Num_Lock, kKeyCodeNumLock, GDK_MOD2_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press Numpad 1 (stage 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_KP_End, kKeyCodeNumpad1, GDK_MOD2_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumpad1); EXPECT_EQ(record->event->logical, kLogicalNumpad1); EXPECT_STREQ(record->event->character, nullptr); // TODO(chrome-bot): EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press NumLock (stage 2 -> 3) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_Num_Lock, kKeyCodeNumLock, GDK_MOD2_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release numpad 1 (stage 3) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_KP_1, kKeyCodeNumpad1, GDK_MOD2_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumpad1); EXPECT_EQ(record->event->logical, kLogicalNumpad1); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release NumLock (stage 3 -> 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Num_Lock, kKeyCodeNumLock, GDK_MOD2_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Press or release digit 1 between presses/releases of Shift. // // GTK will change the virtual key during a key tap, and the embedder // should regularize it. TEST(FlKeyEmbedderResponderTest, ReleaseShiftKeyBetweenDigitKeyEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; GdkModifierType state = static_cast<GdkModifierType>(0); // Press shift left fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_Shift_L, kKeyCodeShiftLeft, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalShiftLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); state = GDK_SHIFT_MASK; // Press digit 1, which is '!' on a US keyboard fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_exclam, kKeyCodeDigit1, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalDigit1); EXPECT_EQ(record->event->logical, kLogicalExclamation); EXPECT_STREQ(record->event->character, "!"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release shift fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Shift_L, kKeyCodeShiftLeft, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalShiftLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); state = static_cast<GdkModifierType>(0); // Release digit 1, which is "1" because shift has been released. fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_1, kKeyCodeDigit1, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalDigit1); EXPECT_EQ(record->event->logical, kLogicalExclamation); // Important EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Press or release letter key between presses/releases of CapsLock. // // This tests interaction between lock keys and non-lock keys in cases that do // not have events missed. TEST(FlKeyEmbedderResponderTest, TapLetterKeysBetweenCapsLockEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Press CapsLock (stage 0 -> 1) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, static_cast<GdkModifierType>(0), kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press key A (stage 1) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_A, kKeyCodeKeyA, GDK_LOCK_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "A"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release CapsLock (stage 1 -> 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, GDK_LOCK_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release key A (stage 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_A, kKeyCodeKeyA, GDK_LOCK_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press CapsLock (stage 2 -> 3) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(105, kPress, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, GDK_LOCK_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press key A (stage 3) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(106, kPress, GDK_KEY_A, kKeyCodeKeyA, GDK_LOCK_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "A"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release CapsLock (stage 3 -> 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(107, kRelease, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, GDK_LOCK_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release key A (stage 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(108, kRelease, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Press or release letter key between presses/releases of CapsLock, on // a platform with reversed logic. // // This happens when using a Chrome remote desktop on MacOS. TEST(FlKeyEmbedderResponderTest, TapLetterKeysBetweenCapsLockEventsReversed) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Press key A (stage 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "a"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press CapsLock (stage 0 -> 1) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, GDK_LOCK_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release CapsLock (stage 1 -> 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, GDK_LOCK_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release key A (stage 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_A, kKeyCodeKeyA, GDK_LOCK_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press key A (stage 2) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(105, kPress, GDK_KEY_A, kKeyCodeKeyA, GDK_LOCK_MASK, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "A"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Press CapsLock (stage 2 -> 3) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(106, kPress, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, static_cast<GdkModifierType>(0), kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release CapsLock (stage 3 -> 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(107, kRelease, GDK_KEY_Caps_Lock, kKeyCodeCapsLock, GDK_LOCK_MASK, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalCapsLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release key A (stage 0) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(108, kRelease, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } TEST(FlKeyEmbedderResponderTest, TurnDuplicateDownEventsToRepeats) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Press KeyA fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Another KeyA down events, which usually means a repeated event. g_expected_handled = false; fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_a, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeRepeat); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "a"); EXPECT_EQ(record->event->synthesized, false); EXPECT_NE(record->callback, nullptr); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release KeyA fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_q, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } TEST(FlKeyEmbedderResponderTest, IgnoreAbruptUpEvent) { FlKeyEmbedderCallRecord* record; EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data // Release KeyA before it was even pressed. g_expected_handled = true; // The empty event is always handled. fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_q, kKeyCodeKeyA, static_cast<GdkModifierType>(0), kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->physical, 0ull); EXPECT_EQ(record->event->logical, 0ull); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); EXPECT_EQ(record->callback, nullptr); clear_g_call_records(); g_object_unref(responder); } // Test if missed modifier keys can be detected and synthesized with state // information upon events that are for this modifier key. TEST(FlKeyEmbedderResponderTest, SynthesizeForDesyncPressingStateOnSelfEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Test 1: synthesize key down. // A key down of control left is missed. GdkModifierType state = GDK_CONTROL_MASK; // Send a ControlLeft up fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kRelease, GDK_KEY_Control_L, kKeyCodeControlLeft, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Test 2: synthesize key up. // Send a ControlLeft down. state = static_cast<GdkModifierType>(0); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_Control_L, kKeyCodeControlLeft, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // A key up of control left is missed. state = static_cast<GdkModifierType>(0); // Send another ControlLeft down fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kPress, GDK_KEY_Control_L, kKeyCodeControlLeft, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 103000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 103000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Send a ControlLeft up to clear up state. state = GDK_CONTROL_MASK; fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(104, kRelease, GDK_KEY_Control_L, kKeyCodeControlLeft, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Test 3: synthesize by right modifier. // A key down of control right is missed. state = GDK_CONTROL_MASK; // Send a ControlRight up. fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(105, kRelease, GDK_KEY_Control_R, kKeyCodeControlRight, state, kIsModifier), verify_response_handled, &user_data); // A ControlLeft down is synthesized, with an empty event. // Reason: The ControlLeft down is synthesized to synchronize the state // showing Control as pressed. The ControlRight event is ignored because // the event is considered a duplicate up event. EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 105000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Test if missed modifier keys can be detected and synthesized with state // information upon events that are not for this modifier key. TEST(FlKeyEmbedderResponderTest, SynthesizeForDesyncPressingStateOnNonSelfEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // A key down of control left is missed. GdkModifierType state = GDK_CONTROL_MASK; // Send a normal event (KeyA down) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_a, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "a"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // A key up of control left is missed. state = static_cast<GdkModifierType>(0); // Send a normal event (KeyA up) fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kRelease, GDK_KEY_A, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Test non-default key mapping. // Press a key with physical CapsLock and logical ControlLeft. state = static_cast<GdkModifierType>(0); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_Control_L, kKeyCodeCapsLock, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // The key up of the control left press is missed. state = static_cast<GdkModifierType>(0); // Send a normal event (KeyA down). fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_A, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); // The synthesized event should have physical CapsLock and logical // ControlLeft. EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "A"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Test if missed modifier keys can be detected and synthesized with state // information upon events that do not have the standard key mapping. TEST(FlKeyEmbedderResponderTest, SynthesizeForDesyncPressingStateOnRemappedEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // Press a key with physical CapsLock and logical ControlLeft. GdkModifierType state = static_cast<GdkModifierType>(0); fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_Control_L, kKeyCodeCapsLock, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // The key up of the control left press is missed. state = static_cast<GdkModifierType>(0); // Send a normal event (KeyA down). fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_A, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); // The synthesized event should have physical CapsLock and logical // ControlLeft. EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalCapsLock); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "A"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Test if missed lock keys can be detected and synthesized with state // information upon events that are not for this modifier key. TEST(FlKeyEmbedderResponderTest, SynthesizeForDesyncLockModeOnNonSelfEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // The NumLock is desynchronized by being enabled. GdkModifierType state = GDK_MOD2_MASK; // Send a normal event fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_a, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, "a"); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // The NumLock is desynchronized by being disabled. state = static_cast<GdkModifierType>(0); // Release key A fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kRelease, GDK_KEY_A, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 4u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 2)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 3)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalKeyA); EXPECT_EQ(record->event->logical, kLogicalKeyA); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // Release NumLock. Since the previous event should have synthesized NumLock // to be released, this should result in only an empty event. g_expected_handled = true; fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(103, kRelease, GDK_KEY_Num_Lock, kKeyCodeNumLock, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->physical, 0ull); EXPECT_EQ(record->event->logical, 0ull); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); EXPECT_EQ(record->callback, nullptr); clear_g_call_records(); g_object_unref(responder); } // Test if missed lock keys can be detected and synthesized with state // information upon events that are for this modifier key. TEST(FlKeyEmbedderResponderTest, SynthesizeForDesyncLockModeOnSelfEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // The NumLock is desynchronized by being enabled. GdkModifierType state = GDK_MOD2_MASK; // NumLock down fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kPress, GDK_KEY_Num_Lock, kKeyCodeNumLock, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 3u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 2)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); // The NumLock is desynchronized by being enabled in a press event. state = GDK_MOD2_MASK; // NumLock up fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(102, kPress, GDK_KEY_Num_Lock, kKeyCodeNumLock, state, kIsModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 4u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 2)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 3)); EXPECT_EQ(record->event->timestamp, 102000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, false); invoke_record_callback_and_verify(record, TRUE, &user_data); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // Ensures that even if the primary event is ignored (due to duplicate // key up or down events), key synthesization is still performed. TEST(FlKeyEmbedderResponderTest, SynthesizationOccursOnIgnoredEvents) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); int user_data = 123; // Arbitrary user data FlKeyEmbedderCallRecord* record; // The NumLock is desynchronized by being enabled, and Control is pressed. GdkModifierType state = static_cast<GdkModifierType>(GDK_MOD2_MASK | GDK_CONTROL_MASK); // Send a KeyA up event, which will be ignored. g_expected_handled = true; // The ignored event is always handled. fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(101, kRelease, GDK_KEY_a, kKeyCodeKeyA, state, kIsNotModifier), verify_response_handled, &user_data); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalNumLock); EXPECT_EQ(record->event->logical, kLogicalNumLock); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->timestamp, 101000); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalControlLeft); EXPECT_EQ(record->event->logical, kLogicalControlLeft); EXPECT_STREQ(record->event->character, nullptr); EXPECT_EQ(record->event->synthesized, true); g_ptr_array_clear(g_call_records); clear_g_call_records(); g_object_unref(responder); } // This test case occurs when the following two cases collide: // // 1. When holding shift, AltRight key gives logical GDK_KEY_Meta_R with the // state bitmask still MOD3 (Alt). // 2. When holding AltRight, ShiftLeft key gives logical GDK_KEY_ISO_Next_Group // with the state bitmask RESERVED_14. // // The resulting event sequence is not perfectly ideal: it had to synthesize // AltLeft down because the physical AltRight key corresponds to logical // MetaRight at the moment. TEST(FlKeyEmbedderResponderTest, HandlesShiftAltVersusGroupNext) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); g_expected_handled = true; guint32 now_time = 1; // A convenient shorthand to simulate events. auto send_key_event = [responder, &now_time](bool is_press, guint keyval, guint16 keycode, GdkModifierType state) { now_time += 1; int user_data = 123; // Arbitrary user data fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(now_time, is_press, keyval, keycode, state, kIsModifier), verify_response_handled, &user_data); }; FlKeyEmbedderCallRecord* record; send_key_event(kPress, GDK_KEY_Shift_L, kKeyCodeShiftLeft, GDK_MODIFIER_RESERVED_25_MASK); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalShiftLeft); EXPECT_EQ(record->event->synthesized, false); send_key_event(kPress, GDK_KEY_Meta_R, kKeyCodeAltRight, static_cast<GdkModifierType>(GDK_SHIFT_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalAltRight); EXPECT_EQ(record->event->logical, kLogicalMetaRight); EXPECT_EQ(record->event->synthesized, false); send_key_event(kRelease, GDK_KEY_ISO_Next_Group, kKeyCodeShiftLeft, static_cast<GdkModifierType>(GDK_SHIFT_MASK | GDK_MOD1_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 5u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 2)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalAltLeft); EXPECT_EQ(record->event->logical, kLogicalAltLeft); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 3)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalAltRight); EXPECT_EQ(record->event->logical, kLogicalMetaRight); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 4)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalShiftLeft); EXPECT_EQ(record->event->synthesized, false); send_key_event(kPress, GDK_KEY_ISO_Next_Group, kKeyCodeShiftLeft, static_cast<GdkModifierType>(GDK_MOD1_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 6u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 5)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalGroupNext); EXPECT_EQ(record->event->synthesized, false); send_key_event(kRelease, GDK_KEY_ISO_Level3_Shift, kKeyCodeAltRight, static_cast<GdkModifierType>(GDK_MOD1_MASK | GDK_MODIFIER_RESERVED_13_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 7u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 6)); EXPECT_EQ(record->event->physical, 0u); EXPECT_EQ(record->event->logical, 0u); send_key_event(kRelease, GDK_KEY_Shift_L, kKeyCodeShiftLeft, static_cast<GdkModifierType>(GDK_MODIFIER_RESERVED_13_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 9u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 7)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalAltLeft); EXPECT_EQ(record->event->logical, kLogicalAltLeft); EXPECT_EQ(record->event->synthesized, true); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 8)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeUp); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalGroupNext); EXPECT_EQ(record->event->synthesized, false); clear_g_call_records(); g_object_unref(responder); } // Shift + AltLeft results in GDK event whose keyval is MetaLeft but whose // keycode is either AltLeft or Shift keycode (depending on which one was // released last). The physical key is usually deduced from the keycode, but in // this case (Shift + AltLeft) a correction is needed otherwise the physical // key won't be the MetaLeft one. // Regression test for https://github.com/flutter/flutter/issues/96082 TEST(FlKeyEmbedderResponderTest, HandlesShiftAltLeftIsMetaLeft) { EXPECT_EQ(g_call_records, nullptr); g_call_records = g_ptr_array_new_with_free_func(g_object_unref); FlKeyResponder* responder = FL_KEY_RESPONDER( fl_key_embedder_responder_new(record_calls, g_call_records)); g_expected_handled = true; guint32 now_time = 1; // A convenient shorthand to simulate events. auto send_key_event = [responder, &now_time](bool is_press, guint keyval, guint16 keycode, GdkModifierType state) { now_time += 1; int user_data = 123; // Arbitrary user data fl_key_responder_handle_event( responder, fl_key_event_new_by_mock(now_time, is_press, keyval, keycode, state, kIsModifier), verify_response_handled, &user_data); }; FlKeyEmbedderCallRecord* record; // ShiftLeft + AltLeft send_key_event(kPress, GDK_KEY_Shift_L, kKeyCodeShiftLeft, GDK_MODIFIER_RESERVED_25_MASK); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalShiftLeft); EXPECT_EQ(record->event->logical, kLogicalShiftLeft); EXPECT_EQ(record->event->synthesized, false); send_key_event(kPress, GDK_KEY_Meta_L, kKeyCodeAltLeft, static_cast<GdkModifierType>(GDK_SHIFT_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalMetaLeft); EXPECT_EQ(record->event->logical, kLogicalMetaLeft); EXPECT_EQ(record->event->synthesized, false); send_key_event(kRelease, GDK_KEY_Meta_L, kKeyCodeAltLeft, static_cast<GdkModifierType>(GDK_MODIFIER_RESERVED_13_MASK | GDK_MODIFIER_RESERVED_25_MASK)); send_key_event(kRelease, GDK_KEY_Shift_L, kKeyCodeShiftLeft, GDK_MODIFIER_RESERVED_25_MASK); g_ptr_array_clear(g_call_records); // ShiftRight + AltLeft send_key_event(kPress, GDK_KEY_Shift_R, kKeyCodeShiftRight, GDK_MODIFIER_RESERVED_25_MASK); EXPECT_EQ(g_call_records->len, 1u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 0)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalShiftRight); EXPECT_EQ(record->event->logical, kLogicalShiftRight); EXPECT_EQ(record->event->synthesized, false); send_key_event(kPress, GDK_KEY_Meta_L, kKeyCodeAltLeft, static_cast<GdkModifierType>(GDK_SHIFT_MASK | GDK_MODIFIER_RESERVED_25_MASK)); EXPECT_EQ(g_call_records->len, 2u); record = FL_KEY_EMBEDDER_CALL_RECORD(g_ptr_array_index(g_call_records, 1)); EXPECT_EQ(record->event->type, kFlutterKeyEventTypeDown); EXPECT_EQ(record->event->physical, kPhysicalMetaLeft); EXPECT_EQ(record->event->logical, kLogicalMetaLeft); EXPECT_EQ(record->event->synthesized, false); clear_g_call_records(); g_object_unref(responder); }
engine/shell/platform/linux/fl_key_embedder_responder_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_key_embedder_responder_test.cc", "repo_id": "engine", "token_count": 31855 }
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. // Included first as it collides with the X11 headers. #include "gtest/gtest.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/fl_method_codec_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_basic_message_channel.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_renderer.h" // Called when the method call response is received in the InvokeMethod // test. static void method_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( FL_METHOD_CHANNEL(object), result, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); FlValue* r = fl_method_response_get_result(response, &error); EXPECT_NE(r, nullptr); EXPECT_EQ(error, nullptr); EXPECT_EQ(fl_value_get_type(r), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(r), "Hello World!"); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks if invoking a method returns a value. TEST(FlMethodChannelTest, InvokeMethod) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); g_autoptr(FlValue) args = fl_value_new_string("Hello World!"); fl_method_channel_invoke_method(channel, "Echo", args, nullptr, method_response_cb, loop); // Blocks here until method_response_cb is called. g_main_loop_run(loop); } // Called when the method call response is received in the // InvokeMethodNullptrArgsMessage test. static void nullptr_args_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( FL_METHOD_CHANNEL(object), result, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); FlValue* r = fl_method_response_get_result(response, &error); EXPECT_NE(r, nullptr); EXPECT_EQ(error, nullptr); EXPECT_EQ(fl_value_get_type(r), FL_VALUE_TYPE_NULL); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks if a method can be invoked with nullptr for arguments. TEST(FlMethodChannelTest, InvokeMethodNullptrArgsMessage) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_invoke_method(channel, "Echo", nullptr, nullptr, nullptr_args_response_cb, loop); // Blocks here until nullptr_args_response_cb is called. g_main_loop_run(loop); } // Called when the method call response is received in the // InvokeMethodError test. static void error_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( FL_METHOD_CHANNEL(object), result, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_ERROR_RESPONSE(response)); EXPECT_STREQ( fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)), "CODE"); EXPECT_STREQ( fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(response)), "MESSAGE"); FlValue* details = fl_method_error_response_get_details(FL_METHOD_ERROR_RESPONSE(response)); EXPECT_NE(details, nullptr); EXPECT_EQ(fl_value_get_type(details), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(details), "DETAILS"); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks if an error response from a method call is handled. TEST(FlMethodChannelTest, InvokeMethodError) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string("CODE")); fl_value_append_take(args, fl_value_new_string("MESSAGE")); fl_value_append_take(args, fl_value_new_string("DETAILS")); fl_method_channel_invoke_method(channel, "Error", args, nullptr, error_response_cb, loop); // Blocks here until error_response_cb is called. g_main_loop_run(loop); } // Called when the method call response is received in the // InvokeMethodNotImplemented test. static void not_implemented_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( FL_METHOD_CHANNEL(object), result, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response)); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks if a not implemeneted response from a method call is handled. TEST(FlMethodChannelTest, InvokeMethodNotImplemented) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_invoke_method(channel, "NotImplemented", nullptr, nullptr, not_implemented_response_cb, loop); // Blocks here until not_implemented_response_cb is called. g_main_loop_run(loop); } // Called when the method call response is received in the // InvokeMethodFailure test. static void failure_response_cb(GObject* object, GAsyncResult* result, gpointer user_data) { g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_channel_invoke_method_finish( FL_METHOD_CHANNEL(object), result, &error); EXPECT_EQ(response, nullptr); EXPECT_NE(error, nullptr); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks if an engine failure calling a method call is handled. TEST(FlMethodChannelTest, InvokeMethodFailure) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new(messenger, "test/failure", FL_METHOD_CODEC(codec)); fl_method_channel_invoke_method(channel, "Echo", nullptr, nullptr, failure_response_cb, loop); // Blocks here until failure_response_cb is called. g_main_loop_run(loop); } // Called when a method call is received from the engine in the // ReceiveMethodCallRespondSuccess test. static void method_call_success_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { EXPECT_STREQ(fl_method_call_get_name(method_call), "Foo"); EXPECT_EQ(fl_value_get_type(fl_method_call_get_args(method_call)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_method_call_get_args(method_call)), "Marco!"); g_autoptr(FlValue) result = fl_value_new_string("Polo!"); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_method_call_respond_success(method_call, result, &error)); EXPECT_EQ(error, nullptr); } // Called when a the test engine notifies us what response we sent in the // ReceiveMethodCallRespondSuccess test. static void method_call_success_response_cb( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response)); FlValue* result = fl_method_success_response_get_result( FL_METHOD_SUCCESS_RESPONSE(response)); EXPECT_EQ(fl_value_get_type(result), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(result), "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 method calls from the engine. TEST(FlMethodChannelTest, ReceiveMethodCallRespondSuccess) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_success_cb, nullptr, nullptr); // Listen for response from the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/responses", method_call_success_response_cb, loop, nullptr); // Trigger the engine to make a method call. g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string("test/standard-method")); fl_value_append_take(args, fl_value_new_string("Foo")); fl_value_append_take(args, fl_value_new_string("Marco!")); fl_method_channel_invoke_method(channel, "InvokeMethod", args, nullptr, nullptr, loop); // Blocks here until method_call_success_response_cb is called. g_main_loop_run(loop); } // Called when a method call is received from the engine in the // ReceiveMethodCallRespondError test. static void method_call_error_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { EXPECT_STREQ(fl_method_call_get_name(method_call), "Foo"); EXPECT_EQ(fl_value_get_type(fl_method_call_get_args(method_call)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_method_call_get_args(method_call)), "Marco!"); g_autoptr(FlValue) details = fl_value_new_string("DETAILS"); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_method_call_respond_error(method_call, "CODE", "MESSAGE", details, &error)); EXPECT_EQ(error, nullptr); } // Called when a the test engine notifies us what response we sent in the // ReceiveMethodCallRespondError test. static void method_call_error_response_cb( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_ERROR_RESPONSE(response)); EXPECT_STREQ( fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)), "CODE"); EXPECT_STREQ( fl_method_error_response_get_message(FL_METHOD_ERROR_RESPONSE(response)), "MESSAGE"); FlValue* details = fl_method_error_response_get_details(FL_METHOD_ERROR_RESPONSE(response)); EXPECT_EQ(fl_value_get_type(details), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(details), "DETAILS"); 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 method calls from the engine. TEST(FlMethodChannelTest, ReceiveMethodCallRespondError) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_error_cb, nullptr, nullptr); // Listen for response from the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/responses", method_call_error_response_cb, loop, nullptr); // Trigger the engine to make a method call. g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string("test/standard-method")); fl_value_append_take(args, fl_value_new_string("Foo")); fl_value_append_take(args, fl_value_new_string("Marco!")); fl_method_channel_invoke_method(channel, "InvokeMethod", args, nullptr, nullptr, loop); // Blocks here until method_call_error_response_cb is called. g_main_loop_run(loop); } // Called when a method call is received from the engine in the // ReceiveMethodCallRespondNotImplemented test. static void method_call_not_implemented_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { EXPECT_STREQ(fl_method_call_get_name(method_call), "Foo"); EXPECT_EQ(fl_value_get_type(fl_method_call_get_args(method_call)), FL_VALUE_TYPE_STRING); EXPECT_STREQ(fl_value_get_string(fl_method_call_get_args(method_call)), "Marco!"); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_method_call_respond_not_implemented(method_call, &error)); EXPECT_EQ(error, nullptr); } // Called when a the test engine notifies us what response we sent in the // ReceiveMethodCallRespondNotImplemented test. static void method_call_not_implemented_response_cb( FlBinaryMessenger* messenger, const gchar* channel, GBytes* message, FlBinaryMessengerResponseHandle* response_handle, gpointer user_data) { g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(GError) error = nullptr; g_autoptr(FlMethodResponse) response = fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error); EXPECT_NE(response, nullptr); EXPECT_EQ(error, nullptr); EXPECT_TRUE(FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response)); 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 method calls from the engine. TEST(FlMethodChannelTest, ReceiveMethodCallRespondNotImplemented) { 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler( channel, method_call_not_implemented_cb, nullptr, nullptr); // Listen for response from the engine. fl_binary_messenger_set_message_handler_on_channel( messenger, "test/responses", method_call_not_implemented_response_cb, loop, nullptr); // Trigger the engine to make a method call. g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string("test/standard-method")); fl_value_append_take(args, fl_value_new_string("Foo")); fl_value_append_take(args, fl_value_new_string("Marco!")); fl_method_channel_invoke_method(channel, "InvokeMethod", args, nullptr, nullptr, loop); // Blocks here until method_call_not_implemented_response_cb is called. g_main_loop_run(loop); } // A test method codec that always generates errors on responses. G_DECLARE_FINAL_TYPE(TestMethodCodec, test_method_codec, TEST, METHOD_CODEC, FlMethodCodec) struct _TestMethodCodec { FlMethodCodec parent_instance; FlStandardMethodCodec* wrapped_codec; }; G_DEFINE_TYPE(TestMethodCodec, test_method_codec, fl_method_codec_get_type()) static void test_method_codec_dispose(GObject* object) { TestMethodCodec* self = TEST_METHOD_CODEC(object); g_clear_object(&self->wrapped_codec); G_OBJECT_CLASS(test_method_codec_parent_class)->dispose(object); } // Implements FlMethodCodec::encode_method_call. static GBytes* test_method_codec_encode_method_call(FlMethodCodec* codec, const gchar* name, FlValue* args, GError** error) { EXPECT_TRUE(TEST_IS_METHOD_CODEC(codec)); TestMethodCodec* self = TEST_METHOD_CODEC(codec); return fl_method_codec_encode_method_call( FL_METHOD_CODEC(self->wrapped_codec), name, args, error); } // Implements FlMethodCodec::decode_method_call. static gboolean test_method_codec_decode_method_call(FlMethodCodec* codec, GBytes* message, gchar** name, FlValue** args, GError** error) { EXPECT_TRUE(TEST_IS_METHOD_CODEC(codec)); TestMethodCodec* self = TEST_METHOD_CODEC(codec); return fl_method_codec_decode_method_call( FL_METHOD_CODEC(self->wrapped_codec), message, name, args, error); } // Implements FlMethodCodec::encode_success_envelope. static GBytes* test_method_codec_encode_success_envelope(FlMethodCodec* codec, FlValue* result, GError** error) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Unsupported type"); return nullptr; } // Implements FlMethodCodec::encode_error_envelope. static GBytes* test_method_codec_encode_error_envelope(FlMethodCodec* codec, const gchar* code, const gchar* message, FlValue* details, GError** error) { g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED, "Unsupported type"); return nullptr; } // Implements FlMethodCodec::encode_decode_response. static FlMethodResponse* test_method_codec_decode_response(FlMethodCodec* codec, GBytes* message, GError** error) { EXPECT_TRUE(TEST_IS_METHOD_CODEC(codec)); TestMethodCodec* self = TEST_METHOD_CODEC(codec); return fl_method_codec_decode_response(FL_METHOD_CODEC(self->wrapped_codec), message, error); } static void test_method_codec_class_init(TestMethodCodecClass* klass) { G_OBJECT_CLASS(klass)->dispose = test_method_codec_dispose; FL_METHOD_CODEC_CLASS(klass)->encode_method_call = test_method_codec_encode_method_call; FL_METHOD_CODEC_CLASS(klass)->decode_method_call = test_method_codec_decode_method_call; FL_METHOD_CODEC_CLASS(klass)->encode_success_envelope = test_method_codec_encode_success_envelope; FL_METHOD_CODEC_CLASS(klass)->encode_error_envelope = test_method_codec_encode_error_envelope; FL_METHOD_CODEC_CLASS(klass)->decode_response = test_method_codec_decode_response; } static void test_method_codec_init(TestMethodCodec* self) { self->wrapped_codec = fl_standard_method_codec_new(); } TestMethodCodec* test_method_codec_new() { return TEST_METHOD_CODEC(g_object_new(test_method_codec_get_type(), nullptr)); } // Called when a method call is received from the engine in the // ReceiveMethodCallRespondSuccessError test. static void method_call_success_error_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { g_autoptr(FlValue) result = fl_value_new_int(42); g_autoptr(GError) response_error = nullptr; EXPECT_FALSE( fl_method_call_respond_success(method_call, result, &response_error)); EXPECT_NE(response_error, nullptr); // Respond to stop a warning occurring about not responding. fl_method_call_respond_not_implemented(method_call, nullptr); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks error correctly handled if provide an unsupported arg in a method call // response. TEST(FlMethodChannelTest, ReceiveMethodCallRespondSuccessError) { 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(TestMethodCodec) codec = test_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler( channel, method_call_success_error_cb, loop, nullptr); // Trigger the engine to make a method call. g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string("test/standard-method")); fl_value_append_take(args, fl_value_new_string("Foo")); fl_value_append_take(args, fl_value_new_string("Marco!")); fl_method_channel_invoke_method(channel, "InvokeMethod", args, nullptr, nullptr, loop); // Blocks here until method_call_success_error_cb is called. g_main_loop_run(loop); } // Called when a method call is received from the engine in the // ReceiveMethodCallRespondErrorError test. static void method_call_error_error_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { g_autoptr(FlValue) details = fl_value_new_int(42); g_autoptr(GError) response_error = nullptr; EXPECT_FALSE(fl_method_call_respond_error(method_call, "error", "ERROR", details, &response_error)); EXPECT_NE(response_error, nullptr); // Respond to stop a warning occurring about not responding. fl_method_call_respond_not_implemented(method_call, nullptr); g_main_loop_quit(static_cast<GMainLoop*>(user_data)); } // Checks error correctly handled if provide an unsupported arg in a method call // response. TEST(FlMethodChannelTest, ReceiveMethodCallRespondErrorError) { 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(TestMethodCodec) codec = test_method_codec_new(); g_autoptr(FlMethodChannel) channel = fl_method_channel_new( messenger, "test/standard-method", FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel, method_call_error_error_cb, loop, nullptr); // Trigger the engine to make a method call. g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string("test/standard-method")); fl_value_append_take(args, fl_value_new_string("Foo")); fl_value_append_take(args, fl_value_new_string("Marco!")); fl_method_channel_invoke_method(channel, "InvokeMethod", args, nullptr, nullptr, loop); // Blocks here until method_call_error_error_cb is called. g_main_loop_run(loop); } struct UserDataReassignMethod { GMainLoop* loop; int count; }; // This callback parses the user data as UserDataReassignMethod, // increases its `count`, and quits `loop`. static void reassign_method_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer raw_user_data) { UserDataReassignMethod* user_data = static_cast<UserDataReassignMethod*>(raw_user_data); user_data->count += 1; g_autoptr(FlValue) result = fl_value_new_string("Polo!"); g_autoptr(GError) error = nullptr; EXPECT_TRUE(fl_method_call_respond_success(method_call, result, &error)); EXPECT_EQ(error, nullptr); g_main_loop_quit(user_data->loop); } // Make sure that the following steps will work properly: // // 1. Register a method channel. // 2. Dispose the method channel, and it's unregistered. // 3. Register a new channel with the same name. // // This is a regression test to https://github.com/flutter/flutter/issues/90817. TEST(FlMethodChannelTest, ReplaceADisposedMethodChannel) { const char* method_name = "test/standard-method"; // The loop is used to pause the main process until the callback is fully // executed. 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string(method_name)); fl_value_append_take(args, fl_value_new_string("FOO")); fl_value_append_take(args, fl_value_new_string("BAR")); // Register the first channel and test if it works. UserDataReassignMethod user_data1{ .loop = loop, .count = 100, }; FlMethodChannel* channel1 = fl_method_channel_new(messenger, method_name, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel1, reassign_method_cb, &user_data1, nullptr); fl_method_channel_invoke_method(channel1, "InvokeMethod", args, nullptr, nullptr, nullptr); g_main_loop_run(loop); EXPECT_EQ(user_data1.count, 101); // Dispose the first channel. g_object_unref(channel1); // Register the second channel and test if it works. UserDataReassignMethod user_data2{ .loop = loop, .count = 100, }; g_autoptr(FlMethodChannel) channel2 = fl_method_channel_new(messenger, method_name, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel2, reassign_method_cb, &user_data2, nullptr); fl_method_channel_invoke_method(channel2, "InvokeMethod", args, nullptr, nullptr, nullptr); g_main_loop_run(loop); EXPECT_EQ(user_data1.count, 101); EXPECT_EQ(user_data2.count, 101); } // Make sure that the following steps will work properly: // // 1. Register a method channel. // 2. Register the same name with a new channel. // 3. Dispose the previous method channel. // // This is a regression test to https://github.com/flutter/flutter/issues/90817. TEST(FlMethodChannelTest, DisposeAReplacedMethodChannel) { const char* method_name = "test/standard-method"; // The loop is used to pause the main process until the callback is fully // executed. 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(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); g_autoptr(FlValue) args = fl_value_new_list(); fl_value_append_take(args, fl_value_new_string(method_name)); fl_value_append_take(args, fl_value_new_string("FOO")); fl_value_append_take(args, fl_value_new_string("BAR")); // Register the first channel and test if it works. UserDataReassignMethod user_data1{ .loop = loop, .count = 100, }; FlMethodChannel* channel1 = fl_method_channel_new(messenger, method_name, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel1, reassign_method_cb, &user_data1, nullptr); fl_method_channel_invoke_method(channel1, "InvokeMethod", args, nullptr, nullptr, nullptr); g_main_loop_run(loop); EXPECT_EQ(user_data1.count, 101); // Register a new channel to the same name. UserDataReassignMethod user_data2{ .loop = loop, .count = 100, }; g_autoptr(FlMethodChannel) channel2 = fl_method_channel_new(messenger, method_name, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(channel2, reassign_method_cb, &user_data2, nullptr); fl_method_channel_invoke_method(channel2, "InvokeMethod", args, nullptr, nullptr, nullptr); g_main_loop_run(loop); EXPECT_EQ(user_data1.count, 101); EXPECT_EQ(user_data2.count, 101); // Dispose the first channel. The new channel should keep working. g_object_unref(channel1); fl_method_channel_invoke_method(channel2, "InvokeMethod", args, nullptr, nullptr, nullptr); g_main_loop_run(loop); EXPECT_EQ(user_data1.count, 101); EXPECT_EQ(user_data2.count, 102); }
engine/shell/platform/linux/fl_method_channel_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_method_channel_test.cc", "repo_id": "engine", "token_count": 13161 }
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. #include <gtk/gtk.h> // Included first as it collides with the X11 headers. #include "gtest/gtest.h" #include "flutter/shell/platform/linux/fl_binary_messenger_private.h" #include "flutter/shell/platform/linux/fl_texture_registrar_private.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_plugin_registrar.h" #include "flutter/shell/platform/linux/testing/fl_test.h" #include "flutter/shell/platform/linux/testing/mock_plugin_registrar.h" // Checks can make a mock registrar. TEST(FlPluginRegistrarTest, FlMockRegistrar) { g_autoptr(FlEngine) engine = make_mock_engine(); g_autoptr(FlBinaryMessenger) messenger = fl_binary_messenger_new(engine); g_autoptr(FlTextureRegistrar) texture_registrar = fl_texture_registrar_new(engine); g_autoptr(FlPluginRegistrar) registrar = fl_mock_plugin_registrar_new(messenger, texture_registrar); EXPECT_TRUE(FL_IS_MOCK_PLUGIN_REGISTRAR(registrar)); EXPECT_EQ(fl_plugin_registrar_get_messenger(registrar), messenger); EXPECT_EQ(fl_plugin_registrar_get_texture_registrar(registrar), texture_registrar); }
engine/shell/platform/linux/fl_plugin_registrar_test.cc/0
{ "file_path": "engine/shell/platform/linux/fl_plugin_registrar_test.cc", "repo_id": "engine", "token_count": 471 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_PLUGIN_H_ #include "flutter/shell/platform/linux/fl_settings.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h" G_BEGIN_DECLS G_DECLARE_FINAL_TYPE(FlSettingsPlugin, fl_settings_plugin, FL, SETTINGS_PLUGIN, GObject); /** * FlSettingsPlugin: * * #FlSettingsPlugin is a plugin that implements the Flutter user settings * channel. */ /** * fl_settings_plugin_new: * @messenger: an #FlEngine * * Creates a new plugin that sends user settings to the Flutter engine. * * Returns: a new #FlSettingsPlugin */ FlSettingsPlugin* fl_settings_plugin_new(FlEngine* engine); /** * fl_settings_plugin_start: * @self: an #FlSettingsPlugin. * * Sends the current settings to the engine and updates when they change. */ void fl_settings_plugin_start(FlSettingsPlugin* plugin, FlSettings* settings); G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_SETTINGS_PLUGIN_H_
engine/shell/platform/linux/fl_settings_plugin.h/0
{ "file_path": "engine/shell/platform/linux/fl_settings_plugin.h", "repo_id": "engine", "token_count": 489 }
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. #include "flutter/shell/platform/linux/fl_text_input_view_delegate.h" G_DEFINE_INTERFACE(FlTextInputViewDelegate, fl_text_input_view_delegate, G_TYPE_OBJECT) static void fl_text_input_view_delegate_default_init( FlTextInputViewDelegateInterface* iface) {} void fl_text_input_view_delegate_translate_coordinates( FlTextInputViewDelegate* self, gint view_x, gint view_y, gint* window_x, gint* window_y) { g_return_if_fail(FL_IS_TEXT_INPUT_VIEW_DELEGATE(self)); FL_TEXT_INPUT_VIEW_DELEGATE_GET_IFACE(self)->translate_coordinates( self, view_x, view_y, window_x, window_y); }
engine/shell/platform/linux/fl_text_input_view_delegate.cc/0
{ "file_path": "engine/shell/platform/linux/fl_text_input_view_delegate.cc", "repo_id": "engine", "token_count": 336 }
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_LINUX_FL_VIEW_PRIVATE_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_FL_VIEW_PRIVATE_H_ #include "flutter/shell/platform/linux/public/flutter_linux/fl_view.h" /** * fl_view_redraw: * @view: an #FlView. * * Indicate the view needs to redraw. */ void fl_view_redraw(FlView* view); /** * fl_view_get_keyboard_state: * @view: an #FlView. * * Returns the keyboard pressed state. The hash table contains one entry per * pressed keys, mapping from the logical key to the physical key.* */ GHashTable* fl_view_get_keyboard_state(FlView* view); #endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_VIEW_PRIVATE_H_
engine/shell/platform/linux/fl_view_private.h/0
{ "file_path": "engine/shell/platform/linux/fl_view_private.h", "repo_id": "engine", "token_count": 287 }
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. #ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CODEC_H_ #define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CODEC_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 "fl_method_response.h" #include "fl_value.h" G_BEGIN_DECLS G_MODULE_EXPORT G_DECLARE_DERIVABLE_TYPE(FlMethodCodec, fl_method_codec, FL, METHOD_CODEC, GObject) /** * FlMethodCodec: * * #FlMethodCodec is an abstract class that encodes and decodes method calls on * a platform channel. Override this class to implement an encoding. * * #FlMethodCodec matches the MethodCodec class in the Flutter services * library. */ struct _FlMethodCodecClass { GObjectClass parent_class; /** * FlMethodCodec::encode_method_call: * @codec: an #FlMethodCodec. * @name: method name. * @args: (allow-none): method arguments, or %NULL. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes a method call. * * Returns: (transfer full): a binary encoding of this method call or %NULL if * not able to encode. */ GBytes* (*encode_method_call)(FlMethodCodec* codec, const gchar* name, FlValue* args, GError** error); /** * FlMethodCodec::decode_method_call: * @codec: an #FlMethodCodec * @message: message to decode. * @name: (transfer full): location to write method name or %NULL if not * required * @args: (transfer full): location to write method arguments, or %NULL if not * required * @error: (allow-none): #GError location to store the error occurring, or * %NULL * * Decodes a method call. * * Returns: %TRUE if successfully decoded. */ gboolean (*decode_method_call)(FlMethodCodec* codec, GBytes* message, gchar** name, FlValue** args, GError** error); /** * FlMethodCodec::encode_success_envelope: * @codec: an #FlMethodCodec. * @result: (allow-none): method result, or %NULL. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes a successful response to a method call. * * Returns: (transfer full): a binary encoding of this response or %NULL if * not able to encode. */ GBytes* (*encode_success_envelope)(FlMethodCodec* codec, FlValue* result, GError** error); /** * FlMethodCodec::encode_error_envelope: * @codec: an #FlMethodCodec. * @code: an error code. * @message: (allow-none): an error message, or %NULL. * @details: (allow-none): error details, or %NULL. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Encodes an error response to a method call. * * Returns: (transfer full): a binary encoding of this response or %NULL if * not able to encode. */ GBytes* (*encode_error_envelope)(FlMethodCodec* codec, const gchar* code, const gchar* message, FlValue* details, GError** error); /** * FlMethodCodec::decode_response: * @codec: an #FlMethodCodec. * @message: message to decode. * @error: (allow-none): #GError location to store the error occurring, or * %NULL. * * Decodes a response to a method call. * * Returns: a new #FlMethodResponse or %NULL on error. */ FlMethodResponse* (*decode_response)(FlMethodCodec* codec, GBytes* message, GError** error); }; G_END_DECLS #endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_METHOD_CODEC_H_
engine/shell/platform/linux/public/flutter_linux/fl_method_codec.h/0
{ "file_path": "engine/shell/platform/linux/public/flutter_linux/fl_method_codec.h", "repo_id": "engine", "token_count": 1960 }
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 "fl_test_gtk_logs.h" #include "gtest/gtest.h" namespace flutter { namespace testing { namespace { bool gtk_initialized = false; GLogWriterFunc log_writer_cb = nullptr; GLogLevelFlags fl_received_log_levels = (GLogLevelFlags)0x0; GLogWriterOutput log_writer(GLogLevelFlags log_level, const GLogField* fields, gsize n_fields, gpointer user_data) { fl_received_log_levels = (GLogLevelFlags)(log_level | fl_received_log_levels); if (log_writer_cb == nullptr) { return g_log_writer_default(log_level, fields, n_fields, user_data); } GLogWriterOutput result = log_writer_cb(log_level, fields, n_fields, user_data); if (result != G_LOG_WRITER_HANDLED) { return g_log_writer_default(log_level, fields, n_fields, user_data); } return result; } } // namespace void fl_ensure_gtk_init(GLogWriterFunc writer) { if (!gtk_initialized) { gtk_init(0, nullptr); g_log_set_writer_func(log_writer, nullptr, nullptr); gtk_initialized = true; } fl_reset_received_gtk_log_levels(); log_writer_cb = writer; } void fl_reset_received_gtk_log_levels() { fl_received_log_levels = (GLogLevelFlags)0x0; } GLogLevelFlags fl_get_received_gtk_log_levels() { return fl_received_log_levels; } } // namespace testing } // namespace flutter
engine/shell/platform/linux/testing/fl_test_gtk_logs.cc/0
{ "file_path": "engine/shell/platform/linux/testing/fl_test_gtk_logs.cc", "repo_id": "engine", "token_count": 620 }
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. #include "flutter/shell/platform/linux/testing/mock_settings.h" using namespace flutter::testing; G_DECLARE_FINAL_TYPE(FlMockSettings, fl_mock_settings, FL, MOCK_SETTINGS, GObject) struct _FlMockSettings { GObject parent_instance; MockSettings* mock; }; static void fl_mock_settings_iface_init(FlSettingsInterface* iface); #define FL_UNUSED(x) (void)x; G_DEFINE_TYPE_WITH_CODE(FlMockSettings, fl_mock_settings, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE(fl_settings_get_type(), fl_mock_settings_iface_init) FL_UNUSED(FL_IS_MOCK_SETTINGS)) static void fl_mock_settings_class_init(FlMockSettingsClass* klass) {} static FlClockFormat fl_mock_settings_get_clock_format(FlSettings* settings) { FlMockSettings* self = FL_MOCK_SETTINGS(settings); return self->mock->fl_settings_get_clock_format(settings); } static FlColorScheme fl_mock_settings_get_color_scheme(FlSettings* settings) { FlMockSettings* self = FL_MOCK_SETTINGS(settings); return self->mock->fl_settings_get_color_scheme(settings); } static gboolean fl_mock_settings_get_enable_animations(FlSettings* settings) { FlMockSettings* self = FL_MOCK_SETTINGS(settings); return self->mock->fl_settings_get_enable_animations(settings); } static gboolean fl_mock_settings_get_high_contrast(FlSettings* settings) { FlMockSettings* self = FL_MOCK_SETTINGS(settings); return self->mock->fl_settings_get_high_contrast(settings); } static gdouble fl_mock_settings_get_text_scaling_factor(FlSettings* settings) { FlMockSettings* self = FL_MOCK_SETTINGS(settings); return self->mock->fl_settings_get_text_scaling_factor(settings); } static void fl_mock_settings_iface_init(FlSettingsInterface* iface) { iface->get_clock_format = fl_mock_settings_get_clock_format; iface->get_color_scheme = fl_mock_settings_get_color_scheme; iface->get_enable_animations = fl_mock_settings_get_enable_animations; iface->get_high_contrast = fl_mock_settings_get_high_contrast; iface->get_text_scaling_factor = fl_mock_settings_get_text_scaling_factor; } static void fl_mock_settings_init(FlMockSettings* self) {} MockSettings::MockSettings() : instance_( FL_SETTINGS(g_object_new(fl_mock_settings_get_type(), nullptr))) { FL_MOCK_SETTINGS(instance_)->mock = this; } MockSettings::~MockSettings() { if (instance_ != nullptr) { g_clear_object(&instance_); } } MockSettings::operator FlSettings*() { return instance_; }
engine/shell/platform/linux/testing/mock_settings.cc/0
{ "file_path": "engine/shell/platform/linux/testing/mock_settings.cc", "repo_id": "engine", "token_count": 1174 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_PLUGIN_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_PLUGIN_H_ #include <string_view> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h" namespace flutter { class FlutterWindowsEngine; // Handles messages on the flutter/accessibility channel. // // See: // https://api.flutter.dev/flutter/semantics/SemanticsService-class.html class AccessibilityPlugin { public: explicit AccessibilityPlugin(FlutterWindowsEngine* engine); // Begin handling accessibility messages on the `binary_messenger`. static void SetUp(BinaryMessenger* binary_messenger, AccessibilityPlugin* plugin); // Announce a message through the assistive technology. virtual void Announce(const std::string_view message); private: // The engine that owns this plugin. FlutterWindowsEngine* engine_ = nullptr; FML_DISALLOW_COPY_AND_ASSIGN(AccessibilityPlugin); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_ACCESSIBILITY_PLUGIN_H_
engine/shell/platform/windows/accessibility_plugin.h/0
{ "file_path": "engine/shell/platform/windows/accessibility_plugin.h", "repo_id": "engine", "token_count": 405 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_H_ #include "flutter/shell/platform/embedder/embedder.h" namespace flutter { // Enables the Flutter engine to render content on Windows. // // The engine uses this to: // // 1. Create backing stores used for rendering Flutter content // 2. Composite and present Flutter content and platform views onto a view // // Platform views are not yet supported. class Compositor { public: virtual ~Compositor() = default; // Creates a backing store used for rendering Flutter content. // // The backing store's configuration is stored in |backing_store_out|. virtual bool CreateBackingStore(const FlutterBackingStoreConfig& config, FlutterBackingStore* backing_store_out) = 0; // Destroys a backing store and releases its resources. virtual bool CollectBackingStore(const FlutterBackingStore* store) = 0; // Present Flutter content and platform views onto the view. virtual bool Present(FlutterViewId view_id, const FlutterLayer** layers, size_t layers_count) = 0; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_COMPOSITOR_H_
engine/shell/platform/windows/compositor.h/0
{ "file_path": "engine/shell/platform/windows/compositor.h", "repo_id": "engine", "token_count": 471 }
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/windows/egl/context.h" #include "flutter/shell/platform/windows/egl/egl.h" namespace flutter { namespace egl { Context::Context(EGLDisplay display, EGLContext context) : display_(display), context_(context) {} Context::~Context() { if (display_ == EGL_NO_DISPLAY && context_ == EGL_NO_CONTEXT) { return; } if (::eglDestroyContext(display_, context_) != EGL_TRUE) { WINDOWS_LOG_EGL_ERROR; } } bool Context::IsCurrent() const { return ::eglGetCurrentContext() == context_; } bool Context::MakeCurrent() const { const auto result = ::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, context_); if (result != EGL_TRUE) { WINDOWS_LOG_EGL_ERROR; return false; } return true; } bool Context::ClearCurrent() const { const auto result = ::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (result != EGL_TRUE) { WINDOWS_LOG_EGL_ERROR; return false; } return true; } const EGLContext& Context::GetHandle() const { return context_; } } // namespace egl } // namespace flutter
engine/shell/platform/windows/egl/context.cc/0
{ "file_path": "engine/shell/platform/windows/egl/context.cc", "repo_id": "engine", "token_count": 510 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_D3D_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_D3D_H_ #include <memory> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/public/flutter_texture_registrar.h" #include "flutter/shell/platform/windows/egl/manager.h" #include "flutter/shell/platform/windows/egl/proc_table.h" #include "flutter/shell/platform/windows/external_texture.h" namespace flutter { // An external texture that is backed by a DXGI surface. class ExternalTextureD3d : public ExternalTexture { public: ExternalTextureD3d( FlutterDesktopGpuSurfaceType type, const FlutterDesktopGpuSurfaceTextureCallback texture_callback, void* user_data, const egl::Manager* egl_manager, std::shared_ptr<egl::ProcTable> gl); virtual ~ExternalTextureD3d(); // |ExternalTexture| bool PopulateTexture(size_t width, size_t height, FlutterOpenGLTexture* opengl_texture) override; private: // Creates or updates the backing texture and associates it with the provided // surface. bool CreateOrUpdateTexture( const FlutterDesktopGpuSurfaceDescriptor* descriptor); // Detaches the previously attached surface, if any. void ReleaseImage(); FlutterDesktopGpuSurfaceType type_; const FlutterDesktopGpuSurfaceTextureCallback texture_callback_; void* const user_data_; const egl::Manager* egl_manager_; std::shared_ptr<egl::ProcTable> gl_; GLuint gl_texture_ = 0; EGLSurface egl_surface_ = EGL_NO_SURFACE; void* last_surface_handle_ = nullptr; FML_DISALLOW_COPY_AND_ASSIGN(ExternalTextureD3d); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_EXTERNAL_TEXTURE_D3D_H_
engine/shell/platform/windows/external_texture_d3d.h/0
{ "file_path": "engine/shell/platform/windows/external_texture_d3d.h", "repo_id": "engine", "token_count": 686 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_ENGINE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_ENGINE_H_ #include <chrono> #include <map> #include <memory> #include <optional> #include <string> #include <string_view> #include <unordered_map> #include <vector> #include "flutter/fml/closure.h" #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/accessibility_bridge.h" #include "flutter/shell/platform/common/app_lifecycle_state.h" #include "flutter/shell/platform/common/client_wrapper/binary_messenger_impl.h" #include "flutter/shell/platform/common/client_wrapper/include/flutter/basic_message_channel.h" #include "flutter/shell/platform/common/incoming_message_dispatcher.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/accessibility_bridge_windows.h" #include "flutter/shell/platform/windows/accessibility_plugin.h" #include "flutter/shell/platform/windows/compositor.h" #include "flutter/shell/platform/windows/cursor_handler.h" #include "flutter/shell/platform/windows/egl/manager.h" #include "flutter/shell/platform/windows/egl/proc_table.h" #include "flutter/shell/platform/windows/flutter_desktop_messenger.h" #include "flutter/shell/platform/windows/flutter_project_bundle.h" #include "flutter/shell/platform/windows/flutter_windows_texture_registrar.h" #include "flutter/shell/platform/windows/keyboard_handler_base.h" #include "flutter/shell/platform/windows/keyboard_key_embedder_handler.h" #include "flutter/shell/platform/windows/platform_handler.h" #include "flutter/shell/platform/windows/platform_view_plugin.h" #include "flutter/shell/platform/windows/public/flutter_windows.h" #include "flutter/shell/platform/windows/settings_plugin.h" #include "flutter/shell/platform/windows/task_runner.h" #include "flutter/shell/platform/windows/text_input_plugin.h" #include "flutter/shell/platform/windows/window_proc_delegate_manager.h" #include "flutter/shell/platform/windows/window_state.h" #include "flutter/shell/platform/windows/windows_lifecycle_manager.h" #include "flutter/shell/platform/windows/windows_proc_table.h" #include "third_party/rapidjson/include/rapidjson/document.h" namespace flutter { // The implicit view's ID. // // See: // https://api.flutter.dev/flutter/dart-ui/PlatformDispatcher/implicitView.html constexpr FlutterViewId kImplicitViewId = 0; class FlutterWindowsView; // Update the thread priority for the Windows engine. static void WindowsPlatformThreadPrioritySetter( FlutterThreadPriority priority) { // TODO(99502): Add support for tracing to the windows embedding so we can // mark thread priorities and success/failure. switch (priority) { case FlutterThreadPriority::kBackground: { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL); break; } case FlutterThreadPriority::kDisplay: { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); break; } case FlutterThreadPriority::kRaster: { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); break; } case FlutterThreadPriority::kNormal: { // For normal or default priority we do not need to set the priority // class. break; } } } // Manages state associated with the underlying FlutterEngine that isn't // related to its display. // // In most cases this will be associated with a FlutterView, but if not will // run in headless mode. class FlutterWindowsEngine { public: // Creates a new Flutter engine object configured to run |project|. FlutterWindowsEngine( const FlutterProjectBundle& project, std::shared_ptr<WindowsProcTable> windows_proc_table = nullptr); virtual ~FlutterWindowsEngine(); // Starts running the entrypoint function specifed in the project bundle. If // unspecified, defaults to main(). // // Returns false if the engine couldn't be started. bool Run(); // Starts running the engine with the given entrypoint. If the empty string // is specified, defaults to the entrypoint function specified in the project // bundle, or main() if both are unspecified. // // Returns false if the engine couldn't be started or if conflicting, // non-default values are passed here and in the project bundle.. // // DEPRECATED: Prefer setting the entrypoint in the FlutterProjectBundle // passed to the constructor and calling the no-parameter overload. bool Run(std::string_view entrypoint); // Returns true if the engine is currently running. virtual bool running() const { return engine_ != nullptr; } // Stops the engine. This invalidates the pointer returned by engine(). // // Returns false if stopping the engine fails, or if it was not running. virtual bool Stop(); // Create a view that can display this engine's content. std::unique_ptr<FlutterWindowsView> CreateView( std::unique_ptr<WindowBindingHandler> window); // Get a view that displays this engine's content. // // Returns null if the view does not exist. FlutterWindowsView* view(FlutterViewId view_id) const; // Returns the currently configured Plugin Registrar. FlutterDesktopPluginRegistrarRef GetRegistrar(); // Registers |callback| to be called when the plugin registrar is destroyed. void AddPluginRegistrarDestructionCallback( FlutterDesktopOnPluginRegistrarDestroyed callback, FlutterDesktopPluginRegistrarRef registrar); // Sets switches member to the given switches. void SetSwitches(const std::vector<std::string>& switches); FlutterDesktopMessengerRef messenger() { return messenger_->ToRef(); } IncomingMessageDispatcher* message_dispatcher() { return message_dispatcher_.get(); } TaskRunner* task_runner() { return task_runner_.get(); } BinaryMessenger* messenger_wrapper() { return messenger_wrapper_.get(); } FlutterWindowsTextureRegistrar* texture_registrar() { return texture_registrar_.get(); } // The EGL manager object. If this is nullptr, then we are // rendering using software instead of OpenGL. egl::Manager* egl_manager() const { return egl_manager_.get(); } WindowProcDelegateManager* window_proc_delegate_manager() { return window_proc_delegate_manager_.get(); } // Informs the engine that the window metrics have changed. void SendWindowMetricsEvent(const FlutterWindowMetricsEvent& event); // Informs the engine of an incoming pointer event. void SendPointerEvent(const FlutterPointerEvent& event); // Informs the engine of an incoming key event. void SendKeyEvent(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* user_data); KeyboardHandlerBase* keyboard_key_handler() { return keyboard_key_handler_.get(); } TextInputPlugin* text_input_plugin() { return text_input_plugin_.get(); } // Sends the given message to the engine, calling |reply| with |user_data| // when a response is received from the engine if they are non-null. bool SendPlatformMessage(const char* channel, const uint8_t* message, const size_t message_size, const FlutterDesktopBinaryReply reply, void* user_data); // Sends the given data as the response to an earlier platform message. void SendPlatformMessageResponse( const FlutterDesktopMessageResponseHandle* handle, const uint8_t* data, size_t data_length); // Callback passed to Flutter engine for notifying window of platform // messages. void HandlePlatformMessage(const FlutterPlatformMessage*); // Informs the engine that the system font list has changed. void ReloadSystemFonts(); // Informs the engine that a new frame is needed to redraw the content. void ScheduleFrame(); // Set the callback that is called when the next frame is drawn. void SetNextFrameCallback(fml::closure callback); // Attempts to register the texture with the given |texture_id|. bool RegisterExternalTexture(int64_t texture_id); // Attempts to unregister the texture with the given |texture_id|. bool UnregisterExternalTexture(int64_t texture_id); // Notifies the engine about a new frame being available for the // given |texture_id|. bool MarkExternalTextureFrameAvailable(int64_t texture_id); // Posts the given callback onto the raster thread. virtual bool PostRasterThreadTask(fml::closure callback) const; // Invoke on the embedder's vsync callback to schedule a frame. void OnVsync(intptr_t baton); // Dispatches a semantics action to the specified semantics node. bool DispatchSemanticsAction(uint64_t id, FlutterSemanticsAction action, fml::MallocMapping data); // Informs the engine that the semantics enabled state has changed. void UpdateSemanticsEnabled(bool enabled); // Returns true if the semantics tree is enabled. bool semantics_enabled() const { return semantics_enabled_; } // Refresh accessibility features and send them to the engine. void UpdateAccessibilityFeatures(); // Refresh high contrast accessibility mode and notify the engine. void UpdateHighContrastMode(); // Returns true if the high contrast feature is enabled. bool high_contrast_enabled() const { return high_contrast_enabled_; } // Register a root isolate create callback. // // The root isolate create callback is invoked at creation of the root Dart // isolate in the app. This may be used to be notified that execution of the // main Dart entrypoint is about to begin, and is used by test infrastructure // to register a native function resolver that can register and resolve // functions marked as native in the Dart code. // // This must be called before calling |Run|. void SetRootIsolateCreateCallback(const fml::closure& callback) { root_isolate_create_callback_ = callback; } // Returns the executable name for this process or "Flutter" if unknown. std::string GetExecutableName() const; // Called when the application quits in response to a quit request. void OnQuit(std::optional<HWND> hwnd, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code); // Called when a WM_CLOSE message is received. void RequestApplicationQuit(HWND hwnd, WPARAM wparam, LPARAM lparam, AppExitType exit_type); // Called when a WM_DWMCOMPOSITIONCHANGED message is received. void OnDwmCompositionChanged(); // Called when a Window receives an event that may alter the application // lifecycle state. void OnWindowStateEvent(HWND hwnd, WindowStateEvent event); // Handle a message from a non-Flutter window in the same application. // Returns a result when the message is consumed and should not be processed // further. std::optional<LRESULT> ProcessExternalWindowMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); WindowsLifecycleManager* lifecycle_manager() { return lifecycle_manager_.get(); } std::shared_ptr<WindowsProcTable> windows_proc_table() { return windows_proc_table_; } protected: // Creates the keyboard key handler. // // Exposing this method allows unit tests to override in order to // capture information. virtual std::unique_ptr<KeyboardHandlerBase> CreateKeyboardKeyHandler( BinaryMessenger* messenger, KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state, KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan); // Creates the text input plugin. // // Exposing this method allows unit tests to override in order to // capture information. virtual std::unique_ptr<TextInputPlugin> CreateTextInputPlugin( BinaryMessenger* messenger); // Invoked by the engine right before the engine is restarted. // // This should reset necessary states to as if the engine has just been // created. This is typically caused by a hot restart (Shift-R in CLI.) void OnPreEngineRestart(); // Invoked by the engine when a listener is set or cleared on a platform // channel. virtual void OnChannelUpdate(std::string name, bool listening); private: // Allows swapping out embedder_api_ calls in tests. friend class EngineModifier; // Sends system locales to the engine. // // Should be called just after the engine is run, and after any relevant // system changes. void SendSystemLocales(); // Sends the current lifecycle state to the framework. void SetLifecycleState(flutter::AppLifecycleState state); // Create the keyboard & text input sub-systems. // // This requires that a view is attached to the engine. // Calling this method again resets the keyboard state. void InitializeKeyboard(); // Send the currently enabled accessibility features to the engine. void SendAccessibilityFeatures(); // The handle to the embedder.h engine instance. FLUTTER_API_SYMBOL(FlutterEngine) engine_ = nullptr; FlutterEngineProcTable embedder_api_ = {}; std::unique_ptr<FlutterProjectBundle> project_; // AOT data, if any. UniqueAotDataPtr aot_data_; // The views displaying the content running in this engine, if any. std::unordered_map<FlutterViewId, FlutterWindowsView*> views_; // Task runner for tasks posted from the engine. std::unique_ptr<TaskRunner> task_runner_; // The plugin messenger handle given to API clients. fml::RefPtr<flutter::FlutterDesktopMessenger> messenger_; // A wrapper around messenger_ for interacting with client_wrapper-level APIs. std::unique_ptr<BinaryMessengerImpl> messenger_wrapper_; // Message dispatch manager for messages from engine_. std::unique_ptr<IncomingMessageDispatcher> message_dispatcher_; // The plugin registrar handle given to API clients. std::unique_ptr<FlutterDesktopPluginRegistrar> plugin_registrar_; // The texture registrar. std::unique_ptr<FlutterWindowsTextureRegistrar> texture_registrar_; // An object used for intializing ANGLE and creating / destroying render // surfaces. If nullptr, ANGLE failed to initialize and software rendering // should be used instead. std::unique_ptr<egl::Manager> egl_manager_; // The compositor that creates backing stores for the engine to render into // and then presents them onto views. std::unique_ptr<Compositor> compositor_; // The plugin registrar managing internal plugins. std::unique_ptr<PluginRegistrar> internal_plugin_registrar_; // Handler for accessibility events. std::unique_ptr<AccessibilityPlugin> accessibility_plugin_; // Handler for cursor events. std::unique_ptr<CursorHandler> cursor_handler_; // Handler for the flutter/platform channel. std::unique_ptr<PlatformHandler> platform_handler_; // Handlers for keyboard events from Windows. std::unique_ptr<KeyboardHandlerBase> keyboard_key_handler_; // Handlers for text events from Windows. std::unique_ptr<TextInputPlugin> text_input_plugin_; // The settings plugin. std::unique_ptr<SettingsPlugin> settings_plugin_; // Callbacks to be called when the engine (and thus the plugin registrar) is // being destroyed. std::map<FlutterDesktopOnPluginRegistrarDestroyed, FlutterDesktopPluginRegistrarRef> plugin_registrar_destruction_callbacks_; // The approximate time between vblank events. std::chrono::nanoseconds FrameInterval(); // The start time used to align frames. std::chrono::nanoseconds start_time_ = std::chrono::nanoseconds::zero(); // An override of the frame interval used by EngineModifier for testing. std::optional<std::chrono::nanoseconds> frame_interval_override_ = std::nullopt; bool semantics_enabled_ = false; bool high_contrast_enabled_ = false; bool enable_impeller_ = false; // The manager for WindowProc delegate registration and callbacks. std::unique_ptr<WindowProcDelegateManager> window_proc_delegate_manager_; // The root isolate creation callback. fml::closure root_isolate_create_callback_; // The on frame drawn callback. fml::closure next_frame_callback_; // Handler for top level window messages. std::unique_ptr<WindowsLifecycleManager> lifecycle_manager_; std::shared_ptr<WindowsProcTable> windows_proc_table_; std::shared_ptr<egl::ProcTable> gl_; std::unique_ptr<PlatformViewPlugin> platform_view_plugin_; FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindowsEngine); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_ENGINE_H_
engine/shell/platform/windows/flutter_windows_engine.h/0
{ "file_path": "engine/shell/platform/windows/flutter_windows_engine.h", "repo_id": "engine", "token_count": 5328 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_EMBEDDER_HANDLER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_EMBEDDER_HANDLER_H_ #include <functional> #include <map> #include <memory> #include <string> #include "flutter/fml/macros.h" #include "flutter/shell/platform/embedder/embedder.h" #include "flutter/shell/platform/windows/keyboard_key_handler.h" namespace flutter { // Encode a 32-bit unicode code point into a UTF-8 byte array. // // See https://en.wikipedia.org/wiki/UTF-8#Encoding for the algorithm. std::string ConvertChar32ToUtf8(char32_t ch); // A delegate of |KeyboardKeyHandler| that handles events by sending // converted |FlutterKeyEvent|s through the embedder API. // // This class communicates with the HardwareKeyboard API in the framework. // // Every key event must result in at least one FlutterKeyEvent, even an empty // one (both logical and physical IDs are 0). This ensures that raw key // messages are always preceded by key data so that the transit mode is // correctly inferred. (Technically only the first key event needs so, but for // simplicity.) class KeyboardKeyEmbedderHandler : public KeyboardKeyHandler::KeyboardKeyHandlerDelegate { public: using SendEventHandler = std::function<void(const FlutterKeyEvent& /* event */, FlutterKeyEventCallback /* callback */, void* /* user_data */)>; using GetKeyStateHandler = std::function<SHORT(int /* nVirtKey */)>; using MapVirtualKeyToScanCode = std::function<SHORT(UINT /* nVirtKey */, bool /* extended */)>; // Build a KeyboardKeyEmbedderHandler. // // Use `send_event` to define how the class should dispatch converted // flutter events, as well as how to receive the response, to the engine. It's // typically FlutterWindowsEngine::SendKeyEvent. The 2nd and 3rd parameter // of the SendEventHandler call might be nullptr. // // Use `get_key_state` to define how the class should get a reliable result of // the state for a virtual key. It's typically Win32's GetKeyState, but can // also be nullptr (for UWP). // // Use `map_vk_to_scan` to define how the class should get map a virtual key // to a scan code. It's typically Win32's MapVirtualKey, but can also be // nullptr (for UWP). explicit KeyboardKeyEmbedderHandler(SendEventHandler send_event, GetKeyStateHandler get_key_state, MapVirtualKeyToScanCode map_vk_to_scan); virtual ~KeyboardKeyEmbedderHandler(); // |KeyboardHandlerBase| void KeyboardHook(int key, int scancode, int action, char32_t character, bool extended, bool was_down, std::function<void(bool)> callback) override; void SyncModifiersIfNeeded(int modifiers_state) override; std::map<uint64_t, uint64_t> GetPressedState() override; private: struct PendingResponse { std::function<void(bool, uint64_t)> callback; uint64_t response_id; }; // The information for a virtual key that's important enough that its // state is checked after every event. struct CriticalKey { // Last seen value of physical key and logical key for the virtual key. // // Used to synthesize down events. uint64_t physical_key; uint64_t logical_key; // Whether to ensure the pressing state of the key (usually for modifier // keys). bool check_pressed; // Whether to ensure the toggled state of the key (usually for lock keys). // // If this is true, `check_pressed` must be true. bool check_toggled; // Whether the lock key is currently toggled on. bool toggled_on; }; // Implements the core logic of |KeyboardHook|, leaving out some state // guards. void KeyboardHookImpl(int key, int scancode, int action, char32_t character, bool extended, bool was_down, std::function<void(bool)> callback); // Assign |critical_keys_| with basic information. void InitCriticalKeys(MapVirtualKeyToScanCode map_virtual_key_to_scan_code); // Update |critical_keys_| with last seen logical and physical key. void UpdateLastSeenCriticalKey(int virtual_key, uint64_t physical_key, uint64_t logical_key); // Check each key's state from |get_key_state_| and synthesize events // if their toggling states have been desynchronized. void SynchronizeCriticalToggledStates(int event_virtual_key, bool is_event_down, bool* event_key_can_be_repeat); // Check each key's state from |get_key_state_| and synthesize events // if their pressing states have been desynchronized. void SynchronizeCriticalPressedStates(int event_virtual_key, int event_physical_key, bool is_event_down, bool event_key_can_be_repeat); // Wraps perform_send_event_ with state tracking. Use this instead of // |perform_send_event_| to send events to the framework. void SendEvent(const FlutterKeyEvent& event, FlutterKeyEventCallback callback, void* user_data); // Send a synthesized down event and update pressing records. void SendSynthesizeDownEvent(uint64_t physical, uint64_t logical); // Send a synthesized up event and update pressing records. void SendSynthesizeUpEvent(uint64_t physical, uint64_t logical); // Send a synthesized up or down event depending on the current pressing // state. void SynthesizeIfNeeded(uint64_t physical_left, uint64_t physical_right, uint64_t logical_left, bool is_pressed); std::function<void(const FlutterKeyEvent&, FlutterKeyEventCallback, void*)> perform_send_event_; GetKeyStateHandler get_key_state_; // A map from physical keys to logical keys, each entry indicating a pressed // key. std::map<uint64_t, uint64_t> pressingRecords_; // Information for key events that have been sent to the framework but yet // to receive the response. Indexed by response IDs. std::map<uint64_t, std::unique_ptr<PendingResponse>> pending_responses_; // A self-incrementing integer, used as the ID for the next entry for // |pending_responses_|. uint64_t response_id_; // Whether any events has been sent with |PerformSendEvent| during a // |KeyboardHook|. bool sent_any_events; // Important keys whose states are checked and guaranteed synchronized // on every key event. // // The following maps map Win32 virtual key to the physical key and logical // key they're last seen. std::map<UINT, CriticalKey> critical_keys_; static uint64_t GetPhysicalKey(int scancode, bool extended); static uint64_t GetLogicalKey(int key, bool extended, int scancode); static void HandleResponse(bool handled, void* user_data); static void ConvertUtf32ToUtf8_(char* out, char32_t ch); static FlutterKeyEvent SynthesizeSimpleEvent(FlutterKeyEventType type, uint64_t physical, uint64_t logical, const char* character); static uint64_t ApplyPlaneToId(uint64_t id, uint64_t plane); static std::map<uint64_t, uint64_t> windowsToPhysicalMap_; static std::map<uint64_t, uint64_t> windowsToLogicalMap_; static std::map<uint64_t, uint64_t> scanCodeToLogicalMap_; // Mask for the 32-bit value portion of the key code. static const uint64_t valueMask; // The plane value for keys which have a Unicode representation. static const uint64_t unicodePlane; // The plane value for the private keys defined by the GTK embedding. static const uint64_t windowsPlane; FML_DISALLOW_COPY_AND_ASSIGN(KeyboardKeyEmbedderHandler); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_KEY_EMBEDDER_HANDLER_H_
engine/shell/platform/windows/keyboard_key_embedder_handler.h/0
{ "file_path": "engine/shell/platform/windows/keyboard_key_embedder_handler.h", "repo_id": "engine", "token_count": 3223 }
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/windows/platform_view_plugin.h" namespace flutter { PlatformViewPlugin::PlatformViewPlugin(BinaryMessenger* messenger, TaskRunner* task_runner) : PlatformViewManager(messenger), task_runner_(task_runner) {} PlatformViewPlugin::~PlatformViewPlugin() {} // TODO(schectman): Impelement platform view lookup. // https://github.com/flutter/flutter/issues/143375 std::optional<HWND> PlatformViewPlugin::GetNativeHandleForId( PlatformViewId id) const { return std::nullopt; } // TODO(schectman): Impelement platform view type registration. // https://github.com/flutter/flutter/issues/143375 void PlatformViewPlugin::RegisterPlatformViewType( std::string_view type_name, const FlutterPlatformViewTypeEntry& type) {} // TODO(schectman): Impelement platform view instantiation. // https://github.com/flutter/flutter/issues/143375 void PlatformViewPlugin::InstantiatePlatformView(PlatformViewId id) {} // TODO(schectman): Impelement platform view addition. // https://github.com/flutter/flutter/issues/143375 bool PlatformViewPlugin::AddPlatformView(PlatformViewId id, std::string_view type_name) { return true; } // TODO(schectman): Impelement platform view focus request. // https://github.com/flutter/flutter/issues/143375 bool PlatformViewPlugin::FocusPlatformView(PlatformViewId id, FocusChangeDirection direction, bool focus) { return true; } } // namespace flutter
engine/shell/platform/windows/platform_view_plugin.cc/0
{ "file_path": "engine/shell/platform/windows/platform_view_plugin.cc", "repo_id": "engine", "token_count": 644 }
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_WINDOWS_TASK_RUNNER_WINDOW_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TASK_RUNNER_WINDOW_H_ #include <windows.h> #include <chrono> #include <memory> #include <string> #include <vector> #include "flutter/fml/macros.h" namespace flutter { // Hidden HWND responsible for processing flutter tasks on main thread class TaskRunnerWindow { public: class Delegate { public: // Executes expired task, and returns the duration until the next task // deadline if exists, otherwise returns `std::chrono::nanoseconds::max()`. // // Each platform implementation must call this to schedule the tasks. virtual std::chrono::nanoseconds ProcessTasks() = 0; }; static std::shared_ptr<TaskRunnerWindow> GetSharedInstance(); // Triggers processing delegate tasks on main thread void WakeUp(); void AddDelegate(Delegate* delegate); void RemoveDelegate(Delegate* delegate); ~TaskRunnerWindow(); private: TaskRunnerWindow(); void ProcessTasks(); void SetTimer(std::chrono::nanoseconds when); WNDCLASS RegisterWindowClass(); LRESULT HandleMessage(UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; static LRESULT CALLBACK WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; HWND window_handle_; std::wstring window_class_name_; std::vector<Delegate*> delegates_; FML_DISALLOW_COPY_AND_ASSIGN(TaskRunnerWindow); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TASK_RUNNER_WINDOW_H_
engine/shell/platform/windows/task_runner_window.h/0
{ "file_path": "engine/shell/platform/windows/task_runner_window.h", "repo_id": "engine", "token_count": 695 }
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_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_DELEGATE_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_DELEGATE_H_ #include "flutter/fml/macros.h" #include "flutter/shell/platform/windows/window_binding_handler_delegate.h" #include "gmock/gmock.h" namespace flutter { namespace testing { class MockWindowBindingHandlerDelegate : public WindowBindingHandlerDelegate { public: MockWindowBindingHandlerDelegate() {} MOCK_METHOD(bool, OnWindowSizeChanged, (size_t, size_t), (override)); MOCK_METHOD(void, OnWindowRepaint, (), (override)); MOCK_METHOD(void, OnPointerMove, (double, double, FlutterPointerDeviceKind, int32_t, int), (override)); MOCK_METHOD(void, OnPointerDown, (double, double, FlutterPointerDeviceKind, int32_t, FlutterPointerMouseButtons), (override)); MOCK_METHOD(void, OnPointerUp, (double, double, FlutterPointerDeviceKind, int32_t, FlutterPointerMouseButtons), (override)); MOCK_METHOD(void, OnPointerLeave, (double, double, FlutterPointerDeviceKind, int32_t), (override)); MOCK_METHOD(void, OnPointerPanZoomStart, (int32_t), (override)); MOCK_METHOD(void, OnPointerPanZoomUpdate, (int32_t, double, double, double, double), (override)); MOCK_METHOD(void, OnPointerPanZoomEnd, (int32_t), (override)); MOCK_METHOD(void, OnText, (const std::u16string&), (override)); MOCK_METHOD(void, OnKey, (int, int, int, char32_t, bool, bool, KeyEventCallback), (override)); MOCK_METHOD(void, OnComposeBegin, (), (override)); MOCK_METHOD(void, OnComposeCommit, (), (override)); MOCK_METHOD(void, OnComposeEnd, (), (override)); MOCK_METHOD(void, OnComposeChange, (const std::u16string&, int), (override)); MOCK_METHOD(void, OnUpdateSemanticsEnabled, (bool), (override)); MOCK_METHOD(gfx::NativeViewAccessible, GetNativeViewAccessible, (), (override)); MOCK_METHOD( void, OnScroll, (double, double, double, double, int, FlutterPointerDeviceKind, int32_t), (override)); MOCK_METHOD(void, OnScrollInertiaCancel, (int32_t), (override)); MOCK_METHOD(void, OnHighContrastChanged, (), (override)); MOCK_METHOD(ui::AXFragmentRootDelegateWin*, GetAxFragmentRootDelegate, (), (override)); MOCK_METHOD(void, OnWindowStateEvent, (HWND, WindowStateEvent), (override)); private: FML_DISALLOW_COPY_AND_ASSIGN(MockWindowBindingHandlerDelegate); }; } // namespace testing } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_WINDOW_BINDING_HANDLER_DELEGATE_H_
engine/shell/platform/windows/testing/mock_window_binding_handler_delegate.h/0
{ "file_path": "engine/shell/platform/windows/testing/mock_window_binding_handler_delegate.h", "repo_id": "engine", "token_count": 1423 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TEXT_INPUT_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_TEXT_INPUT_MANAGER_H_ #include <Windows.h> #include <Windowsx.h> #include <optional> #include <string> #include "flutter/fml/macros.h" #include "flutter/shell/platform/common/geometry.h" namespace flutter { // Management interface for IME-based text input on Windows. // // When inputting text in CJK languages, text is entered via a multi-step // process, where direct keyboard input is buffered into a composing string, // which is then converted into the desired characters by selecting from a // candidates list and committing the change to the string. // // This implementation wraps the Win32 IMM32 APIs and provides a mechanism for // creating and positioning the IME window, a system caret, and the candidates // list as well as for accessing composing and results string contents. class TextInputManager { public: TextInputManager() noexcept = default; virtual ~TextInputManager() = default; // Sets the window handle with which the IME is associated. void SetWindowHandle(HWND window_handle); // Creates a new IME window and system caret. // // This method should be invoked in response to the WM_IME_SETCONTEXT and // WM_IME_STARTCOMPOSITION events. void CreateImeWindow(); // Destroys the current IME window and system caret. // // This method should be invoked in response to the WM_IME_ENDCOMPOSITION // event. void DestroyImeWindow(); // Updates the current IME window and system caret position. // // This method should be invoked when handling user input via // WM_IME_COMPOSITION events. void UpdateImeWindow(); // Updates the current IME window and system caret position. // // This method should be invoked when handling cursor position/size updates. void UpdateCaretRect(const Rect& rect); // Returns the cursor position relative to the start of the composing range. virtual long GetComposingCursorPosition() const; // Returns the contents of the composing string. // // This may be called in response to WM_IME_COMPOSITION events where the // GCS_COMPSTR flag is set in the lparam. In some IMEs, this string may also // be set in events where the GCS_RESULTSTR flag is set. This contains the // in-progress composing string. virtual std::optional<std::u16string> GetComposingString() const; // Returns the contents of the result string. // // This may be called in response to WM_IME_COMPOSITION events where the // GCS_RESULTSTR flag is set in the lparam. This contains the final string to // be committed in the composing region when composition is ended. virtual std::optional<std::u16string> GetResultString() const; /// Aborts IME composing. /// /// Aborts composing, closes the candidates window, and clears the contents /// of the composing string. void AbortComposing(); private: // Returns either the composing string or result string based on the value of // the |type| parameter. std::optional<std::u16string> GetString(int type) const; // Moves the IME composing and candidates windows to the current caret // position. void MoveImeWindow(HIMC imm_context); // The window with which the IME windows are associated. HWND window_handle_ = nullptr; // True if IME-based composing is active. bool ime_active_ = false; // The system caret rect. Rect caret_rect_ = {{0, 0}, {0, 0}}; FML_DISALLOW_COPY_AND_ASSIGN(TextInputManager); }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TEXT_INPUT_MANAGER_H_
engine/shell/platform/windows/text_input_manager.h/0
{ "file_path": "engine/shell/platform/windows/text_input_manager.h", "repo_id": "engine", "token_count": 1067 }
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. #ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWSX_SHIM_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWSX_SHIM_H_ // The Win32 platform header <windowsx.h> contains some macros for // common function names. To work around that, windowsx.h is not to be // included directly, and instead this file should be included. If one // of the removed Win32 macros is wanted, use the expanded form // manually instead. #ifdef _INC_WINDOWS_X #error "There is an include of windowsx.h in the code. Use windowsx_shim.h" #endif // _INC_WINDOWS_X #include <windowsx.h> #undef GetNextSibling // Same as GetWindow(hwnd, GW_HWNDNEXT) #undef GetFirstChild // Same as GetTopWindow(hwnd) #undef IsMaximized // Defined to IsZoomed, use IsZoomed directly instead #undef IsMinimized // Defined to IsIconic, use IsIconic directly instead #undef IsRestored // Macro to check that neither WS_MINIMIZE, nor // WS_MAXIMIZE is set in the GetWindowStyle return // value. #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWSX_SHIM_H_
engine/shell/platform/windows/windowsx_shim.h/0
{ "file_path": "engine/shell/platform/windows/windowsx_shim.h", "repo_id": "engine", "token_count": 437 }
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. // This is used to build an empty snapshot that can be used to start the VM service isolate. void main(List<String> args) {}
engine/shell/vmservice/empty.dart/0
{ "file_path": "engine/shell/vmservice/empty.dart", "repo_id": "engine", "token_count": 74 }
378
Flutter Engine ============== This package describes the dart:ui library, which is the interface between Dart and the Flutter Engine. This package also contains a number of Flutter shell binaries that let you run code that uses the dart:ui library on various platforms.
engine/sky/packages/sky_engine/README.md/0
{ "file_path": "engine/sky/packages/sky_engine/README.md", "repo_id": "engine", "token_count": 62 }
379
# Engine Testing This directory contains the infrastructure for running tests on the engine, which are most often run by Flutter's continuous integration (CI) systems. The tests themselves are located in other directories, closer to the source for each platform, language, and variant. For instance, macOS engine unit tests written in objective C are located in the same directory as the source files, but with a `Test` suffix added (e.g. "FlutterEngineTest.mm" holds the tests for "FlutterEngine.mm", and they are located in the same directory). ## Testing the Engine locally If you are working on the engine, you will want to be able to run tests locally. In order to learn the details of how do that, please consult the [Flutter Wiki page](https://github.com/flutter/flutter/wiki/Testing-the-engine) on the subject.
engine/testing/README.md/0
{ "file_path": "engine/testing/README.md", "repo_id": "engine", "token_count": 202 }
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. #ifndef FLUTTER_TESTING_AUTORELEASEPOOL_TEST_H_ #define FLUTTER_TESTING_AUTORELEASEPOOL_TEST_H_ #include "flutter/fml/platform/darwin/scoped_nsautorelease_pool.h" #include "gtest/gtest.h" namespace flutter::testing { // GoogleTest mixin that runs the test within the scope of an NSAutoReleasePool. // // This can be mixed into test fixture classes that also inherit from gtest's // ::testing::Test base class. class AutoreleasePoolTestMixin { public: AutoreleasePoolTestMixin() = default; ~AutoreleasePoolTestMixin() = default; private: fml::ScopedNSAutoreleasePool autorelease_pool_; FML_DISALLOW_COPY_AND_ASSIGN(AutoreleasePoolTestMixin); }; // GoogleTest fixture that runs the test within the scope of an // NSAutoReleasePool. class AutoreleasePoolTest : public ::testing::Test, public AutoreleasePoolTestMixin { public: AutoreleasePoolTest() = default; ~AutoreleasePoolTest() = default; private: fml::ScopedNSAutoreleasePool autorelease_pool_; FML_DISALLOW_COPY_AND_ASSIGN(AutoreleasePoolTest); }; } // namespace flutter::testing #endif // FLUTTER_TESTING_AUTORELEASEPOOL_TEST_H_
engine/testing/autoreleasepool_test.h/0
{ "file_path": "engine/testing/autoreleasepool_test.h", "repo_id": "engine", "token_count": 459 }
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. // KEEP THIS SYNCHRONIZED WITH ../../lib/web_ui/test/channel_buffers_test.dart import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:litetest/litetest.dart'; ByteData _makeByteData(String str) { final Uint8List list = utf8.encode(str); final ByteBuffer buffer = list.buffer; return ByteData.view(buffer); } void _resize(ui.ChannelBuffers buffers, String name, int newSize) { buffers.handleMessage(_makeByteData('resize\r$name\r$newSize')); } void main() { bool assertsEnabled = false; assert(() { assertsEnabled = true; return true; }()); test('push drain', () async { const String channel = 'foo'; final ByteData data = _makeByteData('bar'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); bool called = false; void callback(ByteData? responseData) { called = true; } buffers.push(channel, data, callback); // Ignoring the deprecated member use because we're specifically testing // deprecated API. // ignore: deprecated_member_use await buffers.drain(channel, (ByteData? drainedData, ui.PlatformMessageResponseCallback drainedCallback) async { expect(drainedData, equals(data)); expect(called, isFalse); drainedCallback(drainedData); expect(called, isTrue); }); }); test('drain is sync', () async { const String channel = 'foo'; final ByteData data = _makeByteData('message'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); void callback(ByteData? responseData) {} buffers.push(channel, data, callback); final List<String> log = <String>[]; final Completer<void> completer = Completer<void>(); scheduleMicrotask(() { log.add('before drain, microtask'); }); log.add('before drain'); // Ignoring the returned future because the completion of the drain is // communicated using the `completer`. // Ignoring the deprecated member use because we're specifically testing // deprecated API. // ignore: deprecated_member_use buffers.drain(channel, (ByteData? drainedData, ui.PlatformMessageResponseCallback drainedCallback) async { log.add('callback'); completer.complete(); }); log.add('after drain, before await'); await completer.future; log.add('after await'); expect(log, <String>[ 'before drain', 'callback', 'after drain, before await', 'before drain, microtask', 'after await' ]); }); test('push drain zero', () async { const String channel = 'foo'; final ByteData data = _makeByteData('bar'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); void callback(ByteData? responseData) {} _resize(buffers, channel, 0); buffers.push(channel, data, callback); bool didCall = false; // Ignoring the deprecated member use because we're specifically testing // deprecated API. // ignore: deprecated_member_use await buffers.drain(channel, (ByteData? drainedData, ui.PlatformMessageResponseCallback drainedCallback) async { didCall = true; }); expect(didCall, equals(false)); }); test('drain when empty', () async { const String channel = 'foo'; final ui.ChannelBuffers buffers = ui.ChannelBuffers(); bool didCall = false; // Ignoring the deprecated member use because we're specifically testing // deprecated API. // ignore: deprecated_member_use await buffers.drain(channel, (ByteData? drainedData, ui.PlatformMessageResponseCallback drainedCallback) async { didCall = true; }); expect(didCall, equals(false)); }); test('overflow', () async { const String channel = 'foo'; final ByteData one = _makeByteData('one'); final ByteData two = _makeByteData('two'); final ByteData three = _makeByteData('three'); final ByteData four = _makeByteData('four'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); void callback(ByteData? responseData) {} _resize(buffers, channel, 3); buffers.push(channel, one, callback); buffers.push(channel, two, callback); buffers.push(channel, three, callback); buffers.push(channel, four, callback); int counter = 0; // Ignoring the deprecated member use because we're specifically testing // deprecated API. // ignore: deprecated_member_use await buffers.drain(channel, (ByteData? drainedData, ui.PlatformMessageResponseCallback drainedCallback) async { switch (counter) { case 0: expect(drainedData, equals(two)); case 1: expect(drainedData, equals(three)); case 2: expect(drainedData, equals(four)); } counter += 1; }); expect(counter, equals(3)); }); test('resize drop', () async { const String channel = 'foo'; final ByteData one = _makeByteData('one'); final ByteData two = _makeByteData('two'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); _resize(buffers, channel, 100); void callback(ByteData? responseData) {} buffers.push(channel, one, callback); buffers.push(channel, two, callback); _resize(buffers, channel, 1); int counter = 0; // Ignoring the deprecated member use because we're specifically testing // deprecated API. // ignore: deprecated_member_use await buffers.drain(channel, (ByteData? drainedData, ui.PlatformMessageResponseCallback drainedCallback) async { switch (counter) { case 0: expect(drainedData, equals(two)); } counter += 1; }); expect(counter, equals(1)); }); test('resize dropping calls callback', () async { const String channel = 'foo'; final ByteData one = _makeByteData('one'); final ByteData two = _makeByteData('two'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); bool didCallCallback = false; void oneCallback(ByteData? responseData) { expect(responseData, isNull); didCallCallback = true; } void twoCallback(ByteData? responseData) { fail('wrong callback called'); } _resize(buffers, channel, 100); buffers.push(channel, one, oneCallback); buffers.push(channel, two, twoCallback); expect(didCallCallback, equals(false)); _resize(buffers, channel, 1); expect(didCallCallback, equals(true)); }); test('overflow calls callback', () async { const String channel = 'foo'; final ByteData one = _makeByteData('one'); final ByteData two = _makeByteData('two'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); bool didCallCallback = false; void oneCallback(ByteData? responseData) { expect(responseData, isNull); didCallCallback = true; } void twoCallback(ByteData? responseData) { fail('wrong callback called'); } _resize(buffers, channel, 1); buffers.push(channel, one, oneCallback); buffers.push(channel, two, twoCallback); expect(didCallCallback, equals(true)); }); test('handle garbage', () async { final ui.ChannelBuffers buffers = ui.ChannelBuffers(); expect(() => buffers.handleMessage(_makeByteData('asdfasdf')), throwsException); }); test('handle resize garbage', () async { final ui.ChannelBuffers buffers = ui.ChannelBuffers(); expect(() => buffers.handleMessage(_makeByteData('resize\rfoo\rbar')), throwsException); }); test('ChannelBuffers.setListener', () async { final List<String> log = <String>[]; final ui.ChannelBuffers buffers = ui.ChannelBuffers(); final ByteData one = _makeByteData('one'); final ByteData two = _makeByteData('two'); final ByteData three = _makeByteData('three'); final ByteData four = _makeByteData('four'); final ByteData five = _makeByteData('five'); final ByteData six = _makeByteData('six'); final ByteData seven = _makeByteData('seven'); buffers.push('a', one, (ByteData? data) { }); buffers.push('b', two, (ByteData? data) { }); buffers.push('a', three, (ByteData? data) { }); log.add('top'); buffers.setListener('a', (ByteData? data, ui.PlatformMessageResponseCallback callback) { expect(data, isNotNull); log.add('a1: ${utf8.decode(data!.buffer.asUint8List())}'); }); log.add('-1'); await null; log.add('-2'); buffers.setListener('a', (ByteData? data, ui.PlatformMessageResponseCallback callback) { expect(data, isNotNull); log.add('a2: ${utf8.decode(data!.buffer.asUint8List())}'); }); log.add('-3'); await null; log.add('-4'); buffers.setListener('b', (ByteData? data, ui.PlatformMessageResponseCallback callback) { expect(data, isNotNull); log.add('b: ${utf8.decode(data!.buffer.asUint8List())}'); }); log.add('-5'); await null; // first microtask after setting listener drains the first message await null; // second microtask ends the draining. log.add('-6'); buffers.push('b', four, (ByteData? data) { }); buffers.push('a', five, (ByteData? data) { }); log.add('-7'); await null; log.add('-8'); buffers.clearListener('a'); buffers.push('a', six, (ByteData? data) { }); buffers.push('b', seven, (ByteData? data) { }); await null; log.add('-9'); expect(log, <String>[ 'top', '-1', 'a1: three', '-2', '-3', '-4', '-5', 'b: two', '-6', 'b: four', 'a2: five', '-7', '-8', 'b: seven', '-9', ]); }); test('ChannelBuffers.clearListener', () async { final List<String> log = <String>[]; final ui.ChannelBuffers buffers = ui.ChannelBuffers(); final ByteData one = _makeByteData('one'); final ByteData two = _makeByteData('two'); final ByteData three = _makeByteData('three'); final ByteData four = _makeByteData('four'); buffers.handleMessage(_makeByteData('resize\ra\r10')); buffers.push('a', one, (ByteData? data) { }); buffers.push('a', two, (ByteData? data) { }); buffers.push('a', three, (ByteData? data) { }); log.add('-1'); buffers.setListener('a', (ByteData? data, ui.PlatformMessageResponseCallback callback) { expect(data, isNotNull); log.add('a1: ${utf8.decode(data!.buffer.asUint8List())}'); }); await null; // handles one log.add('-2'); buffers.clearListener('a'); await null; log.add('-3'); buffers.setListener('a', (ByteData? data, ui.PlatformMessageResponseCallback callback) { expect(data, isNotNull); log.add('a2: ${utf8.decode(data!.buffer.asUint8List())}'); }); log.add('-4'); await null; buffers.push('a', four, (ByteData? data) { }); log.add('-5'); await null; log.add('-6'); await null; log.add('-7'); await null; expect(log, <String>[ '-1', 'a1: one', '-2', '-3', '-4', 'a2: two', '-5', 'a2: three', '-6', 'a2: four', '-7', ]); }); test('ChannelBuffers.handleMessage for resize', () async { final List<String> log = <String>[]; final ui.ChannelBuffers buffers = _TestChannelBuffers(log); // Created as follows: // print(StandardMethodCodec().encodeMethodCall(MethodCall('resize', ['abcdef', 12345])).buffer.asUint8List()); // ...with three 0xFF bytes on either side to ensure the method works with an offset on the underlying buffer. buffers.handleMessage(ByteData.sublistView(Uint8List.fromList(<int>[255, 255, 255, 7, 6, 114, 101, 115, 105, 122, 101, 12, 2, 7, 6, 97, 98, 99, 100, 101, 102, 3, 57, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255]), 3, 27)); expect(log, const <String>['resize abcdef 12345']); }); test('ChannelBuffers.handleMessage for overflow', () async { final List<String> log = <String>[]; final ui.ChannelBuffers buffers = _TestChannelBuffers(log); // Created as follows: // print(StandardMethodCodec().encodeMethodCall(MethodCall('overflow', ['abcdef', false])).buffer.asUint8List()); // ...with three 0xFF bytes on either side to ensure the method works with an offset on the underlying buffer. buffers.handleMessage(ByteData.sublistView(Uint8List.fromList(<int>[255, 255, 255, 7, 8, 111, 118, 101, 114, 102, 108, 111, 119, 12, 2, 7, 6, 97, 98, 99, 100, 101, 102, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255]), 3, 24)); expect(log, const <String>['allowOverflow abcdef false']); }); test('ChannelBuffers uses the right zones', () async { final List<String> log = <String>[]; final ui.ChannelBuffers buffers = ui.ChannelBuffers(); final Zone zone1 = Zone.current.fork(); final Zone zone2 = Zone.current.fork(); zone1.run(() { log.add('first zone run: ${Zone.current == zone1}'); buffers.setListener('a', (ByteData? data, ui.PlatformMessageResponseCallback callback) { log.add('callback1: ${Zone.current == zone1}'); callback(data); }); }); zone2.run(() { log.add('second zone run: ${Zone.current == zone2}'); buffers.push('a', ByteData.sublistView(Uint8List.fromList(<int>[]), 0, 0), (ByteData? data) { log.add('callback2: ${Zone.current == zone2}'); }); }); await null; expect(log, <String>[ 'first zone run: true', 'second zone run: true', 'callback1: true', 'callback2: true', ]); }); test('ChannelBufferspush rejects names with nulls', () async { const String channel = 'foo\u0000bar'; final ByteData blabla = _makeByteData('blabla'); final ui.ChannelBuffers buffers = ui.ChannelBuffers(); try { buffers.push(channel, blabla, (ByteData? data) { }); fail('did not throw as expected'); } on AssertionError catch (e) { expect(e.toString(), contains('U+0000 NULL')); } try { buffers.setListener(channel, (ByteData? data, ui.PlatformMessageResponseCallback callback) { }); fail('did not throw as expected'); } on AssertionError catch (e) { expect(e.toString(), contains('U+0000 NULL')); } }, skip: !assertsEnabled); } class _TestChannelBuffers extends ui.ChannelBuffers { _TestChannelBuffers(this.log); final List<String> log; @override void resize(String name, int newSize) { log.add('resize $name $newSize'); } @override void allowOverflow(String name, bool allowed) { log.add('allowOverflow $name $allowed'); } }
engine/testing/dart/channel_buffers_test.dart/0
{ "file_path": "engine/testing/dart/channel_buffers_test.dart", "repo_id": "engine", "token_count": 5415 }
382
// Copyright 2019 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:litetest/litetest.dart'; import 'package:path/path.dart' as path; void main() { bool assertsEnabled = false; assert(() { assertsEnabled = true; return true; }()); test('Handles are distinct', () async { final Uint8List bytes = await _readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes); final FrameInfo frame = await codec.getNextFrame(); expect(frame.image.width, 2); expect(frame.image.height, 2); final Image handle1 = frame.image.clone(); expect(handle1.width, frame.image.width); expect(handle1.height, frame.image.height); final Image handle2 = handle1.clone(); expect(handle1 != handle2, true); expect(handle1 != frame.image, true); expect(frame.image == frame.image, true); frame.image.dispose(); }); test('Canvas can paint image from handle and byte data from handle', () async { final Uint8List bytes = await _readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes); final FrameInfo frame = await codec.getNextFrame(); expect(frame.image.width, 2); expect(frame.image.height, 2); final Image handle1 = frame.image.clone(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); const Rect rect = Rect.fromLTRB(0, 0, 2, 2); canvas.drawImage(handle1, Offset.zero, Paint()); canvas.drawImageRect(handle1, rect, rect, Paint()); canvas.drawImageNine(handle1, rect, rect, Paint()); canvas.drawAtlas(handle1, <RSTransform>[], <Rect>[], <Color>[], BlendMode.src, rect, Paint()); canvas.drawRawAtlas(handle1, Float32List(0), Float32List(0), Int32List(0), BlendMode.src, rect, Paint()); final Picture picture = recorder.endRecording(); final Image rasterizedImage = await picture.toImage(2, 2); final ByteData sourceData = (await frame.image.toByteData())!; final ByteData handleData = (await handle1.toByteData())!; final ByteData rasterizedData = (await rasterizedImage.toByteData())!; expect(sourceData.buffer.asUint8List(), equals(handleData.buffer.asUint8List())); expect(sourceData.buffer.asUint8List(), equals(rasterizedData.buffer.asUint8List())); }); test('Records stack traces', () async { final Uint8List bytes = await _readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes); final FrameInfo frame = await codec.getNextFrame(); final Image handle1 = frame.image.clone(); final Image handle2 = handle1.clone(); List<StackTrace> stackTraces = frame.image.debugGetOpenHandleStackTraces()!; expect(stackTraces.length, 3); expect(stackTraces, equals(handle1.debugGetOpenHandleStackTraces())); handle1.dispose(); stackTraces = frame.image.debugGetOpenHandleStackTraces()!; expect(stackTraces.length, 2); expect(stackTraces, equals(handle2.debugGetOpenHandleStackTraces())); handle2.dispose(); stackTraces = frame.image.debugGetOpenHandleStackTraces()!; expect(stackTraces.length, 1); expect(stackTraces, equals(frame.image.debugGetOpenHandleStackTraces())); frame.image.dispose(); expect(frame.image.debugGetOpenHandleStackTraces(), isEmpty); }, skip: !assertsEnabled); test('Clones can be compared', () async { final Uint8List bytes = await _readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes); final FrameInfo frame = await codec.getNextFrame(); final Image handle1 = frame.image.clone(); final Image handle2 = handle1.clone(); expect(handle1.isCloneOf(handle2), true); expect(handle2.isCloneOf(handle1), true); expect(handle1.isCloneOf(frame.image), true); handle1.dispose(); expect(handle1.isCloneOf(handle2), true); expect(handle2.isCloneOf(handle1), true); expect(handle1.isCloneOf(frame.image), true); final Codec codec2 = await instantiateImageCodec(bytes); final FrameInfo frame2 = await codec2.getNextFrame(); expect(frame2.image.isCloneOf(frame.image), false); }); test('debugDisposed works', () async { final Uint8List bytes = await _readFile('2x2.png'); final Codec codec = await instantiateImageCodec(bytes); final FrameInfo frame = await codec.getNextFrame(); if (assertsEnabled) { expect(frame.image.debugDisposed, false); } else { expect(() => frame.image.debugDisposed, throwsStateError); } frame.image.dispose(); if (assertsEnabled) { expect(frame.image.debugDisposed, true); } else { expect(() => frame.image.debugDisposed, throwsStateError); } }); } Future<Uint8List> _readFile(String fileName) async { final File file = File(path.join( 'flutter', 'testing', 'resources', fileName, )); return file.readAsBytes(); }
engine/testing/dart/image_dispose_test.dart/0
{ "file_path": "engine/testing/dart/image_dispose_test.dart", "repo_id": "engine", "token_count": 1748 }
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. import 'dart:async'; import 'dart:convert' show base64Decode; import 'dart:developer' as developer; import 'dart:ui'; import 'package:litetest/litetest.dart'; import 'package:vm_service/vm_service.dart' as vms; import 'package:vm_service/vm_service_io.dart'; import 'package:vm_service_protos/vm_service_protos.dart'; import '../impeller_enabled.dart'; Future<void> _testChromeFormatTrace(vms.VmService vmService) async { final vms.Timeline timeline = await vmService.getVMTimeline(); int saveLayerRecordCount = 0; int saveLayerCount = 0; // int flowEventCount = 0; for (final vms.TimelineEvent event in timeline.traceEvents!) { final Map<String, dynamic> json = event.json!; if (json['ph'] == 'B') { if (json['name'] == 'ui.Canvas::saveLayer (Recorded)') { saveLayerRecordCount += 1; } if (json['name'] == 'Canvas::saveLayer') { saveLayerCount += 1; } } // else if (json['ph'] == 's' || json['ph'] == 't' || json['ph'] == 'f') { // flowEventCount += 1; // } } expect(saveLayerRecordCount, 3); expect(saveLayerCount, impellerEnabled ? 2 : 3); // TODO(derekxu16): Deflake https://github.com/flutter/flutter/issues/144394 // expect(flowEventCount, 5); } Future<void> _testPerfettoFormatTrace(vms.VmService vmService) async { final vms.PerfettoTimeline response = await vmService.getPerfettoVMTimeline(); final List<TracePacket> packets = Trace.fromBuffer(base64Decode(response.trace!)).packet; final Iterable<TrackEvent> events = packets .where((TracePacket packet) => packet.hasTrackEvent()) .map((TracePacket packet) => packet.trackEvent); int saveLayerRecordCount = 0; int saveLayerCount = 0; // int flowIdCount = 0; for (final TrackEvent event in events) { if (event.type == TrackEvent_Type.TYPE_SLICE_BEGIN) { if (event.name == 'ui.Canvas::saveLayer (Recorded)') { saveLayerRecordCount += 1; } if (event.name == 'Canvas::saveLayer') { saveLayerCount += 1; } // flowIdCount += event.flowIds.length; } } expect(saveLayerRecordCount, 3); expect(saveLayerCount, impellerEnabled ? 2 : 3); // TODO(derekxu16): Deflake https://github.com/flutter/flutter/issues/144394 // expect(flowIdCount, 5); } void main() { test('Canvas.saveLayer emits tracing', () async { final developer.ServiceProtocolInfo info = await developer.Service.getInfo(); if (info.serverUri == null) { fail('This test must not be run with --disable-vm-service.'); } final vms.VmService vmService = await vmServiceConnectUri( 'ws://localhost:${info.serverUri!.port}${info.serverUri!.path}ws', ); final Completer<void> completer = Completer<void>(); PlatformDispatcher.instance.onBeginFrame = (Duration timeStamp) async { final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawColor(const Color(0xff0000ff), BlendMode.srcOut); // Will saveLayer implicitly for Skia, but not Impeller. canvas.drawPaint(Paint()..imageFilter = ImageFilter.blur(sigmaX: 2, sigmaY: 3)); canvas.saveLayer(null, Paint()); canvas.drawRect(const Rect.fromLTRB(10, 10, 20, 20), Paint()); canvas.saveLayer(const Rect.fromLTWH(0, 0, 100, 100), Paint()); canvas.drawRect(const Rect.fromLTRB(10, 10, 20, 20), Paint()); canvas.drawRect(const Rect.fromLTRB(15, 15, 25, 25), Paint()); canvas.restore(); canvas.restore(); final Picture picture = recorder.endRecording(); final SceneBuilder builder = SceneBuilder(); builder.addPicture(Offset.zero, picture); final Scene scene = builder.build(); await scene.toImage(100, 100); scene.dispose(); completer.complete(); }; PlatformDispatcher.instance.scheduleFrame(); await completer.future; await _testChromeFormatTrace(vmService); await _testPerfettoFormatTrace(vmService); await vmService.dispose(); }); }
engine/testing/dart/observatory/tracing_test.dart/0
{ "file_path": "engine/testing/dart/observatory/tracing_test.dart", "repo_id": "engine", "token_count": 1552 }
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/testing/fixture_test.h" #include <utility> #include "flutter/testing/dart_fixture.h" namespace flutter { namespace testing { FixtureTest::FixtureTest() : DartFixture() {} FixtureTest::FixtureTest(std::string kernel_filename, std::string elf_filename, std::string elf_split_filename) : DartFixture(std::move(kernel_filename), std::move(elf_filename), std::move(elf_split_filename)) {} } // namespace testing } // namespace flutter
engine/testing/fixture_test.cc/0
{ "file_path": "engine/testing/fixture_test.cc", "repo_id": "engine", "token_count": 281 }
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. extern "C" { int RunBenchmarks(int argc, char** argv); } int main(int argc, char* argv[]) { return RunBenchmarks(argc, argv); }
engine/testing/ios/IosBenchmarks/IosBenchmarks/main.mm/0
{ "file_path": "engine/testing/ios/IosBenchmarks/IosBenchmarks/main.mm", "repo_id": "engine", "token_count": 96 }
386
FLUTTER_ENGINE[arch=x86_64]=ios_debug_sim_unopt FLUTTER_ENGINE[arch=arm64]=ios_debug_sim_unopt_arm64 FLUTTER_ENGINE=ios_debug_sim_unopt_arm64
engine/testing/ios/IosUnitTests/Tests/FlutterEngineConfig.xcconfig/0
{ "file_path": "engine/testing/ios/IosUnitTests/Tests/FlutterEngineConfig.xcconfig", "repo_id": "engine", "token_count": 66 }
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. #ifndef FLUTTER_TESTING_POST_TASK_SYNC_H_ #define FLUTTER_TESTING_POST_TASK_SYNC_H_ #include "flutter/fml/task_runner.h" namespace flutter { namespace testing { void PostTaskSync(const fml::RefPtr<fml::TaskRunner>& task_runner, const std::function<void()>& function); } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_POST_TASK_SYNC_H_
engine/testing/post_task_sync.h/0
{ "file_path": "engine/testing/post_task_sync.h", "repo_id": "engine", "token_count": 208 }
388
#!/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. """ A top level harness to run all unit-tests in a specific engine build. """ from pathlib import Path import argparse import errno import glob import logging import logging.handlers import multiprocessing import os import re import shutil import subprocess # Explicitly import the parts of sys that are needed. This is to avoid using # sys.stdout and sys.stderr directly. Instead, only the logger defined below # should be used for output. from sys import exit as sys_exit, platform as sys_platform import tempfile import time import typing import xvfb SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) BUILDROOT_DIR = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..')) OUT_DIR = os.path.join(BUILDROOT_DIR, 'out') GOLDEN_DIR = os.path.join(BUILDROOT_DIR, 'flutter', 'testing', 'resources') FONTS_DIR = os.path.join(BUILDROOT_DIR, 'flutter', 'third_party', 'txt', 'third_party', 'fonts') ROBOTO_FONT_PATH = os.path.join(FONTS_DIR, 'Roboto-Regular.ttf') FONT_SUBSET_DIR = os.path.join(BUILDROOT_DIR, 'flutter', 'tools', 'font_subset') ENCODING = 'UTF-8' LOG_FILE = os.path.join(OUT_DIR, 'run_tests.log') logger = logging.getLogger(__name__) console_logger_handler = logging.StreamHandler() file_logger_handler = logging.FileHandler(LOG_FILE) # Override print so that it uses the logger instead of stdout directly. def print(*args, **kwargs): # pylint: disable=redefined-builtin logger.info(*args, **kwargs) def print_divider(char='='): logger.info('\n') for _ in range(4): logger.info(''.join([char for _ in range(80)])) logger.info('\n') def is_asan(build_dir): with open(os.path.join(build_dir, 'args.gn')) as args: if 'is_asan = true' in args.read(): return True return False def run_cmd( cmd: typing.List[str], forbidden_output: typing.List[str] = None, expect_failure: bool = False, env: typing.Dict[str, str] = None, allowed_failure_output: typing.List[str] = None, **kwargs ) -> None: if forbidden_output is None: forbidden_output = [] if allowed_failure_output is None: allowed_failure_output = [] command_string = ' '.join(cmd) print_divider('>') logger.info('Running command "%s"', command_string) start_time = time.time() process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, universal_newlines=True, **kwargs ) output = '' for line in iter(process.stdout.readline, ''): output += line logger.info(line.rstrip()) process.wait() end_time = time.time() if process.returncode != 0 and not expect_failure: print_divider('!') logger.error( 'Failed Command:\n\n%s\n\nExit Code: %s\n\nOutput:\n%s', command_string, process.returncode, output ) print_divider('!') allowed_failure = False for allowed_string in allowed_failure_output: if allowed_string in output: allowed_failure = True if not allowed_failure: raise RuntimeError('Command "%s" exited with code %s.' % (command_string, process.returncode)) for forbidden_string in forbidden_output: if forbidden_string in output: raise RuntimeError( 'command "%s" contained forbidden string "%s"' % (command_string, forbidden_string) ) print_divider('<') logger.info('Command run successfully in %.2f seconds: %s', end_time - start_time, command_string) def is_mac(): return sys_platform == 'darwin' def is_aarm64(): assert is_mac() output = subprocess.check_output(['sysctl', 'machdep.cpu']) text = output.decode('utf-8') aarm64 = text.find('Apple') >= 0 if not aarm64: assert text.find('GenuineIntel') >= 0 return aarm64 def is_linux(): return sys_platform.startswith('linux') def is_windows(): return sys_platform.startswith(('cygwin', 'win')) def executable_suffix(): return '.exe' if is_windows() else '' def find_executable_path(path): if os.path.exists(path): return path if is_windows(): exe_path = path + '.exe' if os.path.exists(exe_path): return exe_path bat_path = path + '.bat' if os.path.exists(bat_path): return bat_path raise Exception('Executable %s does not exist!' % path) def vulkan_validation_env(build_dir): extra_env = { # pylint: disable=line-too-long # Note: built from //third_party/swiftshader 'VK_ICD_FILENAMES': os.path.join(build_dir, 'vk_swiftshader_icd.json'), # Note: built from //third_party/vulkan_validation_layers:vulkan_gen_json_files # and //third_party/vulkan_validation_layers. 'VK_LAYER_PATH': os.path.join(build_dir, 'vulkan-data'), 'VK_INSTANCE_LAYERS': 'VK_LAYER_KHRONOS_validation', } return extra_env def metal_validation_env(): extra_env = { # pylint: disable=line-too-long # See https://developer.apple.com/documentation/metal/diagnosing_metal_programming_issues_early?language=objc 'MTL_SHADER_VALIDATION': '1', # Enables all shader validation tests. 'MTL_SHADER_VALIDATION_GLOBAL_MEMORY': '1', # Validates accesses to device and constant memory. 'MTL_SHADER_VALIDATION_THREADGROUP_MEMORY': '1', # Validates accesses to threadgroup memory. 'MTL_SHADER_VALIDATION_TEXTURE_USAGE': '1', # Validates that texture references are not nil. } if is_aarm64(): extra_env.update({ 'METAL_DEBUG_ERROR_MODE': '0', # Enables metal validation. 'METAL_DEVICE_WRAPPER_TYPE': '1', # Enables metal validation. }) return extra_env def build_engine_executable_command( build_dir, executable_name, flags=None, coverage=False, gtest=False ): if flags is None: flags = [] unstripped_exe = os.path.join(build_dir, 'exe.unstripped', executable_name) # We cannot run the unstripped binaries directly when coverage is enabled. if is_linux() and os.path.exists(unstripped_exe) and not coverage: # Use unstripped executables in order to get better symbolized crash # stack traces on Linux. executable = unstripped_exe else: executable = find_executable_path(os.path.join(build_dir, executable_name)) coverage_script = os.path.join(BUILDROOT_DIR, 'flutter', 'build', 'generate_coverage.py') if coverage: coverage_flags = [ '-t', executable, '-o', os.path.join(build_dir, 'coverage', executable_name), '-f', 'html' ] updated_flags = ['--args=%s' % ' '.join(flags)] test_command = [coverage_script] + coverage_flags + updated_flags else: test_command = [executable] + flags if gtest: gtest_parallel = os.path.join( BUILDROOT_DIR, 'flutter', 'third_party', 'gtest-parallel', 'gtest-parallel' ) test_command = ['python3', gtest_parallel] + test_command return test_command def run_engine_executable( # pylint: disable=too-many-arguments build_dir, executable_name, executable_filter, flags=None, cwd=BUILDROOT_DIR, forbidden_output=None, allowed_failure_output=None, expect_failure=False, coverage=False, extra_env=None, gtest=False, ): if executable_filter is not None and executable_name not in executable_filter: logger.info('Skipping %s due to filter.', executable_name) return if flags is None: flags = [] if forbidden_output is None: forbidden_output = [] if allowed_failure_output is None: allowed_failure_output = [] if extra_env is None: extra_env = {} unstripped_exe = os.path.join(build_dir, 'exe.unstripped', executable_name) env = os.environ.copy() if is_linux(): env['LD_LIBRARY_PATH'] = build_dir env['VK_DRIVER_FILES'] = os.path.join(build_dir, 'vk_swiftshader_icd.json') if os.path.exists(unstripped_exe): unstripped_vulkan = os.path.join(build_dir, 'lib.unstripped', 'libvulkan.so.1') if os.path.exists(unstripped_vulkan): vulkan_path = unstripped_vulkan else: vulkan_path = os.path.join(build_dir, 'libvulkan.so.1') try: os.symlink(vulkan_path, os.path.join(build_dir, 'exe.unstripped', 'libvulkan.so.1')) except OSError as err: if err.errno == errno.EEXIST: pass else: raise elif is_mac(): env['DYLD_LIBRARY_PATH'] = build_dir else: env['PATH'] = build_dir + ':' + env['PATH'] logger.info('Running %s in %s', executable_name, cwd) test_command = build_engine_executable_command( build_dir, executable_name, flags=flags, coverage=coverage, gtest=gtest, ) env['FLUTTER_BUILD_DIRECTORY'] = build_dir for key, value in extra_env.items(): env[key] = value try: run_cmd( test_command, cwd=cwd, forbidden_output=forbidden_output, expect_failure=expect_failure, env=env, allowed_failure_output=allowed_failure_output, ) except: # The LUCI environment may provide a variable containing a directory path # for additional output files that will be uploaded to cloud storage. # If the command generated a core dump, then run a script to analyze # the dump and output a report that will be uploaded. luci_test_outputs_path = os.environ.get('FLUTTER_TEST_OUTPUTS_DIR') core_path = os.path.join(cwd, 'core') if luci_test_outputs_path and os.path.exists(core_path) and os.path.exists(unstripped_exe): dump_path = os.path.join( luci_test_outputs_path, '%s_%s.txt' % (executable_name, sys_platform) ) logger.error('Writing core dump analysis to %s', dump_path) subprocess.call([ os.path.join(BUILDROOT_DIR, 'flutter', 'testing', 'analyze_core_dump.sh'), BUILDROOT_DIR, unstripped_exe, core_path, dump_path, ]) os.unlink(core_path) raise class EngineExecutableTask(): # pylint: disable=too-many-instance-attributes def __init__( # pylint: disable=too-many-arguments self, build_dir, executable_name, executable_filter, flags=None, cwd=BUILDROOT_DIR, forbidden_output=None, allowed_failure_output=None, expect_failure=False, coverage=False, extra_env=None, ): self.build_dir = build_dir self.executable_name = executable_name self.executable_filter = executable_filter self.flags = flags self.cwd = cwd self.forbidden_output = forbidden_output self.allowed_failure_output = allowed_failure_output self.expect_failure = expect_failure self.coverage = coverage self.extra_env = extra_env def __call__(self, *args): run_engine_executable( self.build_dir, self.executable_name, self.executable_filter, flags=self.flags, cwd=self.cwd, forbidden_output=self.forbidden_output, allowed_failure_output=self.allowed_failure_output, expect_failure=self.expect_failure, coverage=self.coverage, extra_env=self.extra_env, ) def __str__(self): command = build_engine_executable_command( self.build_dir, self.executable_name, flags=self.flags, coverage=self.coverage ) return ' '.join(command) shuffle_flags = [ '--gtest_repeat=2', '--gtest_shuffle', ] def run_cc_tests(build_dir, executable_filter, coverage, capture_core_dump): logger.info('Running Engine Unit-tests.') if capture_core_dump and is_linux(): import resource # pylint: disable=import-outside-toplevel resource.setrlimit(resource.RLIMIT_CORE, (resource.RLIM_INFINITY, resource.RLIM_INFINITY)) repeat_flags = [ '--repeat=2', ] def make_test(name, flags=None, extra_env=None): if flags is None: flags = repeat_flags if extra_env is None: extra_env = {} return (name, flags, extra_env) unittests = [ make_test('client_wrapper_glfw_unittests'), make_test('client_wrapper_unittests'), make_test('common_cpp_core_unittests'), make_test('common_cpp_unittests'), make_test('dart_plugin_registrant_unittests'), make_test('display_list_rendertests'), make_test('display_list_unittests'), make_test('embedder_a11y_unittests'), make_test('embedder_proctable_unittests'), make_test('embedder_unittests'), make_test('fml_unittests'), make_test('fml_arc_unittests'), make_test('no_dart_plugin_registrant_unittests'), make_test('runtime_unittests'), make_test('testing_unittests'), make_test('tonic_unittests'), # The image release unit test can take a while on slow machines. make_test('ui_unittests', flags=repeat_flags + ['--timeout=90']), ] if not is_windows(): unittests += [ # https://github.com/google/googletest/issues/2490 make_test('android_external_view_embedder_unittests'), make_test('jni_unittests'), make_test('platform_view_android_delegate_unittests'), # https://github.com/flutter/flutter/issues/36295 make_test('shell_unittests'), ] if is_windows(): unittests += [ # The accessibility library only supports Mac and Windows. make_test('accessibility_unittests'), make_test('client_wrapper_windows_unittests'), make_test('flutter_windows_unittests'), ] # These unit-tests are Objective-C and can only run on Darwin. if is_mac(): unittests += [ # The accessibility library only supports Mac and Windows. make_test('accessibility_unittests'), make_test('availability_version_check_unittests'), make_test('framework_common_unittests'), make_test('spring_animation_unittests'), make_test('gpu_surface_metal_unittests'), ] if is_linux(): flow_flags = [ '--golden-dir=%s' % GOLDEN_DIR, '--font-file=%s' % ROBOTO_FONT_PATH, ] icu_flags = ['--icu-data-file-path=%s' % os.path.join(build_dir, 'icudtl.dat')] unittests += [ make_test('flow_unittests', flags=repeat_flags + ['--'] + flow_flags), make_test('flutter_glfw_unittests'), make_test('flutter_linux_unittests', extra_env={'G_DEBUG': 'fatal-criticals'}), # https://github.com/flutter/flutter/issues/36296 make_test('txt_unittests', flags=repeat_flags + ['--'] + icu_flags), ] else: flow_flags = ['--gtest_filter=-PerformanceOverlayLayer.Gold'] unittests += [ make_test('flow_unittests', flags=repeat_flags + flow_flags), ] build_name = os.path.basename(build_dir) try: if is_linux(): xvfb.start_virtual_x(build_name, build_dir) for test, flags, extra_env in unittests: run_engine_executable( build_dir, test, executable_filter, flags, coverage=coverage, extra_env=extra_env, gtest=True ) finally: if is_linux(): xvfb.stop_virtual_x(build_name) if is_mac(): # flutter_desktop_darwin_unittests uses global state that isn't handled # correctly by gtest-parallel. # https://github.com/flutter/flutter/issues/104789 if not os.path.basename(build_dir).startswith('host_debug'): # Test is disabled for flaking in debug runs: # https://github.com/flutter/flutter/issues/127441 run_engine_executable( build_dir, 'flutter_desktop_darwin_unittests', executable_filter, shuffle_flags, coverage=coverage ) extra_env = metal_validation_env() extra_env.update(vulkan_validation_env(build_dir)) mac_impeller_unittests_flags = shuffle_flags + [ '--enable_vulkan_validation', '--gtest_filter=-*OpenGLES' # These are covered in the golden tests. ] # Impeller tests are only supported on macOS for now. run_engine_executable( build_dir, 'impeller_unittests', executable_filter, mac_impeller_unittests_flags, coverage=coverage, extra_env=extra_env, # TODO(https://github.com/flutter/flutter/issues/123733): Remove this allowlist. # See also https://github.com/flutter/flutter/issues/114872. allowed_failure_output=[ '[MTLCompiler createVertexStageAndLinkPipelineWithFragment:', '[MTLCompiler pipelineStateWithVariant:', ] ) # Run one interactive Vulkan test with validation enabled. # # TODO(matanlurey): https://github.com/flutter/flutter/issues/134852; enable # more of the suite, and ideally we'd like to use Skia gold and take screen # shots as well. run_engine_executable( build_dir, 'impeller_unittests', executable_filter, shuffle_flags + [ '--enable_vulkan_validation', '--enable_playground', '--playground_timeout_ms=4000', '--gtest_filter="*ColorWheel/Vulkan"', ], coverage=coverage, extra_env=extra_env, ) # Run the Flutter GPU test suite. run_engine_executable( build_dir, 'impeller_dart_unittests', executable_filter, shuffle_flags + [ '--enable_vulkan_validation', # TODO(https://github.com/flutter/flutter/issues/145036) # TODO(https://github.com/flutter/flutter/issues/142642) '--gtest_filter=*Metal', ], coverage=coverage, extra_env=extra_env, ) def run_engine_benchmarks(build_dir, executable_filter): logger.info('Running Engine Benchmarks.') icu_flags = ['--icu-data-file-path=%s' % os.path.join(build_dir, 'icudtl.dat')] run_engine_executable(build_dir, 'shell_benchmarks', executable_filter, icu_flags) run_engine_executable(build_dir, 'fml_benchmarks', executable_filter, icu_flags) run_engine_executable(build_dir, 'ui_benchmarks', executable_filter, icu_flags) run_engine_executable(build_dir, 'display_list_builder_benchmarks', executable_filter, icu_flags) run_engine_executable(build_dir, 'geometry_benchmarks', executable_filter, icu_flags) run_engine_executable(build_dir, 'canvas_benchmarks', executable_filter, icu_flags) if is_linux(): run_engine_executable(build_dir, 'txt_benchmarks', executable_filter, icu_flags) class FlutterTesterOptions(): def __init__( self, multithreaded=False, enable_impeller=False, enable_observatory=False, expect_failure=False ): self.multithreaded = multithreaded self.enable_impeller = enable_impeller self.enable_observatory = enable_observatory self.expect_failure = expect_failure def apply_args(self, command_args): if not self.enable_observatory: command_args.append('--disable-observatory') if self.enable_impeller: command_args += ['--enable-impeller'] else: command_args += ['--no-enable-impeller'] if self.multithreaded: command_args.insert(0, '--force-multithreading') def threading_description(self): if self.multithreaded: return 'multithreaded' return 'single-threaded' def impeller_enabled(self): if self.enable_impeller: return 'impeller swiftshader' return 'skia software' def gather_dart_test(build_dir, dart_file, options): kernel_file_name = os.path.basename(dart_file) + '.dill' kernel_file_output = os.path.join(build_dir, 'gen', kernel_file_name) error_message = "%s doesn't exist. Please run the build that populates %s" % ( kernel_file_output, build_dir ) assert os.path.isfile(kernel_file_output), error_message command_args = [] options.apply_args(command_args) dart_file_contents = open(dart_file, 'r') custom_options = re.findall('// FlutterTesterOptions=(.*)', dart_file_contents.read()) dart_file_contents.close() command_args.extend(custom_options) command_args += [ '--use-test-fonts', '--icu-data-file-path=%s' % os.path.join(build_dir, 'icudtl.dat'), '--flutter-assets-dir=%s' % os.path.join(build_dir, 'gen', 'flutter', 'lib', 'ui', 'assets'), '--disable-asset-fonts', kernel_file_output, ] tester_name = 'flutter_tester' logger.info( "Running test '%s' using '%s' (%s, %s)", kernel_file_name, tester_name, options.threading_description(), options.impeller_enabled() ) forbidden_output = [] if 'unopt' in build_dir or options.expect_failure else ['[ERROR'] return EngineExecutableTask( build_dir, tester_name, None, command_args, forbidden_output=forbidden_output, expect_failure=options.expect_failure, ) def ensure_ios_tests_are_built(ios_out_dir): """Builds the engine variant and the test dylib containing the XCTests""" tmp_out_dir = os.path.join(OUT_DIR, ios_out_dir) ios_test_lib = os.path.join(tmp_out_dir, 'libios_test_flutter.dylib') message = [] message.append('gn --ios --unoptimized --runtime-mode=debug --no-lto --simulator') message.append('ninja -C %s ios_test_flutter' % ios_out_dir) final_message = "%s or %s doesn't exist. Please run the following commands: \n%s" % ( ios_out_dir, ios_test_lib, '\n'.join(message) ) assert os.path.exists(tmp_out_dir) and os.path.exists(ios_test_lib), final_message def assert_expected_xcode_version(): """Checks that the user has a version of Xcode installed""" version_output = subprocess.check_output(['xcodebuild', '-version']) # TODO ricardoamador: remove this check when python 2 is deprecated. version_output = version_output if isinstance(version_output, str) else version_output.decode(ENCODING) version_output = version_output.strip() match = re.match(r'Xcode (\d+)', version_output) message = 'Xcode must be installed to run the iOS embedding unit tests' assert match, message def java_home(): script_path = os.path.dirname(os.path.realpath(__file__)) if is_mac(): return os.path.join( script_path, '..', '..', 'third_party', 'java', 'openjdk', 'Contents', 'Home' ) return os.path.join(script_path, '..', '..', 'third_party', 'java', 'openjdk') def java_bin(): return os.path.join(java_home(), 'bin', 'java.exe' if is_windows() else 'java') def run_java_tests(executable_filter, android_variant='android_debug_unopt'): """Runs the Java JUnit unit tests for the Android embedding""" test_runner_dir = os.path.join( BUILDROOT_DIR, 'flutter', 'shell', 'platform', 'android', 'test_runner' ) gradle_bin = os.path.join( BUILDROOT_DIR, 'third_party', 'gradle', 'bin', 'gradle.bat' if is_windows() else 'gradle' ) flutter_jar = os.path.join(OUT_DIR, android_variant, 'flutter.jar') android_home = os.path.join(BUILDROOT_DIR, 'third_party', 'android_tools', 'sdk') build_dir = os.path.join(OUT_DIR, android_variant, 'robolectric_tests', 'build') gradle_cache_dir = os.path.join(OUT_DIR, android_variant, 'robolectric_tests', '.gradle') test_class = executable_filter if executable_filter else '*' command = [ gradle_bin, '-Pflutter_jar=%s' % flutter_jar, '-Pbuild_dir=%s' % build_dir, 'testDebugUnitTest', '--tests=%s' % test_class, '--rerun-tasks', '--no-daemon', '--project-cache-dir=%s' % gradle_cache_dir, '--gradle-user-home=%s' % gradle_cache_dir, ] env = dict(os.environ, ANDROID_HOME=android_home, JAVA_HOME=java_home()) run_cmd(command, cwd=test_runner_dir, env=env) def run_android_unittest(test_runner_name, android_variant, adb_path): tests_path = os.path.join(OUT_DIR, android_variant, test_runner_name) remote_path = '/data/local/tmp' remote_tests_path = os.path.join(remote_path, test_runner_name) run_cmd([adb_path, 'push', tests_path, remote_path], cwd=BUILDROOT_DIR) try: run_cmd([adb_path, 'shell', remote_tests_path]) except: luci_test_outputs_path = os.environ.get('FLUTTER_TEST_OUTPUTS_DIR') if luci_test_outputs_path: print('>>>>> Test %s failed. Capturing logcat.' % test_runner_name) logcat_path = os.path.join(luci_test_outputs_path, '%s_logcat' % test_runner_name) logcat_file = open(logcat_path, 'w') subprocess.run([adb_path, 'logcat', '-d'], stdout=logcat_file, check=False) raise def run_android_tests(android_variant='android_debug_unopt', adb_path=None): if adb_path is None: adb_path = 'adb' run_android_unittest('flutter_shell_native_unittests', android_variant, adb_path) run_android_unittest('impeller_toolkit_android_unittests', android_variant, adb_path) systrace_test = os.path.join(BUILDROOT_DIR, 'flutter', 'testing', 'android_systrace_test.py') scenario_apk = os.path.join(OUT_DIR, android_variant, 'firebase_apks', 'scenario_app.apk') run_cmd([ systrace_test, '--adb-path', adb_path, '--apk-path', scenario_apk, '--package-name', 'dev.flutter.scenarios', '--activity-name', '.PlatformViewsActivity' ]) def run_objc_tests(ios_variant='ios_debug_sim_unopt', test_filter=None): """Runs Objective-C XCTest unit tests for the iOS embedding""" assert_expected_xcode_version() ios_out_dir = os.path.join(OUT_DIR, ios_variant) ensure_ios_tests_are_built(ios_out_dir) new_simulator_name = 'IosUnitTestsSimulator' # Delete simulators with this name in case any were leaked # from another test run. delete_simulator(new_simulator_name) create_simulator = [ 'xcrun ' 'simctl ' 'create ' '%s com.apple.CoreSimulator.SimDeviceType.iPhone-11' % new_simulator_name ] run_cmd(create_simulator, shell=True) try: ios_unit_test_dir = os.path.join(BUILDROOT_DIR, 'flutter', 'testing', 'ios', 'IosUnitTests') with tempfile.TemporaryDirectory(suffix='ios_embedding_xcresult') as result_bundle_temp: result_bundle_path = os.path.join(result_bundle_temp, 'ios_embedding') # Avoid using xcpretty unless the following can be addressed: # - Make sure all relevant failure output is printed on a failure. # - Make sure that a failing exit code is set for CI. # See https://github.com/flutter/flutter/issues/63742 test_command = [ 'xcodebuild ' '-sdk iphonesimulator ' '-scheme IosUnitTests ' '-resultBundlePath ' + result_bundle_path + ' ' '-destination name=' + new_simulator_name + ' ' 'test ' 'FLUTTER_ENGINE=' + ios_variant ] if test_filter is not None: test_command[0] = test_command[0] + ' -only-testing:%s' % test_filter try: run_cmd(test_command, cwd=ios_unit_test_dir, shell=True) except: # The LUCI environment may provide a variable containing a directory path # for additional output files that will be uploaded to cloud storage. # Upload the xcresult when the tests fail. luci_test_outputs_path = os.environ.get('FLUTTER_TEST_OUTPUTS_DIR') xcresult_bundle = os.path.join(result_bundle_temp, 'ios_embedding.xcresult') if luci_test_outputs_path and os.path.exists(xcresult_bundle): dump_path = os.path.join(luci_test_outputs_path, 'ios_embedding.xcresult') # xcresults contain many little files. Archive the bundle before upload. shutil.make_archive(dump_path, 'zip', root_dir=xcresult_bundle) raise finally: delete_simulator(new_simulator_name) def delete_simulator(simulator_name): # Will delete all simulators with this name. command = [ 'xcrun', 'simctl', 'delete', simulator_name, ] # Let this fail if the simulator was never created. run_cmd(command, expect_failure=True) def gather_dart_tests(build_dir, test_filter): dart_tests_dir = os.path.join( BUILDROOT_DIR, 'flutter', 'testing', 'dart', ) # Now that we have the Sky packages at the hardcoded location, run `dart pub get`. run_engine_executable( build_dir, os.path.join('dart-sdk', 'bin', 'dart'), None, flags=['pub', '--suppress-analytics', 'get', '--offline'], cwd=dart_tests_dir, ) dart_observatory_tests = glob.glob('%s/observatory/*_test.dart' % dart_tests_dir) dart_tests = glob.glob('%s/*_test.dart' % dart_tests_dir) if 'release' not in build_dir: for dart_test_file in dart_observatory_tests: if test_filter is not None and os.path.basename(dart_test_file) not in test_filter: logger.info("Skipping '%s' due to filter.", dart_test_file) else: logger.info("Gathering dart test '%s' with observatory enabled", dart_test_file) for multithreaded in [False, True]: for enable_impeller in [False, True]: yield gather_dart_test( build_dir, dart_test_file, FlutterTesterOptions( multithreaded=multithreaded, enable_impeller=enable_impeller, enable_observatory=True ) ) for dart_test_file in dart_tests: if test_filter is not None and os.path.basename(dart_test_file) not in test_filter: logger.info("Skipping '%s' due to filter.", dart_test_file) else: logger.info("Gathering dart test '%s'", dart_test_file) for multithreaded in [False, True]: for enable_impeller in [False, True]: yield gather_dart_test( build_dir, dart_test_file, FlutterTesterOptions(multithreaded=multithreaded, enable_impeller=enable_impeller) ) def gather_dart_smoke_test(build_dir, test_filter): smoke_test = os.path.join( BUILDROOT_DIR, 'flutter', 'testing', 'smoke_test_failure', 'fail_test.dart', ) if test_filter is not None and os.path.basename(smoke_test) not in test_filter: logger.info("Skipping '%s' due to filter.", smoke_test) else: yield gather_dart_test( build_dir, smoke_test, FlutterTesterOptions(multithreaded=True, expect_failure=True) ) yield gather_dart_test( build_dir, smoke_test, FlutterTesterOptions(multithreaded=False, expect_failure=True) ) def gather_dart_package_tests(build_dir, package_path, extra_opts): dart_tests = glob.glob('%s/test/*_test.dart' % package_path) if not dart_tests: raise Exception('No tests found for Dart package at %s' % package_path) for dart_test_file in dart_tests: opts = ['--disable-dart-dev', dart_test_file] + extra_opts yield EngineExecutableTask( build_dir, os.path.join('dart-sdk', 'bin', 'dart'), None, flags=opts, cwd=package_path ) # Returns a list of Dart packages to test. # # The first element of each tuple in the returned list is the path to the Dart # package to test. It is assumed that the packages follow the convention that # tests are named as '*_test.dart', and reside under a directory called 'test'. # # The second element of each tuple is a list of additional command line # arguments to pass to each of the packages tests. def build_dart_host_test_list(build_dir): dart_host_tests = [ ( os.path.join('flutter', 'ci'), [os.path.join(BUILDROOT_DIR, 'flutter')], ), ( os.path.join('flutter', 'flutter_frontend_server'), [ build_dir, os.path.join(build_dir, 'gen', 'frontend_server.dart.snapshot'), os.path.join(build_dir, 'flutter_patched_sdk') ], ), (os.path.join('flutter', 'testing', 'litetest'), []), (os.path.join('flutter', 'testing', 'skia_gold_client'), []), (os.path.join('flutter', 'testing', 'scenario_app'), []), ( os.path.join('flutter', 'tools', 'api_check'), [os.path.join(BUILDROOT_DIR, 'flutter')], ), (os.path.join('flutter', 'tools', 'build_bucket_golden_scraper'), []), (os.path.join('flutter', 'tools', 'clang_tidy'), []), ( os.path.join('flutter', 'tools', 'const_finder'), [ os.path.join(build_dir, 'gen', 'frontend_server.dart.snapshot'), os.path.join(build_dir, 'flutter_patched_sdk'), os.path.join(build_dir, 'dart-sdk', 'lib', 'libraries.json'), ], ), (os.path.join('flutter', 'tools', 'dir_contents_diff'), []), (os.path.join('flutter', 'tools', 'engine_tool'), []), (os.path.join('flutter', 'tools', 'githooks'), []), (os.path.join('flutter', 'tools', 'header_guard_check'), []), (os.path.join('flutter', 'tools', 'pkg', 'engine_build_configs'), []), (os.path.join('flutter', 'tools', 'pkg', 'engine_repo_tools'), []), (os.path.join('flutter', 'tools', 'pkg', 'git_repo_tools'), []), ] if not is_asan(build_dir): dart_host_tests += [ (os.path.join('flutter', 'tools', 'path_ops', 'dart'), []), ] return dart_host_tests def run_benchmark_tests(build_dir): test_dir = os.path.join(BUILDROOT_DIR, 'flutter', 'testing', 'benchmark') dart_tests = glob.glob('%s/test/*_test.dart' % test_dir) for dart_test_file in dart_tests: opts = ['--disable-dart-dev', dart_test_file] run_engine_executable( build_dir, os.path.join('dart-sdk', 'bin', 'dart'), None, flags=opts, cwd=test_dir ) def worker_init(queue, level): queue_handler = logging.handlers.QueueHandler(queue) log = logging.getLogger(__name__) log.setLevel(logging.INFO) queue_handler.setLevel(level) log.addHandler(queue_handler) def run_engine_tasks_in_parallel(tasks): # Work around a bug in Python. # # The multiprocessing package relies on the win32 WaitForMultipleObjects() # call, which supports waiting on a maximum of MAXIMUM_WAIT_OBJECTS (defined # by Windows to be 64) handles, processes in this case. To avoid hitting # this, we limit ourselves to 60 handles (since there are a couple extra # processes launched for the queue reader and thread wakeup reader). # # See: https://bugs.python.org/issue26903 max_processes = multiprocessing.cpu_count() if sys_platform.startswith(('cygwin', 'win')) and max_processes > 60: max_processes = 60 queue = multiprocessing.Queue() queue_listener = logging.handlers.QueueListener( queue, console_logger_handler, file_logger_handler, respect_handler_level=True, ) queue_listener.start() failures = [] try: with multiprocessing.Pool(max_processes, worker_init, [queue, logger.getEffectiveLevel()]) as pool: async_results = [(t, pool.apply_async(t, ())) for t in tasks] for task, async_result in async_results: try: async_result.get() except Exception as exn: # pylint: disable=broad-except failures += [(task, exn)] finally: queue_listener.stop() if len(failures) > 0: logger.error('The following commands failed:') for task, exn in failures: logger.error('%s\n %s\n\n', str(task), str(exn)) return False return True class DirectoryChange(): """ A scoped change in the CWD. """ old_cwd: str = '' new_cwd: str = '' def __init__(self, new_cwd: str): self.new_cwd = new_cwd def __enter__(self): self.old_cwd = os.getcwd() os.chdir(self.new_cwd) def __exit__(self, exception_type, exception_value, exception_traceback): os.chdir(self.old_cwd) def run_impeller_golden_tests(build_dir: str): """ Executes the impeller golden image tests from in the `variant` build. """ tests_path: str = os.path.join(build_dir, 'impeller_golden_tests') if not os.path.exists(tests_path): raise Exception( 'Cannot find the "impeller_golden_tests" executable in "%s". You may need to build it.' % (build_dir) ) harvester_path: Path = Path(SCRIPT_DIR).parent.joinpath('tools' ).joinpath('golden_tests_harvester') with tempfile.TemporaryDirectory(prefix='impeller_golden') as temp_dir: extra_env = metal_validation_env() extra_env.update(vulkan_validation_env(build_dir)) run_cmd([tests_path, f'--working_dir={temp_dir}'], cwd=build_dir, env=extra_env) dart_bin = os.path.join(build_dir, 'dart-sdk', 'bin', 'dart') golden_path = os.path.join('testing', 'impeller_golden_tests_output.txt') script_path = os.path.join('tools', 'dir_contents_diff', 'bin', 'dir_contents_diff.dart') diff_result = subprocess.run( f'{dart_bin} --disable-dart-dev {script_path} {golden_path} {temp_dir}', check=False, shell=True, stdout=subprocess.PIPE, cwd=os.path.join(BUILDROOT_DIR, 'flutter') ) if diff_result.returncode != 0: print_divider('<') print(diff_result.stdout.decode()) raise RuntimeError('impeller_golden_tests diff failure') # On release builds and local builds, we typically do not have GOLDCTL set, # which on other words means that this invoking the SkiaGoldClient would # throw. Skip this step in those cases and log a notice. if 'GOLDCTL' not in os.environ: print_divider('<') print( 'Skipping the SkiaGoldClient invocation as the GOLDCTL environment variable is not set.' ) return with DirectoryChange(harvester_path): bin_path = Path('.').joinpath('bin').joinpath('golden_tests_harvester.dart') run_cmd([dart_bin, '--disable-dart-dev', str(bin_path), temp_dir]) def main(): parser = argparse.ArgumentParser( description=""" In order to learn the details of running tests in the engine, please consult the Flutter Wiki page on the subject: https://github.com/flutter/flutter/wiki/Testing-the-engine """ ) all_types = [ 'engine', 'dart', 'dart-host', 'benchmarks', 'java', 'android', 'objc', 'font-subset', 'impeller-golden', ] parser.add_argument( '--variant', dest='variant', action='store', default='host_debug_unopt', help='The engine build variant to run the tests for.' ) parser.add_argument( '--type', type=str, default='all', help='A list of test types, default is "all" (equivalent to "%s")' % (','.join(all_types)) ) parser.add_argument( '--engine-filter', type=str, default='', help='A list of engine test executables to run.' ) parser.add_argument( '--dart-filter', type=str, default='', help='A list of Dart test scripts to run in flutter_tester.' ) parser.add_argument( '--dart-host-filter', type=str, default='', help='A list of Dart test scripts to run with the Dart CLI.' ) parser.add_argument( '--java-filter', type=str, default='', help='A single Java test class to run (example: "io.flutter.SmokeTest")' ) parser.add_argument( '--android-variant', dest='android_variant', action='store', default='android_debug_unopt', help='The engine build variant to run java or android tests for' ) parser.add_argument( '--ios-variant', dest='ios_variant', action='store', default='ios_debug_sim_unopt', help='The engine build variant to run objective-c tests for' ) parser.add_argument( '--verbose-dart-snapshot', dest='verbose_dart_snapshot', action='store_true', default=False, help='Show extra dart snapshot logging.' ) parser.add_argument( '--objc-filter', type=str, default=None, help=( 'Filter parameter for which objc tests to run ' '(example: "IosUnitTestsTests/SemanticsObjectTest/testShouldTriggerAnnouncement")' ) ) parser.add_argument( '--coverage', action='store_true', default=None, help='Generate coverage reports for each unit test framework run.' ) parser.add_argument( '--engine-capture-core-dump', dest='engine_capture_core_dump', action='store_true', default=False, help='Capture core dumps from crashes of engine tests.' ) parser.add_argument( '--use-sanitizer-suppressions', dest='sanitizer_suppressions', action='store_true', default=False, help='Provide the sanitizer suppressions lists to the via environment to the tests.' ) parser.add_argument( '--adb-path', dest='adb_path', action='store', default=None, help='Provide the path of adb used for android tests. By default it looks on $PATH.' ) parser.add_argument( '--quiet', dest='quiet', action='store_true', default=False, help='Only emit output when there is an error.' ) parser.add_argument( '--logs-dir', dest='logs_dir', type=str, help='The directory that verbose logs will be copied to in --quiet mode.', ) args = parser.parse_args() logger.addHandler(console_logger_handler) logger.addHandler(file_logger_handler) logger.setLevel(logging.INFO) if args.quiet: file_logger_handler.setLevel(logging.INFO) console_logger_handler.setLevel(logging.WARNING) else: console_logger_handler.setLevel(logging.INFO) if args.type == 'all': types = all_types else: types = args.type.split(',') build_dir = os.path.join(OUT_DIR, args.variant) if args.type != 'java' and args.type != 'android': assert os.path.exists(build_dir), 'Build variant directory %s does not exist!' % build_dir if args.sanitizer_suppressions: assert is_linux() or is_mac( ), 'The sanitizer suppressions flag is only supported on Linux and Mac.' file_dir = os.path.dirname(os.path.abspath(__file__)) command = [ 'env', '-i', 'bash', '-c', 'source {}/sanitizer_suppressions.sh >/dev/null && env'.format(file_dir) ] process = subprocess.Popen(command, stdout=subprocess.PIPE) for line in process.stdout: key, _, value = line.decode('utf8').strip().partition('=') os.environ[key] = value process.communicate() # Avoid pipe deadlock while waiting for termination. success = True engine_filter = args.engine_filter.split(',') if args.engine_filter else None if 'engine' in types: run_cc_tests(build_dir, engine_filter, args.coverage, args.engine_capture_core_dump) # Use this type to exclusively run impeller tests. if 'impeller' in types: build_name = args.variant try: xvfb.start_virtual_x(build_name, build_dir) extra_env = vulkan_validation_env(build_dir) run_engine_executable( build_dir, 'impeller_unittests', engine_filter, shuffle_flags, coverage=args.coverage, extra_env=extra_env ) finally: xvfb.stop_virtual_x(build_name) if 'dart' in types: dart_filter = args.dart_filter.split(',') if args.dart_filter else None tasks = list(gather_dart_smoke_test(build_dir, dart_filter)) tasks += list(gather_dart_tests(build_dir, dart_filter)) success = success and run_engine_tasks_in_parallel(tasks) if 'dart-host' in types: dart_filter = args.dart_host_filter.split(',') if args.dart_host_filter else None dart_host_packages = build_dart_host_test_list(build_dir) tasks = [] for dart_host_package, extra_opts in dart_host_packages: if dart_filter is None or dart_host_package in dart_filter: tasks += list( gather_dart_package_tests( build_dir, os.path.join(BUILDROOT_DIR, dart_host_package), extra_opts, ) ) success = success and run_engine_tasks_in_parallel(tasks) if 'java' in types: assert not is_windows(), "Android engine files can't be compiled on Windows." java_filter = args.java_filter if ',' in java_filter or '*' in java_filter: logger.wraning( 'Can only filter JUnit4 tests by single entire class name, ' 'eg "io.flutter.SmokeTest". Ignoring filter=' + java_filter ) java_filter = None run_java_tests(java_filter, args.android_variant) if 'android' in types: assert not is_windows(), "Android engine files can't be compiled on Windows." run_android_tests(args.android_variant, args.adb_path) if 'objc' in types: assert is_mac(), 'iOS embedding tests can only be run on macOS.' run_objc_tests(args.ios_variant, args.objc_filter) # https://github.com/flutter/flutter/issues/36300 if 'benchmarks' in types and not is_windows(): run_benchmark_tests(build_dir) run_engine_benchmarks(build_dir, engine_filter) variants_to_skip = ['host_release', 'host_profile'] if ('engine' in types or 'font-subset' in types) and args.variant not in variants_to_skip: cmd = ['python3', 'test.py', '--variant', args.variant] if 'arm64' in args.variant: cmd += ['--target-cpu', 'arm64'] run_cmd(cmd, cwd=FONT_SUBSET_DIR) if 'impeller-golden' in types: run_impeller_golden_tests(build_dir) if args.quiet and args.logs_dir: shutil.copy(LOG_FILE, os.path.join(args.logs_dir, 'run_tests.log')) return 0 if success else 1 if __name__ == '__main__': sys_exit(main())
engine/testing/run_tests.py/0
{ "file_path": "engine/testing/run_tests.py", "repo_id": "engine", "token_count": 18601 }
389
// 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 static io.flutter.Build.API_LEVELS; import android.content.Intent; import android.graphics.Rect; import androidx.annotation.NonNull; import androidx.test.filters.LargeTest; import androidx.test.filters.SdkSuppress; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import dev.flutter.scenarios.ExternalTextureFlutterActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @LargeTest public class ExternalTextureTests { private static final int SURFACE_WIDTH = 192; private static final int SURFACE_HEIGHT = 256; Intent intent; @Rule @NonNull public ActivityTestRule<ExternalTextureFlutterActivity> activityRule = new ActivityTestRule<>( ExternalTextureFlutterActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false); @Before public void setUp() { intent = new Intent(Intent.ACTION_MAIN); } @Test public void testCanvasSurface() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "canvas"); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testCanvasSurface"); } @Test public void testMediaSurface() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "media"); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testMediaSurface"); } @Test public void testRotatedMediaSurface_90() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "media"); intent.putExtra("rotation", 90); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testRotatedMediaSurface_90"); } @Test public void testRotatedMediaSurface_180() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "media"); intent.putExtra("rotation", 180); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testRotatedMediaSurface_180"); } @Test public void testRotatedMediaSurface_270() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "media"); intent.putExtra("rotation", 270); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testRotatedMediaSurface_270"); } @Test @SdkSuppress(minSdkVersion = API_LEVELS.API_23) public void testCroppedMediaSurface_bottomLeft() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "image"); intent.putExtra("crop", new Rect(0, 0, SURFACE_WIDTH / 2, SURFACE_HEIGHT / 2)); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testCroppedMediaSurface_bottomLeft"); } @Test @SdkSuppress(minSdkVersion = API_LEVELS.API_23) public void testCroppedMediaSurface_topRight() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "image"); intent.putExtra( "crop", new Rect(SURFACE_WIDTH / 2, SURFACE_HEIGHT / 2, SURFACE_WIDTH, SURFACE_HEIGHT)); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testCroppedMediaSurface_topRight"); } @Test @SdkSuppress(minSdkVersion = API_LEVELS.API_23) public void testCroppedRotatedMediaSurface_bottomLeft_90() throws Exception { intent.putExtra("scenario_name", "display_texture"); intent.putExtra("surface_renderer", "image"); intent.putExtra("crop", new Rect(0, 0, SURFACE_WIDTH / 2, SURFACE_HEIGHT / 2)); intent.putExtra("rotation", 90); ScreenshotUtil.capture( activityRule.launchActivity(intent), "ExternalTextureTests_testCroppedRotatedMediaSurface_bottomLeft_90"); } }
engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ExternalTextureTests.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/ExternalTextureTests.java", "repo_id": "engine", "token_count": 1483 }
390
// // Generated file. Do not edit. // // clang-format off #ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_RUNNER_GENERATEDPLUGINREGISTRANT_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_RUNNER_GENERATEDPLUGINREGISTRANT_H_ #import <Flutter/Flutter.h> NS_ASSUME_NONNULL_BEGIN @interface GeneratedPluginRegistrant : NSObject + (void)registerWithRegistry:(NSObject<FlutterPluginRegistry>*)registry; @end NS_ASSUME_NONNULL_END #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_RUNNER_GENERATEDPLUGINREGISTRANT_H_
engine/testing/scenario_app/ios/Runner/GeneratedPluginRegistrant.h/0
{ "file_path": "engine/testing/scenario_app/ios/Runner/GeneratedPluginRegistrant.h", "repo_id": "engine", "token_count": 219 }
391
// 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. #import "ContinuousTexture.h" @implementation ContinuousTexture + (void)registerWithRegistrar:(nonnull NSObject<FlutterPluginRegistrar>*)registrar { NSObject<FlutterTextureRegistry>* textureRegistry = [registrar textures]; FlutterScenarioTestTexture* texture = [[FlutterScenarioTestTexture alloc] init]; int64_t textureId = [textureRegistry registerTexture:texture]; [NSTimer scheduledTimerWithTimeInterval:0.05 repeats:YES block:^(NSTimer* _Nonnull timer) { [textureRegistry textureFrameAvailable:textureId]; }]; } @end @implementation FlutterScenarioTestTexture - (CVPixelBufferRef _Nullable)copyPixelBuffer { return [self pixelBuffer]; } - (CVPixelBufferRef)pixelBuffer { NSDictionary* options = @{ // This key is required to generate SKPicture with CVPixelBufferRef in metal. (NSString*)kCVPixelBufferMetalCompatibilityKey : @YES }; CVPixelBufferRef pxbuffer = NULL; CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, 200, 200, kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef)options, &pxbuffer); NSAssert(status == kCVReturnSuccess && pxbuffer != NULL, @"Failed to create pixel buffer."); return pxbuffer; } @end
engine/testing/scenario_app/ios/Scenarios/Scenarios/ContinuousTexture.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/ContinuousTexture.m", "repo_id": "engine", "token_count": 595 }
392
// 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/Flutter.h> #import <XCTest/XCTest.h> #import "AppDelegate.h" FLUTTER_ASSERT_ARC @interface FlutterViewControllerInitialRouteTest : XCTestCase @property(nonatomic, strong) FlutterViewController* flutterViewController; @end // This test needs to be in its own file with only one test method because dart:ui // window's defaultRouteName can only be set once per VM. @implementation FlutterViewControllerInitialRouteTest - (void)setUp { [super setUp]; self.continueAfterFailure = NO; } - (void)tearDown { if (self.flutterViewController) { XCTestExpectation* vcDismissed = [self expectationWithDescription:@"dismiss"]; [self.flutterViewController dismissViewControllerAnimated:NO completion:^{ [vcDismissed fulfill]; }]; [self waitForExpectationsWithTimeout:10.0 handler:nil]; } [super tearDown]; } - (void)testSettingInitialRoute { self.flutterViewController = [[FlutterViewController alloc] initWithProject:nil initialRoute:@"myCustomInitialRoute" nibName:nil bundle:nil]; NSObject<FlutterBinaryMessenger>* binaryMessenger = self.flutterViewController.binaryMessenger; __weak typeof(binaryMessenger) weakBinaryMessenger = binaryMessenger; FlutterBinaryMessengerConnection waitingForStatusConnection = [binaryMessenger setMessageHandlerOnChannel:@"waiting_for_status" binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"driver" binaryMessenger:weakBinaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; [channel invokeMethod:@"set_scenario" arguments:@{@"name" : @"initial_route_reply"}]; }]; XCTestExpectation* customInitialRouteSet = [self expectationWithDescription:@"Custom initial route was set on the Dart side"]; FlutterBinaryMessengerConnection initialRoutTestChannelConnection = [binaryMessenger setMessageHandlerOnChannel:@"initial_route_test_channel" binaryMessageHandler:^(NSData* message, FlutterBinaryReply reply) { NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:message options:0 error:nil]; NSString* initialRoute = dict[@"method"]; if ([initialRoute isEqualToString:@"myCustomInitialRoute"]) { [customInitialRouteSet fulfill]; } else { XCTFail(@"Expected initial route to be set to " @"myCustomInitialRoute. Was set to %@ instead", initialRoute); } }]; AppDelegate* appDelegate = (AppDelegate*)UIApplication.sharedApplication.delegate; UIViewController* rootVC = appDelegate.window.rootViewController; [rootVC presentViewController:self.flutterViewController animated:NO completion:nil]; [self waitForExpectationsWithTimeout:30.0 handler:nil]; [binaryMessenger cleanUpConnection:waitingForStatusConnection]; [binaryMessenger cleanUpConnection:initialRoutTestChannelConnection]; } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerInitialRouteTest.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosTests/FlutterViewControllerInitialRouteTest.m", "repo_id": "engine", "token_count": 1828 }
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 "GoldenPlatformViewTests.h" static const NSInteger kSecondsToWaitForPlatformView = 30; @interface PlatformViewUITests : GoldenPlatformViewTests @end @implementation PlatformViewUITests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface NonFullScreenFlutterViewPlatformViewUITests : GoldenPlatformViewTests @end @implementation NonFullScreenFlutterViewPlatformViewUITests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--non-full-screen-flutter-view-platform-view"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface MultiplePlatformViewsTest : GoldenPlatformViewTests @end @implementation MultiplePlatformViewsTest - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-multiple"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface MultiplePlatformViewsBackgroundForegroundTest : GoldenPlatformViewTests @end @implementation MultiplePlatformViewsBackgroundForegroundTest - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-multiple-background-foreground"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [[XCUIDevice sharedDevice] pressButton:XCUIDeviceButtonHome]; [self.application activate]; [self checkPlatformViewGolden]; } @end // Clip Rect Tests @interface PlatformViewMutationClipRectTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipRectTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-cliprect"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationClipRectAfterMovedTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipRectAfterMovedTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-cliprect-after-moved"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { // This test needs to wait for several frames for the PlatformView to settle to // the correct position. The PlatformView accessiblity is set to platform_view[10000] when it is // ready. XCUIElement* element = self.application.otherElements[@"platform_view[10000]"]; 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 checkPlatformViewGolden]; } @end @interface PlatformViewMutationClipRRectTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipRRectTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-cliprrect"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationLargeClipRRectTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationLargeClipRRectTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-large-cliprrect"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationClipPathTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipPathTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-clippath"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationClipRectWithTransformTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipRectWithTransformTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-cliprect-with-transform"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationClipRRectWithTransformTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipRRectWithTransformTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-cliprrect-with-transform"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationLargeClipRRectWithTransformTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationLargeClipRRectWithTransformTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-large-cliprrect-with-transform"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationClipPathWithTransformTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationClipPathWithTransformTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-clippath-with-transform"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface TwoPlatformViewClipRectTests : GoldenPlatformViewTests @end @implementation TwoPlatformViewClipRectTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--two-platform-view-clip-rect"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface TwoPlatformViewClipRRectTests : GoldenPlatformViewTests @end @implementation TwoPlatformViewClipRRectTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--two-platform-view-clip-rrect"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface TwoPlatformViewClipPathTests : GoldenPlatformViewTests @end @implementation TwoPlatformViewClipPathTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--two-platform-view-clip-path"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationTransformTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationTransformTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-transform"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewMutationOpacityTests : GoldenPlatformViewTests @end @implementation PlatformViewMutationOpacityTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-opacity"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewWithOtherBackdropFilterTests : GoldenPlatformViewTests @end @implementation PlatformViewWithOtherBackdropFilterTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-with-other-backdrop-filter"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface TwoPlatformViewsWithOtherBackDropFilterTests : GoldenPlatformViewTests @end @implementation TwoPlatformViewsWithOtherBackDropFilterTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--two-platform-views-with-other-backdrop-filter"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { // (TODO)cyanglaz: remove the threshold adjustment after all the ci migrates to macOS13. // https://github.com/flutter/flutter/issues/133207 if ([NSProcessInfo processInfo].operatingSystemVersion.majorVersion >= 13) { self.rmseThreadhold = 0.7; } [self checkPlatformViewGolden]; } @end @interface PlatformViewWithNegativeOtherBackDropFilterTests : GoldenPlatformViewTests @end @implementation PlatformViewWithNegativeOtherBackDropFilterTests - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-with-negative-backdrop-filter"]; return [super initWithManager:manager invocation:invocation]; } - (void)testPlatformView { [self checkPlatformViewGolden]; } @end @interface PlatformViewRotation : GoldenPlatformViewTests @end @implementation PlatformViewRotation - (instancetype)initWithInvocation:(NSInvocation*)invocation { GoldenTestManager* manager = [[GoldenTestManager alloc] initWithLaunchArg:@"--platform-view-rotate"]; return [super initWithManager:manager invocation:invocation]; } - (void)tearDown { XCUIDevice.sharedDevice.orientation = UIDeviceOrientationPortrait; [super tearDown]; } - (void)testPlatformView { XCUIDevice.sharedDevice.orientation = UIDeviceOrientationLandscapeLeft; [self checkPlatformViewGolden]; } @end @interface PlatformViewWithContinuousTexture : XCTestCase @end @implementation PlatformViewWithContinuousTexture - (void)setUp { self.continueAfterFailure = NO; } - (void)testPlatformViewWithContinuousTexture { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--platform-view-with-continuous-texture", @"--with-continuous-texture" ]; [app launch]; XCUIElement* platformView = app.textViews.firstMatch; BOOL exists = [platformView 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)); } XCTAssertNotNil(platformView); } @end @interface PlatformViewScrollingUnderWidget : XCTestCase @end @implementation PlatformViewScrollingUnderWidget - (void)setUp { [super setUp]; self.continueAfterFailure = NO; } - (void)testPlatformViewScrollingUnderWidget { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--platform-view-scrolling-under-widget", @"--with-continuous-texture" ]; [app launch]; XCUIElement* platformView = app.textViews.firstMatch; BOOL exists = [platformView 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)); } // Wait and let the scenario app scroll a bit. XCTWaiterResult waitResult = [XCTWaiter waitForExpectations:@[ [[XCTestExpectation alloc] initWithDescription:@"Wait for 5 seconds"] ] timeout:5]; // If the waiter is not interrupted, we know the app is in a valid state after timeout, thus the // test passes. XCTAssert(waitResult != XCTWaiterResultInterrupted); } @end @interface PlatformViewWithClipsScrolling : XCTestCase @end @implementation PlatformViewWithClipsScrolling - (void)setUp { [super setUp]; self.continueAfterFailure = NO; } - (void)testPlatformViewsWithClipsScrolling { XCUIApplication* app = [[XCUIApplication alloc] init]; app.launchArguments = @[ @"--platform-views-with-clips-scrolling", @"platform_views_with_clips_scrolling" ]; [app launch]; XCUIElement* platformView = app.textViews.firstMatch; BOOL exists = [platformView 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)); } // Wait and let the scenario app scroll a bit. XCTWaiterResult waitResult = [XCTWaiter waitForExpectations:@[ [[XCTestExpectation alloc] initWithDescription:@"Wait for 5 seconds"] ] timeout:5]; // If the waiter is not interrupted, we know the app is in a valid state after timeout, thus the // test passes. XCTAssert(waitResult != XCTWaiterResultInterrupted); } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/PlatformViewUITests.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/PlatformViewUITests.m", "repo_id": "engine", "token_count": 4679 }
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 'animated_color_square.dart'; import 'bogus_font_text.dart'; import 'darwin_app_extension_scenario.dart'; import 'darwin_system_font.dart'; import 'get_bitmap_scenario.dart'; import 'initial_route_reply.dart'; import 'locale_initialization.dart'; import 'platform_view.dart'; import 'poppable_screen.dart'; import 'scenario.dart'; import 'solid_blue.dart'; import 'texture.dart'; import 'touches_scenario.dart'; typedef _ScenarioFactory = Scenario Function(FlutterView view); int _viewId = 0; Map<String, _ScenarioFactory> _scenarios = <String, _ScenarioFactory>{ 'animated_color_square': (FlutterView view) => AnimatedColorSquareScenario(view), 'solid_blue': (FlutterView view) => SolidBlueScenario(view), 'locale_initialization': (FlutterView view) => LocaleInitialization(view), 'platform_view': (FlutterView view) => PlatformViewScenario(view, id: _viewId++), 'platform_view_no_overlay_intersection': (FlutterView view) => PlatformViewNoOverlayIntersectionScenario(view, id: _viewId++), 'platform_view_larger_than_display_size': (FlutterView view) => PlatformViewLargerThanDisplaySize(view, id: _viewId++), 'platform_view_partial_intersection': (FlutterView view) => PlatformViewPartialIntersectionScenario(view, id: _viewId++), 'platform_view_two_intersecting_overlays': (FlutterView view) => PlatformViewTwoIntersectingOverlaysScenario(view, id: _viewId++), 'platform_view_one_overlay_two_intersecting_overlays': (FlutterView view) => PlatformViewOneOverlayTwoIntersectingOverlaysScenario(view, id: _viewId++), 'platform_view_multiple_without_overlays': (FlutterView view) => MultiPlatformViewWithoutOverlaysScenario(view, firstId: _viewId++, secondId: _viewId++), 'platform_view_max_overlays': (FlutterView view) => PlatformViewMaxOverlaysScenario(view, id: _viewId++), 'platform_view_cliprect': (FlutterView view) => PlatformViewClipRectScenario(view, id: _viewId++), 'platform_view_cliprect_with_transform': (FlutterView view) => PlatformViewClipRectWithTransformScenario(view, id: _viewId++), 'platform_view_cliprect_after_moved': (FlutterView view) => PlatformViewClipRectAfterMovedScenario(view, id: _viewId++), 'platform_view_cliprrect': (FlutterView view) => PlatformViewClipRRectScenario(view, id: _viewId++), 'platform_view_large_cliprrect': (FlutterView view) => PlatformViewLargeClipRRectScenario(view, id: _viewId++), 'platform_view_cliprrect_with_transform': (FlutterView view) => PlatformViewClipRRectWithTransformScenario(view, id: _viewId++), 'platform_view_large_cliprrect_with_transform': (FlutterView view) => PlatformViewLargeClipRRectWithTransformScenario(view, id: _viewId++), 'platform_view_clippath': (FlutterView view) => PlatformViewClipPathScenario(view, id: _viewId++), 'platform_view_clippath_with_transform': (FlutterView view) => PlatformViewClipPathWithTransformScenario(view, id: _viewId++), 'platform_view_transform': (FlutterView view) => PlatformViewTransformScenario(view, id: _viewId++), 'platform_view_opacity': (FlutterView view) => PlatformViewOpacityScenario(view, id: _viewId++), 'platform_view_with_other_backdrop_filter': (FlutterView view) => PlatformViewWithOtherBackDropFilter(view, id: _viewId++), 'two_platform_views_with_other_backdrop_filter': (FlutterView view) => TwoPlatformViewsWithOtherBackDropFilter(view, firstId: _viewId++, secondId: _viewId++), 'platform_view_with_negative_backdrop_filter': (FlutterView view) => PlatformViewWithNegativeBackDropFilter(view, id: _viewId++), 'platform_view_multiple': (FlutterView view) => MultiPlatformViewScenario(view, firstId: _viewId++, secondId: _viewId++), 'platform_view_multiple_background_foreground': (FlutterView view) => MultiPlatformViewBackgroundForegroundScenario(view, firstId: _viewId++, secondId: _viewId++), 'non_full_screen_flutter_view_platform_view': (FlutterView view) => NonFullScreenFlutterViewPlatformViewScenario(view, id: _viewId++), 'poppable_screen': (FlutterView view) => PoppableScreenScenario(view), 'platform_view_rotate': (FlutterView view) => PlatformViewScenario(view, id: _viewId++), 'platform_view_gesture_reject_eager': (FlutterView view) => PlatformViewForTouchIOSScenario(view, id: _viewId++, accept: false), 'platform_view_gesture_accept': (FlutterView view) => PlatformViewForTouchIOSScenario(view, id: _viewId++, accept: true), 'platform_view_gesture_reject_after_touches_ended': (FlutterView view) => PlatformViewForTouchIOSScenario(view, id: _viewId++, accept: false, rejectUntilTouchesEnded: true), 'platform_view_gesture_accept_with_overlapping_platform_views': (FlutterView view) => PlatformViewForOverlappingPlatformViewsScenario(view, foregroundId: _viewId++, backgroundId: _viewId++), 'platform_view_scrolling_under_widget':(FlutterView view) => PlatformViewScrollingUnderWidget(view, firstPlatformViewId: _viewId++, lastPlatformViewId: _viewId+=16), 'platform_views_with_clips_scrolling':(FlutterView view) => PlatformViewsWithClipsScrolling(view, firstPlatformViewId: _viewId++, lastPlatformViewId: _viewId+=16), 'two_platform_view_clip_rect': (FlutterView view) => TwoPlatformViewClipRect(view, firstId: _viewId++, secondId: _viewId++), 'two_platform_view_clip_rrect': (FlutterView view) => TwoPlatformViewClipRRect(view, firstId: _viewId++, secondId: _viewId++), 'two_platform_view_clip_path': (FlutterView view) => TwoPlatformViewClipPath(view, firstId: _viewId++, secondId: _viewId++), 'tap_status_bar': (FlutterView view) => TouchesScenario(view), 'initial_route_reply': (FlutterView view) => InitialRouteReply(view), 'platform_view_with_continuous_texture': (FlutterView view) => PlatformViewWithContinuousTexture(view, id: _viewId++), 'bogus_font_text': (FlutterView view) => BogusFontText(view), 'spawn_engine_works' : (FlutterView view) => BogusFontText(view), 'pointer_events': (FlutterView view) => TouchesScenario(view), 'display_texture': (FlutterView view) => DisplayTexture(view), 'get_bitmap': (FlutterView view) => GetBitmapScenario(view), 'app_extension': (FlutterView view) => DarwinAppExtensionScenario(view), 'darwin_system_font': (FlutterView view) => DarwinSystemFont(view), }; Map<String, dynamic> _currentScenarioParams = <String, dynamic>{}; Scenario? _currentScenarioInstance; /// Loads an scenario. /// The map must contain a `name` entry, which equals to the name of the scenario. void loadScenario(Map<String, dynamic> scenario, FlutterView view) { final String scenarioName = scenario['name'] as String; assert(_scenarios[scenarioName] != null); _currentScenarioParams = scenario; if (_currentScenarioInstance != null) { _currentScenarioInstance!.unmount(); } _currentScenarioInstance = _scenarios[scenario['name']]!(view); view.platformDispatcher.scheduleFrame(); print('Loading scenario $scenarioName'); } /// Gets the loaded [Scenario]. Scenario? get currentScenario { return _currentScenarioInstance; } /// Gets the parameters passed to the app over the channel. Map<String, dynamic> get scenarioParams { return Map<String, dynamic>.from(_currentScenarioParams); }
engine/testing/scenario_app/lib/src/scenarios.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/scenarios.dart", "repo_id": "engine", "token_count": 2368 }
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. #ifndef FLUTTER_TESTING_TEST_DART_NATIVE_RESOLVER_H_ #define FLUTTER_TESTING_TEST_DART_NATIVE_RESOLVER_H_ #include <functional> #include <map> #include <memory> #include <string> #include "flutter/fml/macros.h" #include "third_party/dart/runtime/include/dart_api.h" #define CREATE_NATIVE_ENTRY(native_entry) \ ([&]() { \ static ::flutter::testing::NativeEntry closure; \ static Dart_NativeFunction entrypoint = [](Dart_NativeArguments args) { \ closure(args); \ }; \ closure = (native_entry); \ return entrypoint; \ })() namespace flutter { namespace testing { using NativeEntry = std::function<void(Dart_NativeArguments)>; class TestDartNativeResolver : public std::enable_shared_from_this<TestDartNativeResolver> { public: TestDartNativeResolver(); ~TestDartNativeResolver(); void AddNativeCallback(const std::string& name, Dart_NativeFunction callback); void AddFfiNativeCallback(const std::string& name, void* callback_ptr); void SetNativeResolverForIsolate(); private: std::map<std::string, Dart_NativeFunction> native_callbacks_; std::map<std::string, void*> ffi_native_callbacks_; Dart_NativeFunction ResolveCallback(const std::string& name) const; void* ResolveFfiCallback(const std::string& name) const; static Dart_NativeFunction DartNativeEntryResolverCallback( Dart_Handle dart_name, int num_of_arguments, bool* auto_setup_scope); static void* FfiNativeResolver(const char* name, uintptr_t args_n); FML_DISALLOW_COPY_AND_ASSIGN(TestDartNativeResolver); }; } // namespace testing } // namespace flutter #endif // FLUTTER_TESTING_TEST_DART_NATIVE_RESOLVER_H_
engine/testing/test_dart_native_resolver.h/0
{ "file_path": "engine/testing/test_dart_native_resolver.h", "repo_id": "engine", "token_count": 985 }
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/test_vulkan_surface.h" #include <memory> #include "flutter/fml/logging.h" #include "flutter/testing/test_vulkan_context.h" #include "third_party/skia/include/core/SkColorSpace.h" #include "third_party/skia/include/core/SkColorType.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/core/SkSurfaceProps.h" #include "third_party/skia/include/gpu/GrBackendSurface.h" #include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h" #include "third_party/skia/include/gpu/ganesh/vk/GrVkBackendSurface.h" #include "third_party/skia/include/gpu/vk/GrVkTypes.h" namespace flutter { namespace testing { TestVulkanSurface::TestVulkanSurface(TestVulkanImage&& image) : image_(std::move(image)){}; std::unique_ptr<TestVulkanSurface> TestVulkanSurface::Create( const TestVulkanContext& context, const SkISize& surface_size) { auto image_result = context.CreateImage(surface_size); if (!image_result.has_value()) { FML_LOG(ERROR) << "Could not create VkImage."; return nullptr; } GrVkImageInfo image_info = { .fImage = image_result.value().GetImage(), .fImageTiling = VK_IMAGE_TILING_OPTIMAL, .fImageLayout = VK_IMAGE_LAYOUT_UNDEFINED, .fFormat = VK_FORMAT_R8G8B8A8_UNORM, .fImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, .fSampleCount = 1, .fLevelCount = 1, }; auto backend_texture = GrBackendTextures::MakeVk( surface_size.width(), surface_size.height(), image_info); SkSurfaceProps surface_properties(0, kUnknown_SkPixelGeometry); auto result = std::unique_ptr<TestVulkanSurface>( new TestVulkanSurface(std::move(image_result.value()))); result->surface_ = SkSurfaces::WrapBackendTexture( context.GetGrDirectContext().get(), // context backend_texture, // back-end texture kTopLeft_GrSurfaceOrigin, // surface origin 1, // sample count kRGBA_8888_SkColorType, // color type SkColorSpace::MakeSRGB(), // color space &surface_properties, // surface properties nullptr, // release proc nullptr // release context ); if (!result->surface_) { FML_LOG(ERROR) << "Could not wrap VkImage as an SkSurface Vulkan render texture."; return nullptr; } return result; } bool TestVulkanSurface::IsValid() const { return surface_ != nullptr; } sk_sp<SkImage> TestVulkanSurface::GetSurfaceSnapshot() const { if (!IsValid()) { return nullptr; } if (!surface_) { FML_LOG(ERROR) << "Aborting snapshot because of on-screen surface " "acquisition failure."; return nullptr; } auto device_snapshot = surface_->makeImageSnapshot(); if (!device_snapshot) { FML_LOG(ERROR) << "Could not create the device snapshot while attempting " "to snapshot the Vulkan surface."; return nullptr; } auto host_snapshot = device_snapshot->makeRasterImage(); if (!host_snapshot) { FML_LOG(ERROR) << "Could not create the host snapshot while attempting to " "snapshot the Vulkan surface."; return nullptr; } return host_snapshot; } VkImage TestVulkanSurface::GetImage() { return image_.GetImage(); } } // namespace testing } // namespace flutter
engine/testing/test_vulkan_surface.cc/0
{ "file_path": "engine/testing/test_vulkan_surface.cc", "repo_id": "engine", "token_count": 1587 }
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. import("//flutter/common/config.gni") source_set("ax") { visibility = [ "//flutter/third_party/accessibility/*" ] public_configs = [ "//flutter/third_party/accessibility:accessibility_config" ] sources = [ "platform/ax_platform_node.cc", "platform/ax_platform_node.h", "platform/ax_platform_node_base.cc", "platform/ax_platform_node_base.h", "platform/ax_platform_node_delegate.h", "platform/ax_platform_node_delegate_base.cc", "platform/ax_platform_node_delegate_base.h", "platform/ax_platform_tree_manager.h", "platform/ax_unique_id.cc", "platform/ax_unique_id.h", "platform/compute_attributes.cc", "platform/compute_attributes.h", ] sources += [ "ax_action_data.cc", "ax_action_data.h", "ax_action_handler.cc", "ax_action_handler.h", "ax_action_handler_base.cc", "ax_action_handler_base.h", "ax_active_popup.cc", "ax_active_popup.h", "ax_base_export.h", "ax_clipping_behavior.h", "ax_constants.h", "ax_coordinate_system.h", "ax_enum_util.cc", "ax_enum_util.h", "ax_enums.h", "ax_event_generator.cc", "ax_event_generator.h", "ax_event_intent.cc", "ax_event_intent.h", "ax_export.h", "ax_mode.cc", "ax_mode.h", "ax_mode_observer.h", "ax_node.cc", "ax_node.h", "ax_node_data.cc", "ax_node_data.h", "ax_node_position.cc", "ax_node_position.h", "ax_node_text_styles.cc", "ax_node_text_styles.h", "ax_offscreen_result.h", "ax_position.h", "ax_range.h", "ax_relative_bounds.cc", "ax_relative_bounds.h", "ax_role_properties.cc", "ax_role_properties.h", "ax_table_info.cc", "ax_table_info.h", "ax_tree.cc", "ax_tree.h", "ax_tree_data.cc", "ax_tree_data.h", "ax_tree_id.cc", "ax_tree_id.h", "ax_tree_id_registry.cc", "ax_tree_id_registry.h", "ax_tree_manager.h", "ax_tree_manager_map.cc", "ax_tree_manager_map.h", "ax_tree_observer.cc", "ax_tree_observer.h", "ax_tree_update.h", ] if (is_mac) { sources += [ "platform/ax_platform_node_mac.h", "platform/ax_platform_node_mac.mm", ] } else if (is_win) { sources += [ "platform/ax_fragment_root_delegate_win.h", "platform/ax_fragment_root_win.cc", "platform/ax_fragment_root_win.h", "platform/ax_platform_node_delegate_utils_win.cc", "platform/ax_platform_node_delegate_utils_win.h", "platform/ax_platform_node_textprovider_win.cc", "platform/ax_platform_node_textprovider_win.h", "platform/ax_platform_node_textrangeprovider_win.cc", "platform/ax_platform_node_textrangeprovider_win.h", "platform/ax_platform_node_win.cc", "platform/ax_platform_node_win.h", "platform/uia_registrar_win.cc", "platform/uia_registrar_win.h", ] libs = [ "oleacc.lib", "uiautomationcore.lib", ] deps = [ "//flutter/fml:fml", "//flutter/third_party/icu:icui18n", ] } public_deps = [ "//flutter/third_party/accessibility/ax_build", "//flutter/third_party/accessibility/base", "//flutter/third_party/accessibility/gfx", ] }
engine/third_party/accessibility/ax/BUILD.gn/0
{ "file_path": "engine/third_party/accessibility/ax/BUILD.gn", "repo_id": "engine", "token_count": 1576 }
398
// Copyright 2018 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_ENUMS_H_ #define UI_ACCESSIBILITY_AX_ENUMS_H_ // For new entries to the following four enums, also add to // extensions/common/api/automation.idl. This is enforced // by a PRESUBMIT check. // // Explanation of in-lined comments next to some enum values/attributes: // // Web: this attribute is only used in web content. // // Native: this attribute is only used in native UI. // // Implicit: for events, it would be cleaner if we just updated the AX node and // each platform fired the appropriate events to indicate which // platform-specific attributes changed. // // if Native / [Platform1, ...] is specified, the attribute is only used // on those platforms. // // If unspecified, the attribute is used across web and native on multiple // platforms. namespace ax { namespace mojom { enum class Event { kNone, kActiveDescendantChanged, kAlert, kAriaAttributeChanged, // Implicit kAutocorrectionOccured, // Unknown: http://crbug.com/392498 kBlur, // Remove: http://crbug.com/392502 kCheckedStateChanged, // Implicit kChildrenChanged, kClicked, kControlsChanged, kDocumentSelectionChanged, kDocumentTitleChanged, kEndOfTest, // Sentinel value indicating the end of a test kExpandedChanged, // Web kFocus, kFocusAfterMenuClose, kFocusContext, // Contextual focus event that must delay the next focus event kHide, // Remove: http://crbug.com/392502 kHitTestResult, kHover, kImageFrameUpdated, // Web kInvalidStatusChanged, // Implicit kLayoutComplete, // Web kLiveRegionCreated, // Implicit kLiveRegionChanged, // Web kLoadComplete, // Web kLoadStart, // Web / AuraLinux kLocationChanged, // Web kMediaStartedPlaying, // Native / Automation kMediaStoppedPlaying, // Native / Automation kMenuEnd, // Native / web: menu interaction has ended. kMenuListItemSelected, // Web kMenuListValueChanged, // Web kMenuPopupEnd, // Native / web: a menu/submenu is hidden/closed. kMenuPopupStart, // Native / web: a menu/submenu is shown/opened. kMenuStart, // Native / web: menu interaction has begun. kMouseCanceled, kMouseDragged, kMouseMoved, kMousePressed, kMouseReleased, kRowCollapsed, kRowCountChanged, kRowExpanded, kScrollPositionChanged, // Web kScrolledToAnchor, // Web kSelectedChildrenChanged, // Web kSelection, // Native kSelectionAdd, // Native kSelectionRemove, // Native kShow, // Native / Automation kStateChanged, // Native / Automation kTextChanged, kWindowActivated, // Native kWindowDeactivated, // Native kWindowVisibilityChanged, // Native kTextSelectionChanged, kTooltipClosed, kTooltipOpened, kTreeChanged, // Accessibility tree changed. Don't // explicitly fire an accessibility event, // only implicitly due to the change. kValueChanged, kMinValue = kNone, kMaxValue = kValueChanged, }; // Accessibility object roles. // The majority of these roles come from the ARIA specification. Reference // the latest draft for proper usage. // // Roles not included by the ARIA specification should be avoided, especially // internal roles used by the accessibility infrastructure. // // Explanation of in-lined comments next to some enum values. // // Web: this attribute is only used in web content. // // Native: this attribute is only used in native UI. enum class Role { kNone, kAbbr, kAlert, kAlertDialog, kAnchor, kApplication, kArticle, kAudio, kBanner, kBlockquote, kButton, kCanvas, kCaption, kCaret, kCell, kCheckBox, kClient, kCode, kColorWell, kColumn, kColumnHeader, kComboBoxGrouping, kComboBoxMenuButton, kComplementary, kComment, kContentDeletion, kContentInsertion, kContentInfo, kDate, kDateTime, kDefinition, kDescriptionList, kDescriptionListDetail, kDescriptionListTerm, kDesktop, // internal kDetails, kDialog, kDirectory, kDisclosureTriangle, // -------------------------------------------------------------- // DPub Roles: // https://www.w3.org/TR/dpub-aam-1.0/#mapping_role_table kDocAbstract, kDocAcknowledgments, kDocAfterword, kDocAppendix, kDocBackLink, kDocBiblioEntry, kDocBibliography, kDocBiblioRef, kDocChapter, kDocColophon, kDocConclusion, kDocCover, kDocCredit, kDocCredits, kDocDedication, kDocEndnote, kDocEndnotes, kDocEpigraph, kDocEpilogue, kDocErrata, kDocExample, kDocFootnote, kDocForeword, kDocGlossary, kDocGlossRef, kDocIndex, kDocIntroduction, kDocNoteRef, kDocNotice, kDocPageBreak, kDocPageList, kDocPart, kDocPreface, kDocPrologue, kDocPullquote, kDocQna, kDocSubtitle, kDocTip, kDocToc, // End DPub roles. // -------------------------------------------------------------- kDocument, kEmbeddedObject, kEmphasis, kFeed, kFigcaption, kFigure, kFooter, kFooterAsNonLandmark, kForm, kGenericContainer, // -------------------------------------------------------------- // ARIA Graphics module roles: // https://rawgit.com/w3c/graphics-aam/master/#mapping_role_table kGraphicsDocument, kGraphicsObject, kGraphicsSymbol, // End ARIA Graphics module roles. // -------------------------------------------------------------- kGrid, kGroup, kHeader, kHeaderAsNonLandmark, kHeading, kIframe, kIframePresentational, kIgnored, kImage, kImageMap, kImeCandidate, kInlineTextBox, kInputTime, kKeyboard, kLabelText, kLayoutTable, kLayoutTableCell, kLayoutTableRow, kLegend, kLineBreak, kLink, kList, kListBox, kListBoxOption, // kListGrid behaves similar to an ARIA grid but is primarily used by // TableView and its subclasses, so that they could be exposed correctly on // certain platforms. kListGrid, // Native kListItem, kListMarker, kLog, kMain, kMark, kMarquee, kMath, kMenu, kMenuBar, kMenuItem, kMenuItemCheckBox, kMenuItemRadio, kMenuListOption, kMenuListPopup, kMeter, kNavigation, kNote, kPane, kParagraph, kPdfActionableHighlight, // PDF specific highlight role. kPluginObject, kPopUpButton, kPortal, kPre, kPresentational, kProgressIndicator, kRadioButton, kRadioGroup, kRegion, kRootWebArea, kRow, kRowGroup, kRowHeader, kRuby, kRubyAnnotation, kScrollBar, kScrollView, kSearch, kSearchBox, kSection, kSlider, kSliderThumb, kSpinButton, kSplitter, kStaticText, kStatus, kStrong, kSuggestion, kSvgRoot, kSwitch, kTab, kTabList, kTabPanel, kTable, kTableHeaderContainer, kTerm, kTextField, kTextFieldWithComboBox, kTime, kTimer, kTitleBar, kToggleButton, kToolbar, kTooltip, kTree, kTreeGrid, kTreeItem, kUnknown, kVideo, kWebArea, kWebView, kWindow, kMinValue = kNone, kMaxValue = kWindow, }; enum class State { kNone, kAutofillAvailable, kCollapsed, kDefault, kEditable, kExpanded, kFocusable, // Grows horizontally, e.g. most toolbars and separators. kHorizontal, kHovered, // Skip over this node in the accessibility tree, but keep its subtree. kIgnored, kInvisible, kLinked, kMultiline, kMultiselectable, kProtected, kRequired, kRichlyEditable, // Grows vertically, e.g. menu or combo box. kVertical, kVisited, kMinValue = kNone, kMaxValue = kVisited, }; // An action to be taken on an accessibility node. // In contrast to |AXDefaultActionVerb|, these describe what happens to the // object, e.g. "FOCUS". enum class Action { kNone, // Request image annotations for all the eligible images on a page. kAnnotatePageImages, kBlur, // Notifies a node that it no longer has accessibility focus. // Currently used only on Android and only internally, it's not // exposed to the open web. See kSetAccessibilityFocus, below. kClearAccessibilityFocus, // Collapse the collapsible node. kCollapse, kCustomAction, // Decrement a slider or range control by one step value. kDecrement, // Do the default action for an object, typically this means "click". kDoDefault, // Expand the expandable node. kExpand, kFocus, // Return the content of this image object in the image_data attribute. kGetImageData, // Gets the bounding rect for a range of text. kGetTextLocation, kHideTooltip, // Given a point, find the object it corresponds to and fire a // |AXActionData.hit_test_event_to_fire| event on it in response. kHitTest, // Increment a slider or range control by one step value. kIncrement, // For internal use only; signals to tree sources to invalidate an entire // tree. kInternalInvalidateTree, // Load inline text boxes for this subtree, providing information // about word boundaries, line layout, and individual character // bounding boxes. kLoadInlineTextBoxes, // Delete any selected text in the control's text value and // insert |AXActionData::value| in its place, like when typing or pasting. kReplaceSelectedText, // Scrolls by approximately one screen in a specific direction. Should be // called on a node that has scrollable boolean set to true. kScrollBackward, kScrollDown, kScrollForward, kScrollLeft, kScrollRight, kScrollUp, // Scroll any scrollable containers to make the target object visible // on the screen. Optionally pass a subfocus rect in // AXActionData.target_rect, in node-local coordinates. kScrollToMakeVisible, // Scroll the given object to a specified point on the screen in // global screen coordinates. Pass a point in AXActionData.target_point. kScrollToPoint, // Notifies a node that it has accessibility focus. // Currently used only on Android and only internally, it's not // exposed to the open web. See kClearAccessibilityFocus, above. kSetAccessibilityFocus, kSetScrollOffset, kSetSelection, // Don't focus this node, but set it as the sequential focus navigation // starting point, so that pressing Tab moves to the next element // following this one, for example. kSetSequentialFocusNavigationStartingPoint, // Replace the value of the control with AXActionData::value and // reset the selection, if applicable. kSetValue, kShowContextMenu, // Send an event signaling the end of a test. kSignalEndOfTest, kShowTooltip, // Used for looping through the enum, This must be the last value of this // enum. kMinValue = kNone, kMaxValue = kShowTooltip, }; enum class ActionFlags { kNone, kRequestImages, kRequestInlineTextBoxes, kMinValue = kNone, kMaxValue = kRequestInlineTextBoxes, }; // A list of valid values for the horizontal and vertical scroll alignment // arguments in |AXActionData|. These values control where a node is scrolled // in the viewport. enum class ScrollAlignment { kNone, kScrollAlignmentCenter, kScrollAlignmentTop, kScrollAlignmentBottom, kScrollAlignmentLeft, kScrollAlignmentRight, kScrollAlignmentClosestEdge, kMinValue = kNone, kMaxValue = kScrollAlignmentClosestEdge, }; // A list of valid values for the scroll behavior argument to argument in // |AXActionData|. These values control whether a node is scrolled in the // viewport if it is already visible. enum class ScrollBehavior { kNone, kDoNotScrollIfVisible, kScrollIfVisible, kMinValue = kNone, kMaxValue = kScrollIfVisible, }; // A list of valid values for the |AXIntAttribute| |default_action_verb|. // These will describe the action that will be performed on a given node when // executing the default action, which is a click. // In contrast to |AXAction|, these describe what the user can do on the // object, e.g. "PRESS", not what happens to the object as a result. // Only one verb can be used at a time to describe the default action. enum class DefaultActionVerb { kNone, kActivate, kCheck, kClick, // A click will be performed on one of the node's ancestors. // This happens when the node itself is not clickable, but one of its // ancestors has click handlers attached which are able to capture the click // as it bubbles up. kClickAncestor, kJump, kOpen, kPress, kSelect, kUncheck, kMinValue = kNone, kMaxValue = kUncheck, }; // A change to the accessibility tree. enum class Mutation { kNone, kNodeCreated, kSubtreeCreated, kNodeChanged, kNodeRemoved, kMinValue = kNone, kMaxValue = kNodeRemoved, }; enum class StringAttribute { kNone, kAccessKey, // Only used when invalid_state == invalid_state_other. kAriaInvalidValue, kAutoComplete, kChildTreeId, kClassName, kContainerLiveRelevant, kContainerLiveStatus, kDescription, kDisplay, // Only present when different from parent. kFontFamily, kHtmlTag, // Stores an automatic image annotation if one is available. Only valid on // ax::mojom::Role::kImage. See kImageAnnotationStatus, too. kImageAnnotation, kImageDataUrl, kInnerHtml, kInputType, kKeyShortcuts, // Only present when different from parent. kLanguage, kName, kLiveRelevant, kLiveStatus, // Only if not already exposed in kName (NameFrom::kPlaceholder) kPlaceholder, kRole, kRoleDescription, // Only if not already exposed in kName (NameFrom::kTitle) kTooltip, kUrl, kValue, kMinValue = kNone, kMaxValue = kValue, }; enum class IntAttribute { kNone, kDefaultActionVerb, // Scrollable container attributes. kScrollX, kScrollXMin, kScrollXMax, kScrollY, kScrollYMin, kScrollYMax, // Attributes for retrieving the endpoints of a selection. kTextSelStart, kTextSelEnd, // aria_col* and aria_row* attributes kAriaColumnCount, kAriaCellColumnIndex, kAriaCellColumnSpan, kAriaRowCount, kAriaCellRowIndex, kAriaCellRowSpan, // Table attributes. kTableRowCount, kTableColumnCount, kTableHeaderId, // Table row attributes. kTableRowIndex, kTableRowHeaderId, // Table column attributes. kTableColumnIndex, kTableColumnHeaderId, // Table cell attributes. kTableCellColumnIndex, kTableCellColumnSpan, kTableCellRowIndex, kTableCellRowSpan, kSortDirection, // Tree control attributes. kHierarchicalLevel, // What information was used to compute the object's name // (of type AXNameFrom). kNameFrom, // What information was used to compute the object's description // (of type AXDescriptionFrom). kDescriptionFrom, // Relationships between this element and other elements. kActivedescendantId, kErrormessageId, kInPageLinkTargetId, kMemberOfId, kNextOnLineId, kPopupForId, kPreviousOnLineId, // Input restriction, if any, such as readonly or disabled. // Of type AXRestriction, see below. // No value or enabled control or other object that is not disabled. kRestriction, // Position or Number of items in current set of listitems or treeitems kSetSize, kPosInSet, // In the case of Role::kColorWell, specifies the selected color. kColorValue, // Indicates the element that represents the current item within a container // or set of related elements. kAriaCurrentState, // Text attributes. // Foreground and background color in RGBA. kBackgroundColor, kColor, kHasPopup, // Image annotation status, of type ImageAnnotationStatus. kImageAnnotationStatus, // Indicates if a form control has invalid input or // if an element has an aria-invalid attribute. kInvalidState, // Of type AXCheckedState kCheckedState, // The list style type. Only available on list items. kListStyle, // Specifies the alignment of the text, e.g. left, center, right, justify kTextAlign, // Specifies the direction of the text, e.g., right-to-left. kTextDirection, // Specifies the position of the text, e.g., subscript. kTextPosition, // Bold, italic, underline, etc. kTextStyle, // The overline text decoration style. kTextOverlineStyle, // The strikethrough text decoration style. kTextStrikethroughStyle, // The underline text decoration style. kTextUnderlineStyle, // Focus traversal in views and Android. kPreviousFocusId, kNextFocusId, // For indicating what functions can be performed when a dragged object // is released on the drop target. // Note: aria-dropeffect is deprecated in WAI-ARIA 1.1. kDropeffect, // The DOMNodeID from Blink. Currently only populated when using // the accessibility tree for PDF exporting. Warning, this is totally // unrelated to the accessibility node ID, or the ID attribute for an // HTML element - it's an ID used to uniquely identify nodes in Blink. kDOMNodeId, kMinValue = kNone, kMaxValue = kDOMNodeId, }; enum class FloatAttribute { kNone, // Range attributes. kValueForRange, kMinValueForRange, kMaxValueForRange, kStepValueForRange, // Text attributes. // Font size is in pixels. kFontSize, // Font weight can take on any arbitrary numeric value. Increments of 100 in // range [0, 900] represent keywords such as light, normal, bold, etc. 0 is // the default. kFontWeight, // The text indent of the text, in mm. kTextIndent, kMinValue = kNone, kMaxValue = kTextIndent, }; // These attributes can take three states: // true, false, or undefined/unset. // // Some attributes are only ever true or unset. In these cases, undefined is // equivalent to false. In other attributes, all three states have meaning. // // Finally, note that different tree sources can use all three states for a // given attribute, while another tree source only uses two. enum class BoolAttribute { kNone, // Generic busy state, does not have to be on a live region. kBusy, // The object is at the root of an editable field, such as a content // editable. kEditableRoot, // Live region attributes. kContainerLiveAtomic, kContainerLiveBusy, kLiveAtomic, // If a dialog box is marked as explicitly modal kModal, // If this is set, all of the other fields in this struct should // be ignored and only the locations should change. kUpdateLocationOnly, // Set on a canvas element if it has fallback content. kCanvasHasFallback, // Indicates this node is user-scrollable, e.g. overflow:scroll|auto, as // opposed to only programmatically scrollable, like overflow:hidden, or // not scrollable at all, e.g. overflow:visible. kScrollable, // A hint to clients that the node is clickable. kClickable, // Indicates that this node clips its children, i.e. may have // overflow: hidden or clip children by default. kClipsChildren, // Indicates that this node is not selectable because the style has // user-select: none. Note that there may be other reasons why a node is // not selectable - for example, bullets in a list. However, this attribute // is only set on user-select: none. kNotUserSelectableStyle, // Indicates whether this node is selected or unselected. kSelected, // Indicates whether this node is selected due to selection follows focus. kSelectedFromFocus, // Indicates whether this node supports text location. kSupportsTextLocation, // Indicates whether this node can be grabbed for drag-and-drop operation. // Note: aria-grabbed is deprecated in WAI-ARIA 1.1. kGrabbed, // Indicates whether this node causes a hard line-break // (e.g. block level elements, or <br>) kIsLineBreakingObject, // Indicates whether this node causes a page break kIsPageBreakingObject, // True if the node has any ARIA attributes set. kHasAriaAttribute, kMinValue = kNone, kMaxValue = kHasAriaAttribute, }; enum class IntListAttribute { kNone, // Ids of nodes that are children of this node logically, but are // not children of this node in the tree structure. As an example, // a table cell is a child of a row, and an 'indirect' child of a // column. kIndirectChildIds, // Relationships between this element and other elements. kControlsIds, kDetailsIds, kDescribedbyIds, kFlowtoIds, kLabelledbyIds, kRadioGroupIds, // For static text. These int lists must be the same size; they represent // the start and end character offset of each marker. Examples of markers // include spelling and grammar errors, and find-in-page matches. kMarkerTypes, kMarkerStarts, kMarkerEnds, // For inline text. This is the pixel position of the end of this // character within the bounding rectangle of this object, in the // direction given by StringAttribute::kTextDirection. For example, // for left-to-right text, the first offset is the right coordinate of // the first character within the object's bounds, the second offset // is the right coordinate of the second character, and so on. kCharacterOffsets, // Used for caching. Do not read directly. Use // |AXNode::GetOrComputeLineStartOffsets| // For all text fields and content editable roots: A list of the start // offsets of each line inside this object. kCachedLineStarts, // For inline text. These int lists must be the same size; they represent // the start and end character offset of each word within this text. kWordStarts, kWordEnds, // Used for an UI element to define custom actions for it. For example, a // list UI will allow a user to reorder items in the list by dragging the // items. Developer can expose those actions as custom actions. Currently // custom actions are used only in Android window. kCustomActionIds, kMinValue = kNone, kMaxValue = kCustomActionIds, }; enum class StringListAttribute { kNone, // Descriptions for custom actions. This must be aligned with // custom_action_ids. kCustomActionDescriptions, kMinValue = kNone, kMaxValue = kCustomActionDescriptions, }; enum class ListStyle { kNone, kCircle, kDisc, kImage, kNumeric, kSquare, kOther, // Language specific ordering (alpha, roman, cjk-ideographic, etc...) kMinValue = kNone, kMaxValue = kOther, }; enum class MarkerType { kNone = 0, kSpelling = 1, kGrammar = 2, kTextMatch = 4, // DocumentMarker::MarkerType::Composition = 8 is ignored for accessibility // purposes kActiveSuggestion = 16, kSuggestion = 32, kMinValue = kNone, kMaxValue = kSuggestion, }; // Describes a move direction in the accessibility tree that is independent of // the left-to-right or right-to-left direction of the text. For example, a // forward movement will always move to the next node in depth-first pre-order // traversal. enum class MoveDirection { kForward, kBackward, kNone = kForward, kMinValue = kForward, kMaxValue = kBackward, }; // Describes the edit or selection command that resulted in a selection or a // text changed event. enum class Command { kClearSelection, kCut, kDelete, kDictate, kExtendSelection, // The existing selection has been extended or shrunk. kFormat, // The text attributes, such as font size, have changed. kInsert, kMarker, // A document marker has been added or removed. kMoveSelection, // The selection has been moved by a specific granularity. kPaste, kReplace, kSetSelection, // A completely new selection has been set. kType, kNone = kType, kMinValue = kClearSelection, kMaxValue = kType, }; // Defines a set of text boundaries in the accessibility tree. // // Most boundaries come in three flavors: A "WordStartOrEnd" boundary for // example differs from a "WordStart" or a "WordEnd" boundary in that the first // would consider both the start and the end of the word to be boundaries, while // the other two would consider only the start or the end respectively. // // An "Object" boundary is found at the start or end of a node's entire text, // e.g. at the start or end of a text field. // // TODO(nektar): Split TextBoundary into TextUnit and TextBoundary. enum class TextBoundary { kCharacter, kFormat, kLineEnd, kLineStart, kLineStartOrEnd, kObject, kPageEnd, kPageStart, kPageStartOrEnd, kParagraphEnd, kParagraphStart, kParagraphStartOrEnd, kSentenceEnd, kSentenceStart, kSentenceStartOrEnd, kWebPage, kWordEnd, kWordStart, kWordStartOrEnd, kNone = kObject, kMinValue = kCharacter, kMaxValue = kWordStartOrEnd, }; // Types of text alignment according to the IAccessible2 Object Attributes spec. enum class TextAlign { kNone, kLeft, kRight, kCenter, kJustify, kMinValue = kNone, kMaxValue = kJustify, }; enum class WritingDirection { kNone, kLtr, kRtl, kTtb, kBtt, kMinValue = kNone, kMaxValue = kBtt, }; enum class TextPosition { kNone, kSubscript, kSuperscript, kMinValue = kNone, kMaxValue = kSuperscript, }; // A Java counterpart will be generated for this enum. // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.ui.accessibility enum class TextStyle { kBold, kItalic, kUnderline, kLineThrough, kOverline, kNone, kMinValue = kBold, kMaxValue = kNone, }; enum class TextDecorationStyle { kNone, kDotted, kDashed, kSolid, kDouble, kWavy, kMinValue = kNone, kMaxValue = kWavy, }; enum class AriaCurrentState { kNone, kFalse, kTrue, kPage, kStep, kLocation, kUnclippedLocation, kDate, kTime, kMinValue = kNone, kMaxValue = kTime, }; enum class HasPopup { kFalse = 0, kTrue, kMenu, kListbox, kTree, kGrid, kDialog, kNone = kFalse, kMinValue = kNone, kMaxValue = kDialog, }; enum class InvalidState { kNone, kFalse, kTrue, kOther, kMinValue = kNone, kMaxValue = kOther, }; // Input restriction associated with an object. // No value for a control means it is enabled. // Use read_only for a textbox that allows focus/selection but not input. // Use disabled for a control or group of controls that disallows input. enum class Restriction { kNone, kReadOnly, kDisabled, kMinValue = kNone, kMaxValue = kDisabled, }; enum class CheckedState { kNone, kFalse, kTrue, kMixed, kMinValue = kNone, kMaxValue = kMixed, }; enum class SortDirection { kNone, kUnsorted, kAscending, kDescending, kOther, kMinValue = kNone, kMaxValue = kOther, }; enum class NameFrom { kNone, kUninitialized, kAttribute, // E.g. aria-label. kAttributeExplicitlyEmpty, kCaption, // E.g. in the case of a table, from a caption element. kContents, kPlaceholder, // E.g. from an HTML placeholder attribute on a text field. kRelatedElement, // E.g. from a figcaption Element in a figure. kTitle, // E.g. <input type="text" title="title">. kValue, // E.g. <input type="button" value="Button's name">. kMinValue = kNone, kMaxValue = kValue, }; enum class DescriptionFrom { kNone, kUninitialized, kAttribute, kContents, kRelatedElement, kTitle, kMinValue = kNone, kMaxValue = kTitle, }; enum class EventFrom { kNone, kUser, kPage, kAction, kMinValue = kNone, kMaxValue = kAction, }; // Touch gestures on Chrome OS. enum class Gesture { kNone, kClick, kSwipeLeft1, kSwipeUp1, kSwipeRight1, kSwipeDown1, kSwipeLeft2, kSwipeUp2, kSwipeRight2, kSwipeDown2, kSwipeLeft3, kSwipeUp3, kSwipeRight3, kSwipeDown3, kSwipeLeft4, kSwipeUp4, kSwipeRight4, kSwipeDown4, kTap2, kTap3, kTap4, kTouchExplore, kMinValue = kNone, kMaxValue = kTouchExplore, }; enum class TextAffinity { kNone, kDownstream, kUpstream, kMinValue = kNone, kMaxValue = kUpstream, }; // Compares two nodes in an accessibility tree in pre-order traversal. enum class TreeOrder { kNone, // Not in the same tree, or other error. kUndefined, // First node is before the second one. kBefore, // Nodes are the same. kEqual, // First node is after the second one. kAfter, kMinValue = kNone, kMaxValue = kAfter, }; // For internal use by ui::AXTreeID / ui::AXTreeID. enum class AXTreeIDType { kUnknown, // The Tree ID is unknown. kToken, // Every other tree ID must have a valid unguessable token. kMinValue = kUnknown, kMaxValue = kToken, }; enum class ImageAnnotationStatus { // Not an image, or image annotation feature not enabled. kNone, // Not eligible due to the scheme of the page. Image annotations are only // generated for images on http, https, file and data URLs. kWillNotAnnotateDueToScheme, // Not loaded yet, already labeled by the author, or not eligible // due to size, type, etc. kIneligibleForAnnotation, // Eligible to be automatically annotated if the user requests it. // This is communicated to the user via a tutor message. kEligibleForAnnotation, // Eligible to be automatically annotated but this is not communicated to the // user. kSilentlyEligibleForAnnotation, // An annotation has been requested but has not been received yet. kAnnotationPending, // An annotation has been provided and kImageAnnotation contains the // annotation text. kAnnotationSucceeded, // The annotation request was processed successfully, but it was not // possible to come up with an annotation for this image. kAnnotationEmpty, // The image is classified as adult content and no annotation will // be generated. kAnnotationAdult, // The annotation process failed, e.g. unable to contact the server, // request timed out, etc. kAnnotationProcessFailed, kMinValue = kNone, kMaxValue = kAnnotationProcessFailed, }; enum class Dropeffect { kNone, kCopy, kExecute, kLink, kMove, kPopup, kMinValue = kNone, kMaxValue = kPopup, }; } // namespace mojom } // namespace ax #endif // UI_ACCESSIBILITY_AX_ENUMS_H_
engine/third_party/accessibility/ax/ax_enums.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_enums.h", "repo_id": "engine", "token_count": 9901 }
399
// Copyright 2016 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_NODE_POSITION_H_ #define UI_ACCESSIBILITY_AX_NODE_POSITION_H_ #include <cstdint> #include <vector> #include "ax_enums.h" #include "ax_export.h" #include "ax_node.h" #include "ax_position.h" #include "ax_tree_id.h" namespace ui { // AXNodePosition includes implementations of AXPosition methods which require // knowledge of the AXPosition AXNodeType (which is unknown by AXPosition). class AX_EXPORT AXNodePosition : public AXPosition<AXNodePosition, AXNode> { public: // Creates either a text or a tree position, depending on the type of the node // provided. static AXPositionInstance CreatePosition( const AXNode& node, int child_index_or_text_offset, ax::mojom::TextAffinity affinity = ax::mojom::TextAffinity::kDownstream); AXNodePosition(); ~AXNodePosition() override; AXNodePosition(const AXNodePosition& other); AXPositionInstance Clone() const override; std::u16string GetText() const override; bool IsInLineBreak() const override; bool IsInTextObject() const override; bool IsInWhiteSpace() const override; int MaxTextOffset() const override; protected: void AnchorChild(int child_index, AXTreeID* tree_id, AXNode::AXID* child_id) const override; int AnchorChildCount() const override; int AnchorUnignoredChildCount() const override; int AnchorIndexInParent() const override; int AnchorSiblingCount() const override; std::stack<AXNode*> GetAncestorAnchors() const override; AXNode* GetLowestUnignoredAncestor() const override; void AnchorParent(AXTreeID* tree_id, AXNode::AXID* parent_id) const override; AXNode* GetNodeInTree(AXTreeID tree_id, AXNode::AXID node_id) const override; AXNode::AXID GetAnchorID(AXNode* node) const override; AXTreeID GetTreeID(AXNode* node) const override; bool IsEmbeddedObjectInParent() const override; bool IsInLineBreakingObject() const override; ax::mojom::Role GetAnchorRole() const override; ax::mojom::Role GetRole(AXNode* node) const override; AXNodeTextStyles GetTextStyles() const override; std::vector<int32_t> GetWordStartOffsets() const override; std::vector<int32_t> GetWordEndOffsets() const override; AXNode::AXID GetNextOnLineID(AXNode::AXID node_id) const override; AXNode::AXID GetPreviousOnLineID(AXNode::AXID node_id) const override; private: // Returns the parent node of the provided child. Returns the parent // node's tree id and node id through the provided output parameters, // |parent_tree_id| and |parent_id|. static AXNode* GetParent(AXNode* child, AXTreeID child_tree_id, AXTreeID* parent_tree_id, AXNode::AXID* parent_id); }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_NODE_POSITION_H_
engine/third_party/accessibility/ax/ax_node_position.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_node_position.h", "repo_id": "engine", "token_count": 1044 }
400
// 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_tree.h" #include <algorithm> #include <cstddef> #include <numeric> #include <utility> #include "ax_enums.h" #include "ax_node.h" #include "ax_node_position.h" #include "ax_role_properties.h" #include "ax_table_info.h" #include "ax_tree_observer.h" #include "base/auto_reset.h" #include "base/string_utils.h" namespace ui { namespace { std::string TreeToStringHelper(const AXNode* node, int indent) { if (!node) return ""; return std::accumulate( node->children().cbegin(), node->children().cend(), std::string(2 * indent, ' ') + node->data().ToString() + "\n", [indent](const std::string& str, const auto* child) { return str + TreeToStringHelper(child, indent + 1); }); } template <typename K, typename V> bool KeyValuePairsKeysMatch(std::vector<std::pair<K, V>> pairs1, std::vector<std::pair<K, V>> pairs2) { if (pairs1.size() != pairs2.size()) return false; for (size_t i = 0; i < pairs1.size(); ++i) { if (pairs1[i].first != pairs2[i].first) return false; } return true; } template <typename K, typename V> std::map<K, V> MapFromKeyValuePairs(std::vector<std::pair<K, V>> pairs) { std::map<K, V> result; for (size_t i = 0; i < pairs.size(); ++i) result[pairs[i].first] = pairs[i].second; return result; } // Given two vectors of <K, V> key, value pairs representing an "old" vs "new" // state, or "before" vs "after", calls a callback function for each key that // changed value. Note that if an attribute is removed, that will result in // a call to the callback with the value changing from the previous value to // |empty_value|, and similarly when an attribute is added. template <typename K, typename V, typename F> void CallIfAttributeValuesChanged(const std::vector<std::pair<K, V>>& pairs1, const std::vector<std::pair<K, V>>& pairs2, const V& empty_value, F callback) { // Fast path - if they both have the same keys in the same order. if (KeyValuePairsKeysMatch(pairs1, pairs2)) { for (size_t i = 0; i < pairs1.size(); ++i) { if (pairs1[i].second != pairs2[i].second) callback(pairs1[i].first, pairs1[i].second, pairs2[i].second); } return; } // Slower path - they don't have the same keys in the same order, so // check all keys against each other, using maps to prevent this from // becoming O(n^2) as the size grows. auto map1 = MapFromKeyValuePairs(pairs1); auto map2 = MapFromKeyValuePairs(pairs2); for (size_t i = 0; i < pairs1.size(); ++i) { const auto& new_iter = map2.find(pairs1[i].first); if (pairs1[i].second != empty_value && new_iter == map2.end()) callback(pairs1[i].first, pairs1[i].second, empty_value); } for (size_t i = 0; i < pairs2.size(); ++i) { const auto& iter = map1.find(pairs2[i].first); if (iter == map1.end()) callback(pairs2[i].first, empty_value, pairs2[i].second); else if (iter->second != pairs2[i].second) callback(pairs2[i].first, iter->second, pairs2[i].second); } } bool IsCollapsed(const AXNode* node) { return node && node->data().HasState(ax::mojom::State::kCollapsed); } } // namespace // This object is used to track structure changes that will occur for a specific // AXID. This includes how many times we expect that a node with a specific AXID // will be created and/or destroyed, and how many times a subtree rooted at AXID // expects to be destroyed during an AXTreeUpdate. // // An AXTreeUpdate is a serialized representation of an atomic change to an // AXTree. See also |AXTreeUpdate| which documents the nature and invariants // required to atomically update the AXTree. // // The reason that we must track these counts, and the reason these are counts // rather than a bool/flag is because an AXTreeUpdate may contain multiple // AXNodeData updates for a given AXID. A common way that this occurs is when // multiple AXTreeUpdates are merged together, combining their AXNodeData list. // Additionally AXIDs may be reused after being removed from the tree, // most notably when "reparenting" a node. A "reparent" occurs when an AXID is // first destroyed from the tree then created again in the same AXTreeUpdate, // which may also occur multiple times with merged updates. // // We need to accumulate these counts for 3 reasons : // 1. To determine what structure changes *will* occur before applying // updates to the tree so that we can notify observers of structure changes // when the tree is still in a stable and unchanged state. // 2. Capture any errors *before* applying updates to the tree structure // due to the order of (or lack of) AXNodeData entries in the update // so we can abort a bad update instead of applying it partway. // 3. To validate that the expectations we accumulate actually match // updates that are applied to the tree. // // To reiterate the invariants that this structure is taking a dependency on // from |AXTreeUpdate|, suppose that the next AXNodeData to be applied is // |node|. The following invariants must hold: // 1. Either // a) |node.id| is already in the tree, or // b) the tree is empty, and // |node| is the new root of the tree, and // |node.role| == WebAXRoleRootWebArea. // 2. Every child id in |node.child_ids| must either be already a child // of this node, or a new id not previously in the tree. It is not // allowed to "reparent" a child to this node without first removing // that child from its previous parent. // 3. When a new id appears in |node.child_ids|, the tree should create a // new uninitialized placeholder node for it immediately. That // placeholder must be updated within the same AXTreeUpdate, otherwise // it's a fatal error. This guarantees the tree is always complete // before or after an AXTreeUpdate. struct PendingStructureChanges { explicit PendingStructureChanges(const AXNode* node) : destroy_subtree_count(0), destroy_node_count(0), create_node_count(0), node_exists(!!node), parent_node_id((node && node->parent()) ? std::optional<AXNode::AXID>{node->parent()->id()} : std::nullopt), last_known_data(node ? &node->data() : nullptr) {} // Returns true if this node has any changes remaining. // This includes pending subtree or node destruction, and node creation. bool DoesNodeExpectAnyStructureChanges() const { return DoesNodeExpectSubtreeWillBeDestroyed() || DoesNodeExpectNodeWillBeDestroyed() || DoesNodeExpectNodeWillBeCreated(); } // Returns true if there are any pending changes that require destroying // this node or its subtree. bool DoesNodeExpectSubtreeOrNodeWillBeDestroyed() const { return DoesNodeExpectSubtreeWillBeDestroyed() || DoesNodeExpectNodeWillBeDestroyed(); } // Returns true if the subtree rooted at this node needs to be destroyed // during the update, but this may not be the next action that needs to be // performed on the node. bool DoesNodeExpectSubtreeWillBeDestroyed() const { return destroy_subtree_count; } // Returns true if this node needs to be destroyed during the update, but this // may not be the next action that needs to be performed on the node. bool DoesNodeExpectNodeWillBeDestroyed() const { return destroy_node_count; } // Returns true if this node needs be created during the update, but this // may not be the next action that needs to be performed on the node. bool DoesNodeExpectNodeWillBeCreated() const { return create_node_count; } // Returns true if this node would exist in the tree as of the last pending // update that was processed, and the node has not been provided node data. bool DoesNodeRequireInit() const { return node_exists && !last_known_data; } // Keep track of the number of times the subtree rooted at this node // will be destroyed. // An example of when this count may be larger than 1 is if updates were // merged together. A subtree may be [created,] destroyed, created, and // destroyed again within the same |AXTreeUpdate|. The important takeaway here // is that an update may request destruction of a subtree rooted at an // AXID more than once, not that a specific subtree is being destroyed // more than once. int32_t destroy_subtree_count; // Keep track of the number of times this node will be destroyed. // An example of when this count may be larger than 1 is if updates were // merged together. A node may be [created,] destroyed, created, and destroyed // again within the same |AXTreeUpdate|. The important takeaway here is that // an AXID may request destruction more than once, not that a specific node // is being destroyed more than once. int32_t destroy_node_count; // Keep track of the number of times this node will be created. // An example of when this count may be larger than 1 is if updates were // merged together. A node may be [destroyed,] created, destroyed, and created // again within the same |AXTreeUpdate|. The important takeaway here is that // an AXID may request creation more than once, not that a specific node is // being created more than once. int32_t create_node_count; // Keep track of whether this node exists in the tree as of the last pending // update that was processed. bool node_exists; // Keep track of the parent id for this node as of the last pending // update that was processed. std::optional<AXNode::AXID> parent_node_id; // Keep track of the last known node data for this node. // This will be null either when a node does not exist in the tree, or // when the node is new and has not been initialized with node data yet. // This is needed to determine what children have changed between pending // updates. const AXNodeData* last_known_data; }; // Represents the different states when computing PendingStructureChanges // required for tree Unserialize. enum class AXTreePendingStructureStatus { // PendingStructureChanges have not begun computation. kNotStarted, // PendingStructureChanges are currently being computed. kComputing, // All PendingStructureChanges have successfully been computed. kComplete, // An error occurred when computing pending changes. kFailed, }; // Intermediate state to keep track of during a tree update. struct AXTreeUpdateState { explicit AXTreeUpdateState(const AXTree& tree) : pending_update_status(AXTreePendingStructureStatus::kNotStarted), root_will_be_created(false), tree(tree) {} // Returns whether this update removes |node|. bool IsRemovedNode(const AXNode* node) const { return base::Contains(removed_node_ids, node->id()); } // Returns whether this update creates a node marked by |node_id|. bool IsCreatedNode(AXNode::AXID node_id) const { return base::Contains(new_node_ids, node_id); } // Returns whether this update creates |node|. bool IsCreatedNode(const AXNode* node) const { return IsCreatedNode(node->id()); } // Returns whether this update reparents |node|. bool IsReparentedNode(const AXNode* node) const { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } PendingStructureChanges* data = GetPendingStructureChanges(node->id()); if (!data) return false; // In order to know if the node will be reparented during the update, // we check if either the node will be destroyed or has been destroyed at // least once during the update. // Since this method is only allowed to be called after calculating all // pending structure changes, |node_exists| tells us if the node should // exist after all updates have been applied. return (data->DoesNodeExpectNodeWillBeDestroyed() || IsRemovedNode(node)) && data->node_exists; } // Returns true if the node should exist in the tree but doesn't have // any node data yet. bool DoesPendingNodeRequireInit(AXNode::AXID node_id) const { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } PendingStructureChanges* data = GetPendingStructureChanges(node_id); return data && data->DoesNodeRequireInit(); } // Returns the parent node id for the pending node. std::optional<AXNode::AXID> GetParentIdForPendingNode(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } PendingStructureChanges* data = GetOrCreatePendingStructureChanges(node_id); BASE_DCHECK(!data->parent_node_id || ShouldPendingNodeExistInTree(*data->parent_node_id)); return data->parent_node_id; } // Returns true if this node should exist in the tree. bool ShouldPendingNodeExistInTree(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } return GetOrCreatePendingStructureChanges(node_id)->node_exists; } // Returns the last known node data for a pending node. const AXNodeData& GetLastKnownPendingNodeData(AXNode::AXID node_id) const { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } static base::NoDestructor<ui::AXNodeData> empty_data; PendingStructureChanges* data = GetPendingStructureChanges(node_id); return (data && data->last_known_data) ? *data->last_known_data : *empty_data; } // Clear the last known pending data for |node_id|. void ClearLastKnownPendingNodeData(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } GetOrCreatePendingStructureChanges(node_id)->last_known_data = nullptr; } // Update the last known pending node data for |node_data.id|. void SetLastKnownPendingNodeData(const AXNodeData* node_data) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } GetOrCreatePendingStructureChanges(node_data->id)->last_known_data = node_data; } // Returns the number of times the update is expected to destroy a // subtree rooted at |node_id|. int32_t GetPendingDestroySubtreeCount(AXNode::AXID node_id) const { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } if (PendingStructureChanges* data = GetPendingStructureChanges(node_id)) return data->destroy_subtree_count; return 0; } // Increments the number of times the update is expected to // destroy a subtree rooted at |node_id|. // Returns true on success, false on failure when the node will not exist. bool IncrementPendingDestroySubtreeCount(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } PendingStructureChanges* data = GetOrCreatePendingStructureChanges(node_id); if (!data->node_exists) return false; ++data->destroy_subtree_count; return true; } // Decrements the number of times the update is expected to // destroy a subtree rooted at |node_id|. void DecrementPendingDestroySubtreeCount(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } if (PendingStructureChanges* data = GetPendingStructureChanges(node_id)) { BASE_DCHECK(data->destroy_subtree_count > 0); --data->destroy_subtree_count; } } // Returns the number of times the update is expected to destroy // a node with |node_id|. int32_t GetPendingDestroyNodeCount(AXNode::AXID node_id) const { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } if (PendingStructureChanges* data = GetPendingStructureChanges(node_id)) return data->destroy_node_count; return 0; } // Increments the number of times the update is expected to // destroy a node with |node_id|. // Returns true on success, false on failure when the node will not exist. bool IncrementPendingDestroyNodeCount(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } PendingStructureChanges* data = GetOrCreatePendingStructureChanges(node_id); if (!data->node_exists) return false; ++data->destroy_node_count; data->node_exists = false; data->last_known_data = nullptr; data->parent_node_id = std::nullopt; if (pending_root_id == node_id) pending_root_id = std::nullopt; return true; } // Decrements the number of times the update is expected to // destroy a node with |node_id|. void DecrementPendingDestroyNodeCount(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } if (PendingStructureChanges* data = GetPendingStructureChanges(node_id)) { BASE_DCHECK(data->destroy_node_count > 0); --data->destroy_node_count; } } // Returns the number of times the update is expected to create // a node with |node_id|. int32_t GetPendingCreateNodeCount(AXNode::AXID node_id) const { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } if (PendingStructureChanges* data = GetPendingStructureChanges(node_id)) return data->create_node_count; return 0; } // Increments the number of times the update is expected to // create a node with |node_id|. // Returns true on success, false on failure when the node will already exist. bool IncrementPendingCreateNodeCount( AXNode::AXID node_id, std::optional<AXNode::AXID> parent_node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } PendingStructureChanges* data = GetOrCreatePendingStructureChanges(node_id); if (data->node_exists) return false; ++data->create_node_count; data->node_exists = true; data->parent_node_id = parent_node_id; return true; } // Decrements the number of times the update is expected to // create a node with |node_id|. void DecrementPendingCreateNodeCount(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComplete != pending_update_status) { BASE_LOG() << "This method should not be called before pending changes have " "finished computing."; BASE_UNREACHABLE(); } if (PendingStructureChanges* data = GetPendingStructureChanges(node_id)) { BASE_DCHECK(data->create_node_count > 0); --data->create_node_count; } } // Returns whether this update must invalidate the unignored cached // values for |node_id|. bool InvalidatesUnignoredCachedValues(AXNode::AXID node_id) { return base::Contains(invalidate_unignored_cached_values_ids, node_id); } // Adds the parent of |node_id| to the list of nodes to invalidate unignored // cached values. void InvalidateParentNodeUnignoredCacheValues(AXNode::AXID node_id) { if (AXTreePendingStructureStatus::kComputing != pending_update_status) { BASE_LOG() << "This method should only be called while computing " "pending changes, " "before updates are made to the tree."; BASE_UNREACHABLE(); } std::optional<AXNode::AXID> parent_node_id = GetParentIdForPendingNode(node_id); if (parent_node_id) { invalidate_unignored_cached_values_ids.insert(*parent_node_id); } } // Indicates the status for calculating what changes will occur during // an update before the update applies changes. AXTreePendingStructureStatus pending_update_status; // Keeps track of the root node id when calculating what changes will occur // during an update before the update applies changes. std::optional<AXNode::AXID> pending_root_id; // Keeps track of whether the root node will need to be created as a new node. // This may occur either when the root node does not exist before applying // updates to the tree (new tree), or if the root is the |node_id_to_clear| // and will be destroyed before applying AXNodeData updates to the tree. bool root_will_be_created; // During an update, this keeps track of all nodes that have been // implicitly referenced as part of this update, but haven't been // updated yet. It's an error if there are any pending nodes at the // end of Unserialize. std::set<AXNode::AXID> pending_nodes; // Keeps track of nodes whose cached unignored child count, or unignored // index in parent may have changed, and must be updated. std::set<AXNode::AXID> invalidate_unignored_cached_values_ids; // Keeps track of nodes that have changed their node data. std::set<AXNode::AXID> node_data_changed_ids; // Keeps track of new nodes created during this update. std::set<AXNode::AXID> new_node_ids; // Keeps track of any nodes removed. Nodes are removed when their AXID no // longer exist in the parent |child_ids| list, or the node is part of to the // subtree of the AXID that was explicitally cleared with |node_id_to_clear|. // Used to identify re-parented nodes. A re-parented occurs when any AXID // is first removed from the tree then added to the tree again. std::set<AXNode::AXID> removed_node_ids; // Maps between a node id and its pending update information. std::map<AXNode::AXID, std::unique_ptr<PendingStructureChanges>> node_id_to_pending_data; // Maps between a node id and the data it owned before being updated. // We need to keep this around in order to correctly fire post-update events. std::map<AXNode::AXID, AXNodeData> old_node_id_to_data; // Optional copy of the old tree data, only populated when the tree // data has changed. std::optional<AXTreeData> old_tree_data; private: PendingStructureChanges* GetPendingStructureChanges( AXNode::AXID node_id) const { auto iter = node_id_to_pending_data.find(node_id); return (iter != node_id_to_pending_data.cend()) ? iter->second.get() : nullptr; } PendingStructureChanges* GetOrCreatePendingStructureChanges( AXNode::AXID node_id) { auto iter = node_id_to_pending_data.find(node_id); if (iter == node_id_to_pending_data.cend()) { const AXNode* node = tree.GetFromId(node_id); iter = node_id_to_pending_data .emplace(std::make_pair( node_id, std::make_unique<PendingStructureChanges>(node))) .first; } return iter->second.get(); } // We need to hold onto a reference to the AXTree so that we can // lazily initialize |PendingStructureChanges| objects. const AXTree& tree; }; AXTree::NodeSetSizePosInSetInfo::NodeSetSizePosInSetInfo() = default; AXTree::NodeSetSizePosInSetInfo::~NodeSetSizePosInSetInfo() = default; struct AXTree::OrderedSetContent { explicit OrderedSetContent(const AXNode* ordered_set = nullptr) : ordered_set_(ordered_set) {} ~OrderedSetContent() = default; std::vector<const AXNode*> set_items_; // Some ordered set items may not be associated with an ordered set. const AXNode* ordered_set_; }; struct AXTree::OrderedSetItemsMap { OrderedSetItemsMap() = default; ~OrderedSetItemsMap() = default; // Check if a particular hierarchical level exists in this map. bool HierarchicalLevelExists(std::optional<int> level) { if (items_map_.find(level) == items_map_.end()) return false; return true; } // Add the OrderedSetContent to the corresponding hierarchical level in the // map. void Add(std::optional<int> level, const OrderedSetContent& ordered_set_content) { if (!HierarchicalLevelExists(level)) items_map_[level] = std::vector<OrderedSetContent>(); items_map_[level].push_back(ordered_set_content); } // Add an ordered set item to the OrderedSetItemsMap given its hierarchical // level. We always want to append the item to the last OrderedSetContent of // that hierarchical level, due to the following: // - The last OrderedSetContent on any level of the items map is in progress // of being populated. // - All other OrderedSetContent other than the last one on a level // represents a complete ordered set and should not be modified. void AddItemToBack(std::optional<int> level, const AXNode* item) { if (!HierarchicalLevelExists(level)) return; std::vector<OrderedSetContent>& sets_list = items_map_[level]; if (!sets_list.empty()) { OrderedSetContent& ordered_set_content = sets_list.back(); ordered_set_content.set_items_.push_back(item); } } // Retrieve the first OrderedSetContent of the OrderedSetItemsMap. OrderedSetContent* GetFirstOrderedSetContent() { if (items_map_.empty()) return nullptr; std::vector<OrderedSetContent>& sets_list = items_map_.begin()->second; if (sets_list.empty()) return nullptr; return &(sets_list.front()); } // Clears all the content in the map. void Clear() { items_map_.clear(); } // Maps a hierarchical level to a list of OrderedSetContent. std::map<std::optional<int32_t>, std::vector<OrderedSetContent>> items_map_; }; AXTree::AXTree() { AXNodeData root; root.id = AXNode::kInvalidAXID; AXTreeUpdate initial_state; initial_state.root_id = AXNode::kInvalidAXID; initial_state.nodes.push_back(root); if (!Unserialize(initial_state)) { BASE_LOG() << error(); BASE_UNREACHABLE(); } } AXTree::AXTree(const AXTreeUpdate& initial_state) { if (!Unserialize(initial_state)) { BASE_LOG() << error(); BASE_UNREACHABLE(); } } AXTree::~AXTree() { Destroy(); } void AXTree::AddObserver(AXTreeObserver* observer) { observers_.push_back(observer); } bool AXTree::HasObserver(AXTreeObserver* observer) { return std::find(observers_.begin(), observers_.end(), observer) != observers_.end(); } void AXTree::RemoveObserver(AXTreeObserver* observer) { const auto it = std::find(observers_.begin(), observers_.end(), observer); if (it == observers_.end()) return; observers_.erase(it); } AXTreeID AXTree::GetAXTreeID() const { return data().tree_id; } AXNode* AXTree::GetFromId(int32_t id) const { auto iter = id_map_.find(id); return iter != id_map_.end() ? iter->second : nullptr; } void AXTree::Destroy() { table_info_map_.clear(); if (root_) { RecursivelyNotifyNodeDeletedForTreeTeardown(root_); base::AutoReset<bool> update_state_resetter(&tree_update_in_progress_, true); DestroyNodeAndSubtree(root_, nullptr); root_ = nullptr; } } void AXTree::UpdateData(const AXTreeData& new_data) { if (data_ == new_data) return; AXTreeData old_data = data_; data_ = new_data; for (AXTreeObserver* observer : observers_) observer->OnTreeDataChanged(this, old_data, new_data); } gfx::RectF AXTree::RelativeToTreeBoundsInternal(const AXNode* node, gfx::RectF bounds, bool* offscreen, bool clip_bounds, bool allow_recursion) const { // If |bounds| is uninitialized, which is not the same as empty, // start with the node bounds. if (bounds.width() == 0 && bounds.height() == 0) { bounds = node->data().relative_bounds.bounds; // If the node bounds is empty (either width or height is zero), // try to compute good bounds from the children. // If a tree update is in progress, skip this step as children may be in a // bad state. if (bounds.IsEmpty() && !GetTreeUpdateInProgressState() && allow_recursion) { for (size_t i = 0; i < node->children().size(); i++) { ui::AXNode* child = node->children()[i]; bool ignore_offscreen; gfx::RectF child_bounds = RelativeToTreeBoundsInternal( child, gfx::RectF(), &ignore_offscreen, clip_bounds, /* allow_recursion = */ false); bounds.Union(child_bounds); } if (bounds.width() > 0 && bounds.height() > 0) { return bounds; } } } else { bounds.Offset(node->data().relative_bounds.bounds.x(), node->data().relative_bounds.bounds.y()); } const AXNode* original_node = node; while (node != nullptr) { if (node->data().relative_bounds.transform) node->data().relative_bounds.transform->TransformRect(&bounds); // Apply any transforms and offsets for each node and then walk up to // its offset container. If no offset container is specified, coordinates // are relative to the root node. const AXNode* container = GetFromId(node->data().relative_bounds.offset_container_id); if (!container && container != root()) container = root(); if (!container || container == node) break; gfx::RectF container_bounds = container->data().relative_bounds.bounds; bounds.Offset(container_bounds.x(), container_bounds.y()); int scroll_x = 0; int scroll_y = 0; if (container->data().GetIntAttribute(ax::mojom::IntAttribute::kScrollX, &scroll_x) && container->data().GetIntAttribute(ax::mojom::IntAttribute::kScrollY, &scroll_y)) { bounds.Offset(-scroll_x, -scroll_y); } // Get the intersection between the bounds and the container. gfx::RectF intersection = bounds; intersection.Intersect(container_bounds); // Calculate the clipped bounds to determine offscreen state. gfx::RectF clipped = bounds; // If this node has the kClipsChildren attribute set, clip the rect to fit. if (container->data().GetBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren)) { if (!intersection.IsEmpty()) { // We can simply clip it to the container. clipped = intersection; } else { // Totally offscreen. Find the nearest edge or corner. // Make the minimum dimension 1 instead of 0. if (clipped.x() >= container_bounds.width()) { clipped.set_x(container_bounds.right() - 1); clipped.set_width(1); } else if (clipped.x() + clipped.width() <= 0) { clipped.set_x(container_bounds.x()); clipped.set_width(1); } if (clipped.y() >= container_bounds.height()) { clipped.set_y(container_bounds.bottom() - 1); clipped.set_height(1); } else if (clipped.y() + clipped.height() <= 0) { clipped.set_y(container_bounds.y()); clipped.set_height(1); } } } if (clip_bounds) bounds = clipped; if (container->data().GetBoolAttribute( ax::mojom::BoolAttribute::kClipsChildren) && intersection.IsEmpty() && !clipped.IsEmpty()) { // If it is offscreen with respect to its parent, and the node itself is // not empty, label it offscreen. // Here we are extending the definition of offscreen to include elements // that are clipped by their parents in addition to those clipped by // the rootWebArea. // No need to update |offscreen| if |intersection| is not empty, because // it should be false by default. if (offscreen != nullptr) *offscreen |= true; } node = container; } // If we don't have any size yet, try to adjust the bounds to fill the // nearest ancestor that does have bounds. // // The rationale is that it's not useful to the user for an object to // have no width or height and it's probably a bug; it's better to // reflect the bounds of the nearest ancestor rather than a 0x0 box. // Tag this node as 'offscreen' because it has no true size, just a // size inherited from the ancestor. if (bounds.width() == 0 && bounds.height() == 0) { const AXNode* ancestor = original_node->parent(); gfx::RectF ancestor_bounds; while (ancestor) { ancestor_bounds = ancestor->data().relative_bounds.bounds; if (ancestor_bounds.width() > 0 || ancestor_bounds.height() > 0) break; ancestor = ancestor->parent(); } if (ancestor && allow_recursion) { bool ignore_offscreen; bool allow_recursion = false; ancestor_bounds = RelativeToTreeBoundsInternal( ancestor, gfx::RectF(), &ignore_offscreen, clip_bounds, allow_recursion); gfx::RectF original_bounds = original_node->data().relative_bounds.bounds; if (original_bounds.x() == 0 && original_bounds.y() == 0) { bounds = ancestor_bounds; } else { bounds.set_width(std::max(0.0f, ancestor_bounds.right() - bounds.x())); bounds.set_height( std::max(0.0f, ancestor_bounds.bottom() - bounds.y())); } if (offscreen != nullptr) *offscreen |= true; } } return bounds; } gfx::RectF AXTree::RelativeToTreeBounds(const AXNode* node, gfx::RectF bounds, bool* offscreen, bool clip_bounds) const { bool allow_recursion = true; return RelativeToTreeBoundsInternal(node, bounds, offscreen, clip_bounds, allow_recursion); } gfx::RectF AXTree::GetTreeBounds(const AXNode* node, bool* offscreen, bool clip_bounds) const { return RelativeToTreeBounds(node, gfx::RectF(), offscreen, clip_bounds); } std::set<int32_t> AXTree::GetReverseRelations(ax::mojom::IntAttribute attr, int32_t dst_id) const { BASE_DCHECK(IsNodeIdIntAttribute(attr)); // Conceptually, this is the "const" version of: // return int_reverse_relations_[attr][dst_id]; const auto& attr_relations = int_reverse_relations_.find(attr); if (attr_relations != int_reverse_relations_.end()) { const auto& result = attr_relations->second.find(dst_id); if (result != attr_relations->second.end()) return result->second; } return std::set<int32_t>(); } std::set<int32_t> AXTree::GetReverseRelations(ax::mojom::IntListAttribute attr, int32_t dst_id) const { BASE_DCHECK(IsNodeIdIntListAttribute(attr)); // Conceptually, this is the "const" version of: // return intlist_reverse_relations_[attr][dst_id]; const auto& attr_relations = intlist_reverse_relations_.find(attr); if (attr_relations != intlist_reverse_relations_.end()) { const auto& result = attr_relations->second.find(dst_id); if (result != attr_relations->second.end()) return result->second; } return std::set<int32_t>(); } std::set<int32_t> AXTree::GetNodeIdsForChildTreeId( AXTreeID child_tree_id) const { // Conceptually, this is the "const" version of: // return child_tree_id_reverse_map_[child_tree_id]; const auto& result = child_tree_id_reverse_map_.find(child_tree_id); if (result != child_tree_id_reverse_map_.end()) return result->second; return std::set<int32_t>(); } const std::set<AXTreeID> AXTree::GetAllChildTreeIds() const { std::set<AXTreeID> result; for (auto entry : child_tree_id_reverse_map_) result.insert(entry.first); return result; } bool AXTree::Unserialize(const AXTreeUpdate& update) { AXTreeUpdateState update_state(*this); const AXNode::AXID old_root_id = root_ ? root_->id() : AXNode::kInvalidAXID; // Accumulates the work that will be required to update the AXTree. // This allows us to notify observers of structure changes when the // tree is still in a stable and unchanged state. if (!ComputePendingChanges(update, &update_state)) return false; // Notify observers of subtrees and nodes that are about to be destroyed or // reparented, this must be done before applying any updates to the tree. for (auto&& pair : update_state.node_id_to_pending_data) { const AXNode::AXID node_id = pair.first; const std::unique_ptr<PendingStructureChanges>& data = pair.second; if (data->DoesNodeExpectSubtreeOrNodeWillBeDestroyed()) { if (AXNode* node = GetFromId(node_id)) { if (data->DoesNodeExpectSubtreeWillBeDestroyed()) NotifySubtreeWillBeReparentedOrDeleted(node, &update_state); if (data->DoesNodeExpectNodeWillBeDestroyed()) NotifyNodeWillBeReparentedOrDeleted(node, &update_state); } } } // Notify observers of nodes that are about to change their data. // This must be done before applying any updates to the tree. // This is iterating in reverse order so that we only notify once per node id, // and that we only notify the initial node data against the final node data, // unless the node is a new root. std::set<int32_t> notified_node_data_will_change; for (size_t i = update.nodes.size(); i-- > 0;) { const AXNodeData& new_data = update.nodes[i]; const bool is_new_root = update_state.root_will_be_created && new_data.id == update.root_id; if (!is_new_root) { AXNode* node = GetFromId(new_data.id); if (node && notified_node_data_will_change.insert(new_data.id).second) NotifyNodeDataWillChange(node->data(), new_data); } } // Now that we have finished sending events for changes that will happen, // set update state to true. |tree_update_in_progress_| gets set back to // false whenever this function exits. base::AutoReset<bool> update_state_resetter(&tree_update_in_progress_, true); // Handle |node_id_to_clear| before applying ordinary node updates. // We distinguish between updating the root, e.g. changing its children or // some of its attributes, or replacing the root completely. If the root is // being updated, update.node_id_to_clear should hold the current root's ID. // Otherwise if the root is being replaced, update.root_id should hold the ID // of the new root. bool root_updated = false; if (update.node_id_to_clear != AXNode::kInvalidAXID) { if (AXNode* cleared_node = GetFromId(update.node_id_to_clear)) { BASE_DCHECK(root_); if (cleared_node == root_) { // Only destroy the root if the root was replaced and not if it's simply // updated. To figure out if the root was simply updated, we compare // the ID of the new root with the existing root ID. if (update.root_id != old_root_id) { // Clear root_ before calling DestroySubtree so that root_ doesn't // ever point to an invalid node. AXNode* old_root = root_; root_ = nullptr; DestroySubtree(old_root, &update_state); } else { // If the root has simply been updated, we treat it like an update to // any other node. root_updated = true; } } // If the tree doesn't exists any more because the root has just been // replaced, there is nothing more to clear. if (root_) { for (auto* child : cleared_node->children()) DestroySubtree(child, &update_state); std::vector<AXNode*> children; cleared_node->SwapChildren(&children); update_state.pending_nodes.insert(cleared_node->id()); } } } BASE_DCHECK(!GetFromId(update.root_id) == update_state.root_will_be_created); // Update the tree data, do not call |UpdateData| since we want to defer // the |OnTreeDataChanged| event until after the tree has finished updating. if (update.has_tree_data && data_ != update.tree_data) { update_state.old_tree_data = data_; data_ = update.tree_data; } // Update all of the nodes in the update. for (size_t i = 0; i < update.nodes.size(); ++i) { const bool is_new_root = update_state.root_will_be_created && update.nodes[i].id == update.root_id; if (!UpdateNode(update.nodes[i], is_new_root, &update_state)) return false; } if (!root_) { error_ = "Tree has no root."; return false; } if (!ValidatePendingChangesComplete(update_state)) return false; // Look for changes to nodes that are a descendant of a table, // and invalidate their table info if so. We have to walk up the // ancestry of every node that was updated potentially, so keep track of // ids that were checked to eliminate duplicate work. std::set<int32_t> table_ids_checked; for (size_t i = 0; i < update.nodes.size(); ++i) { AXNode* node = GetFromId(update.nodes[i].id); while (node) { if (table_ids_checked.find(node->id()) != table_ids_checked.end()) break; // Remove any table infos. const auto& table_info_entry = table_info_map_.find(node->id()); if (table_info_entry != table_info_map_.end()) table_info_entry->second->Invalidate(); table_ids_checked.insert(node->id()); node = node->parent(); } } // Clears |node_set_size_pos_in_set_info_map_| node_set_size_pos_in_set_info_map_.clear(); std::vector<AXTreeObserver::Change> changes; changes.reserve(update.nodes.size()); std::set<AXNode::AXID> visited_observer_changes; for (size_t i = 0; i < update.nodes.size(); ++i) { AXNode* node = GetFromId(update.nodes[i].id); if (!node || !visited_observer_changes.emplace(update.nodes[i].id).second) continue; bool is_new_node = update_state.IsCreatedNode(node); bool is_reparented_node = update_state.IsReparentedNode(node); AXTreeObserver::ChangeType change = AXTreeObserver::NODE_CHANGED; if (is_new_node) { if (is_reparented_node) { // A reparented subtree is any new node whose parent either doesn't // exist, or whose parent is not new. // Note that we also need to check for the special case when we update // the root without replacing it. bool is_subtree = !node->parent() || !update_state.IsCreatedNode(node->parent()) || (node->parent() == root_ && root_updated); change = is_subtree ? AXTreeObserver::SUBTREE_REPARENTED : AXTreeObserver::NODE_REPARENTED; } else { // A new subtree is any new node whose parent is either not new, or // whose parent happens to be new only because it has been reparented. // Note that we also need to check for the special case when we update // the root without replacing it. bool is_subtree = !node->parent() || !update_state.IsCreatedNode(node->parent()) || update_state.IsRemovedNode(node->parent()) || (node->parent() == root_ && root_updated); change = is_subtree ? AXTreeObserver::SUBTREE_CREATED : AXTreeObserver::NODE_CREATED; } } changes.push_back(AXTreeObserver::Change(node, change)); } // Update the unignored cached values as necessary, ensuring that we only // update once for each unignored node. // If the node is ignored, we must update from an unignored ancestor. std::set<AXNode::AXID> updated_unignored_cached_values_ids; for (AXNode::AXID node_id : update_state.invalidate_unignored_cached_values_ids) { AXNode* node = GetFromId(node_id); while (node && node->data().IsIgnored()) node = node->parent(); if (node && updated_unignored_cached_values_ids.insert(node->id()).second) node->UpdateUnignoredCachedValues(); } // Tree is no longer updating. SetTreeUpdateInProgressState(false); // Now that the tree is stable and its nodes have been updated, notify if // the tree data changed. We must do this after updating nodes in case the // root has been replaced, so observers have the most up-to-date information. if (update_state.old_tree_data) { for (AXTreeObserver* observer : observers_) observer->OnTreeDataChanged(this, *update_state.old_tree_data, data_); } // Now that the unignored cached values are up to date, update observers to // the nodes that were deleted from the tree but not reparented. for (AXNode::AXID node_id : update_state.removed_node_ids) { if (!update_state.IsCreatedNode(node_id)) NotifyNodeHasBeenDeleted(node_id); } // Now that the unignored cached values are up to date, update observers to // new nodes in the tree. for (AXNode::AXID node_id : update_state.new_node_ids) NotifyNodeHasBeenReparentedOrCreated(GetFromId(node_id), &update_state); // Now that the unignored cached values are up to date, update observers to // node changes. for (AXNode::AXID node_data_changed_id : update_state.node_data_changed_ids) { AXNode* node = GetFromId(node_data_changed_id); BASE_DCHECK(node); // If the node exists and is in the old data map, then the node data // may have changed unless this is a new root. const bool is_new_root = update_state.root_will_be_created && node_data_changed_id == update.root_id; if (!is_new_root) { auto it = update_state.old_node_id_to_data.find(node_data_changed_id); if (it != update_state.old_node_id_to_data.end()) { const AXNodeData& old_node_data = it->second; NotifyNodeDataHasBeenChanged(node, old_node_data, node->data()); } } // |OnNodeChanged| should be fired for all nodes that have been updated. for (AXTreeObserver* observer : observers_) observer->OnNodeChanged(this, node); } for (AXTreeObserver* observer : observers_) observer->OnAtomicUpdateFinished(this, root_->id() != old_root_id, changes); return true; } AXTableInfo* AXTree::GetTableInfo(const AXNode* const_table_node) const { BASE_DCHECK(!GetTreeUpdateInProgressState()); // Note: the const_casts are here because we want this function to be able // to be called from a const virtual function on AXNode. AXTableInfo is // computed on demand and cached, but that's an implementation detail // we want to hide from users of this API. AXNode* table_node = const_cast<AXNode*>(const_table_node); AXTree* tree = const_cast<AXTree*>(this); BASE_DCHECK(table_node); const auto& cached = table_info_map_.find(table_node->id()); if (cached != table_info_map_.end()) { // Get existing table info, and update if invalid because the // tree has changed since the last time we accessed it. AXTableInfo* table_info = cached->second.get(); if (!table_info->valid()) { if (!table_info->Update()) { // If Update() returned false, this is no longer a valid table. // Remove it from the map. table_info_map_.erase(table_node->id()); return nullptr; } } return table_info; } AXTableInfo* table_info = AXTableInfo::Create(tree, table_node); if (!table_info) return nullptr; table_info_map_[table_node->id()] = std::unique_ptr<AXTableInfo>(table_info); return table_info; } std::string AXTree::ToString() const { return "AXTree" + data_.ToString() + "\n" + TreeToStringHelper(root_, 0); } AXNode* AXTree::CreateNode(AXNode* parent, AXNode::AXID id, size_t index_in_parent, AXTreeUpdateState* update_state) { BASE_DCHECK(GetTreeUpdateInProgressState()); // |update_state| must already contain information about all of the expected // changes and invalidations to apply. If any of these are missing, observers // may not be notified of changes. BASE_DCHECK(!GetFromId(id)); BASE_DCHECK(update_state->GetPendingCreateNodeCount(id) > 0); BASE_DCHECK(update_state->InvalidatesUnignoredCachedValues(id)); BASE_DCHECK(!parent || update_state->InvalidatesUnignoredCachedValues(parent->id())); update_state->DecrementPendingCreateNodeCount(id); update_state->new_node_ids.insert(id); // If this node is the root, use the given index_in_parent as the unignored // index in parent to provide consistency with index_in_parent. AXNode* new_node = new AXNode(this, parent, id, index_in_parent, parent ? 0 : index_in_parent); id_map_[new_node->id()] = new_node; return new_node; } bool AXTree::ComputePendingChanges(const AXTreeUpdate& update, AXTreeUpdateState* update_state) { if (AXTreePendingStructureStatus::kNotStarted != update_state->pending_update_status) { BASE_LOG() << "Pending changes have already started being computed."; BASE_UNREACHABLE(); } update_state->pending_update_status = AXTreePendingStructureStatus::kComputing; base::AutoReset<std::optional<AXNode::AXID>> pending_root_id_resetter( &update_state->pending_root_id, root_ ? std::optional<AXNode::AXID>{root_->id()} : std::nullopt); // We distinguish between updating the root, e.g. changing its children or // some of its attributes, or replacing the root completely. If the root is // being updated, update.node_id_to_clear should hold the current root's ID. // Otherwise if the root is being replaced, update.root_id should hold the ID // of the new root. if (update.node_id_to_clear != AXNode::kInvalidAXID) { if (AXNode* cleared_node = GetFromId(update.node_id_to_clear)) { BASE_DCHECK(root_); if (cleared_node == root_ && update.root_id != update_state->pending_root_id) { // Only destroy the root if the root was replaced and not if it's simply // updated. To figure out if the root was simply updated, we compare // the ID of the new root with the existing root ID. MarkSubtreeForDestruction(*update_state->pending_root_id, update_state); } // If the tree has been marked for destruction because the root will be // replaced, there is nothing more to clear. if (update_state->ShouldPendingNodeExistInTree(root_->id())) { update_state->invalidate_unignored_cached_values_ids.insert( cleared_node->id()); update_state->ClearLastKnownPendingNodeData(cleared_node->id()); for (AXNode* child : cleared_node->children()) { MarkSubtreeForDestruction(child->id(), update_state); } } } } update_state->root_will_be_created = !GetFromId(update.root_id) || !update_state->ShouldPendingNodeExistInTree(update.root_id); // Populate |update_state| with all of the changes that will be performed // on the tree during the update. for (const AXNodeData& new_data : update.nodes) { bool is_new_root = update_state->root_will_be_created && new_data.id == update.root_id; if (!ComputePendingChangesToNode(new_data, is_new_root, update_state)) { update_state->pending_update_status = AXTreePendingStructureStatus::kFailed; return false; } } update_state->pending_update_status = AXTreePendingStructureStatus::kComplete; return true; } bool AXTree::ComputePendingChangesToNode(const AXNodeData& new_data, bool is_new_root, AXTreeUpdateState* update_state) { // Compare every child's index in parent in the update with the existing // index in parent. If the order has changed, invalidate the cached // unignored index in parent. for (size_t j = 0; j < new_data.child_ids.size(); j++) { AXNode* node = GetFromId(new_data.child_ids[j]); if (node && node->GetIndexInParent() != j) update_state->InvalidateParentNodeUnignoredCacheValues(node->id()); } // If the node does not exist in the tree throw an error unless this // is the new root and it can be created. if (!update_state->ShouldPendingNodeExistInTree(new_data.id)) { if (!is_new_root) { error_ = base::StringPrintf( "%d will not be in the tree and is not the new root", new_data.id); return false; } // Creation is implicit for new root nodes. If |new_data.id| is already // pending for creation, then it must be a duplicate entry in the tree. if (!update_state->IncrementPendingCreateNodeCount(new_data.id, std::nullopt)) { error_ = base::StringPrintf( "Node %d is already pending for creation, cannot be the new root", new_data.id); return false; } if (update_state->pending_root_id) { MarkSubtreeForDestruction(*update_state->pending_root_id, update_state); } update_state->pending_root_id = new_data.id; } // Create a set of new child ids so we can use it to find the nodes that // have been added and removed. Returns false if a duplicate is found. std::set<AXNode::AXID> new_child_id_set; for (AXNode::AXID new_child_id : new_data.child_ids) { if (base::Contains(new_child_id_set, new_child_id)) { error_ = base::StringPrintf("Node %d has duplicate child id %d", new_data.id, new_child_id); return false; } new_child_id_set.insert(new_child_id); } // If the node has not been initialized yet then its node data has either been // cleared when handling |node_id_to_clear|, or it's a new node. // In either case, all children must be created. if (update_state->DoesPendingNodeRequireInit(new_data.id)) { update_state->invalidate_unignored_cached_values_ids.insert(new_data.id); // If this node has been cleared via |node_id_to_clear| or is a new node, // the last-known parent's unignored cache needs to be updated. update_state->InvalidateParentNodeUnignoredCacheValues(new_data.id); for (AXNode::AXID child_id : new_child_id_set) { // If a |child_id| is already pending for creation, then it must be a // duplicate entry in the tree. update_state->invalidate_unignored_cached_values_ids.insert(child_id); if (!update_state->IncrementPendingCreateNodeCount(child_id, new_data.id)) { error_ = base::StringPrintf( "Node %d is already pending for creation, cannot be a new child", child_id); return false; } } update_state->SetLastKnownPendingNodeData(&new_data); return true; } const AXNodeData& old_data = update_state->GetLastKnownPendingNodeData(new_data.id); // Create a set of old child ids so we can use it to find the nodes that // have been added and removed. std::set<AXNode::AXID> old_child_id_set(old_data.child_ids.cbegin(), old_data.child_ids.cend()); std::vector<AXNode::AXID> create_or_destroy_ids; std::set_symmetric_difference( old_child_id_set.cbegin(), old_child_id_set.cend(), new_child_id_set.cbegin(), new_child_id_set.cend(), std::back_inserter(create_or_destroy_ids)); // If the node has changed ignored state or there are any differences in // its children, then its unignored cached values must be invalidated. const bool ignored_changed = old_data.IsIgnored() != new_data.IsIgnored(); if (!create_or_destroy_ids.empty() || ignored_changed) { update_state->invalidate_unignored_cached_values_ids.insert(new_data.id); // If this ignored state had changed also invalidate the parent. update_state->InvalidateParentNodeUnignoredCacheValues(new_data.id); } for (AXNode::AXID child_id : create_or_destroy_ids) { if (base::Contains(new_child_id_set, child_id)) { // This is a serious error - nodes should never be reparented without // first being removed from the tree. If a node exists in the tree already // then adding it to a new parent would mean stealing the node from its // old parent which hadn't been updated to reflect the change. if (update_state->ShouldPendingNodeExistInTree(child_id)) { error_ = base::StringPrintf( "Node %d is not marked for destruction, would be reparented to %d", child_id, new_data.id); return false; } // If a |child_id| is already pending for creation, then it must be a // duplicate entry in the tree. update_state->invalidate_unignored_cached_values_ids.insert(child_id); if (!update_state->IncrementPendingCreateNodeCount(child_id, new_data.id)) { error_ = base::StringPrintf( "Node %d is already pending for creation, cannot be a new child", child_id); return false; } } else { // If |child_id| does not exist in the new set, then it has // been removed from |node|, and the subtree must be deleted. MarkSubtreeForDestruction(child_id, update_state); } } update_state->SetLastKnownPendingNodeData(&new_data); return true; } bool AXTree::UpdateNode(const AXNodeData& src, bool is_new_root, AXTreeUpdateState* update_state) { BASE_DCHECK(GetTreeUpdateInProgressState()); // This method updates one node in the tree based on serialized data // received in an AXTreeUpdate. See AXTreeUpdate for pre and post // conditions. // Look up the node by id. If it's not found, then either the root // of the tree is being swapped, or we're out of sync with the source // and this is a serious error. AXNode* node = GetFromId(src.id); if (node) { update_state->pending_nodes.erase(node->id()); UpdateReverseRelations(node, src); if (!update_state->IsCreatedNode(node) || update_state->IsReparentedNode(node)) { update_state->old_node_id_to_data.insert( std::make_pair(node->id(), node->TakeData())); } node->SetData(src); } else { if (!is_new_root) { error_ = base::StringPrintf("%d is not in the tree and not the new root", src.id); return false; } node = CreateNode(nullptr, src.id, 0, update_state); UpdateReverseRelations(node, src); node->SetData(src); } // If we come across a page breaking object, mark the tree as a paginated root if (src.GetBoolAttribute(ax::mojom::BoolAttribute::kIsPageBreakingObject)) has_pagination_support_ = true; update_state->node_data_changed_ids.insert(node->id()); // First, delete nodes that used to be children of this node but aren't // anymore. DeleteOldChildren(node, src.child_ids, update_state); // Now build a new children vector, reusing nodes when possible, // and swap it in. std::vector<AXNode*> new_children; bool success = CreateNewChildVector(node, src.child_ids, &new_children, update_state); node->SwapChildren(&new_children); // Update the root of the tree if needed. if (is_new_root) { // Make sure root_ always points to something valid or null_, even inside // DestroySubtree. AXNode* old_root = root_; root_ = node; if (old_root && old_root != node) DestroySubtree(old_root, update_state); } return success; } void AXTree::NotifySubtreeWillBeReparentedOrDeleted( AXNode* node, const AXTreeUpdateState* update_state) { BASE_DCHECK(!GetTreeUpdateInProgressState()); if (node->id() == AXNode::kInvalidAXID) return; for (AXTreeObserver* observer : observers_) { if (update_state->IsReparentedNode(node)) { observer->OnSubtreeWillBeReparented(this, node); } else { observer->OnSubtreeWillBeDeleted(this, node); } } } void AXTree::NotifyNodeWillBeReparentedOrDeleted( AXNode* node, const AXTreeUpdateState* update_state) { BASE_DCHECK(!GetTreeUpdateInProgressState()); AXNode::AXID id = node->id(); if (id == AXNode::kInvalidAXID) return; table_info_map_.erase(id); for (AXTreeObserver* observer : observers_) { if (update_state->IsReparentedNode(node)) { observer->OnNodeWillBeReparented(this, node); } else { observer->OnNodeWillBeDeleted(this, node); } } if (table_info_map_.find(id) != table_info_map_.end()) { BASE_LOG() << "Table info should never be recreated during node deletion"; BASE_UNREACHABLE(); } } void AXTree::RecursivelyNotifyNodeDeletedForTreeTeardown(AXNode* node) { BASE_DCHECK(!GetTreeUpdateInProgressState()); if (node->id() == AXNode::kInvalidAXID) return; for (AXTreeObserver* observer : observers_) observer->OnNodeDeleted(this, node->id()); for (auto* child : node->children()) RecursivelyNotifyNodeDeletedForTreeTeardown(child); } void AXTree::NotifyNodeHasBeenDeleted(AXNode::AXID node_id) { BASE_DCHECK(!GetTreeUpdateInProgressState()); if (node_id == AXNode::kInvalidAXID) return; for (AXTreeObserver* observer : observers_) observer->OnNodeDeleted(this, node_id); } void AXTree::NotifyNodeHasBeenReparentedOrCreated( AXNode* node, const AXTreeUpdateState* update_state) { BASE_DCHECK(!GetTreeUpdateInProgressState()); if (node->id() == AXNode::kInvalidAXID) return; for (AXTreeObserver* observer : observers_) { if (update_state->IsReparentedNode(node)) { observer->OnNodeReparented(this, node); } else { observer->OnNodeCreated(this, node); } } } void AXTree::NotifyNodeDataWillChange(const AXNodeData& old_data, const AXNodeData& new_data) { BASE_DCHECK(!GetTreeUpdateInProgressState()); if (new_data.id == AXNode::kInvalidAXID) return; for (AXTreeObserver* observer : observers_) observer->OnNodeDataWillChange(this, old_data, new_data); } void AXTree::NotifyNodeDataHasBeenChanged(AXNode* node, const AXNodeData& old_data, const AXNodeData& new_data) { BASE_DCHECK(!GetTreeUpdateInProgressState()); if (node->id() == AXNode::kInvalidAXID) return; for (AXTreeObserver* observer : observers_) observer->OnNodeDataChanged(this, old_data, new_data); if (old_data.role != new_data.role) { for (AXTreeObserver* observer : observers_) observer->OnRoleChanged(this, node, old_data.role, new_data.role); } if (old_data.state != new_data.state) { for (int32_t i = static_cast<int32_t>(ax::mojom::State::kNone) + 1; i <= static_cast<int32_t>(ax::mojom::State::kMaxValue); ++i) { ax::mojom::State state = static_cast<ax::mojom::State>(i); if (old_data.HasState(state) != new_data.HasState(state)) { for (AXTreeObserver* observer : observers_) observer->OnStateChanged(this, node, state, new_data.HasState(state)); } } } auto string_callback = [this, node](ax::mojom::StringAttribute attr, const std::string& old_string, const std::string& new_string) { for (AXTreeObserver* observer : observers_) { observer->OnStringAttributeChanged(this, node, attr, old_string, new_string); } }; CallIfAttributeValuesChanged(old_data.string_attributes, new_data.string_attributes, std::string(), string_callback); auto bool_callback = [this, node](ax::mojom::BoolAttribute attr, const bool& old_bool, const bool& new_bool) { for (AXTreeObserver* observer : observers_) observer->OnBoolAttributeChanged(this, node, attr, new_bool); }; CallIfAttributeValuesChanged(old_data.bool_attributes, new_data.bool_attributes, false, bool_callback); auto float_callback = [this, node](ax::mojom::FloatAttribute attr, const float& old_float, const float& new_float) { for (AXTreeObserver* observer : observers_) observer->OnFloatAttributeChanged(this, node, attr, old_float, new_float); }; CallIfAttributeValuesChanged(old_data.float_attributes, new_data.float_attributes, 0.0f, float_callback); auto int_callback = [this, node](ax::mojom::IntAttribute attr, const int& old_int, const int& new_int) { for (AXTreeObserver* observer : observers_) observer->OnIntAttributeChanged(this, node, attr, old_int, new_int); }; CallIfAttributeValuesChanged(old_data.int_attributes, new_data.int_attributes, 0, int_callback); auto intlist_callback = [this, node]( ax::mojom::IntListAttribute attr, const std::vector<int32_t>& old_intlist, const std::vector<int32_t>& new_intlist) { for (AXTreeObserver* observer : observers_) observer->OnIntListAttributeChanged(this, node, attr, old_intlist, new_intlist); }; CallIfAttributeValuesChanged(old_data.intlist_attributes, new_data.intlist_attributes, std::vector<int32_t>(), intlist_callback); auto stringlist_callback = [this, node](ax::mojom::StringListAttribute attr, const std::vector<std::string>& old_stringlist, const std::vector<std::string>& new_stringlist) { for (AXTreeObserver* observer : observers_) observer->OnStringListAttributeChanged( this, node, attr, old_stringlist, new_stringlist); }; CallIfAttributeValuesChanged(old_data.stringlist_attributes, new_data.stringlist_attributes, std::vector<std::string>(), stringlist_callback); } void AXTree::UpdateReverseRelations(AXNode* node, const AXNodeData& new_data) { BASE_DCHECK(GetTreeUpdateInProgressState()); const AXNodeData& old_data = node->data(); int id = new_data.id; auto int_callback = [this, id](ax::mojom::IntAttribute attr, const int& old_id, const int& new_id) { if (!IsNodeIdIntAttribute(attr)) return; // Remove old_id -> id from the map, and clear map keys if their // values are now empty. auto& map = int_reverse_relations_[attr]; if (map.find(old_id) != map.end()) { map[old_id].erase(id); if (map[old_id].empty()) map.erase(old_id); } // Add new_id -> id to the map, unless new_id is zero indicating that // we're only removing a relation. if (new_id) map[new_id].insert(id); }; CallIfAttributeValuesChanged(old_data.int_attributes, new_data.int_attributes, 0, int_callback); auto intlist_callback = [this, id](ax::mojom::IntListAttribute attr, const std::vector<int32_t>& old_idlist, const std::vector<int32_t>& new_idlist) { if (!IsNodeIdIntListAttribute(attr)) return; auto& map = intlist_reverse_relations_[attr]; for (int32_t old_id : old_idlist) { if (map.find(old_id) != map.end()) { map[old_id].erase(id); if (map[old_id].empty()) map.erase(old_id); } } for (int32_t new_id : new_idlist) intlist_reverse_relations_[attr][new_id].insert(id); }; CallIfAttributeValuesChanged(old_data.intlist_attributes, new_data.intlist_attributes, std::vector<int32_t>(), intlist_callback); auto string_callback = [this, id](ax::mojom::StringAttribute attr, const std::string& old_string, const std::string& new_string) { if (attr == ax::mojom::StringAttribute::kChildTreeId) { // Remove old_string -> id from the map, and clear map keys if // their values are now empty. AXTreeID old_ax_tree_id = AXTreeID::FromString(old_string); if (child_tree_id_reverse_map_.find(old_ax_tree_id) != child_tree_id_reverse_map_.end()) { child_tree_id_reverse_map_[old_ax_tree_id].erase(id); if (child_tree_id_reverse_map_[old_ax_tree_id].empty()) child_tree_id_reverse_map_.erase(old_ax_tree_id); } // Add new_string -> id to the map, unless new_id is zero indicating that // we're only removing a relation. if (!new_string.empty()) { AXTreeID new_ax_tree_id = AXTreeID::FromString(new_string); child_tree_id_reverse_map_[new_ax_tree_id].insert(id); } } }; CallIfAttributeValuesChanged(old_data.string_attributes, new_data.string_attributes, std::string(), string_callback); } bool AXTree::ValidatePendingChangesComplete( const AXTreeUpdateState& update_state) { if (!update_state.pending_nodes.empty()) { error_ = "Nodes left pending by the update:"; for (const AXNode::AXID pending_id : update_state.pending_nodes) { error_ += base::StringPrintf(" %d", pending_id); } return false; } if (!update_state.node_id_to_pending_data.empty()) { std::string destroy_subtree_ids; std::string destroy_node_ids; std::string create_node_ids; bool has_pending_changes = false; for (auto&& pair : update_state.node_id_to_pending_data) { const AXNode::AXID pending_id = pair.first; const std::unique_ptr<PendingStructureChanges>& data = pair.second; if (data->DoesNodeExpectAnyStructureChanges()) { if (data->DoesNodeExpectSubtreeWillBeDestroyed()) destroy_subtree_ids += base::StringPrintf(" %d", pending_id); if (data->DoesNodeExpectNodeWillBeDestroyed()) destroy_node_ids += base::StringPrintf(" %d", pending_id); if (data->DoesNodeExpectNodeWillBeCreated()) create_node_ids += base::StringPrintf(" %d", pending_id); has_pending_changes = true; } } if (has_pending_changes) { std::ostringstream stringStream; stringStream << "Changes left pending by the update; destroy subtrees: " << destroy_subtree_ids.c_str() << ", destroy nodes: " << destroy_node_ids.c_str() << ", create nodes: " << create_node_ids.c_str(); error_ = stringStream.str(); } return !has_pending_changes; } return true; } void AXTree::MarkSubtreeForDestruction(AXNode::AXID node_id, AXTreeUpdateState* update_state) { update_state->IncrementPendingDestroySubtreeCount(node_id); MarkNodesForDestructionRecursive(node_id, update_state); } void AXTree::MarkNodesForDestructionRecursive(AXNode::AXID node_id, AXTreeUpdateState* update_state) { // If this subtree has already been marked for destruction, return so // we don't walk it again. if (!update_state->ShouldPendingNodeExistInTree(node_id)) return; const AXNodeData& last_known_data = update_state->GetLastKnownPendingNodeData(node_id); update_state->IncrementPendingDestroyNodeCount(node_id); for (AXNode::AXID child_id : last_known_data.child_ids) { MarkNodesForDestructionRecursive(child_id, update_state); } } void AXTree::DestroySubtree(AXNode* node, AXTreeUpdateState* update_state) { BASE_DCHECK(GetTreeUpdateInProgressState()); // |update_state| must already contain information about all of the expected // changes and invalidations to apply. If any of these are missing, observers // may not be notified of changes. BASE_DCHECK(update_state); BASE_DCHECK(update_state->GetPendingDestroySubtreeCount(node->id()) > 0); BASE_DCHECK(!node->parent() || update_state->InvalidatesUnignoredCachedValues( node->parent()->id())); update_state->DecrementPendingDestroySubtreeCount(node->id()); DestroyNodeAndSubtree(node, update_state); } void AXTree::DestroyNodeAndSubtree(AXNode* node, AXTreeUpdateState* update_state) { BASE_DCHECK(GetTreeUpdateInProgressState()); BASE_DCHECK(!update_state || update_state->GetPendingDestroyNodeCount(node->id()) > 0); // Clear out any reverse relations. AXNodeData empty_data; empty_data.id = node->id(); UpdateReverseRelations(node, empty_data); id_map_.erase(node->id()); for (auto* child : node->children()) DestroyNodeAndSubtree(child, update_state); if (update_state) { update_state->pending_nodes.erase(node->id()); update_state->DecrementPendingDestroyNodeCount(node->id()); update_state->removed_node_ids.insert(node->id()); update_state->new_node_ids.erase(node->id()); update_state->node_data_changed_ids.erase(node->id()); if (update_state->IsReparentedNode(node)) { update_state->old_node_id_to_data.emplace( std::make_pair(node->id(), node->TakeData())); } } node->Destroy(); } void AXTree::DeleteOldChildren(AXNode* node, const std::vector<int32_t>& new_child_ids, AXTreeUpdateState* update_state) { BASE_DCHECK(GetTreeUpdateInProgressState()); // Create a set of child ids in |src| for fast lookup, we know the set does // not contain duplicate entries already, because that was handled when // populating |update_state| with information about all of the expected // changes to be applied. std::set<int32_t> new_child_id_set(new_child_ids.begin(), new_child_ids.end()); // Delete the old children. for (AXNode* child : node->children()) { if (!base::Contains(new_child_id_set, child->id())) DestroySubtree(child, update_state); } } bool AXTree::CreateNewChildVector(AXNode* node, const std::vector<int32_t>& new_child_ids, std::vector<AXNode*>* new_children, AXTreeUpdateState* update_state) { BASE_DCHECK(GetTreeUpdateInProgressState()); bool success = true; for (size_t i = 0; i < new_child_ids.size(); ++i) { int32_t child_id = new_child_ids[i]; AXNode* child = GetFromId(child_id); if (child) { if (child->parent() != node) { // This is a serious error - nodes should never be reparented. // If this case occurs, continue so this node isn't left in an // inconsistent state, but return failure at the end. error_ = base::StringPrintf( "Node %d reparented from %d to %d", child->id(), child->parent() ? child->parent()->id() : 0, node->id()); success = false; continue; } child->SetIndexInParent(i); } else { child = CreateNode(node, child_id, i, update_state); update_state->pending_nodes.insert(child->id()); } new_children->push_back(child); } return success; } void AXTree::SetEnableExtraMacNodes(bool enabled) { if (enable_extra_mac_nodes_ == enabled) return; // No change. if (enable_extra_mac_nodes_ && !enabled) { BASE_LOG() << "We don't support disabling the extra Mac nodes once enabled."; BASE_UNREACHABLE(); return; } BASE_DCHECK(0U == table_info_map_.size()); enable_extra_mac_nodes_ = enabled; } int32_t AXTree::GetNextNegativeInternalNodeId() { int32_t return_value = next_negative_internal_node_id_; next_negative_internal_node_id_--; if (next_negative_internal_node_id_ > 0) next_negative_internal_node_id_ = -1; return return_value; } void AXTree::PopulateOrderedSetItemsMap( const AXNode& original_node, const AXNode* ordered_set, OrderedSetItemsMap* items_map_to_be_populated) const { // Ignored nodes are not a part of ordered sets. if (original_node.IsIgnored()) return; // Not all ordered set containers support hierarchical level, but their set // items may support hierarchical level. For example, container <tree> does // not support level, but <treeitem> supports level. For ordered sets like // this, the set container (e.g. <tree>) will take on the min of the levels // of its direct children(e.g. <treeitem>), if the children's levels are // defined. std::optional<int> ordered_set_min_level = ordered_set->GetHierarchicalLevel(); for (AXNode::UnignoredChildIterator child = ordered_set->UnignoredChildrenBegin(); child != ordered_set->UnignoredChildrenEnd(); ++child) { std::optional<int> child_level = child->GetHierarchicalLevel(); if (child_level) { ordered_set_min_level = ordered_set_min_level ? std::min(child_level, ordered_set_min_level) : child_level; } } RecursivelyPopulateOrderedSetItemsMap(original_node, ordered_set, ordered_set, ordered_set_min_level, std::nullopt, items_map_to_be_populated); // If after RecursivelyPopulateOrderedSetItemsMap() call, the corresponding // level (i.e. |ordered_set_min_level|) does not exist in // |items_map_to_be_populated|, and |original_node| equals |ordered_set|, we // know |original_node| is an empty ordered set and contains no set items. // However, |original_node| may still have set size attribute, so we still // want to add this empty set (i.e. original_node/ordered_set) to // |items_map_to_be_populated|. if (&original_node == ordered_set && !items_map_to_be_populated->HierarchicalLevelExists( ordered_set_min_level)) { items_map_to_be_populated->Add(ordered_set_min_level, OrderedSetContent(&original_node)); } } void AXTree::RecursivelyPopulateOrderedSetItemsMap( const AXNode& original_node, const AXNode* ordered_set, const AXNode* local_parent, std::optional<int> ordered_set_min_level, std::optional<int> prev_level, OrderedSetItemsMap* items_map_to_be_populated) const { // For optimization purpose, we want to only populate set items that are // direct descendants of |ordered_set|, since we will only be calculating // PosInSet & SetSize of items of that level. So we skip items on deeper // levels by stop searching recursively on node |local_parent| that turns out // to be an ordered set whose role matches that of |ordered_set|. However, // when we encounter a flattened structure such as the following: // <div role="tree"> // <div role="treeitem" aria-level="1"></div> // <div role="treeitem" aria-level="2"></div> // <div role="treeitem" aria-level="3"></div> // </div> // This optimization won't apply, we will end up populating items from all // levels. if (ordered_set->data().role == local_parent->data().role && ordered_set != local_parent) return; for (AXNode::UnignoredChildIterator itr = local_parent->UnignoredChildrenBegin(); itr != local_parent->UnignoredChildrenEnd(); ++itr) { const AXNode* child = itr.get(); // Invisible children should not be counted. // However, in the collapsed container case (e.g. a combobox), items can // still be chosen/navigated. However, the options in these collapsed // containers are historically marked invisible. Therefore, in that case, // count the invisible items. Only check 2 levels up, as combobox containers // are never higher. if (child->data().HasState(ax::mojom::State::kInvisible) && !IsCollapsed(local_parent) && !IsCollapsed(local_parent->parent())) { continue; } std::optional<int> curr_level = child->GetHierarchicalLevel(); // Add child to |items_map_to_be_populated| if role matches with the role of // |ordered_set|. If role of node is kRadioButton, don't add items of other // roles, even if item role matches the role of |ordered_set|. if (child->data().role == ax::mojom::Role::kComment || (original_node.data().role == ax::mojom::Role::kRadioButton && child->data().role == ax::mojom::Role::kRadioButton) || (original_node.data().role != ax::mojom::Role::kRadioButton && child->SetRoleMatchesItemRole(ordered_set))) { // According to WAI-ARIA spec, some ordered set items do not support // hierarchical level while its ordered set container does. For example, // <tab> does not support level, while <tablist> supports level. // https://www.w3.org/WAI/PF/aria/roles#tab // https://www.w3.org/WAI/PF/aria/roles#tablist // For this special case, when we add set items (e.g. tab) to // |items_map_to_be_populated|, set item is placed at the same level as // its container (e.g. tablist) in |items_map_to_be_populated|. if (!curr_level && child->GetUnignoredParent() == ordered_set) curr_level = ordered_set_min_level; // We only add child to |items_map_to_be_populated| if the child set item // is at the same hierarchical level as |ordered_set|'s level. if (!items_map_to_be_populated->HierarchicalLevelExists(curr_level)) { bool use_ordered_set = child->SetRoleMatchesItemRole(ordered_set) && ordered_set_min_level == curr_level; const AXNode* child_ordered_set = use_ordered_set ? ordered_set : nullptr; items_map_to_be_populated->Add(curr_level, OrderedSetContent(child_ordered_set)); } items_map_to_be_populated->AddItemToBack(curr_level, child); } // If |child| is an ignored container for ordered set and should not be used // to contribute to |items_map_to_be_populated|, we recurse into |child|'s // descendants to populate |items_map_to_be_populated|. if (child->IsIgnoredContainerForOrderedSet()) { RecursivelyPopulateOrderedSetItemsMap(original_node, ordered_set, child, ordered_set_min_level, curr_level, items_map_to_be_populated); } // If |curr_level| goes up one level from |prev_level|, which indicates // the ordered set of |prev_level| is closed, we add a new OrderedSetContent // on the previous level of |items_map_to_be_populated| to signify this. // Consider the example below: // <div role="tree"> // <div role="treeitem" aria-level="1"></div> // <!--- set1-level2 --> // <div role="treeitem" aria-level="2"></div> // <div role="treeitem" aria-level="2"></div> <--|prev_level| // <div role="treeitem" aria-level="1" id="item2-level1"> <--|curr_level| // </div> // <!--- set2-level2 --> // <div role="treeitem" aria-level="2"></div> // <div role="treeitem" aria-level="2"></div> // </div> // |prev_level| is on the last item of "set1-level2" and |curr_level| is on // "item2-level1". Since |curr_level| is up one level from |prev_level|, we // already completed adding all items from "set1-level2" to // |items_map_to_be_populated|. So we close up "set1-level2" by adding a new // OrderedSetContent to level 2. When |curr_level| ends up on the items of // "set2-level2" next, it has a fresh new set to be populated. if (child->SetRoleMatchesItemRole(ordered_set) && curr_level < prev_level) items_map_to_be_populated->Add(prev_level, OrderedSetContent()); prev_level = curr_level; } } // Given an ordered_set, compute pos_in_set and set_size for all of its items // and store values in cache. // Ordered_set should never be nullptr. void AXTree::ComputeSetSizePosInSetAndCache(const AXNode& node, const AXNode* ordered_set) { BASE_DCHECK(ordered_set); // Set items role::kComment and role::kRadioButton are special cases and do // not necessarily need to be contained in an ordered set. if (node.data().role != ax::mojom::Role::kComment && node.data().role != ax::mojom::Role::kRadioButton && !node.SetRoleMatchesItemRole(ordered_set) && !IsSetLike(node.data().role)) return; // Find all items within ordered_set and add to |items_map_to_be_populated|. OrderedSetItemsMap items_map_to_be_populated; PopulateOrderedSetItemsMap(node, ordered_set, &items_map_to_be_populated); // If ordered_set role is kPopUpButton and it wraps a kMenuListPopUp, then we // would like it to inherit the SetSize from the kMenuListPopUp it wraps. To // do this, we treat the kMenuListPopUp as the ordered_set and eventually // assign its SetSize value to the kPopUpButton. if (node.data().role == ax::mojom::Role::kPopUpButton && node.GetUnignoredChildCount() > 0) { // kPopUpButtons are only allowed to contain one kMenuListPopUp. // The single element is guaranteed to be a kMenuListPopUp because that is // the only item role that matches the ordered set role of kPopUpButton. // Please see AXNode::SetRoleMatchesItemRole for more details. OrderedSetContent* set_content = items_map_to_be_populated.GetFirstOrderedSetContent(); if (set_content && set_content->set_items_.size() == 1) { const AXNode* menu_list_popup = set_content->set_items_.front(); if (menu_list_popup->data().role == ax::mojom::Role::kMenuListPopup) { items_map_to_be_populated.Clear(); PopulateOrderedSetItemsMap(node, menu_list_popup, &items_map_to_be_populated); set_content = items_map_to_be_populated.GetFirstOrderedSetContent(); // Replace |set_content|'s ordered set container with |node| // (Role::kPopUpButton), which acts as the set container for nodes with // Role::kMenuListOptions (children of |menu_list_popup|). if (set_content) set_content->ordered_set_ = &node; } } } // Iterate over all items from OrderedSetItemsMap to compute and cache each // ordered set item's PosInSet and SetSize and corresponding ordered set // container's SetSize. for (auto element : items_map_to_be_populated.items_map_) { for (const OrderedSetContent& ordered_set_content : element.second) { ComputeSetSizePosInSetAndCacheHelper(ordered_set_content); } } } void AXTree::ComputeSetSizePosInSetAndCacheHelper( const OrderedSetContent& ordered_set_content) { // Keep track of number of items in the set. int32_t num_elements = 0; // Keep track of largest ordered set item's |aria-setsize| attribute value. int32_t max_item_set_size_from_attribute = 0; for (const AXNode* item : ordered_set_content.set_items_) { // |item|'s PosInSet value is the maximum of accumulated number of // elements count and the value from its |aria-posinset| attribute. int32_t pos_in_set_value = std::max(num_elements + 1, item->GetIntAttribute(ax::mojom::IntAttribute::kPosInSet)); // For |item| that has defined hierarchical level and |aria-posinset| // attribute, the attribute value takes precedence. // Note: According to WAI-ARIA spec, items that support // |aria-posinset| do not necessarily support hierarchical level. if (item->GetHierarchicalLevel() && item->HasIntAttribute(ax::mojom::IntAttribute::kPosInSet)) pos_in_set_value = item->GetIntAttribute(ax::mojom::IntAttribute::kPosInSet); num_elements = pos_in_set_value; // Cache computed PosInSet value for |item|. node_set_size_pos_in_set_info_map_[item->id()] = NodeSetSizePosInSetInfo(); node_set_size_pos_in_set_info_map_[item->id()].pos_in_set = pos_in_set_value; // Track the largest set size for this OrderedSetContent. max_item_set_size_from_attribute = std::max(max_item_set_size_from_attribute, item->GetIntAttribute(ax::mojom::IntAttribute::kSetSize)); } // End of iterating over each item in |ordered_set_content|. // The SetSize of an ordered set (and all of its items) is the maximum of // the following values: // 1. The number of elements in the ordered set. // 2. The largest item set size from |aria-setsize| attribute. // 3. The ordered set container's |aria-setsize| attribute value. int32_t set_size_value = std::max(num_elements, max_item_set_size_from_attribute); // Cache the hierarchical level and set size of |ordered_set_content|'s set // container, if the container exists. if (const AXNode* ordered_set = ordered_set_content.ordered_set_) { set_size_value = std::max( set_size_value, ordered_set->GetIntAttribute(ax::mojom::IntAttribute::kSetSize)); // Cache |ordered_set|'s hierarchical level. std::optional<int> ordered_set_level = ordered_set->GetHierarchicalLevel(); if (node_set_size_pos_in_set_info_map_.find(ordered_set->id()) == node_set_size_pos_in_set_info_map_.end()) { node_set_size_pos_in_set_info_map_[ordered_set->id()] = NodeSetSizePosInSetInfo(); node_set_size_pos_in_set_info_map_[ordered_set->id()] .lowest_hierarchical_level = ordered_set_level; } else if (node_set_size_pos_in_set_info_map_[ordered_set->id()] .lowest_hierarchical_level > ordered_set_level) { node_set_size_pos_in_set_info_map_[ordered_set->id()] .lowest_hierarchical_level = ordered_set_level; } // Cache |ordered_set|'s set size. node_set_size_pos_in_set_info_map_[ordered_set->id()].set_size = set_size_value; } // Cache the set size of |ordered_set_content|'s set items. for (const AXNode* item : ordered_set_content.set_items_) { // If item's hierarchical level and |aria-setsize| attribute are specified, // the item's |aria-setsize| value takes precedence. if (item->GetHierarchicalLevel() && item->HasIntAttribute(ax::mojom::IntAttribute::kSetSize)) node_set_size_pos_in_set_info_map_[item->id()].set_size = item->GetIntAttribute(ax::mojom::IntAttribute::kSetSize); else node_set_size_pos_in_set_info_map_[item->id()].set_size = set_size_value; } // End of iterating over each item in |ordered_set_content|. } std::optional<int> AXTree::GetPosInSet(const AXNode& node) { if (node.data().role == ax::mojom::Role::kPopUpButton && node.GetUnignoredChildCount() == 0 && node.HasIntAttribute(ax::mojom::IntAttribute::kPosInSet)) { return node.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet); } if (node_set_size_pos_in_set_info_map_.find(node.id()) != node_set_size_pos_in_set_info_map_.end()) { // If item's id is in the cache, return stored PosInSet value. return node_set_size_pos_in_set_info_map_[node.id()].pos_in_set; } if (GetTreeUpdateInProgressState()) return std::nullopt; // Only allow this to be called on nodes that can hold PosInSet values, // which are defined in the ARIA spec. if (!node.IsOrderedSetItem() || node.IsIgnored()) return std::nullopt; const AXNode* ordered_set = node.GetOrderedSet(); if (!ordered_set) return std::nullopt; // Compute, cache, then return. ComputeSetSizePosInSetAndCache(node, ordered_set); std::optional<int> pos_in_set = node_set_size_pos_in_set_info_map_[node.id()].pos_in_set; if (pos_in_set.has_value() && pos_in_set.value() < 1) return std::nullopt; return pos_in_set; } std::optional<int> AXTree::GetSetSize(const AXNode& node) { if (node.data().role == ax::mojom::Role::kPopUpButton && node.GetUnignoredChildCount() == 0 && node.HasIntAttribute(ax::mojom::IntAttribute::kSetSize)) { return node.GetIntAttribute(ax::mojom::IntAttribute::kSetSize); } if (node_set_size_pos_in_set_info_map_.find(node.id()) != node_set_size_pos_in_set_info_map_.end()) { // If item's id is in the cache, return stored SetSize value. return node_set_size_pos_in_set_info_map_[node.id()].set_size; } if (GetTreeUpdateInProgressState()) return std::nullopt; // Only allow this to be called on nodes that can hold SetSize values, which // are defined in the ARIA spec. However, we allow set-like items to receive // SetSize values for internal purposes. if ((!node.IsOrderedSetItem() && !node.IsOrderedSet()) || node.IsIgnored() || node.IsEmbeddedGroup()) { return std::nullopt; } // If |node| is item-like, find its outerlying ordered set. Otherwise, // |node| is the ordered set. const AXNode* ordered_set = &node; if (IsItemLike(node.data().role)) ordered_set = node.GetOrderedSet(); if (!ordered_set) return std::nullopt; // For popup buttons that control a single element, inherit the controlled // item's SetSize. Skip this block if the popup button controls itself. if (node.data().role == ax::mojom::Role::kPopUpButton) { const auto& controls_ids = node.data().GetIntListAttribute( ax::mojom::IntListAttribute::kControlsIds); if (controls_ids.size() == 1 && GetFromId(controls_ids[0]) && controls_ids[0] != node.id()) { const AXNode& controlled_item = *GetFromId(controls_ids[0]); std::optional<int> controlled_item_set_size = GetSetSize(controlled_item); node_set_size_pos_in_set_info_map_[node.id()].set_size = controlled_item_set_size; return controlled_item_set_size; } } // Compute, cache, then return. ComputeSetSizePosInSetAndCache(node, ordered_set); std::optional<int> set_size = node_set_size_pos_in_set_info_map_[node.id()].set_size; if (set_size.has_value() && set_size.value() < 0) return std::nullopt; return set_size; } AXTree::Selection AXTree::GetUnignoredSelection() const { Selection unignored_selection = { data().sel_is_backward, data().sel_anchor_object_id, data().sel_anchor_offset, data().sel_anchor_affinity, data().sel_focus_object_id, data().sel_focus_offset, data().sel_focus_affinity}; AXNode* anchor_node = GetFromId(data().sel_anchor_object_id); AXNode* focus_node = GetFromId(data().sel_focus_object_id); AXNodePosition::AXPositionInstance anchor_position = anchor_node ? AXNodePosition::CreatePosition(*anchor_node, data().sel_anchor_offset, data().sel_anchor_affinity) : AXNodePosition::CreateNullPosition(); // Null positions are never ignored. if (anchor_position->IsIgnored()) { anchor_position = anchor_position->AsUnignoredPosition( data().sel_is_backward ? AXPositionAdjustmentBehavior::kMoveForward : AXPositionAdjustmentBehavior::kMoveBackward); // Any selection endpoint that is inside a leaf node is expressed as a text // position in AXTreeData. if (anchor_position->IsLeafTreePosition()) anchor_position = anchor_position->AsTextPosition(); // We do not expect the selection to have an endpoint on an inline text // box as this will create issues with parts of the code that don't use // inline text boxes. if (anchor_position->IsTextPosition() && anchor_position->GetAnchor()->data().role == ax::mojom::Role::kInlineTextBox) { anchor_position = anchor_position->CreateParentPosition(); } switch (anchor_position->kind()) { case AXPositionKind::NULL_POSITION: // If one of the selection endpoints is invalid, then both endpoints // should be unset. unignored_selection.anchor_object_id = AXNode::kInvalidAXID; unignored_selection.anchor_offset = -1; unignored_selection.anchor_affinity = ax::mojom::TextAffinity::kDownstream; unignored_selection.focus_object_id = AXNode::kInvalidAXID; unignored_selection.focus_offset = -1; unignored_selection.focus_affinity = ax::mojom::TextAffinity::kDownstream; return unignored_selection; case AXPositionKind::TREE_POSITION: unignored_selection.anchor_object_id = anchor_position->anchor_id(); unignored_selection.anchor_offset = anchor_position->child_index(); unignored_selection.anchor_affinity = ax::mojom::TextAffinity::kDownstream; break; case AXPositionKind::TEXT_POSITION: unignored_selection.anchor_object_id = anchor_position->anchor_id(); unignored_selection.anchor_offset = anchor_position->text_offset(); unignored_selection.anchor_affinity = anchor_position->affinity(); break; } } AXNodePosition::AXPositionInstance focus_position = focus_node ? AXNodePosition::CreatePosition(*focus_node, data().sel_focus_offset, data().sel_focus_affinity) : AXNodePosition::CreateNullPosition(); // Null positions are never ignored. if (focus_position->IsIgnored()) { focus_position = focus_position->AsUnignoredPosition( !data().sel_is_backward ? AXPositionAdjustmentBehavior::kMoveForward : AXPositionAdjustmentBehavior::kMoveBackward); // Any selection endpoint that is inside a leaf node is expressed as a text // position in AXTreeData. if (focus_position->IsLeafTreePosition()) focus_position = focus_position->AsTextPosition(); // We do not expect the selection to have an endpoint on an inline text // box as this will create issues with parts of the code that don't use // inline text boxes. if (focus_position->IsTextPosition() && focus_position->GetAnchor()->data().role == ax::mojom::Role::kInlineTextBox) { focus_position = focus_position->CreateParentPosition(); } switch (focus_position->kind()) { case AXPositionKind::NULL_POSITION: // If one of the selection endpoints is invalid, then both endpoints // should be unset. unignored_selection.anchor_object_id = AXNode::kInvalidAXID; unignored_selection.anchor_offset = -1; unignored_selection.anchor_affinity = ax::mojom::TextAffinity::kDownstream; unignored_selection.focus_object_id = AXNode::kInvalidAXID; unignored_selection.focus_offset = -1; unignored_selection.focus_affinity = ax::mojom::TextAffinity::kDownstream; return unignored_selection; case AXPositionKind::TREE_POSITION: unignored_selection.focus_object_id = focus_position->anchor_id(); unignored_selection.focus_offset = focus_position->child_index(); unignored_selection.focus_affinity = ax::mojom::TextAffinity::kDownstream; break; case AXPositionKind::TEXT_POSITION: unignored_selection.focus_object_id = focus_position->anchor_id(); unignored_selection.focus_offset = focus_position->text_offset(); unignored_selection.focus_affinity = focus_position->affinity(); break; } } return unignored_selection; } bool AXTree::GetTreeUpdateInProgressState() const { return tree_update_in_progress_; } void AXTree::SetTreeUpdateInProgressState(bool set_tree_update_value) { tree_update_in_progress_ = set_tree_update_value; } bool AXTree::HasPaginationSupport() const { return has_pagination_support_; } } // namespace ui
engine/third_party/accessibility/ax/ax_tree.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_tree.cc", "repo_id": "engine", "token_count": 39296 }
401
// 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. #include "ax_fragment_root_win.h" #include <unordered_map> #include "ax_fragment_root_delegate_win.h" #include "ax_platform_node_win.h" #include "base/win/atl_module.h" #include "uia_registrar_win.h" namespace ui { class AXFragmentRootPlatformNodeWin : public AXPlatformNodeWin, public IItemContainerProvider, public IRawElementProviderFragmentRoot, public IRawElementProviderAdviseEvents { public: BEGIN_COM_MAP(AXFragmentRootPlatformNodeWin) COM_INTERFACE_ENTRY(IItemContainerProvider) COM_INTERFACE_ENTRY(IRawElementProviderFragmentRoot) COM_INTERFACE_ENTRY(IRawElementProviderAdviseEvents) COM_INTERFACE_ENTRY_CHAIN(AXPlatformNodeWin) END_COM_MAP() static AXFragmentRootPlatformNodeWin* Create( AXPlatformNodeDelegate* delegate) { // Make sure ATL is initialized in this module. win::CreateATLModuleIfNeeded(); CComObject<AXFragmentRootPlatformNodeWin>* instance = nullptr; HRESULT hr = CComObject<AXFragmentRootPlatformNodeWin>::CreateInstance(&instance); BASE_DCHECK(SUCCEEDED(hr)); instance->Init(delegate); instance->AddRef(); return instance; } // // IItemContainerProvider methods. // IFACEMETHODIMP FindItemByProperty( IRawElementProviderSimple* start_after_element, PROPERTYID property_id, VARIANT value, IRawElementProviderSimple** result) override { UIA_VALIDATE_CALL_1_ARG(result); *result = nullptr; // We currently only support the custom UIA property ID for unique id. if (property_id == UiaRegistrarWin::GetInstance().GetUiaUniqueIdPropertyId() && value.vt == VT_BSTR) { int32_t ax_unique_id; // TODO(gw280): https://github.com/flutter/flutter/issues/78802 // detect and handle errors ax_unique_id = std::stoi(value.bstrVal); // In the Windows accessibility platform implementation, id 0 represents // self; a positive id represents the immediate descendants; and a // negative id represents a unique id that can be mapped to any node. if (AXPlatformNodeWin* result_platform_node = static_cast<AXPlatformNodeWin*>(GetFromUniqueId(-ax_unique_id))) { if (start_after_element) { Microsoft::WRL::ComPtr<AXPlatformNodeWin> start_after_platform_node; if (!SUCCEEDED(start_after_element->QueryInterface( IID_PPV_ARGS(&start_after_platform_node)))) return E_INVALIDARG; // We want |result| to be nullptr if it comes before or is equal to // |start_after_element|. if (start_after_platform_node->CompareTo(*result_platform_node) >= 0) return S_OK; } return result_platform_node->QueryInterface(IID_PPV_ARGS(result)); } } return E_INVALIDARG; } // // IRawElementProviderSimple methods. // IFACEMETHODIMP get_HostRawElementProvider( IRawElementProviderSimple** host_element_provider) override { UIA_VALIDATE_CALL_1_ARG(host_element_provider); HWND hwnd = GetDelegate()->GetTargetForNativeAccessibilityEvent(); return UiaHostProviderFromHwnd(hwnd, host_element_provider); } IFACEMETHODIMP GetPatternProvider(PATTERNID pattern_id, IUnknown** result) override { UIA_VALIDATE_CALL_1_ARG(result); *result = nullptr; if (pattern_id == UIA_ItemContainerPatternId) { AddRef(); *result = static_cast<IItemContainerProvider*>(this); return S_OK; } return AXPlatformNodeWin::GetPatternProviderImpl(pattern_id, result); } IFACEMETHODIMP GetPropertyValue(PROPERTYID property_id, VARIANT* result) override { UIA_VALIDATE_CALL_1_ARG(result); switch (property_id) { default: // UIA has a built-in provider that will expose values for several // properties based on the HWND. This information is useful to someone // examining the accessibility tree using tools such as Inspect. Return // VT_EMPTY for most properties so that we don't override values from // the default provider with blank data. result->vt = VT_EMPTY; break; case UIA_IsControlElementPropertyId: case UIA_IsContentElementPropertyId: // Override IsControlElement and IsContentElement to fine tune which // fragment roots appear in the control and content views. result->vt = VT_BOOL; result->boolVal = static_cast<AXFragmentRootWin*>(GetDelegate())->IsControlElement() ? VARIANT_TRUE : VARIANT_FALSE; break; } return S_OK; } // // IRawElementProviderFragment methods. // IFACEMETHODIMP get_FragmentRoot( IRawElementProviderFragmentRoot** fragment_root) override { UIA_VALIDATE_CALL_1_ARG(fragment_root); QueryInterface(IID_PPV_ARGS(fragment_root)); return S_OK; } // // IRawElementProviderFragmentRoot methods. // IFACEMETHODIMP ElementProviderFromPoint( double screen_physical_pixel_x, double screen_physical_pixel_y, IRawElementProviderFragment** element_provider) override { UIA_VALIDATE_CALL_1_ARG(element_provider); *element_provider = nullptr; gfx::NativeViewAccessible hit_element = nullptr; // Descend the tree until we get a non-hit or can't go any further. AXPlatformNode* node_to_test = this; do { gfx::NativeViewAccessible test_result = node_to_test->GetDelegate()->HitTestSync(screen_physical_pixel_x, screen_physical_pixel_y); if (test_result != nullptr && test_result != hit_element) { hit_element = test_result; node_to_test = AXPlatformNode::FromNativeViewAccessible(test_result); } else { node_to_test = nullptr; } } while (node_to_test); if (hit_element) hit_element->QueryInterface(element_provider); return S_OK; } IFACEMETHODIMP GetFocus(IRawElementProviderFragment** focus) override { UIA_VALIDATE_CALL_1_ARG(focus); *focus = nullptr; gfx::NativeViewAccessible focused_element = nullptr; // GetFocus() can return a node at the root of a subtree, for example when // transitioning from Views into web content. In such cases we want to // continue drilling to retrieve the actual focused element. AXPlatformNode* node_to_test = this; do { gfx::NativeViewAccessible test_result = node_to_test->GetDelegate()->GetFocus(); if (test_result != nullptr && test_result != focused_element) { focused_element = test_result; node_to_test = AXPlatformNode::FromNativeViewAccessible(focused_element); } else { node_to_test = nullptr; } } while (node_to_test); if (focused_element) focused_element->QueryInterface(IID_PPV_ARGS(focus)); return S_OK; } // // IRawElementProviderAdviseEvents methods. // IFACEMETHODIMP AdviseEventAdded(EVENTID event_id, SAFEARRAY* property_ids) override { if (event_id == UIA_LiveRegionChangedEventId) { live_region_change_listeners_++; if (live_region_change_listeners_ == 1) { // Fire a LiveRegionChangedEvent for each live-region to tell the // newly-attached assistive technology about the regions. // // Ideally we'd be able to direct these events to only the // newly-attached AT, but we don't have that capability, so we only // fire events when the *first* AT attaches. (A common scenario will // be an attached screen-reader, then a software-keyboard attaches to // handle an input field; we don't want the screen-reader to announce // that every live-region has changed.) There isn't a perfect solution, // but this heuristic seems to work well in practice. FireLiveRegionChangeRecursive(); } } return S_OK; } IFACEMETHODIMP AdviseEventRemoved(EVENTID event_id, SAFEARRAY* property_ids) override { if (event_id == UIA_LiveRegionChangedEventId) { BASE_DCHECK(live_region_change_listeners_ > 0); live_region_change_listeners_--; } return S_OK; } private: int32_t live_region_change_listeners_ = 0; }; class AXFragmentRootMapWin { public: static AXFragmentRootMapWin& GetInstance() { static base::NoDestructor<AXFragmentRootMapWin> instance; return *instance; } void AddFragmentRoot(gfx::AcceleratedWidget widget, AXFragmentRootWin* fragment_root) { map_[widget] = fragment_root; } void RemoveFragmentRoot(gfx::AcceleratedWidget widget) { map_.erase(widget); } ui::AXFragmentRootWin* GetFragmentRoot(gfx::AcceleratedWidget widget) const { const auto& entry = map_.find(widget); if (entry != map_.end()) return entry->second; return nullptr; } ui::AXFragmentRootWin* GetFragmentRootParentOf( gfx::NativeViewAccessible accessible) const { for (const auto& entry : map_) { AXPlatformNodeDelegate* child = entry.second->GetChildNodeDelegate(); if (child && (child->GetNativeViewAccessible() == accessible)) return entry.second; } return nullptr; } private: std::unordered_map<gfx::AcceleratedWidget, AXFragmentRootWin*> map_; }; AXFragmentRootWin::AXFragmentRootWin(gfx::AcceleratedWidget widget, AXFragmentRootDelegateWin* delegate) : widget_(widget), delegate_(delegate), alert_node_(nullptr) { platform_node_ = ui::AXFragmentRootPlatformNodeWin::Create(this); AXFragmentRootMapWin::GetInstance().AddFragmentRoot(widget, this); } AXFragmentRootWin::~AXFragmentRootWin() { AXFragmentRootMapWin::GetInstance().RemoveFragmentRoot(widget_); platform_node_->Destroy(); platform_node_ = nullptr; } AXFragmentRootWin* AXFragmentRootWin::GetForAcceleratedWidget( gfx::AcceleratedWidget widget) { return AXFragmentRootMapWin::GetInstance().GetFragmentRoot(widget); } // static AXFragmentRootWin* AXFragmentRootWin::GetFragmentRootParentOf( gfx::NativeViewAccessible accessible) { return AXFragmentRootMapWin::GetInstance().GetFragmentRootParentOf( accessible); } gfx::NativeViewAccessible AXFragmentRootWin::GetNativeViewAccessible() { return platform_node_.Get(); } bool AXFragmentRootWin::IsControlElement() { return delegate_->IsAXFragmentRootAControlElement(); } gfx::NativeViewAccessible AXFragmentRootWin::GetParent() { return delegate_->GetParentOfAXFragmentRoot(); } int AXFragmentRootWin::GetChildCount() const { return delegate_->GetChildOfAXFragmentRoot() ? 1 : 0; } gfx::NativeViewAccessible AXFragmentRootWin::ChildAtIndex(int index) { if (index == 0) { return delegate_->GetChildOfAXFragmentRoot(); } else if (index == 1 && alert_node_) { return alert_node_; } return nullptr; } gfx::NativeViewAccessible AXFragmentRootWin::GetNextSibling() { int child_index = GetIndexInParentOfChild(); if (child_index >= 0) { AXPlatformNodeDelegate* parent = GetParentNodeDelegate(); if (parent && child_index < (parent->GetChildCount() - 1)) return GetParentNodeDelegate()->ChildAtIndex(child_index + 1); } return nullptr; } gfx::NativeViewAccessible AXFragmentRootWin::GetPreviousSibling() { int child_index = GetIndexInParentOfChild(); if (child_index > 0) return GetParentNodeDelegate()->ChildAtIndex(child_index - 1); return nullptr; } gfx::NativeViewAccessible AXFragmentRootWin::HitTestSync(int x, int y) const { AXPlatformNodeDelegate* child_delegate = GetChildNodeDelegate(); if (child_delegate) return child_delegate->HitTestSync(x, y); return nullptr; } gfx::NativeViewAccessible AXFragmentRootWin::GetFocus() { AXPlatformNodeDelegate* child_delegate = GetChildNodeDelegate(); if (child_delegate) return child_delegate->GetFocus(); return nullptr; } const ui::AXUniqueId& AXFragmentRootWin::GetUniqueId() const { return unique_id_; } gfx::AcceleratedWidget AXFragmentRootWin::GetTargetForNativeAccessibilityEvent() { return widget_; } AXPlatformNode* AXFragmentRootWin::GetFromTreeIDAndNodeID( const ui::AXTreeID& ax_tree_id, int32_t node_id) { AXPlatformNodeDelegate* child_delegate = GetChildNodeDelegate(); if (child_delegate) return child_delegate->GetFromTreeIDAndNodeID(ax_tree_id, node_id); return nullptr; } AXPlatformNodeDelegate* AXFragmentRootWin::GetParentNodeDelegate() const { gfx::NativeViewAccessible parent = delegate_->GetParentOfAXFragmentRoot(); if (parent) return ui::AXPlatformNode::FromNativeViewAccessible(parent)->GetDelegate(); return nullptr; } AXPlatformNodeDelegate* AXFragmentRootWin::GetChildNodeDelegate() const { gfx::NativeViewAccessible child = delegate_->GetChildOfAXFragmentRoot(); if (child) return ui::AXPlatformNode::FromNativeViewAccessible(child)->GetDelegate(); return nullptr; } int AXFragmentRootWin::GetIndexInParentOfChild() const { AXPlatformNodeDelegate* parent = GetParentNodeDelegate(); if (!parent) return 0; AXPlatformNodeDelegate* child = GetChildNodeDelegate(); if (child) { int child_count = parent->GetChildCount(); for (int child_index = 0; child_index < child_count; child_index++) { if (ui::AXPlatformNode::FromNativeViewAccessible( parent->ChildAtIndex(child_index)) ->GetDelegate() == child) return child_index; } } return 0; } void AXFragmentRootWin::SetAlertNode(AXPlatformNodeWin* alert_node) { alert_node_ = alert_node; } gfx::Rect AXFragmentRootWin::GetBoundsRect(AXCoordinateSystem sys, AXClippingBehavior clip, AXOffscreenResult* result) const { AXPlatformNodeDelegate* child = GetChildNodeDelegate(); if (!child) { return gfx::Rect(); } return child->GetBoundsRect(sys, clip, result); } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_fragment_root_win.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_fragment_root_win.cc", "repo_id": "engine", "token_count": 5503 }
402
// 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. #include "ax_platform_node_mac_unittest.h" #include "ax_platform_node_mac.h" #include "gtest/gtest.h" #include "test_ax_node_wrapper.h" #include "third_party/accessibility/ax/ax_node_data.h" namespace ui { AXPlatformNodeMacTest::AXPlatformNodeMacTest() = default; AXPlatformNodeMacTest::~AXPlatformNodeMacTest() = default; void AXPlatformNodeMacTest::SetUp() {} void AXPlatformNodeMacTest::TearDown() { // Destroy the tree and make sure we're not leaking any objects. DestroyTree(); TestAXNodeWrapper::SetGlobalIsWebContent(false); ASSERT_EQ(0U, AXPlatformNodeBase::GetInstanceCountForTesting()); } AXPlatformNode* AXPlatformNodeMacTest::AXPlatformNodeFromNode(AXNode* node) { const TestAXNodeWrapper* wrapper = TestAXNodeWrapper::GetOrCreate(GetTree(), node); return wrapper ? wrapper->ax_platform_node() : nullptr; } // Verify that we can get an AXPlatformNodeMac and AXPlatformNodeCocoa from the tree. TEST_F(AXPlatformNodeMacTest, CanGetCocoaPlatformNodeFromTree) { AXNodeData root; root.id = 1; root.relative_bounds.bounds = gfx::RectF(0, 0, 40, 40); Init(root); AXNode* root_node = GetRootAsAXNode(); ASSERT_TRUE(root_node != nullptr); AXPlatformNode* platform_node = AXPlatformNodeFromNode(root_node); ASSERT_TRUE(platform_node != nullptr); AXPlatformNodeCocoa* native_root = platform_node->GetNativeViewAccessible(); EXPECT_TRUE(native_root != nullptr); } // Test that [AXPlatformNodeCocoa accessbilityRangeForPosition:] doesn't crash. // https://github.com/flutter/flutter/issues/102416 TEST_F(AXPlatformNodeMacTest, AccessibilityRangeForPositionDoesntCrash) { AXNodeData root; root.id = 1; root.relative_bounds.bounds = gfx::RectF(0, 0, 40, 40); Init(root); AXNode* root_node = GetRootAsAXNode(); ASSERT_TRUE(root_node != nullptr); AXPlatformNode* platform_node = AXPlatformNodeFromNode(root_node); ASSERT_TRUE(platform_node != nullptr); NSPoint point = NSMakePoint(0, 0); AXPlatformNodeCocoa* native_root = platform_node->GetNativeViewAccessible(); ASSERT_TRUE(native_root != nullptr); [native_root accessibilityRangeForPosition:(NSPoint)point]; } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_platform_node_mac_unittest.mm/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_mac_unittest.mm", "repo_id": "engine", "token_count": 775 }
403
// 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_unique_id.h" #include <memory> #include <unordered_set> #include "base/container_utils.h" #include "base/logging.h" namespace ui { namespace { std::unordered_set<int32_t> g_assigned_ids; } // namespace AXUniqueId::AXUniqueId() : AXUniqueId(INT32_MAX) {} AXUniqueId::AXUniqueId(const int32_t max_id) : id_(GetNextAXUniqueId(max_id)) {} AXUniqueId::~AXUniqueId() { g_assigned_ids.erase(id_); } bool AXUniqueId::operator==(const AXUniqueId& other) const { return Get() == other.Get(); } bool AXUniqueId::operator!=(const AXUniqueId& other) const { return !(*this == other); } bool AXUniqueId::IsAssigned(const int32_t id) const { return base::Contains(g_assigned_ids, id); } int32_t AXUniqueId::GetNextAXUniqueId(const int32_t max_id) { static int32_t current_id = 0; static bool has_wrapped = false; const int32_t prev_id = current_id; do { if (current_id >= max_id) { current_id = 1; has_wrapped = true; } else { ++current_id; } if (current_id == prev_id) { BASE_LOG() << "There are over 2 billion available IDs, so the newly " "created ID cannot be equal to the most recently created " "ID."; } // If it |has_wrapped| then we need to continue until we find the first // unassigned ID. } while (has_wrapped && IsAssigned(current_id)); g_assigned_ids.insert(current_id); return current_id; } } // namespace ui
engine/third_party/accessibility/ax/platform/ax_unique_id.cc/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_unique_id.cc", "repo_id": "engine", "token_count": 631 }
404
// 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. #ifndef ACCESSIBILITY_BASE_AUTO_RESET_H_ #define ACCESSIBILITY_BASE_AUTO_RESET_H_ #include <utility> // base::AutoReset<> is useful for setting a variable to a new value only within // a particular scope. An base::AutoReset<> object resets a variable to its // original value upon destruction, making it an alternative to writing // "var = false;" or "var = old_val;" at all of a block's exit points. // // This should be obvious, but note that an base::AutoReset<> instance should // have a shorter lifetime than its scoped_variable, to prevent invalid memory // writes when the base::AutoReset<> object is destroyed. namespace base { template <typename T> class AutoReset { public: template <typename U> AutoReset(T* scoped_variable, U&& new_value) : scoped_variable_(scoped_variable), original_value_( std::exchange(*scoped_variable_, std::forward<U>(new_value))) {} AutoReset(AutoReset&& other) : scoped_variable_(std::exchange(other.scoped_variable_, nullptr)), original_value_(std::move(other.original_value_)) {} AutoReset& operator=(AutoReset&& rhs) { scoped_variable_ = std::exchange(rhs.scoped_variable_, nullptr); original_value_ = std::move(rhs.original_value_); return *this; } ~AutoReset() { if (scoped_variable_) *scoped_variable_ = std::move(original_value_); } private: T* scoped_variable_; T original_value_; }; } // namespace base #endif // ACCESSIBILITY_BASE_AUTO_RESET_H_
engine/third_party/accessibility/base/auto_reset.h/0
{ "file_path": "engine/third_party/accessibility/base/auto_reset.h", "repo_id": "engine", "token_count": 579 }
405
// 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. #ifndef BASE_NUMERICS_MATH_CONSTANTS_H_ #define BASE_NUMERICS_MATH_CONSTANTS_H_ namespace base { constexpr double kPiDouble = 3.14159265358979323846; constexpr float kPiFloat = 3.14159265358979323846f; // The mean acceleration due to gravity on Earth in m/s^2. constexpr double kMeanGravityDouble = 9.80665; constexpr float kMeanGravityFloat = 9.80665f; } // namespace base #endif // BASE_NUMERICS_MATH_CONSTANTS_H_
engine/third_party/accessibility/base/numerics/math_constants.h/0
{ "file_path": "engine/third_party/accessibility/base/numerics/math_constants.h", "repo_id": "engine", "token_count": 208 }
406
// 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 BASE_TEST_GTEST_UTIL_H_ #define BASE_TEST_GTEST_UTIL_H_ #include <string> #include <utility> #include <vector> #include "base/compiler_specific.h" #include "build/build_config.h" #include "gtest/gtest.h" // EXPECT/ASSERT_DCHECK_DEATH is intended to replace EXPECT/ASSERT_DEBUG_DEATH // when the death is expected to be caused by a DCHECK. Contrary to // EXPECT/ASSERT_DEBUG_DEATH however, it doesn't execute the statement in non- // dcheck builds as DCHECKs are intended to catch things that should never // happen and as such executing the statement results in undefined behavior // (|statement| is compiled in unsupported configurations nonetheless). // Death tests misbehave on Android. // TODO(gw280): once https://github.com/flutter/flutter/issues/78491 is resolved // we can potentially remove the condition on NDEBUG here. #if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) && !defined(NDEBUG) // EXPECT/ASSERT_DCHECK_DEATH tests verify that a DCHECK is hit ("Check failed" // is part of the error message), but intentionally do not expose the gtest // death test's full |regex| parameter to avoid users having to verify the exact // syntax of the error message produced by the DCHECK. #define EXPECT_DCHECK_DEATH(statement) EXPECT_DEATH(statement, "Check failed") #define ASSERT_DCHECK_DEATH(statement) ASSERT_DEATH(statement, "Check failed") #else // defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) && !defined(NDEBUG) #define EXPECT_DCHECK_DEATH(statement) \ GTEST_UNSUPPORTED_DEATH_TEST(statement, "Check failed", ) #define ASSERT_DCHECK_DEATH(statement) \ GTEST_UNSUPPORTED_DEATH_TEST(statement, "Check failed", return) #endif // defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) && !defined(NDEBUG) // As above, but for CHECK(). #if defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) // Official builds will eat stream parameters, so don't check the error message. #if defined(OFFICIAL_BUILD) && defined(NDEBUG) #define EXPECT_CHECK_DEATH(statement) EXPECT_DEATH(statement, "") #define ASSERT_CHECK_DEATH(statement) ASSERT_DEATH(statement, "") #else #define EXPECT_CHECK_DEATH(statement) EXPECT_DEATH(statement, "Check failed") #define ASSERT_CHECK_DEATH(statement) ASSERT_DEATH(statement, "Check failed") #endif // defined(OFFICIAL_BUILD) && defined(NDEBUG) #else // defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) // Note GTEST_UNSUPPORTED_DEATH_TEST takes a |regex| only to see whether it is a // valid regex. It is never evaluated. #define EXPECT_CHECK_DEATH(statement) \ GTEST_UNSUPPORTED_DEATH_TEST(statement, "", ) #define ASSERT_CHECK_DEATH(statement) \ GTEST_UNSUPPORTED_DEATH_TEST(statement, "", return) #endif // defined(GTEST_HAS_DEATH_TEST) && !defined(OS_ANDROID) #endif // BASE_TEST_GTEST_UTIL_H_
engine/third_party/accessibility/base/test/gtest_util.h/0
{ "file_path": "engine/third_party/accessibility/base/test/gtest_util.h", "repo_id": "engine", "token_count": 992 }
407
// Copyright (c) 2010 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/scoped_variant.h" #include <propvarutil.h> #include <wrl/client.h> #include <algorithm> #include <functional> #include "base/logging.h" #include "base/numerics/ranges.h" #include "base/win/variant_util.h" namespace base { namespace win { // Global, const instance of an empty variant. const VARIANT ScopedVariant::kEmptyVariant = {{{VT_EMPTY}}}; ScopedVariant::ScopedVariant(ScopedVariant&& var) { var_.vt = VT_EMPTY; Reset(var.Release()); } ScopedVariant::~ScopedVariant() { static_assert(sizeof(ScopedVariant) == sizeof(VARIANT), "ScopedVariantSize"); ::VariantClear(&var_); } ScopedVariant::ScopedVariant(const wchar_t* str) { var_.vt = VT_EMPTY; Set(str); } ScopedVariant::ScopedVariant(const wchar_t* str, UINT length) { var_.vt = VT_BSTR; var_.bstrVal = ::SysAllocStringLen(str, length); } ScopedVariant::ScopedVariant(long value, VARTYPE vt) { var_.vt = vt; var_.lVal = value; } ScopedVariant::ScopedVariant(int value) { var_.vt = VT_I4; var_.lVal = value; } ScopedVariant::ScopedVariant(bool value) { var_.vt = VT_BOOL; var_.boolVal = value ? VARIANT_TRUE : VARIANT_FALSE; } ScopedVariant::ScopedVariant(double value, VARTYPE vt) { BASE_DCHECK(vt == VT_R8 || vt == VT_DATE); var_.vt = vt; var_.dblVal = value; } ScopedVariant::ScopedVariant(IDispatch* dispatch) { var_.vt = VT_EMPTY; Set(dispatch); } ScopedVariant::ScopedVariant(IUnknown* unknown) { var_.vt = VT_EMPTY; Set(unknown); } ScopedVariant::ScopedVariant(SAFEARRAY* safearray) { var_.vt = VT_EMPTY; Set(safearray); } ScopedVariant::ScopedVariant(const VARIANT& var) { var_.vt = VT_EMPTY; Set(var); } void ScopedVariant::Reset(const VARIANT& var) { if (&var != &var_) { ::VariantClear(&var_); var_ = var; } } VARIANT ScopedVariant::Release() { VARIANT var = var_; var_.vt = VT_EMPTY; return var; } void ScopedVariant::Swap(ScopedVariant& var) { VARIANT tmp = var_; var_ = var.var_; var.var_ = tmp; } VARIANT* ScopedVariant::Receive() { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "variant leak. type: " << var_.vt; return &var_; } VARIANT ScopedVariant::Copy() const { VARIANT ret = {{{VT_EMPTY}}}; ::VariantCopy(&ret, &var_); return ret; } int ScopedVariant::Compare(const VARIANT& other, bool ignore_case) const { BASE_DCHECK(!V_ISARRAY(&var_)) << "Comparison is not supported when |this| owns a SAFEARRAY"; BASE_DCHECK(!V_ISARRAY(&other)) << "Comparison is not supported when |other| owns a SAFEARRAY"; const bool this_is_empty = var_.vt == VT_EMPTY || var_.vt == VT_NULL; const bool other_is_empty = other.vt == VT_EMPTY || other.vt == VT_NULL; // 1. VT_NULL and VT_EMPTY is always considered less-than any other VARTYPE. if (this_is_empty) return other_is_empty ? 0 : -1; if (other_is_empty) return 1; // 2. If both VARIANTS have either VT_UNKNOWN or VT_DISPATCH even if the // VARTYPEs do not match, the address of its IID_IUnknown is compared to // guarantee a logical ordering even though it is not a meaningful order. // e.g. (a.Compare(b) != b.Compare(a)) unless (a == b). const bool this_is_unknown = var_.vt == VT_UNKNOWN || var_.vt == VT_DISPATCH; const bool other_is_unknown = other.vt == VT_UNKNOWN || other.vt == VT_DISPATCH; if (this_is_unknown && other_is_unknown) { // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface // Query IID_IUnknown to determine whether the two variants point // to the same instance of an object Microsoft::WRL::ComPtr<IUnknown> this_unknown; Microsoft::WRL::ComPtr<IUnknown> other_unknown; V_UNKNOWN(&var_)->QueryInterface(IID_PPV_ARGS(&this_unknown)); V_UNKNOWN(&other)->QueryInterface(IID_PPV_ARGS(&other_unknown)); if (this_unknown.Get() == other_unknown.Get()) return 0; // std::less for any pointer type yields a strict total order even if the // built-in operator< does not. return std::less<>{}(this_unknown.Get(), other_unknown.Get()) ? -1 : 1; } // 3. If the VARTYPEs do not match, then the value of the VARTYPE is compared. if (V_VT(&var_) != V_VT(&other)) return (V_VT(&var_) < V_VT(&other)) ? -1 : 1; const VARTYPE shared_vartype = V_VT(&var_); // 4. Comparing VT_BSTR values is a lexicographical comparison of the contents // of the BSTR, taking into account |ignore_case|. if (shared_vartype == VT_BSTR) { ULONG flags = ignore_case ? NORM_IGNORECASE : 0; HRESULT hr = ::VarBstrCmp(V_BSTR(&var_), V_BSTR(&other), LOCALE_USER_DEFAULT, flags); BASE_DCHECK(SUCCEEDED(hr) && hr != VARCMP_NULL) << "unsupported variant comparison: " << var_.vt << " and " << other.vt; switch (hr) { case VARCMP_LT: return -1; case VARCMP_GT: case VARCMP_NULL: return 1; default: return 0; } } // 5. Otherwise returns the lexicographical comparison of the values held by // the two VARIANTS that share the same VARTYPE. return ::VariantCompare(var_, other); } void ScopedVariant::Set(const wchar_t* str) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_BSTR; var_.bstrVal = ::SysAllocString(str); } void ScopedVariant::Set(int8_t i8) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_I1; var_.cVal = i8; } void ScopedVariant::Set(uint8_t ui8) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_UI1; var_.bVal = ui8; } void ScopedVariant::Set(int16_t i16) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_I2; var_.iVal = i16; } void ScopedVariant::Set(uint16_t ui16) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_UI2; var_.uiVal = ui16; } void ScopedVariant::Set(int32_t i32) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_I4; var_.lVal = i32; } void ScopedVariant::Set(uint32_t ui32) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_UI4; var_.ulVal = ui32; } void ScopedVariant::Set(int64_t i64) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_I8; var_.llVal = i64; } void ScopedVariant::Set(uint64_t ui64) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_UI8; var_.ullVal = ui64; } void ScopedVariant::Set(float r32) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_R4; var_.fltVal = r32; } void ScopedVariant::Set(double r64) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_R8; var_.dblVal = r64; } void ScopedVariant::SetDate(DATE date) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_DATE; var_.date = date; } void ScopedVariant::Set(IDispatch* disp) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_DISPATCH; var_.pdispVal = disp; if (disp) disp->AddRef(); } void ScopedVariant::Set(bool b) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_BOOL; var_.boolVal = b ? VARIANT_TRUE : VARIANT_FALSE; } void ScopedVariant::Set(IUnknown* unk) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; var_.vt = VT_UNKNOWN; var_.punkVal = unk; if (unk) unk->AddRef(); } void ScopedVariant::Set(SAFEARRAY* array) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; if (SUCCEEDED(::SafeArrayGetVartype(array, &var_.vt))) { var_.vt |= VT_ARRAY; var_.parray = array; } else { BASE_DCHECK(!array) << "Unable to determine safearray vartype"; var_.vt = VT_EMPTY; } } void ScopedVariant::Set(const VARIANT& var) { BASE_DCHECK(!IsLeakableVarType(var_.vt)) << "leaking variant: " << var_.vt; if (FAILED(::VariantCopy(&var_, &var))) { BASE_DLOG() << "Error: VariantCopy failed"; var_.vt = VT_EMPTY; } } ScopedVariant& ScopedVariant::operator=(ScopedVariant&& var) { if (var.ptr() != &var_) Reset(var.Release()); return *this; } ScopedVariant& ScopedVariant::operator=(const VARIANT& var) { if (&var != &var_) { VariantClear(&var_); Set(var); } return *this; } bool ScopedVariant::IsLeakableVarType(VARTYPE vt) { bool leakable = false; switch (vt & VT_TYPEMASK) { case VT_BSTR: case VT_DISPATCH: // we treat VT_VARIANT as leakable to err on the safe side. case VT_VARIANT: case VT_UNKNOWN: case VT_SAFEARRAY: // very rarely used stuff (if ever): case VT_VOID: case VT_PTR: case VT_CARRAY: case VT_USERDEFINED: case VT_LPSTR: case VT_LPWSTR: case VT_RECORD: case VT_INT_PTR: case VT_UINT_PTR: case VT_FILETIME: case VT_BLOB: case VT_STREAM: case VT_STORAGE: case VT_STREAMED_OBJECT: case VT_STORED_OBJECT: case VT_BLOB_OBJECT: case VT_VERSIONED_STREAM: case VT_BSTR_BLOB: leakable = true; break; } if (!leakable && (vt & VT_ARRAY) != 0) { leakable = true; } return leakable; } } // namespace win } // namespace base
engine/third_party/accessibility/base/win/scoped_variant.cc/0
{ "file_path": "engine/third_party/accessibility/base/win/scoped_variant.cc", "repo_id": "engine", "token_count": 3964 }
408
// 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. #include "point_conversions.h" #include "base/numerics/safe_conversions.h" namespace gfx { Point ToFlooredPoint(const PointF& point) { return Point(base::ClampFloor(point.x()), base::ClampFloor(point.y())); } Point ToCeiledPoint(const PointF& point) { return Point(base::ClampCeil(point.x()), base::ClampCeil(point.y())); } Point ToRoundedPoint(const PointF& point) { return Point(base::ClampRound(point.x()), base::ClampRound(point.y())); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/point_conversions.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/point_conversions.cc", "repo_id": "engine", "token_count": 228 }
409
// 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. #include "size_f.h" #include "base/string_utils.h" namespace gfx { float SizeF::GetArea() const { return width() * height(); } void SizeF::Enlarge(float grow_width, float grow_height) { SetSize(width() + grow_width, height() + grow_height); } void SizeF::SetToMin(const SizeF& other) { width_ = width() <= other.width() ? width() : other.width(); height_ = height() <= other.height() ? height() : other.height(); } void SizeF::SetToMax(const SizeF& other) { width_ = width() >= other.width() ? width() : other.width(); height_ = height() >= other.height() ? height() : other.height(); } std::string SizeF::ToString() const { return base::StringPrintf("%fx%f", width(), height()); } SizeF ScaleSize(const SizeF& s, float x_scale, float y_scale) { SizeF scaled_s(s); scaled_s.Scale(x_scale, y_scale); return scaled_s; } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/size_f.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/size_f.cc", "repo_id": "engine", "token_count": 354 }
410
// 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_RANGE_RANGE_H_ #define UI_GFX_RANGE_RANGE_H_ #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <ostream> #include <string> #include "ax_build/build_config.h" #include "gfx_range_export.h" #if defined(OS_APPLE) #if __OBJC__ #import <Foundation/Foundation.h> #else typedef struct _NSRange NSRange; #endif #endif // defined(OS_APPLE) namespace gfx { // This class represents either a forward range [min, max) or a reverse range // (max, min]. |start_| is always the first of these and |end_| the second; as a // result, the range is forward if (start_ <= end_). The zero-width range // [val, val) is legal, contains and intersects itself, and is contained by and // intersects any nonempty range [min, max) where min <= val < max. class GFX_RANGE_EXPORT Range { public: // Creates an empty range {0,0}. constexpr Range() : Range(0) {} // Initializes the range with a start and end. constexpr Range(uint32_t start, uint32_t end) : start_(start), end_(end) {} // Initializes the range with the same start and end positions. constexpr explicit Range(uint32_t position) : Range(position, position) {} // Platform constructors. #if defined(OS_APPLE) explicit Range(const NSRange& range); #endif // Returns a range that is invalid, which is {UINT32_MAX,UINT32_MAX}. static constexpr Range InvalidRange() { return Range(std::numeric_limits<uint32_t>::max()); } // Checks if the range is valid through comparison to InvalidRange(). constexpr bool IsValid() const { return *this != InvalidRange(); } // Getters and setters. constexpr uint32_t start() const { return start_; } void set_start(uint32_t start) { start_ = start; } constexpr uint32_t end() const { return end_; } void set_end(uint32_t end) { end_ = end; } // Returns the absolute value of the length. constexpr uint32_t length() const { return GetMax() - GetMin(); } constexpr bool is_reversed() const { return start() > end(); } constexpr bool is_empty() const { return start() == end(); } // Returns the minimum and maximum values. constexpr uint32_t GetMin() const { return start() < end() ? start() : end(); } constexpr uint32_t GetMax() const { return start() > end() ? start() : end(); } constexpr bool operator==(const Range& other) const { return start() == other.start() && end() == other.end(); } constexpr bool operator!=(const Range& other) const { return !(*this == other); } constexpr bool EqualsIgnoringDirection(const Range& other) const { return GetMin() == other.GetMin() && GetMax() == other.GetMax(); } // Returns true if this range intersects the specified |range|. constexpr bool Intersects(const Range& range) const { return Intersect(range).IsValid(); } // Returns true if this range contains the specified |range|. constexpr bool Contains(const Range& range) const { return range.IsBoundedBy(*this) && // A non-empty range doesn't contain the range [max, max). (range.GetMax() != GetMax() || range.is_empty() == is_empty()); } // Returns true if this range is contained by the specified |range| or it is // an empty range and ending the range |range|. constexpr bool IsBoundedBy(const Range& range) const { return IsValid() && range.IsValid() && GetMin() >= range.GetMin() && GetMax() <= range.GetMax(); } // Computes the intersection of this range with the given |range|. // If they don't intersect, it returns an InvalidRange(). // The returned range is always empty or forward (never reversed). constexpr Range Intersect(const Range& range) const { const uint32_t min = std::max(GetMin(), range.GetMin()); const uint32_t max = std::min(GetMax(), range.GetMax()); return (min < max || Contains(range) || range.Contains(*this)) ? Range(min, max) : InvalidRange(); } #if defined(OS_APPLE) Range& operator=(const NSRange& range); // NSRange does not store the directionality of a range, so if this // is_reversed(), the range will get flipped when converted to an NSRange. NSRange ToNSRange() const; #endif // GTK+ has no concept of a range. std::string ToString() const; private: // Note: we use uint32_t instead of size_t because this struct is sent over // IPC which could span 32 & 64 bit processes. This is fine since text spans // shouldn't exceed UINT32_MAX even on 64 bit builds. uint32_t start_; uint32_t end_; }; GFX_RANGE_EXPORT std::ostream& operator<<(std::ostream& os, const Range& range); } // namespace gfx #endif // UI_GFX_RANGE_RANGE_H_
engine/third_party/accessibility/gfx/range/range.h/0
{ "file_path": "engine/third_party/accessibility/gfx/range/range.h", "repo_id": "engine", "token_count": 1567 }
411