text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_H_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_H_
#import <AppKit/AppKit.h>
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterBinaryMessenger.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
/**
* A plugin to configure and control the native system menu.
*
* Responsible for bridging the native macOS menu system with the Flutter
* framework's PlatformMenuBar class, via method channels.
*/
@interface FlutterMenuPlugin : NSObject <FlutterPlugin>
/**
* Registers a FlutterMenuPlugin with the given registrar.
*/
+ (void)registerWithRegistrar:(nonnull id<FlutterPluginRegistrar>)registrar;
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTERMENUPLUGIN_H_
| engine/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h",
"repo_id": "engine",
"token_count": 380
} | 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.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterRenderer.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterExternalTexture.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h"
#include "flutter/shell/platform/embedder/embedder.h"
#pragma mark - Static callbacks that require the engine.
static FlutterMetalTexture OnGetNextDrawable(FlutterEngine* engine,
const FlutterFrameInfo* frameInfo) {
NSCAssert(NO, @"The renderer config should not be used to get the next drawable.");
return FlutterMetalTexture{};
}
static bool OnPresentDrawable(FlutterEngine* engine, const FlutterMetalTexture* texture) {
NSCAssert(NO, @"The renderer config should not be used to present drawable.");
return false;
}
static bool OnAcquireExternalTexture(FlutterEngine* engine,
int64_t textureIdentifier,
size_t width,
size_t height,
FlutterMetalExternalTexture* metalTexture) {
return [engine.renderer populateTextureWithIdentifier:textureIdentifier
metalTexture:metalTexture];
}
#pragma mark - FlutterRenderer implementation
@implementation FlutterRenderer {
FlutterDarwinContextMetalSkia* _darwinMetalContext;
}
- (instancetype)initWithFlutterEngine:(nonnull FlutterEngine*)flutterEngine {
self = [super initWithDelegate:self engine:flutterEngine];
if (self) {
_device = MTLCreateSystemDefaultDevice();
if (!_device) {
NSLog(@"Could not acquire Metal device.");
return nil;
}
_commandQueue = [_device newCommandQueue];
if (!_commandQueue) {
NSLog(@"Could not create Metal command queue.");
return nil;
}
_darwinMetalContext = [[FlutterDarwinContextMetalSkia alloc] initWithMTLDevice:_device
commandQueue:_commandQueue];
}
return self;
}
- (FlutterRendererConfig)createRendererConfig {
FlutterRendererConfig config = {
.type = FlutterRendererType::kMetal,
.metal = {
.struct_size = sizeof(FlutterMetalRendererConfig),
.device = (__bridge FlutterMetalDeviceHandle)_device,
.present_command_queue = (__bridge FlutterMetalCommandQueueHandle)_commandQueue,
.get_next_drawable_callback =
reinterpret_cast<FlutterMetalTextureCallback>(OnGetNextDrawable),
.present_drawable_callback =
reinterpret_cast<FlutterMetalPresentCallback>(OnPresentDrawable),
.external_texture_frame_callback =
reinterpret_cast<FlutterMetalTextureFrameCallback>(OnAcquireExternalTexture),
}};
return config;
}
#pragma mark - Embedder callback implementations.
- (BOOL)populateTextureWithIdentifier:(int64_t)textureID
metalTexture:(FlutterMetalExternalTexture*)textureOut {
FlutterExternalTexture* texture = [self getTextureWithID:textureID];
return [texture populateTexture:textureOut];
}
#pragma mark - FlutterTextureRegistrar methods.
- (FlutterExternalTexture*)onRegisterTexture:(id<FlutterTexture>)texture {
return [[FlutterExternalTexture alloc] initWithFlutterTexture:texture
darwinMetalContext:_darwinMetalContext];
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterRenderer.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterRenderer.mm",
"repo_id": "engine",
"token_count": 1504
} | 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.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizer.h"
#import "flutter/fml/synchronization/waitable_event.h"
#import "flutter/testing/testing.h"
@interface FlutterThreadSynchronizerTestScaffold : NSObject
@property(nonatomic, readonly, nonnull) FlutterThreadSynchronizer* synchronizer;
- (nullable instancetype)init;
- (void)dispatchMainTask:(nonnull void (^)())task;
- (void)dispatchRenderTask:(nonnull void (^)())task;
- (void)joinMain;
- (void)joinRender;
@end
@implementation FlutterThreadSynchronizerTestScaffold {
dispatch_queue_t _mainQueue;
std::shared_ptr<fml::AutoResetWaitableEvent> _mainLatch;
dispatch_queue_t _renderQueue;
std::shared_ptr<fml::AutoResetWaitableEvent> _renderLatch;
FlutterThreadSynchronizer* _synchronizer;
}
@synthesize synchronizer = _synchronizer;
- (nullable instancetype)init {
self = [super init];
if (self != nil) {
_mainQueue = dispatch_queue_create("MAIN", DISPATCH_QUEUE_SERIAL);
_renderQueue = dispatch_queue_create("RENDER", DISPATCH_QUEUE_SERIAL);
_synchronizer = [[FlutterThreadSynchronizer alloc] initWithMainQueue:_mainQueue];
}
return self;
}
- (void)dispatchMainTask:(nonnull void (^)())task {
dispatch_async(_mainQueue, task);
}
- (void)dispatchRenderTask:(nonnull void (^)())task {
dispatch_async(_renderQueue, task);
}
- (void)joinMain {
fml::AutoResetWaitableEvent latch;
fml::AutoResetWaitableEvent* pLatch = &latch;
dispatch_async(_mainQueue, ^{
pLatch->Signal();
});
latch.Wait();
}
- (void)joinRender {
fml::AutoResetWaitableEvent latch;
fml::AutoResetWaitableEvent* pLatch = &latch;
dispatch_async(_renderQueue, ^{
pLatch->Signal();
});
latch.Wait();
}
@end
TEST(FlutterThreadSynchronizerTest, RegularCommit) {
FlutterThreadSynchronizerTestScaffold* scaffold =
[[FlutterThreadSynchronizerTestScaffold alloc] init];
FlutterThreadSynchronizer* synchronizer = scaffold.synchronizer;
// Initial resize: does not block until the first frame.
__block int notifiedResize = 0;
[scaffold dispatchMainTask:^{
[synchronizer registerView:1];
[synchronizer beginResizeForView:1
size:CGSize{5, 5}
notify:^{
notifiedResize += 1;
}];
}];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinMain];
EXPECT_EQ(notifiedResize, 1);
// Still does not block.
[scaffold dispatchMainTask:^{
[synchronizer beginResizeForView:1
size:CGSize{7, 7}
notify:^{
notifiedResize += 1;
}];
}];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinMain];
EXPECT_EQ(notifiedResize, 2);
// First frame
__block int notifiedCommit = 0;
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{7, 7}
notify:^{
notifiedCommit += 1;
}];
}];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinRender];
EXPECT_EQ(notifiedCommit, 1);
}
TEST(FlutterThreadSynchronizerTest, ResizingBlocksRenderingUntilSizeMatches) {
FlutterThreadSynchronizerTestScaffold* scaffold =
[[FlutterThreadSynchronizerTestScaffold alloc] init];
FlutterThreadSynchronizer* synchronizer = scaffold.synchronizer;
// A latch to ensure that a beginResizeForView: call has at least executed
// something, so that the isWaitingWhenMutexIsAvailable: call correctly stops
// at either when beginResizeForView: finishes or waits half way.
fml::AutoResetWaitableEvent begunResizingLatch;
fml::AutoResetWaitableEvent* begunResizing = &begunResizingLatch;
// Initial resize: does not block until the first frame.
[scaffold dispatchMainTask:^{
[synchronizer registerView:1];
[synchronizer beginResizeForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinMain];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
// First frame.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
// Resize to (7, 7): blocks until the next frame.
[scaffold dispatchMainTask:^{
[synchronizer beginResizeForView:1
size:CGSize{7, 7}
notify:^{
begunResizing->Signal();
}];
}];
begunResizing->Wait();
EXPECT_TRUE([synchronizer isWaitingWhenMutexIsAvailable]);
// Render with old size.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_TRUE([synchronizer isWaitingWhenMutexIsAvailable]);
// Render with new size.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{7, 7}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinMain];
}
TEST(FlutterThreadSynchronizerTest, ShutdownMakesEverythingNonBlocking) {
FlutterThreadSynchronizerTestScaffold* scaffold =
[[FlutterThreadSynchronizerTestScaffold alloc] init];
FlutterThreadSynchronizer* synchronizer = scaffold.synchronizer;
fml::AutoResetWaitableEvent begunResizingLatch;
fml::AutoResetWaitableEvent* begunResizing = &begunResizingLatch;
// Initial resize
[scaffold dispatchMainTask:^{
[synchronizer registerView:1];
[synchronizer beginResizeForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinMain];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
// Push a frame.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold dispatchMainTask:^{
[synchronizer shutdown];
}];
// Resize to (7, 7). Should not block any frames since it has shut down.
[scaffold dispatchMainTask:^{
[synchronizer beginResizeForView:1
size:CGSize{7, 7}
notify:^{
begunResizing->Signal();
}];
}];
begunResizing->Wait();
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinMain];
// All further calls should be unblocking.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{9, 9}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
}
TEST(FlutterThreadSynchronizerTest, RegularCommitForMultipleViews) {
FlutterThreadSynchronizerTestScaffold* scaffold =
[[FlutterThreadSynchronizerTestScaffold alloc] init];
FlutterThreadSynchronizer* synchronizer = scaffold.synchronizer;
fml::AutoResetWaitableEvent begunResizingLatch;
fml::AutoResetWaitableEvent* begunResizing = &begunResizingLatch;
// Initial resize: does not block until the first frame.
[scaffold dispatchMainTask:^{
[synchronizer registerView:1];
[synchronizer registerView:2];
[synchronizer beginResizeForView:1
size:CGSize{5, 5}
notify:^{
}];
[synchronizer beginResizeForView:2
size:CGSize{15, 15}
notify:^{
begunResizing->Signal();
}];
}];
begunResizing->Wait();
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinMain];
// Still does not block.
[scaffold dispatchMainTask:^{
[synchronizer beginResizeForView:1
size:CGSize{7, 7}
notify:^{
begunResizing->Signal();
}];
}];
begunResizing->Signal();
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
[scaffold joinMain];
// First frame
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{7, 7}
notify:^{
}];
[synchronizer performCommitForView:2
size:CGSize{15, 15}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
}
TEST(FlutterThreadSynchronizerTest, ResizingForMultipleViews) {
FlutterThreadSynchronizerTestScaffold* scaffold =
[[FlutterThreadSynchronizerTestScaffold alloc] init];
FlutterThreadSynchronizer* synchronizer = scaffold.synchronizer;
fml::AutoResetWaitableEvent begunResizingLatch;
fml::AutoResetWaitableEvent* begunResizing = &begunResizingLatch;
// Initial resize: does not block until the first frame.
[scaffold dispatchMainTask:^{
[synchronizer registerView:1];
[synchronizer registerView:2];
[synchronizer beginResizeForView:1
size:CGSize{5, 5}
notify:^{
}];
[synchronizer beginResizeForView:2
size:CGSize{15, 15}
notify:^{
}];
}];
[scaffold joinMain];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
// First frame.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{5, 5}
notify:^{
}];
[synchronizer performCommitForView:2
size:CGSize{15, 15}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
// Resize view 2 to (17, 17): blocks until the next frame.
[scaffold dispatchMainTask:^{
[synchronizer beginResizeForView:2
size:CGSize{17, 17}
notify:^{
begunResizing->Signal();
}];
}];
begunResizing->Wait();
EXPECT_TRUE([synchronizer isWaitingWhenMutexIsAvailable]);
// Render view 1 with the size. Still blocking.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_TRUE([synchronizer isWaitingWhenMutexIsAvailable]);
// Render view 2 with the old size. Still blocking.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{15, 15}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_TRUE([synchronizer isWaitingWhenMutexIsAvailable]);
// Render view 1 with the size.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:1
size:CGSize{5, 5}
notify:^{
}];
}];
[scaffold joinRender];
EXPECT_TRUE([synchronizer isWaitingWhenMutexIsAvailable]);
// Render view 2 with the new size. Unblocks.
[scaffold dispatchRenderTask:^{
[synchronizer performCommitForView:2
size:CGSize{17, 17}
notify:^{
}];
}];
[scaffold joinRender];
[scaffold joinMain];
EXPECT_FALSE([synchronizer isWaitingWhenMutexIsAvailable]);
}
| engine/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizerTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterThreadSynchronizerTest.mm",
"repo_id": "engine",
"token_count": 6273
} | 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.
#include <Carbon/Carbon.h>
#import <Foundation/Foundation.h>
#import <OCMock/OCMock.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/FlutterViewController_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProvider.h"
#import "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
#import "flutter/testing/testing.h"
#include "third_party/googletest/googletest/include/gtest/gtest.h"
namespace flutter::testing {
TEST(FlutterViewEngineProviderUnittests, GetViewReturnsTheCorrectView) {
FlutterViewEngineProvider* viewProvider;
id mockEngine = CreateMockFlutterEngine(@"");
__block id mockFlutterViewController;
OCMStub([mockEngine viewControllerForId:0])
.ignoringNonObjectArgs()
.andDo(^(NSInvocation* invocation) {
FlutterViewId viewId;
[invocation getArgument:&viewId atIndex:2];
if (viewId == kFlutterImplicitViewId) {
if (mockFlutterViewController != nil) {
[invocation setReturnValue:&mockFlutterViewController];
}
}
});
viewProvider = [[FlutterViewEngineProvider alloc] initWithEngine:mockEngine];
// When the view controller is not set, the returned view is nil.
EXPECT_EQ([viewProvider viewForId:0], nil);
// When the view controller is set, the returned view is the controller's view.
mockFlutterViewController = OCMStrictClassMock([FlutterViewController class]);
id mockView = OCMStrictClassMock([FlutterView class]);
OCMStub([mockFlutterViewController flutterView]).andReturn(mockView);
EXPECT_EQ([viewProvider viewForId:0], mockView);
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProviderTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewEngineProviderTest.mm",
"repo_id": "engine",
"token_count": 707
} | 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_EMBEDDER_EMBEDDER_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_H_
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
// This file defines an Application Binary Interface (ABI), which requires more
// stability than regular code to remain functional for exchanging messages
// between different versions of the embedding and the engine, to allow for both
// forward and backward compatibility.
//
// Specifically,
// - The order, type, and size of the struct members below must remain the same,
// and members should not be removed.
// - New structures that are part of the ABI must be defined with "size_t
// struct_size;" as their first member, which should be initialized using
// "sizeof(Type)".
// - Enum values must not change or be removed.
// - Enum members without explicit values must not be reordered.
// - Function signatures (names, argument counts, argument order, and argument
// type) cannot change.
// - The core behavior of existing functions cannot change.
// - Instead of nesting structures by value within another structure/union,
// prefer nesting by pointer. This ensures that adding members to the nested
// struct does not break the ABI of the parent struct/union.
// - Instead of array of structures, prefer array of pointers to structures.
// This ensures that array indexing does not break if members are added
// to the structure.
//
// These changes are allowed:
// - Adding new struct members at the end of a structure as long as the struct
// is not nested within another struct by value.
// - Adding new enum members with a new value.
// - Renaming a struct member as long as its type, size, and intent remain the
// same.
// - Renaming an enum member as long as its value and intent remains the same.
//
// It is expected that struct members and implicitly-valued enums will not
// always be declared in an order that is optimal for the reader, since members
// will be added over time, and they can't be reordered.
//
// Existing functions should continue to appear from the caller's point of view
// to operate as they did when they were first introduced, so introduce a new
// function instead of modifying the core behavior of a function (and continue
// to support the existing function with the previous behavior).
#if defined(__cplusplus)
extern "C" {
#endif
#ifndef FLUTTER_EXPORT
#define FLUTTER_EXPORT
#endif // FLUTTER_EXPORT
#ifdef FLUTTER_API_SYMBOL_PREFIX
#define FLUTTER_EMBEDDING_CONCAT(a, b) a##b
#define FLUTTER_EMBEDDING_ADD_PREFIX(symbol, prefix) \
FLUTTER_EMBEDDING_CONCAT(prefix, symbol)
#define FLUTTER_API_SYMBOL(symbol) \
FLUTTER_EMBEDDING_ADD_PREFIX(symbol, FLUTTER_API_SYMBOL_PREFIX)
#else
#define FLUTTER_API_SYMBOL(symbol) symbol
#endif
#define FLUTTER_ENGINE_VERSION 1
typedef enum {
kSuccess = 0,
kInvalidLibraryVersion,
kInvalidArguments,
kInternalInconsistency,
} FlutterEngineResult;
typedef enum {
kOpenGL,
kSoftware,
/// Metal is only supported on Darwin platforms (macOS / iOS).
/// iOS version >= 10.0 (device), 13.0 (simulator)
/// macOS version >= 10.14
kMetal,
kVulkan,
} FlutterRendererType;
/// Additional accessibility features that may be enabled by the platform.
/// Must match the `AccessibilityFeatures` enum in window.dart.
typedef enum {
/// Indicate there is a running accessibility service which is changing the
/// interaction model of the device.
kFlutterAccessibilityFeatureAccessibleNavigation = 1 << 0,
/// Indicate the platform is inverting the colors of the application.
kFlutterAccessibilityFeatureInvertColors = 1 << 1,
/// Request that animations be disabled or simplified.
kFlutterAccessibilityFeatureDisableAnimations = 1 << 2,
/// Request that text be rendered at a bold font weight.
kFlutterAccessibilityFeatureBoldText = 1 << 3,
/// Request that certain animations be simplified and parallax effects
/// removed.
kFlutterAccessibilityFeatureReduceMotion = 1 << 4,
/// Request that UI be rendered with darker colors.
kFlutterAccessibilityFeatureHighContrast = 1 << 5,
/// Request to show on/off labels inside switches.
kFlutterAccessibilityFeatureOnOffSwitchLabels = 1 << 6,
} FlutterAccessibilityFeature;
/// The set of possible actions that can be conveyed to a semantics node.
///
/// Must match the `SemanticsAction` enum in semantics.dart.
typedef enum {
/// The equivalent of a user briefly tapping the screen with the finger
/// without moving it.
kFlutterSemanticsActionTap = 1 << 0,
/// The equivalent of a user pressing and holding the screen with the finger
/// for a few seconds without moving it.
kFlutterSemanticsActionLongPress = 1 << 1,
/// The equivalent of a user moving their finger across the screen from right
/// to left.
kFlutterSemanticsActionScrollLeft = 1 << 2,
/// The equivalent of a user moving their finger across the screen from left
/// to
/// right.
kFlutterSemanticsActionScrollRight = 1 << 3,
/// The equivalent of a user moving their finger across the screen from bottom
/// to top.
kFlutterSemanticsActionScrollUp = 1 << 4,
/// The equivalent of a user moving their finger across the screen from top to
/// bottom.
kFlutterSemanticsActionScrollDown = 1 << 5,
/// Increase the value represented by the semantics node.
kFlutterSemanticsActionIncrease = 1 << 6,
/// Decrease the value represented by the semantics node.
kFlutterSemanticsActionDecrease = 1 << 7,
/// A request to fully show the semantics node on screen.
kFlutterSemanticsActionShowOnScreen = 1 << 8,
/// Move the cursor forward by one character.
kFlutterSemanticsActionMoveCursorForwardByCharacter = 1 << 9,
/// Move the cursor backward by one character.
kFlutterSemanticsActionMoveCursorBackwardByCharacter = 1 << 10,
/// Set the text selection to the given range.
kFlutterSemanticsActionSetSelection = 1 << 11,
/// Copy the current selection to the clipboard.
kFlutterSemanticsActionCopy = 1 << 12,
/// Cut the current selection and place it in the clipboard.
kFlutterSemanticsActionCut = 1 << 13,
/// Paste the current content of the clipboard.
kFlutterSemanticsActionPaste = 1 << 14,
/// Indicate that the node has gained accessibility focus.
kFlutterSemanticsActionDidGainAccessibilityFocus = 1 << 15,
/// Indicate that the node has lost accessibility focus.
kFlutterSemanticsActionDidLoseAccessibilityFocus = 1 << 16,
/// Indicate that the user has invoked a custom accessibility action.
kFlutterSemanticsActionCustomAction = 1 << 17,
/// A request that the node should be dismissed.
kFlutterSemanticsActionDismiss = 1 << 18,
/// Move the cursor forward by one word.
kFlutterSemanticsActionMoveCursorForwardByWord = 1 << 19,
/// Move the cursor backward by one word.
kFlutterSemanticsActionMoveCursorBackwardByWord = 1 << 20,
/// Replace the current text in the text field.
kFlutterSemanticsActionSetText = 1 << 21,
} FlutterSemanticsAction;
/// The set of properties that may be associated with a semantics node.
///
/// Must match the `SemanticsFlag` enum in semantics.dart.
typedef enum {
/// The semantics node has the quality of either being "checked" or
/// "unchecked".
kFlutterSemanticsFlagHasCheckedState = 1 << 0,
/// Whether a semantics node is checked.
kFlutterSemanticsFlagIsChecked = 1 << 1,
/// Whether a semantics node is selected.
kFlutterSemanticsFlagIsSelected = 1 << 2,
/// Whether the semantic node represents a button.
kFlutterSemanticsFlagIsButton = 1 << 3,
/// Whether the semantic node represents a text field.
kFlutterSemanticsFlagIsTextField = 1 << 4,
/// Whether the semantic node currently holds the user's focus.
kFlutterSemanticsFlagIsFocused = 1 << 5,
/// The semantics node has the quality of either being "enabled" or
/// "disabled".
kFlutterSemanticsFlagHasEnabledState = 1 << 6,
/// Whether a semantic node that hasEnabledState is currently enabled.
kFlutterSemanticsFlagIsEnabled = 1 << 7,
/// Whether a semantic node is in a mutually exclusive group.
kFlutterSemanticsFlagIsInMutuallyExclusiveGroup = 1 << 8,
/// Whether a semantic node is a header that divides content into sections.
kFlutterSemanticsFlagIsHeader = 1 << 9,
/// Whether the value of the semantics node is obscured.
kFlutterSemanticsFlagIsObscured = 1 << 10,
/// Whether the semantics node is the root of a subtree for which a route name
/// should be announced.
kFlutterSemanticsFlagScopesRoute = 1 << 11,
/// Whether the semantics node label is the name of a visually distinct route.
kFlutterSemanticsFlagNamesRoute = 1 << 12,
/// Whether the semantics node is considered hidden.
kFlutterSemanticsFlagIsHidden = 1 << 13,
/// Whether the semantics node represents an image.
kFlutterSemanticsFlagIsImage = 1 << 14,
/// Whether the semantics node is a live region.
kFlutterSemanticsFlagIsLiveRegion = 1 << 15,
/// The semantics node has the quality of either being "on" or "off".
kFlutterSemanticsFlagHasToggledState = 1 << 16,
/// If true, the semantics node is "on". If false, the semantics node is
/// "off".
kFlutterSemanticsFlagIsToggled = 1 << 17,
/// Whether the platform can scroll the semantics node when the user attempts
/// to move the accessibility focus to an offscreen child.
///
/// For example, a `ListView` widget has implicit scrolling so that users can
/// easily move the accessibility focus to the next set of children. A
/// `PageView` widget does not have implicit scrolling, so that users don't
/// navigate to the next page when reaching the end of the current one.
kFlutterSemanticsFlagHasImplicitScrolling = 1 << 18,
/// Whether the value of the semantics node is coming from a multi-line text
/// field.
///
/// This is used for text fields to distinguish single-line text fields from
/// multi-line ones.
kFlutterSemanticsFlagIsMultiline = 1 << 19,
/// Whether the semantic node is read only.
///
/// Only applicable when kFlutterSemanticsFlagIsTextField flag is on.
kFlutterSemanticsFlagIsReadOnly = 1 << 20,
/// Whether the semantic node can hold the user's focus.
kFlutterSemanticsFlagIsFocusable = 1 << 21,
/// Whether the semantics node represents a link.
kFlutterSemanticsFlagIsLink = 1 << 22,
/// Whether the semantics node represents a slider.
kFlutterSemanticsFlagIsSlider = 1 << 23,
/// Whether the semantics node represents a keyboard key.
kFlutterSemanticsFlagIsKeyboardKey = 1 << 24,
/// Whether the semantics node represents a tristate checkbox in mixed state.
kFlutterSemanticsFlagIsCheckStateMixed = 1 << 25,
/// The semantics node has the quality of either being "expanded" or
/// "collapsed".
kFlutterSemanticsFlagHasExpandedState = 1 << 26,
/// Whether a semantic node that hasExpandedState is currently expanded.
kFlutterSemanticsFlagIsExpanded = 1 << 27,
} FlutterSemanticsFlag;
typedef enum {
/// Text has unknown text direction.
kFlutterTextDirectionUnknown = 0,
/// Text is read from right to left.
kFlutterTextDirectionRTL = 1,
/// Text is read from left to right.
kFlutterTextDirectionLTR = 2,
} FlutterTextDirection;
/// Valid values for priority of Thread.
typedef enum {
/// Suitable for threads that shouldn't disrupt high priority work.
kBackground = 0,
/// Default priority level.
kNormal = 1,
/// Suitable for threads which generate data for the display.
kDisplay = 2,
/// Suitable for thread which raster data.
kRaster = 3,
} FlutterThreadPriority;
typedef struct _FlutterEngine* FLUTTER_API_SYMBOL(FlutterEngine);
/// Unique identifier for views.
///
/// View IDs are generated by the embedder and are
/// opaque to the engine; the engine does not interpret view IDs in any way.
typedef int64_t FlutterViewId;
typedef struct {
/// horizontal scale factor
double scaleX;
/// horizontal skew factor
double skewX;
/// horizontal translation
double transX;
/// vertical skew factor
double skewY;
/// vertical scale factor
double scaleY;
/// vertical translation
double transY;
/// input x-axis perspective factor
double pers0;
/// input y-axis perspective factor
double pers1;
/// perspective scale factor
double pers2;
} FlutterTransformation;
typedef void (*VoidCallback)(void* /* user data */);
typedef enum {
/// Specifies an OpenGL texture target type. Textures are specified using
/// the FlutterOpenGLTexture struct.
kFlutterOpenGLTargetTypeTexture,
/// Specifies an OpenGL frame-buffer target type. Framebuffers are specified
/// using the FlutterOpenGLFramebuffer struct.
kFlutterOpenGLTargetTypeFramebuffer,
} FlutterOpenGLTargetType;
/// A pixel format to be used for software rendering.
///
/// A single pixel always stored as a POT number of bytes. (so in practice
/// either 1, 2, 4, 8, 16 bytes per pixel)
///
/// There are two kinds of pixel formats:
/// - formats where all components are 8 bits, called array formats
/// The component order as specified in the pixel format name is the
/// order of the components' bytes in memory, with the leftmost component
/// occupying the lowest memory address.
///
/// - all other formats are called packed formats, and the component order
/// as specified in the format name refers to the order in the native type.
/// for example, for kFlutterSoftwarePixelFormatRGB565, the R component
/// uses the 5 least significant bits of the uint16_t pixel value.
///
/// Each pixel format in this list is documented with an example on how to get
/// the color components from the pixel.
/// - for packed formats, p is the pixel value as a word. For example, you can
/// get the pixel value for a RGB565 formatted buffer like this:
/// uint16_t p = ((const uint16_t*) allocation)[row_bytes * y / bpp + x];
/// (with bpp being the bytes per pixel, so 2 for RGB565)
///
/// - for array formats, p is a pointer to the pixel value. For example, you
/// can get the p for a RGBA8888 formatted buffer like this:
/// const uint8_t *p = ((const uint8_t*) allocation) + row_bytes*y + x*4;
typedef enum {
/// pixel with 8 bit grayscale value.
/// The grayscale value is the luma value calculated from r, g, b
/// according to BT.709. (gray = r*0.2126 + g*0.7152 + b*0.0722)
kFlutterSoftwarePixelFormatGray8,
/// pixel with 5 bits red, 6 bits green, 5 bits blue, in 16-bit word.
/// r = p & 0x3F; g = (p>>5) & 0x3F; b = p>>11;
kFlutterSoftwarePixelFormatRGB565,
/// pixel with 4 bits for alpha, red, green, blue; in 16-bit word.
/// r = p & 0xF; g = (p>>4) & 0xF; b = (p>>8) & 0xF; a = p>>12;
kFlutterSoftwarePixelFormatRGBA4444,
/// pixel with 8 bits for red, green, blue, alpha.
/// r = p[0]; g = p[1]; b = p[2]; a = p[3];
kFlutterSoftwarePixelFormatRGBA8888,
/// pixel with 8 bits for red, green and blue and 8 unused bits.
/// r = p[0]; g = p[1]; b = p[2];
kFlutterSoftwarePixelFormatRGBX8888,
/// pixel with 8 bits for blue, green, red and alpha.
/// r = p[2]; g = p[1]; b = p[0]; a = p[3];
kFlutterSoftwarePixelFormatBGRA8888,
/// either kFlutterSoftwarePixelFormatBGRA8888 or
/// kFlutterSoftwarePixelFormatRGBA8888 depending on CPU endianess and OS
kFlutterSoftwarePixelFormatNative32,
} FlutterSoftwarePixelFormat;
typedef struct {
/// Target texture of the active texture unit (example GL_TEXTURE_2D or
/// GL_TEXTURE_RECTANGLE).
uint32_t target;
/// The name of the texture.
uint32_t name;
/// The texture format (example GL_RGBA8).
uint32_t format;
/// User data to be returned on the invocation of the destruction callback.
void* user_data;
/// Callback invoked (on an engine managed thread) that asks the embedder to
/// collect the texture.
VoidCallback destruction_callback;
/// Optional parameters for texture height/width, default is 0, non-zero means
/// the texture has the specified width/height. Usually, when the texture type
/// is GL_TEXTURE_RECTANGLE, we need to specify the texture width/height to
/// tell the embedder to scale when rendering.
/// Width of the texture.
size_t width;
/// Height of the texture.
size_t height;
} FlutterOpenGLTexture;
typedef struct {
/// The target of the color attachment of the frame-buffer. For example,
/// GL_TEXTURE_2D or GL_RENDERBUFFER. In case of ambiguity when dealing with
/// Window bound frame-buffers, 0 may be used.
uint32_t target;
/// The name of the framebuffer.
uint32_t name;
/// User data to be returned on the invocation of the destruction callback.
void* user_data;
/// Callback invoked (on an engine managed thread) that asks the embedder to
/// collect the framebuffer.
VoidCallback destruction_callback;
} FlutterOpenGLFramebuffer;
typedef bool (*BoolCallback)(void* /* user data */);
typedef FlutterTransformation (*TransformationCallback)(void* /* user data */);
typedef uint32_t (*UIntCallback)(void* /* user data */);
typedef bool (*SoftwareSurfacePresentCallback)(void* /* user data */,
const void* /* allocation */,
size_t /* row bytes */,
size_t /* height */);
typedef void* (*ProcResolver)(void* /* user data */, const char* /* name */);
typedef bool (*TextureFrameCallback)(void* /* user data */,
int64_t /* texture identifier */,
size_t /* width */,
size_t /* height */,
FlutterOpenGLTexture* /* texture out */);
typedef void (*VsyncCallback)(void* /* user data */, intptr_t /* baton */);
typedef void (*OnPreEngineRestartCallback)(void* /* user data */);
/// A structure to represent the width and height.
typedef struct {
double width;
double height;
} FlutterSize;
/// A structure to represent the width and height.
///
/// See: \ref FlutterSize when the value are not integers.
typedef struct {
uint32_t width;
uint32_t height;
} FlutterUIntSize;
/// A structure to represent a rectangle.
typedef struct {
double left;
double top;
double right;
double bottom;
} FlutterRect;
/// A structure to represent a 2D point.
typedef struct {
double x;
double y;
} FlutterPoint;
/// A structure to represent a rounded rectangle.
typedef struct {
FlutterRect rect;
FlutterSize upper_left_corner_radius;
FlutterSize upper_right_corner_radius;
FlutterSize lower_right_corner_radius;
FlutterSize lower_left_corner_radius;
} FlutterRoundedRect;
/// A structure to represent a damage region.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterDamage).
size_t struct_size;
/// The number of rectangles within the damage region.
size_t num_rects;
/// The actual damage region(s) in question.
FlutterRect* damage;
} FlutterDamage;
/// This information is passed to the embedder when requesting a frame buffer
/// object.
///
/// See: \ref FlutterOpenGLRendererConfig.fbo_with_frame_info_callback,
/// \ref FlutterMetalRendererConfig.get_next_drawable_callback,
/// and \ref FlutterVulkanRendererConfig.get_next_image_callback.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterFrameInfo).
size_t struct_size;
/// The size of the surface that will be backed by the fbo.
FlutterUIntSize size;
} FlutterFrameInfo;
/// Callback for when a frame buffer object is requested.
typedef uint32_t (*UIntFrameInfoCallback)(
void* /* user data */,
const FlutterFrameInfo* /* frame info */);
/// Callback for when a frame buffer object is requested with necessary
/// information for partial repaint.
typedef void (*FlutterFrameBufferWithDamageCallback)(
void* /* user data */,
const intptr_t /* fbo id */,
FlutterDamage* /* existing damage */);
/// This information is passed to the embedder when a surface is presented.
///
/// See: \ref FlutterOpenGLRendererConfig.present_with_info.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterPresentInfo).
size_t struct_size;
/// Id of the fbo backing the surface that was presented.
uint32_t fbo_id;
/// Damage representing the area that the compositor needs to render.
FlutterDamage frame_damage;
/// Damage used to set the buffer's damage region.
FlutterDamage buffer_damage;
} FlutterPresentInfo;
/// Callback for when a surface is presented.
typedef bool (*BoolPresentInfoCallback)(
void* /* user data */,
const FlutterPresentInfo* /* present info */);
typedef struct {
/// The size of this struct. Must be sizeof(FlutterOpenGLRendererConfig).
size_t struct_size;
BoolCallback make_current;
BoolCallback clear_current;
/// Specifying one (and only one) of `present` or `present_with_info` is
/// required. Specifying both is an error and engine initialization will be
/// terminated. The return value indicates success of the present call. If
/// the intent is to use dirty region management, present_with_info must be
/// defined as present will not succeed in communicating information about
/// damage.
BoolCallback present;
/// Specifying one (and only one) of the `fbo_callback` or
/// `fbo_with_frame_info_callback` is required. Specifying both is an error
/// and engine intialization will be terminated. The return value indicates
/// the id of the frame buffer object that flutter will obtain the gl surface
/// from.
UIntCallback fbo_callback;
/// This is an optional callback. Flutter will ask the emebdder to create a GL
/// context current on a background thread. If the embedder is able to do so,
/// Flutter will assume that this context is in the same sharegroup as the
/// main rendering context and use this context for asynchronous texture
/// uploads. Though optional, it is recommended that all embedders set this
/// callback as it will lead to better performance in texture handling.
BoolCallback make_resource_current;
/// By default, the renderer config assumes that the FBO does not change for
/// the duration of the engine run. If this argument is true, the
/// engine will ask the embedder for an updated FBO target (via an
/// fbo_callback invocation) after a present call.
bool fbo_reset_after_present;
/// The transformation to apply to the render target before any rendering
/// operations. This callback is optional.
/// @attention When using a custom compositor, the layer offset and sizes
/// will be affected by this transformation. It will be
/// embedder responsibility to render contents at the
/// transformed offset and size. This is useful for embedders
/// that want to render transformed contents directly into
/// hardware overlay planes without having to apply extra
/// transformations to layer contents (which may necessitate
/// an expensive off-screen render pass).
TransformationCallback surface_transformation;
ProcResolver gl_proc_resolver;
/// When the embedder specifies that a texture has a frame available, the
/// engine will call this method (on an internal engine managed thread) so
/// that external texture details can be supplied to the engine for subsequent
/// composition.
TextureFrameCallback gl_external_texture_frame_callback;
/// Specifying one (and only one) of the `fbo_callback` or
/// `fbo_with_frame_info_callback` is required. Specifying both is an error
/// and engine intialization will be terminated. The return value indicates
/// the id of the frame buffer object (fbo) that flutter will obtain the gl
/// surface from. When using this variant, the embedder is passed a
/// `FlutterFrameInfo` struct that indicates the properties of the surface
/// that flutter will acquire from the returned fbo.
UIntFrameInfoCallback fbo_with_frame_info_callback;
/// Specifying one (and only one) of `present` or `present_with_info` is
/// required. Specifying both is an error and engine initialization will be
/// terminated. When using this variant, the embedder is passed a
/// `FlutterPresentInfo` struct that the embedder can use to release any
/// resources. The return value indicates success of the present call. This
/// callback is essential for dirty region management. If not defined, all the
/// pixels on the screen will be rendered at every frame (regardless of
/// whether damage is actually being computed or not). This is because the
/// information that is passed along to the callback contains the frame and
/// buffer damage that are essential for dirty region management.
BoolPresentInfoCallback present_with_info;
/// Specifying this callback is a requirement for dirty region management.
/// Dirty region management will only render the areas of the screen that have
/// changed in between frames, greatly reducing rendering times and energy
/// consumption. To take advantage of these benefits, it is necessary to
/// define populate_existing_damage as a callback that takes user
/// data, an FBO ID, and an existing damage FlutterDamage. The callback should
/// use the given FBO ID to identify the FBO's exisiting damage (i.e. areas
/// that have changed since the FBO was last used) and use it to populate the
/// given existing damage variable. This callback is dependent on either
/// fbo_callback or fbo_with_frame_info_callback being defined as they are
/// responsible for providing populate_existing_damage with the FBO's
/// ID. Not specifying populate_existing_damage will result in full
/// repaint (i.e. rendering all the pixels on the screen at every frame).
FlutterFrameBufferWithDamageCallback populate_existing_damage;
} FlutterOpenGLRendererConfig;
/// Alias for id<MTLDevice>.
typedef const void* FlutterMetalDeviceHandle;
/// Alias for id<MTLCommandQueue>.
typedef const void* FlutterMetalCommandQueueHandle;
/// Alias for id<MTLTexture>.
typedef const void* FlutterMetalTextureHandle;
/// Pixel format for the external texture.
typedef enum {
kYUVA,
kRGBA,
} FlutterMetalExternalTexturePixelFormat;
/// YUV color space for the YUV external texture.
typedef enum {
kBT601FullRange,
kBT601LimitedRange,
} FlutterMetalExternalTextureYUVColorSpace;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterMetalExternalTexture).
size_t struct_size;
/// Height of the texture.
size_t width;
/// Height of the texture.
size_t height;
/// The pixel format type of the external.
FlutterMetalExternalTexturePixelFormat pixel_format;
/// Represents the size of the `textures` array.
size_t num_textures;
/// Supported textures are YUVA and RGBA, in case of YUVA we expect 2 texture
/// handles to be provided by the embedder, Y first and UV next. In case of
/// RGBA only one should be passed.
/// These are individually aliases for id<MTLTexture>. These textures are
/// retained by the engine for the period of the composition. Once these
/// textures have been unregistered via the
/// `FlutterEngineUnregisterExternalTexture`, the embedder has to release
/// these textures.
FlutterMetalTextureHandle* textures;
/// The YUV color space of the YUV external texture.
FlutterMetalExternalTextureYUVColorSpace yuv_color_space;
} FlutterMetalExternalTexture;
/// Callback to provide an external texture for a given texture_id.
/// See: external_texture_frame_callback.
typedef bool (*FlutterMetalTextureFrameCallback)(
void* /* user data */,
int64_t /* texture identifier */,
size_t /* width */,
size_t /* height */,
FlutterMetalExternalTexture* /* texture out */);
typedef struct {
/// The size of this struct. Must be sizeof(FlutterMetalTexture).
size_t struct_size;
/// Embedder provided unique identifier to the texture buffer. Given that the
/// `texture` handle is passed to the engine to render to, the texture buffer
/// is itself owned by the embedder. This `texture_id` is then also given to
/// the embedder in the present callback.
int64_t texture_id;
/// Handle to the MTLTexture that is owned by the embedder. Engine will render
/// the frame into this texture.
///
/// A NULL texture is considered invalid.
FlutterMetalTextureHandle texture;
/// A baton that is not interpreted by the engine in any way. It will be given
/// back to the embedder in the destruction callback below. Embedder resources
/// may be associated with this baton.
void* user_data;
/// The callback invoked by the engine when it no longer needs this backing
/// store.
VoidCallback destruction_callback;
} FlutterMetalTexture;
/// Callback for when a metal texture is requested.
typedef FlutterMetalTexture (*FlutterMetalTextureCallback)(
void* /* user data */,
const FlutterFrameInfo* /* frame info */);
/// Callback for when a metal texture is presented. The texture_id here
/// corresponds to the texture_id provided by the embedder in the
/// `FlutterMetalTextureCallback` callback.
typedef bool (*FlutterMetalPresentCallback)(
void* /* user data */,
const FlutterMetalTexture* /* texture */);
typedef struct {
/// The size of this struct. Must be sizeof(FlutterMetalRendererConfig).
size_t struct_size;
/// Alias for id<MTLDevice>.
FlutterMetalDeviceHandle device;
/// Alias for id<MTLCommandQueue>.
FlutterMetalCommandQueueHandle present_command_queue;
/// The callback that gets invoked when the engine requests the embedder for a
/// texture to render to.
///
/// Not used if a FlutterCompositor is supplied in FlutterProjectArgs.
FlutterMetalTextureCallback get_next_drawable_callback;
/// The callback presented to the embedder to present a fully populated metal
/// texture to the user.
///
/// Not used if a FlutterCompositor is supplied in FlutterProjectArgs.
FlutterMetalPresentCallback present_drawable_callback;
/// When the embedder specifies that a texture has a frame available, the
/// engine will call this method (on an internal engine managed thread) so
/// that external texture details can be supplied to the engine for subsequent
/// composition.
FlutterMetalTextureFrameCallback external_texture_frame_callback;
} FlutterMetalRendererConfig;
/// Alias for VkInstance.
typedef void* FlutterVulkanInstanceHandle;
/// Alias for VkPhysicalDevice.
typedef void* FlutterVulkanPhysicalDeviceHandle;
/// Alias for VkDevice.
typedef void* FlutterVulkanDeviceHandle;
/// Alias for VkQueue.
typedef void* FlutterVulkanQueueHandle;
/// Alias for VkImage.
typedef uint64_t FlutterVulkanImageHandle;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterVulkanImage).
size_t struct_size;
/// Handle to the VkImage that is owned by the embedder. The engine will
/// bind this image for writing the frame.
FlutterVulkanImageHandle image;
/// The VkFormat of the image (for example: VK_FORMAT_R8G8B8A8_UNORM).
uint32_t format;
} FlutterVulkanImage;
/// Callback to fetch a Vulkan function pointer for a given instance. Normally,
/// this should return the results of vkGetInstanceProcAddr.
typedef void* (*FlutterVulkanInstanceProcAddressCallback)(
void* /* user data */,
FlutterVulkanInstanceHandle /* instance */,
const char* /* name */);
/// Callback for when a VkImage is requested.
typedef FlutterVulkanImage (*FlutterVulkanImageCallback)(
void* /* user data */,
const FlutterFrameInfo* /* frame info */);
/// Callback for when a VkImage has been written to and is ready for use by the
/// embedder.
typedef bool (*FlutterVulkanPresentCallback)(
void* /* user data */,
const FlutterVulkanImage* /* image */);
typedef struct {
/// The size of this struct. Must be sizeof(FlutterVulkanRendererConfig).
size_t struct_size;
/// The Vulkan API version. This should match the value set in
/// VkApplicationInfo::apiVersion when the VkInstance was created.
uint32_t version;
/// VkInstance handle. Must not be destroyed before `FlutterEngineShutdown` is
/// called.
FlutterVulkanInstanceHandle instance;
/// VkPhysicalDevice handle.
FlutterVulkanPhysicalDeviceHandle physical_device;
/// VkDevice handle. Must not be destroyed before `FlutterEngineShutdown` is
/// called.
FlutterVulkanDeviceHandle device;
/// The queue family index of the VkQueue supplied in the next field.
uint32_t queue_family_index;
/// VkQueue handle.
/// The queue should not be used without protection from a mutex to make sure
/// it is not used simultaneously with other threads. That mutex should match
/// the one injected via the |get_instance_proc_address_callback|.
/// There is a proposal to remove the need for the mutex at
/// https://github.com/flutter/flutter/issues/134573.
FlutterVulkanQueueHandle queue;
/// The number of instance extensions available for enumerating in the next
/// field.
size_t enabled_instance_extension_count;
/// Array of enabled instance extension names. This should match the names
/// passed to `VkInstanceCreateInfo.ppEnabledExtensionNames` when the instance
/// was created, but any subset of enabled instance extensions may be
/// specified.
/// This field is optional; `nullptr` may be specified.
/// This memory is only accessed during the call to FlutterEngineInitialize.
const char** enabled_instance_extensions;
/// The number of device extensions available for enumerating in the next
/// field.
size_t enabled_device_extension_count;
/// Array of enabled logical device extension names. This should match the
/// names passed to `VkDeviceCreateInfo.ppEnabledExtensionNames` when the
/// logical device was created, but any subset of enabled logical device
/// extensions may be specified.
/// This field is optional; `nullptr` may be specified.
/// This memory is only accessed during the call to FlutterEngineInitialize.
/// For example: VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME
const char** enabled_device_extensions;
/// The callback invoked when resolving Vulkan function pointers.
/// At a bare minimum this should be used to swap out any calls that operate
/// on vkQueue's for threadsafe variants that obtain locks for their duration.
/// The functions to swap out are "vkQueueSubmit" and "vkQueueWaitIdle". An
/// example of how to do that can be found in the test
/// "EmbedderTest.CanSwapOutVulkanCalls" unit-test in
/// //shell/platform/embedder/tests/embedder_vk_unittests.cc.
FlutterVulkanInstanceProcAddressCallback get_instance_proc_address_callback;
/// The callback invoked when the engine requests a VkImage from the embedder
/// for rendering the next frame.
/// Not used if a FlutterCompositor is supplied in FlutterProjectArgs.
FlutterVulkanImageCallback get_next_image_callback;
/// The callback invoked when a VkImage has been written to and is ready for
/// use by the embedder. Prior to calling this callback, the engine performs
/// a host sync, and so the VkImage can be used in a pipeline by the embedder
/// without any additional synchronization.
/// Not used if a FlutterCompositor is supplied in FlutterProjectArgs.
FlutterVulkanPresentCallback present_image_callback;
} FlutterVulkanRendererConfig;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterSoftwareRendererConfig).
size_t struct_size;
/// The callback presented to the embedder to present a fully populated buffer
/// to the user. The pixel format of the buffer is the native 32-bit RGBA
/// format. The buffer is owned by the Flutter engine and must be copied in
/// this callback if needed.
SoftwareSurfacePresentCallback surface_present_callback;
} FlutterSoftwareRendererConfig;
typedef struct {
FlutterRendererType type;
union {
FlutterOpenGLRendererConfig open_gl;
FlutterSoftwareRendererConfig software;
FlutterMetalRendererConfig metal;
FlutterVulkanRendererConfig vulkan;
};
} FlutterRendererConfig;
typedef struct {
/// The size of this struct.
/// Must be sizeof(FlutterRemoveViewResult).
size_t struct_size;
/// True if the remove view operation succeeded.
bool removed;
/// The |FlutterRemoveViewInfo.user_data|.
void* user_data;
} FlutterRemoveViewResult;
/// The callback invoked by the engine when the engine has attempted to remove
/// a view.
///
/// The |FlutterRemoveViewResult| will be deallocated once the callback returns.
typedef void (*FlutterRemoveViewCallback)(
const FlutterRemoveViewResult* /* result */);
typedef struct {
/// The size of this struct.
/// Must be sizeof(FlutterRemoveViewInfo).
size_t struct_size;
/// The identifier for the view to remove.
///
/// The implicit view cannot be removed if it is enabled.
FlutterViewId view_id;
/// A baton that is not interpreted by the engine in any way.
/// It will be given back to the embedder in |remove_view_callback|.
/// Embedder resources may be associated with this baton.
void* user_data;
/// Called once the engine has attempted to remove the view.
/// This callback is required.
///
/// The embedder must not destroy the underlying surface until the callback is
/// invoked with a `removed` value of `true`.
///
/// This callback is invoked on an internal engine managed thread.
/// Embedders must re-thread if necessary.
///
/// The |result| argument will be deallocated when the callback returns.
FlutterRemoveViewCallback remove_view_callback;
} FlutterRemoveViewInfo;
/// Display refers to a graphics hardware system consisting of a framebuffer,
/// typically a monitor or a screen. This ID is unique per display and is
/// stable until the Flutter application restarts.
typedef uint64_t FlutterEngineDisplayId;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterWindowMetricsEvent).
size_t struct_size;
/// Physical width of the window.
size_t width;
/// Physical height of the window.
size_t height;
/// Scale factor for the physical screen.
double pixel_ratio;
/// Horizontal physical location of the left side of the window on the screen.
size_t left;
/// Vertical physical location of the top of the window on the screen.
size_t top;
/// Top inset of window.
double physical_view_inset_top;
/// Right inset of window.
double physical_view_inset_right;
/// Bottom inset of window.
double physical_view_inset_bottom;
/// Left inset of window.
double physical_view_inset_left;
/// The identifier of the display the view is rendering on.
FlutterEngineDisplayId display_id;
/// The view that this event is describing.
int64_t view_id;
} FlutterWindowMetricsEvent;
/// The phase of the pointer event.
typedef enum {
kCancel,
/// The pointer, which must have been down (see kDown), is now up.
///
/// For touch, this means that the pointer is no longer in contact with the
/// screen. For a mouse, it means the last button was released. Note that if
/// any other buttons are still pressed when one button is released, that
/// should be sent as a kMove rather than a kUp.
kUp,
/// The pointer, which must have been up, is now down.
///
/// For touch, this means that the pointer has come into contact with the
/// screen. For a mouse, it means a button is now pressed. Note that if any
/// other buttons are already pressed when a new button is pressed, that
/// should be sent as a kMove rather than a kDown.
kDown,
/// The pointer moved while down.
///
/// This is also used for changes in button state that don't cause a kDown or
/// kUp, such as releasing one of two pressed buttons.
kMove,
/// The pointer is now sending input to Flutter. For instance, a mouse has
/// entered the area where the Flutter content is displayed.
///
/// A pointer should always be added before sending any other events.
kAdd,
/// The pointer is no longer sending input to Flutter. For instance, a mouse
/// has left the area where the Flutter content is displayed.
///
/// A removed pointer should no longer send events until sending a new kAdd.
kRemove,
/// The pointer moved while up.
kHover,
/// A pan/zoom started on this pointer.
kPanZoomStart,
/// The pan/zoom updated.
kPanZoomUpdate,
/// The pan/zoom ended.
kPanZoomEnd,
} FlutterPointerPhase;
/// The device type that created a pointer event.
typedef enum {
kFlutterPointerDeviceKindMouse = 1,
kFlutterPointerDeviceKindTouch,
kFlutterPointerDeviceKindStylus,
kFlutterPointerDeviceKindTrackpad,
} FlutterPointerDeviceKind;
/// Flags for the `buttons` field of `FlutterPointerEvent` when `device_kind`
/// is `kFlutterPointerDeviceKindMouse`.
typedef enum {
kFlutterPointerButtonMousePrimary = 1 << 0,
kFlutterPointerButtonMouseSecondary = 1 << 1,
kFlutterPointerButtonMouseMiddle = 1 << 2,
kFlutterPointerButtonMouseBack = 1 << 3,
kFlutterPointerButtonMouseForward = 1 << 4,
/// If a mouse has more than five buttons, send higher bit shifted values
/// corresponding to the button number: 1 << 5 for the 6th, etc.
} FlutterPointerMouseButtons;
/// The type of a pointer signal.
typedef enum {
kFlutterPointerSignalKindNone,
kFlutterPointerSignalKindScroll,
kFlutterPointerSignalKindScrollInertiaCancel,
kFlutterPointerSignalKindScale,
} FlutterPointerSignalKind;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterPointerEvent).
size_t struct_size;
FlutterPointerPhase phase;
/// The timestamp at which the pointer event was generated. The timestamp
/// should be specified in microseconds and the clock should be the same as
/// that used by `FlutterEngineGetCurrentTime`.
size_t timestamp;
/// The x coordinate of the pointer event in physical pixels.
double x;
/// The y coordinate of the pointer event in physical pixels.
double y;
/// An optional device identifier. If this is not specified, it is assumed
/// that the embedder has no multi-touch capability.
int32_t device;
FlutterPointerSignalKind signal_kind;
/// The x offset of the scroll in physical pixels.
double scroll_delta_x;
/// The y offset of the scroll in physical pixels.
double scroll_delta_y;
/// The type of the device generating this event.
/// Backwards compatibility note: If this is not set, the device will be
/// treated as a mouse, with the primary button set for `kDown` and `kMove`.
/// If set explicitly to `kFlutterPointerDeviceKindMouse`, you must set the
/// correct buttons.
FlutterPointerDeviceKind device_kind;
/// The buttons currently pressed, if any.
int64_t buttons;
/// The x offset of the pan/zoom in physical pixels.
double pan_x;
/// The y offset of the pan/zoom in physical pixels.
double pan_y;
/// The scale of the pan/zoom, where 1.0 is the initial scale.
double scale;
/// The rotation of the pan/zoom in radians, where 0.0 is the initial angle.
double rotation;
/// The identifier of the view that received the pointer event.
FlutterViewId view_id;
} FlutterPointerEvent;
typedef enum {
kFlutterKeyEventTypeUp = 1,
kFlutterKeyEventTypeDown,
kFlutterKeyEventTypeRepeat,
} FlutterKeyEventType;
typedef enum {
kFlutterKeyEventDeviceTypeKeyboard = 1,
kFlutterKeyEventDeviceTypeDirectionalPad,
kFlutterKeyEventDeviceTypeGamepad,
kFlutterKeyEventDeviceTypeJoystick,
kFlutterKeyEventDeviceTypeHdmi,
} FlutterKeyEventDeviceType;
/// A structure to represent a key event.
///
/// Sending `FlutterKeyEvent` via `FlutterEngineSendKeyEvent` results in a
/// corresponding `FlutterKeyEvent` to be dispatched in the framework. It is
/// embedder's responsibility to ensure the regularity of sent events, since the
/// framework only performs simple one-to-one mapping. The events must conform
/// the following rules:
///
/// * Each key press sequence shall consist of one key down event (`kind` being
/// `kFlutterKeyEventTypeDown`), zero or more repeat events, and one key up
/// event, representing a physical key button being pressed, held, and
/// released.
/// * All events throughout a key press sequence shall have the same `physical`
/// and `logical`. Having different `character`s is allowed.
///
/// A `FlutterKeyEvent` with `physical` 0 and `logical` 0 is an empty event.
/// This is the only case either `physical` or `logical` can be 0. An empty
/// event must be sent if a key message should be converted to no
/// `FlutterKeyEvent`s, for example, when a key down message is received for a
/// key that has already been pressed according to the record. This is to ensure
/// some `FlutterKeyEvent` arrives at the framework before raw key message.
/// See https://github.com/flutter/flutter/issues/87230.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterKeyEvent).
size_t struct_size;
/// The timestamp at which the key event was generated. The timestamp should
/// be specified in microseconds and the clock should be the same as that used
/// by `FlutterEngineGetCurrentTime`.
double timestamp;
/// The event kind.
FlutterKeyEventType type;
/// The USB HID code for the physical key of the event.
///
/// For the full definition and list of pre-defined physical keys, see
/// `PhysicalKeyboardKey` from the framework.
///
/// The only case that `physical` might be 0 is when this is an empty event.
/// See `FlutterKeyEvent` for introduction.
uint64_t physical;
/// The key ID for the logical key of this event.
///
/// For the full definition and a list of pre-defined logical keys, see
/// `LogicalKeyboardKey` from the framework.
///
/// The only case that `logical` might be 0 is when this is an empty event.
/// See `FlutterKeyEvent` for introduction.
uint64_t logical;
/// Null-terminated character input from the event. Can be null. Ignored for
/// up events.
const char* character;
/// True if this event does not correspond to a native event.
///
/// The embedder is likely to skip events and/or construct new events that do
/// not correspond to any native events in order to conform the regularity
/// of events (as documented in `FlutterKeyEvent`). An example is when a key
/// up is missed due to loss of window focus, on a platform that provides
/// query to key pressing status, the embedder might realize that the key has
/// been released at the next key event, and should construct a synthesized up
/// event immediately before the actual event.
///
/// An event being synthesized means that the `timestamp` might greatly
/// deviate from the actual time when the event occurs physically.
bool synthesized;
/// The source device for the key event.
FlutterKeyEventDeviceType device_type;
} FlutterKeyEvent;
typedef void (*FlutterKeyEventCallback)(bool /* handled */,
void* /* user_data */);
struct _FlutterPlatformMessageResponseHandle;
typedef struct _FlutterPlatformMessageResponseHandle
FlutterPlatformMessageResponseHandle;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterPlatformMessage).
size_t struct_size;
const char* channel;
const uint8_t* message;
size_t message_size;
/// The response handle on which to invoke
/// `FlutterEngineSendPlatformMessageResponse` when the response is ready.
/// `FlutterEngineSendPlatformMessageResponse` must be called for all messages
/// received by the embedder. Failure to call
/// `FlutterEngineSendPlatformMessageResponse` will cause a memory leak. It is
/// not safe to send multiple responses on a single response object.
const FlutterPlatformMessageResponseHandle* response_handle;
} FlutterPlatformMessage;
typedef void (*FlutterPlatformMessageCallback)(
const FlutterPlatformMessage* /* message*/,
void* /* user data */);
typedef void (*FlutterDataCallback)(const uint8_t* /* data */,
size_t /* size */,
void* /* user data */);
/// The identifier of the platform view. This identifier is specified by the
/// application when a platform view is added to the scene via the
/// `SceneBuilder.addPlatformView` call.
typedef int64_t FlutterPlatformViewIdentifier;
/// `FlutterSemanticsNode` ID used as a sentinel to signal the end of a batch of
/// semantics node updates. This is unused if using
/// `FlutterUpdateSemanticsCallback2`.
FLUTTER_EXPORT
extern const int32_t kFlutterSemanticsNodeIdBatchEnd;
// The enumeration of possible string attributes that affect how assistive
// technologies announce a string.
//
// See dart:ui's implementers of the StringAttribute abstract class.
typedef enum {
// Indicates the string should be announced character by character.
kSpellOut,
// Indicates the string should be announced using the specified locale.
kLocale,
} FlutterStringAttributeType;
// Indicates the assistive technology should announce out the string character
// by character.
//
// See dart:ui's SpellOutStringAttribute.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterSpellOutStringAttribute).
size_t struct_size;
} FlutterSpellOutStringAttribute;
// Indicates the assistive technology should announce the string using the
// specified locale.
//
// See dart:ui's LocaleStringAttribute.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterLocaleStringAttribute).
size_t struct_size;
// The locale of this attribute.
const char* locale;
} FlutterLocaleStringAttribute;
// Indicates how the assistive technology should treat the string.
//
// See dart:ui's StringAttribute.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterStringAttribute).
size_t struct_size;
// The position this attribute starts.
size_t start;
// The next position after the attribute ends.
size_t end;
/// The type of the attribute described by the subsequent union.
FlutterStringAttributeType type;
union {
// Indicates the string should be announced character by character.
const FlutterSpellOutStringAttribute* spell_out;
// Indicates the string should be announced using the specified locale.
const FlutterLocaleStringAttribute* locale;
};
} FlutterStringAttribute;
/// A node that represents some semantic data.
///
/// The semantics tree is maintained during the semantics phase of the pipeline
/// (i.e., during PipelineOwner.flushSemantics), which happens after
/// compositing. Updates are then pushed to embedders via the registered
/// `FlutterUpdateSemanticsCallback`.
///
/// @deprecated Use `FlutterSemanticsNode2` instead. In order to preserve
/// ABI compatibility for existing users, no new fields will be
/// added to this struct. New fields will continue to be added
/// to `FlutterSemanticsNode2`.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterSemanticsNode).
size_t struct_size;
/// The unique identifier for this node.
int32_t id;
/// The set of semantics flags associated with this node.
FlutterSemanticsFlag flags;
/// The set of semantics actions applicable to this node.
FlutterSemanticsAction actions;
/// The position at which the text selection originates.
int32_t text_selection_base;
/// The position at which the text selection terminates.
int32_t text_selection_extent;
/// The total number of scrollable children that contribute to semantics.
int32_t scroll_child_count;
/// The index of the first visible semantic child of a scroll node.
int32_t scroll_index;
/// The current scrolling position in logical pixels if the node is
/// scrollable.
double scroll_position;
/// The maximum in-range value for `scrollPosition` if the node is scrollable.
double scroll_extent_max;
/// The minimum in-range value for `scrollPosition` if the node is scrollable.
double scroll_extent_min;
/// The elevation along the z-axis at which the rect of this semantics node is
/// located above its parent.
double elevation;
/// Describes how much space the semantics node takes up along the z-axis.
double thickness;
/// A textual description of the node.
const char* label;
/// A brief description of the result of performing an action on the node.
const char* hint;
/// A textual description of the current value of the node.
const char* value;
/// A value that `value` will have after a kFlutterSemanticsActionIncrease`
/// action has been performed.
const char* increased_value;
/// A value that `value` will have after a kFlutterSemanticsActionDecrease`
/// action has been performed.
const char* decreased_value;
/// The reading direction for `label`, `value`, `hint`, `increasedValue`,
/// `decreasedValue`, and `tooltip`.
FlutterTextDirection text_direction;
/// The bounding box for this node in its coordinate system.
FlutterRect rect;
/// The transform from this node's coordinate system to its parent's
/// coordinate system.
FlutterTransformation transform;
/// The number of children this node has.
size_t child_count;
/// Array of child node IDs in traversal order. Has length `child_count`.
const int32_t* children_in_traversal_order;
/// Array of child node IDs in hit test order. Has length `child_count`.
const int32_t* children_in_hit_test_order;
/// The number of custom accessibility action associated with this node.
size_t custom_accessibility_actions_count;
/// Array of `FlutterSemanticsCustomAction` IDs associated with this node.
/// Has length `custom_accessibility_actions_count`.
const int32_t* custom_accessibility_actions;
/// Identifier of the platform view associated with this semantics node, or
/// -1 if none.
FlutterPlatformViewIdentifier platform_view_id;
/// A textual tooltip attached to the node.
const char* tooltip;
} FlutterSemanticsNode;
/// A node in the Flutter semantics tree.
///
/// The semantics tree is maintained during the semantics phase of the pipeline
/// (i.e., during PipelineOwner.flushSemantics), which happens after
/// compositing. Updates are then pushed to embedders via the registered
/// `FlutterUpdateSemanticsCallback2`.
///
/// @see https://api.flutter.dev/flutter/semantics/SemanticsNode-class.html
typedef struct {
/// The size of this struct. Must be sizeof(FlutterSemanticsNode).
size_t struct_size;
/// The unique identifier for this node.
int32_t id;
/// The set of semantics flags associated with this node.
FlutterSemanticsFlag flags;
/// The set of semantics actions applicable to this node.
FlutterSemanticsAction actions;
/// The position at which the text selection originates.
int32_t text_selection_base;
/// The position at which the text selection terminates.
int32_t text_selection_extent;
/// The total number of scrollable children that contribute to semantics.
int32_t scroll_child_count;
/// The index of the first visible semantic child of a scroll node.
int32_t scroll_index;
/// The current scrolling position in logical pixels if the node is
/// scrollable.
double scroll_position;
/// The maximum in-range value for `scrollPosition` if the node is scrollable.
double scroll_extent_max;
/// The minimum in-range value for `scrollPosition` if the node is scrollable.
double scroll_extent_min;
/// The elevation along the z-axis at which the rect of this semantics node is
/// located above its parent.
double elevation;
/// Describes how much space the semantics node takes up along the z-axis.
double thickness;
/// A textual description of the node.
const char* label;
/// A brief description of the result of performing an action on the node.
const char* hint;
/// A textual description of the current value of the node.
const char* value;
/// A value that `value` will have after a kFlutterSemanticsActionIncrease`
/// action has been performed.
const char* increased_value;
/// A value that `value` will have after a kFlutterSemanticsActionDecrease`
/// action has been performed.
const char* decreased_value;
/// The reading direction for `label`, `value`, `hint`, `increasedValue`,
/// `decreasedValue`, and `tooltip`.
FlutterTextDirection text_direction;
/// The bounding box for this node in its coordinate system.
FlutterRect rect;
/// The transform from this node's coordinate system to its parent's
/// coordinate system.
FlutterTransformation transform;
/// The number of children this node has.
size_t child_count;
/// Array of child node IDs in traversal order. Has length `child_count`.
const int32_t* children_in_traversal_order;
/// Array of child node IDs in hit test order. Has length `child_count`.
const int32_t* children_in_hit_test_order;
/// The number of custom accessibility action associated with this node.
size_t custom_accessibility_actions_count;
/// Array of `FlutterSemanticsCustomAction` IDs associated with this node.
/// Has length `custom_accessibility_actions_count`.
const int32_t* custom_accessibility_actions;
/// Identifier of the platform view associated with this semantics node, or
/// -1 if none.
FlutterPlatformViewIdentifier platform_view_id;
/// A textual tooltip attached to the node.
const char* tooltip;
// The number of string attributes associated with the `label`.
size_t label_attribute_count;
// Array of string attributes associated with the `label`.
// Has length `label_attribute_count`.
const FlutterStringAttribute** label_attributes;
// The number of string attributes associated with the `hint`.
size_t hint_attribute_count;
// Array of string attributes associated with the `hint`.
// Has length `hint_attribute_count`.
const FlutterStringAttribute** hint_attributes;
// The number of string attributes associated with the `value`.
size_t value_attribute_count;
// Array of string attributes associated with the `value`.
// Has length `value_attribute_count`.
const FlutterStringAttribute** value_attributes;
// The number of string attributes associated with the `increased_value`.
size_t increased_value_attribute_count;
// Array of string attributes associated with the `increased_value`.
// Has length `increased_value_attribute_count`.
const FlutterStringAttribute** increased_value_attributes;
// The number of string attributes associated with the `decreased_value`.
size_t decreased_value_attribute_count;
// Array of string attributes associated with the `decreased_value`.
// Has length `decreased_value_attribute_count`.
const FlutterStringAttribute** decreased_value_attributes;
} FlutterSemanticsNode2;
/// `FlutterSemanticsCustomAction` ID used as a sentinel to signal the end of a
/// batch of semantics custom action updates. This is unused if using
/// `FlutterUpdateSemanticsCallback2`.
FLUTTER_EXPORT
extern const int32_t kFlutterSemanticsCustomActionIdBatchEnd;
/// A custom semantics action, or action override.
///
/// Custom actions can be registered by applications in order to provide
/// semantic actions other than the standard actions available through the
/// `FlutterSemanticsAction` enum.
///
/// Action overrides are custom actions that the application developer requests
/// to be used in place of the standard actions in the `FlutterSemanticsAction`
/// enum.
///
/// @deprecated Use `FlutterSemanticsCustomAction2` instead. In order to
/// preserve ABI compatility for existing users, no new fields
/// will be added to this struct. New fields will continue to
/// be added to `FlutterSemanticsCustomAction2`.
typedef struct {
/// The size of the struct. Must be sizeof(FlutterSemanticsCustomAction).
size_t struct_size;
/// The unique custom action or action override ID.
int32_t id;
/// For overridden standard actions, corresponds to the
/// `FlutterSemanticsAction` to override.
FlutterSemanticsAction override_action;
/// The user-readable name of this custom semantics action.
const char* label;
/// The hint description of this custom semantics action.
const char* hint;
} FlutterSemanticsCustomAction;
/// A custom semantics action, or action override.
///
/// Custom actions can be registered by applications in order to provide
/// semantic actions other than the standard actions available through the
/// `FlutterSemanticsAction` enum.
///
/// Action overrides are custom actions that the application developer requests
/// to be used in place of the standard actions in the `FlutterSemanticsAction`
/// enum.
///
/// @see
/// https://api.flutter.dev/flutter/semantics/CustomSemanticsAction-class.html
typedef struct {
/// The size of the struct. Must be sizeof(FlutterSemanticsCustomAction).
size_t struct_size;
/// The unique custom action or action override ID.
int32_t id;
/// For overridden standard actions, corresponds to the
/// `FlutterSemanticsAction` to override.
FlutterSemanticsAction override_action;
/// The user-readable name of this custom semantics action.
const char* label;
/// The hint description of this custom semantics action.
const char* hint;
} FlutterSemanticsCustomAction2;
/// A batch of updates to semantics nodes and custom actions.
///
/// @deprecated Use `FlutterSemanticsUpdate2` instead. Adding members
/// to `FlutterSemanticsNode` or `FlutterSemanticsCustomAction`
/// breaks the ABI of this struct.
typedef struct {
/// The size of the struct. Must be sizeof(FlutterSemanticsUpdate).
size_t struct_size;
/// The number of semantics node updates.
size_t nodes_count;
// Array of semantics nodes. Has length `nodes_count`.
FlutterSemanticsNode* nodes;
/// The number of semantics custom action updates.
size_t custom_actions_count;
/// Array of semantics custom actions. Has length `custom_actions_count`.
FlutterSemanticsCustomAction* custom_actions;
} FlutterSemanticsUpdate;
/// A batch of updates to semantics nodes and custom actions.
typedef struct {
/// The size of the struct. Must be sizeof(FlutterSemanticsUpdate2).
size_t struct_size;
/// The number of semantics node updates.
size_t node_count;
// Array of semantics node pointers. Has length `node_count`.
FlutterSemanticsNode2** nodes;
/// The number of semantics custom action updates.
size_t custom_action_count;
/// Array of semantics custom action pointers. Has length
/// `custom_action_count`.
FlutterSemanticsCustomAction2** custom_actions;
} FlutterSemanticsUpdate2;
typedef void (*FlutterUpdateSemanticsNodeCallback)(
const FlutterSemanticsNode* /* semantics node */,
void* /* user data */);
typedef void (*FlutterUpdateSemanticsCustomActionCallback)(
const FlutterSemanticsCustomAction* /* semantics custom action */,
void* /* user data */);
typedef void (*FlutterUpdateSemanticsCallback)(
const FlutterSemanticsUpdate* /* semantics update */,
void* /* user data*/);
typedef void (*FlutterUpdateSemanticsCallback2)(
const FlutterSemanticsUpdate2* /* semantics update */,
void* /* user data*/);
/// An update to whether a message channel has a listener set or not.
typedef struct {
// The size of the struct. Must be sizeof(FlutterChannelUpdate).
size_t struct_size;
/// The name of the channel.
const char* channel;
/// True if a listener has been set, false if one has been cleared.
bool listening;
} FlutterChannelUpdate;
typedef void (*FlutterChannelUpdateCallback)(
const FlutterChannelUpdate* /* channel update */,
void* /* user data */);
typedef struct _FlutterTaskRunner* FlutterTaskRunner;
typedef struct {
FlutterTaskRunner runner;
uint64_t task;
} FlutterTask;
typedef void (*FlutterTaskRunnerPostTaskCallback)(
FlutterTask /* task */,
uint64_t /* target time nanos */,
void* /* user data */);
/// An interface used by the Flutter engine to execute tasks at the target time
/// on a specified thread. There should be a 1-1 relationship between a thread
/// and a task runner. It is undefined behavior to run a task on a thread that
/// is not associated with its task runner.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterTaskRunnerDescription).
size_t struct_size;
void* user_data;
/// May be called from any thread. Should return true if tasks posted on the
/// calling thread will be run on that same thread.
///
/// @attention This field is required.
BoolCallback runs_task_on_current_thread_callback;
/// May be called from any thread. The given task should be executed by the
/// embedder on the thread associated with that task runner by calling
/// `FlutterEngineRunTask` at the given target time. The system monotonic
/// clock should be used for the target time. The target time is the absolute
/// time from epoch (NOT a delta) at which the task must be returned back to
/// the engine on the correct thread. If the embedder needs to calculate a
/// delta, `FlutterEngineGetCurrentTime` may be called and the difference used
/// as the delta.
///
/// @attention This field is required.
FlutterTaskRunnerPostTaskCallback post_task_callback;
/// A unique identifier for the task runner. If multiple task runners service
/// tasks on the same thread, their identifiers must match.
size_t identifier;
} FlutterTaskRunnerDescription;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterCustomTaskRunners).
size_t struct_size;
/// Specify the task runner for the thread on which the `FlutterEngineRun`
/// call is made. The same task runner description can be specified for both
/// the render and platform task runners. This makes the Flutter engine use
/// the same thread for both task runners.
const FlutterTaskRunnerDescription* platform_task_runner;
/// Specify the task runner for the thread on which the render tasks will be
/// run. The same task runner description can be specified for both the render
/// and platform task runners. This makes the Flutter engine use the same
/// thread for both task runners.
const FlutterTaskRunnerDescription* render_task_runner;
/// Specify a callback that is used to set the thread priority for embedder
/// task runners.
void (*thread_priority_setter)(FlutterThreadPriority);
} FlutterCustomTaskRunners;
typedef struct {
/// The type of the OpenGL backing store. Currently, it can either be a
/// texture or a framebuffer.
FlutterOpenGLTargetType type;
union {
/// A texture for Flutter to render into.
FlutterOpenGLTexture texture;
/// A framebuffer for Flutter to render into. The embedder must ensure that
/// the framebuffer is complete.
FlutterOpenGLFramebuffer framebuffer;
};
} FlutterOpenGLBackingStore;
typedef struct {
/// A pointer to the raw bytes of the allocation described by this software
/// backing store.
const void* allocation;
/// The number of bytes in a single row of the allocation.
size_t row_bytes;
/// The number of rows in the allocation.
size_t height;
/// A baton that is not interpreted by the engine in any way. It will be given
/// back to the embedder in the destruction callback below. Embedder resources
/// may be associated with this baton.
void* user_data;
/// The callback invoked by the engine when it no longer needs this backing
/// store.
VoidCallback destruction_callback;
} FlutterSoftwareBackingStore;
typedef struct {
size_t struct_size;
/// A pointer to the raw bytes of the allocation described by this software
/// backing store.
const void* allocation;
/// The number of bytes in a single row of the allocation.
size_t row_bytes;
/// The number of rows in the allocation.
size_t height;
/// A baton that is not interpreted by the engine in any way. It will be given
/// back to the embedder in the destruction callback below. Embedder resources
/// may be associated with this baton.
void* user_data;
/// The callback invoked by the engine when it no longer needs this backing
/// store.
VoidCallback destruction_callback;
/// The pixel format that the engine should use to render into the allocation.
/// In most cases, kR
FlutterSoftwarePixelFormat pixel_format;
} FlutterSoftwareBackingStore2;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterMetalBackingStore).
size_t struct_size;
union {
// A Metal texture for Flutter to render into. Ownership is not transferred
// to Flutter; the texture is CFRetained on successfully being passed in and
// CFReleased when no longer used.
FlutterMetalTexture texture;
};
} FlutterMetalBackingStore;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterVulkanBackingStore).
size_t struct_size;
/// The image that the layer will be rendered to. This image must already be
/// available for the engine to bind for writing when it's given to the engine
/// via the backing store creation callback. The engine will perform a host
/// sync for all layers prior to calling the compositor present callback, and
/// so the written layer images can be freely bound by the embedder without
/// any additional synchronization.
const FlutterVulkanImage* image;
/// A baton that is not interpreted by the engine in any way. It will be given
/// back to the embedder in the destruction callback below. Embedder resources
/// may be associated with this baton.
void* user_data;
/// The callback invoked by the engine when it no longer needs this backing
/// store.
VoidCallback destruction_callback;
} FlutterVulkanBackingStore;
typedef enum {
/// Indicates that the Flutter application requested that an opacity be
/// applied to the platform view.
kFlutterPlatformViewMutationTypeOpacity,
/// Indicates that the Flutter application requested that the platform view be
/// clipped using a rectangle.
kFlutterPlatformViewMutationTypeClipRect,
/// Indicates that the Flutter application requested that the platform view be
/// clipped using a rounded rectangle.
kFlutterPlatformViewMutationTypeClipRoundedRect,
/// Indicates that the Flutter application requested that the platform view be
/// transformed before composition.
kFlutterPlatformViewMutationTypeTransformation,
} FlutterPlatformViewMutationType;
typedef struct {
/// The type of the mutation described by the subsequent union.
FlutterPlatformViewMutationType type;
union {
double opacity;
FlutterRect clip_rect;
FlutterRoundedRect clip_rounded_rect;
FlutterTransformation transformation;
};
} FlutterPlatformViewMutation;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterPlatformView).
size_t struct_size;
/// The identifier of this platform view. This identifier is specified by the
/// application when a platform view is added to the scene via the
/// `SceneBuilder.addPlatformView` call.
FlutterPlatformViewIdentifier identifier;
/// The number of mutations to be applied to the platform view by the embedder
/// before on-screen composition.
size_t mutations_count;
/// The mutations to be applied by this platform view before it is composited
/// on-screen. The Flutter application may transform the platform view but
/// these transformations cannot be affected by the Flutter compositor because
/// it does not render platform views. Since the embedder is responsible for
/// composition of these views, it is also the embedder's responsibility to
/// affect the appropriate transformation.
///
/// The mutations must be applied in order. The mutations done in the
/// collection don't take into account the device pixel ratio or the root
/// surface transformation. If these exist, the first mutation in the list
/// will be a transformation mutation to make sure subsequent mutations are in
/// the correct coordinate space.
const FlutterPlatformViewMutation** mutations;
} FlutterPlatformView;
typedef enum {
/// Specifies an OpenGL backing store. Can either be an OpenGL texture or
/// framebuffer.
kFlutterBackingStoreTypeOpenGL,
/// Specified an software allocation for Flutter to render into using the CPU.
kFlutterBackingStoreTypeSoftware,
/// Specifies a Metal backing store. This is backed by a Metal texture.
kFlutterBackingStoreTypeMetal,
/// Specifies a Vulkan backing store. This is backed by a Vulkan VkImage.
kFlutterBackingStoreTypeVulkan,
/// Specifies a allocation that the engine should render into using
/// software rendering.
kFlutterBackingStoreTypeSoftware2,
} FlutterBackingStoreType;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterBackingStore).
size_t struct_size;
/// A baton that is not interpreted by the engine in any way. The embedder may
/// use this to associate resources that are tied to the lifecycle of the
/// `FlutterBackingStore`.
void* user_data;
/// Specifies the type of backing store.
FlutterBackingStoreType type;
/// Indicates if this backing store was updated since the last time it was
/// associated with a presented layer.
bool did_update;
union {
/// The description of the OpenGL backing store.
FlutterOpenGLBackingStore open_gl;
/// The description of the software backing store.
FlutterSoftwareBackingStore software;
/// The description of the software backing store.
FlutterSoftwareBackingStore2 software2;
// The description of the Metal backing store.
FlutterMetalBackingStore metal;
// The description of the Vulkan backing store.
FlutterVulkanBackingStore vulkan;
};
} FlutterBackingStore;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterBackingStoreConfig).
size_t struct_size;
/// The size of the render target the engine expects to render into.
FlutterSize size;
} FlutterBackingStoreConfig;
typedef enum {
/// Indicates that the contents of this layer are rendered by Flutter into a
/// backing store.
kFlutterLayerContentTypeBackingStore,
/// Indicates that the contents of this layer are determined by the embedder.
kFlutterLayerContentTypePlatformView,
} FlutterLayerContentType;
/// A region represented by a collection of non-overlapping rectangles.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterRegion).
size_t struct_size;
/// Number of rectangles in the region.
size_t rects_count;
/// The rectangles that make up the region.
FlutterRect* rects;
} FlutterRegion;
/// Contains additional information about the backing store provided
/// during presentation to the embedder.
typedef struct {
size_t struct_size;
/// The area of the backing store that contains Flutter contents. Pixels
/// outside of this area are transparent and the embedder may choose not
/// to render them. Coordinates are in physical pixels.
FlutterRegion* paint_region;
} FlutterBackingStorePresentInfo;
typedef struct {
/// This size of this struct. Must be sizeof(FlutterLayer).
size_t struct_size;
/// Each layer displays contents in one way or another. The type indicates
/// whether those contents are specified by Flutter or the embedder.
FlutterLayerContentType type;
union {
/// Indicates that the contents of this layer are rendered by Flutter into a
/// backing store.
const FlutterBackingStore* backing_store;
/// Indicates that the contents of this layer are determined by the
/// embedder.
const FlutterPlatformView* platform_view;
};
/// The offset of this layer (in physical pixels) relative to the top left of
/// the root surface used by the engine.
FlutterPoint offset;
/// The size of the layer (in physical pixels).
FlutterSize size;
/// Extra information for the backing store that the embedder may
/// use during presentation.
FlutterBackingStorePresentInfo* backing_store_present_info;
// Time in nanoseconds at which this frame is scheduled to be presented. 0 if
// not known. See FlutterEngineGetCurrentTime().
uint64_t presentation_time;
} FlutterLayer;
typedef struct {
/// The size of this struct.
/// Must be sizeof(FlutterPresentViewInfo).
size_t struct_size;
/// The identifier of the target view.
FlutterViewId view_id;
/// The layers that should be composited onto the view.
const FlutterLayer** layers;
/// The count of layers.
size_t layers_count;
/// The |FlutterCompositor.user_data|.
void* user_data;
} FlutterPresentViewInfo;
typedef bool (*FlutterBackingStoreCreateCallback)(
const FlutterBackingStoreConfig* config,
FlutterBackingStore* backing_store_out,
void* user_data);
typedef bool (*FlutterBackingStoreCollectCallback)(
const FlutterBackingStore* renderer,
void* user_data);
typedef bool (*FlutterLayersPresentCallback)(const FlutterLayer** layers,
size_t layers_count,
void* user_data);
/// The callback invoked when the embedder should present to a view.
///
/// The |FlutterPresentViewInfo| will be deallocated once the callback returns.
typedef bool (*FlutterPresentViewCallback)(
const FlutterPresentViewInfo* /* present info */);
typedef struct {
/// This size of this struct. Must be sizeof(FlutterCompositor).
size_t struct_size;
/// A baton that in not interpreted by the engine in any way. If it passed
/// back to the embedder in `FlutterCompositor.create_backing_store_callback`,
/// `FlutterCompositor.collect_backing_store_callback`,
/// `FlutterCompositor.present_layers_callback`, and
/// `FlutterCompositor.present_view_callback`.
void* user_data;
/// A callback invoked by the engine to obtain a backing store for a specific
/// `FlutterLayer`.
///
/// On ABI stability: Callers must take care to restrict access within
/// `FlutterBackingStore::struct_size` when specifying a new backing store to
/// the engine. This only matters if the embedder expects to be used with
/// engines older than the version whose headers it used during compilation.
FlutterBackingStoreCreateCallback create_backing_store_callback;
/// A callback invoked by the engine to release the backing store. The
/// embedder may collect any resources associated with the backing store.
FlutterBackingStoreCollectCallback collect_backing_store_callback;
/// Callback invoked by the engine to composite the contents of each layer
/// onto the implicit view.
///
/// DEPRECATED: Use |present_view_callback| to support multiple views.
///
/// Only one of `present_layers_callback` and `present_view_callback` may be
/// provided. Providing both is an error and engine initialization will
/// terminate.
FlutterLayersPresentCallback present_layers_callback;
/// Avoid caching backing stores provided by this compositor.
bool avoid_backing_store_cache;
/// Callback invoked by the engine to composite the contents of each layer
/// onto the specified view.
///
/// Only one of `present_layers_callback` and `present_view_callback` may be
/// provided. Providing both is an error and engine initialization will
/// terminate.
FlutterPresentViewCallback present_view_callback;
} FlutterCompositor;
typedef struct {
/// This size of this struct. Must be sizeof(FlutterLocale).
size_t struct_size;
/// The language code of the locale. For example, "en". This is a required
/// field. The string must be null terminated. It may be collected after the
/// call to `FlutterEngineUpdateLocales`.
const char* language_code;
/// The country code of the locale. For example, "US". This is a an optional
/// field. The string must be null terminated if present. It may be collected
/// after the call to `FlutterEngineUpdateLocales`. If not present, a
/// `nullptr` may be specified.
const char* country_code;
/// The script code of the locale. This is a an optional field. The string
/// must be null terminated if present. It may be collected after the call to
/// `FlutterEngineUpdateLocales`. If not present, a `nullptr` may be
/// specified.
const char* script_code;
/// The variant code of the locale. This is a an optional field. The string
/// must be null terminated if present. It may be collected after the call to
/// `FlutterEngineUpdateLocales`. If not present, a `nullptr` may be
/// specified.
const char* variant_code;
} FlutterLocale;
/// Callback that returns the system locale.
///
/// Embedders that implement this callback should return the `FlutterLocale`
/// from the `supported_locales` list that most closely matches the
/// user/device's preferred locale.
///
/// This callback does not currently provide the user_data baton.
/// https://github.com/flutter/flutter/issues/79826
typedef const FlutterLocale* (*FlutterComputePlatformResolvedLocaleCallback)(
const FlutterLocale** /* supported_locales*/,
size_t /* Number of locales*/);
typedef struct {
/// This size of this struct. Must be sizeof(FlutterDisplay).
size_t struct_size;
FlutterEngineDisplayId display_id;
/// This is set to true if the embedder only has one display. In cases where
/// this is set to true, the value of display_id is ignored. In cases where
/// this is not set to true, it is expected that a valid display_id be
/// provided.
bool single_display;
/// This represents the refresh period in frames per second. This value may be
/// zero if the device is not running or unavailable or unknown.
double refresh_rate;
/// The width of the display, in physical pixels.
size_t width;
/// The height of the display, in physical pixels.
size_t height;
/// The pixel ratio of the display, which is used to convert physical pixels
/// to logical pixels.
double device_pixel_ratio;
} FlutterEngineDisplay;
/// The update type parameter that is passed to
/// `FlutterEngineNotifyDisplayUpdate`.
typedef enum {
/// `FlutterEngineDisplay`s that were active during start-up. A display is
/// considered active if:
/// 1. The frame buffer hardware is connected.
/// 2. The display is drawable, e.g. it isn't being mirrored from another
/// connected display or sleeping.
kFlutterEngineDisplaysUpdateTypeStartup,
kFlutterEngineDisplaysUpdateTypeCount,
} FlutterEngineDisplaysUpdateType;
typedef int64_t FlutterEngineDartPort;
typedef enum {
kFlutterEngineDartObjectTypeNull,
kFlutterEngineDartObjectTypeBool,
kFlutterEngineDartObjectTypeInt32,
kFlutterEngineDartObjectTypeInt64,
kFlutterEngineDartObjectTypeDouble,
kFlutterEngineDartObjectTypeString,
/// The object will be made available to Dart code as an instance of
/// Uint8List.
kFlutterEngineDartObjectTypeBuffer,
} FlutterEngineDartObjectType;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterEngineDartBuffer).
size_t struct_size;
/// An opaque baton passed back to the embedder when the
/// buffer_collect_callback is invoked. The engine does not interpret this
/// field in any way.
void* user_data;
/// This is an optional field.
///
/// When specified, the engine will assume that the buffer is owned by the
/// embedder. When the data is no longer needed by any isolate, this callback
/// will be made on an internal engine managed thread. The embedder is free to
/// collect the buffer here. When this field is specified, it is the embedders
/// responsibility to keep the buffer alive and not modify it till this
/// callback is invoked by the engine. The user data specified in the callback
/// is the value of `user_data` field in this struct.
///
/// When NOT specified, the VM creates an internal copy of the buffer. The
/// caller is free to modify the buffer as necessary or collect it immediately
/// after the call to `FlutterEnginePostDartObject`.
///
/// @attention The buffer_collect_callback is will only be invoked by the
/// engine when the `FlutterEnginePostDartObject` method
/// returns kSuccess. In case of non-successful calls to this
/// method, it is the embedders responsibility to collect the
/// buffer.
VoidCallback buffer_collect_callback;
/// A pointer to the bytes of the buffer. When the buffer is owned by the
/// embedder (by specifying the `buffer_collect_callback`), Dart code may
/// modify that embedder owned buffer. For this reason, it is important that
/// this buffer not have page protections that restrict writing to this
/// buffer.
uint8_t* buffer;
/// The size of the buffer.
size_t buffer_size;
} FlutterEngineDartBuffer;
/// This struct specifies the native representation of a Dart object that can be
/// sent via a send port to any isolate in the VM that has the corresponding
/// receive port.
///
/// All fields in this struct are copied out in the call to
/// `FlutterEnginePostDartObject` and the caller is free to reuse or collect
/// this struct after that call.
typedef struct {
FlutterEngineDartObjectType type;
union {
bool bool_value;
int32_t int32_value;
int64_t int64_value;
double double_value;
/// A null terminated string. This string will be copied by the VM in the
/// call to `FlutterEnginePostDartObject` and must be collected by the
/// embedder after that call is made.
const char* string_value;
const FlutterEngineDartBuffer* buffer_value;
};
} FlutterEngineDartObject;
/// This enum allows embedders to determine the type of the engine thread in the
/// FlutterNativeThreadCallback. Based on the thread type, the embedder may be
/// able to tweak the thread priorities for optimum performance.
typedef enum {
/// The Flutter Engine considers the thread on which the FlutterEngineRun call
/// is made to be the platform thread. There is only one such thread per
/// engine instance.
kFlutterNativeThreadTypePlatform,
/// This is the thread the Flutter Engine uses to execute rendering commands
/// based on the selected client rendering API. There is only one such thread
/// per engine instance.
kFlutterNativeThreadTypeRender,
/// This is a dedicated thread on which the root Dart isolate is serviced.
/// There is only one such thread per engine instance.
kFlutterNativeThreadTypeUI,
/// Multiple threads are used by the Flutter engine to perform long running
/// background tasks.
kFlutterNativeThreadTypeWorker,
} FlutterNativeThreadType;
/// A callback made by the engine in response to
/// `FlutterEnginePostCallbackOnAllNativeThreads` on all internal thread.
typedef void (*FlutterNativeThreadCallback)(FlutterNativeThreadType type,
void* user_data);
/// AOT data source type.
typedef enum {
kFlutterEngineAOTDataSourceTypeElfPath
} FlutterEngineAOTDataSourceType;
/// This struct specifies one of the various locations the engine can look for
/// AOT data sources.
typedef struct {
FlutterEngineAOTDataSourceType type;
union {
/// Absolute path to an ELF library file.
const char* elf_path;
};
} FlutterEngineAOTDataSource;
// Logging callback for Dart application messages.
//
// The `tag` parameter contains a null-terminated string containing a logging
// tag or component name that can be used to identify system log messages from
// the app. The `message` parameter contains a null-terminated string
// containing the message to be logged. `user_data` is a user data baton passed
// in `FlutterEngineRun`.
typedef void (*FlutterLogMessageCallback)(const char* /* tag */,
const char* /* message */,
void* /* user_data */);
/// An opaque object that describes the AOT data that can be used to launch a
/// FlutterEngine instance in AOT mode.
typedef struct _FlutterEngineAOTData* FlutterEngineAOTData;
typedef struct {
/// The size of this struct. Must be sizeof(FlutterProjectArgs).
size_t struct_size;
/// The path to the Flutter assets directory containing project assets. The
/// string can be collected after the call to `FlutterEngineRun` returns. The
/// string must be NULL terminated.
const char* assets_path;
/// The path to the Dart file containing the `main` entry point.
/// The string can be collected after the call to `FlutterEngineRun` returns.
/// The string must be NULL terminated.
///
/// @deprecated As of Dart 2, running from Dart source is no longer
/// supported. Dart code should now be compiled to kernel form
/// and will be loaded by from `kernel_blob.bin` in the assets
/// directory. This struct member is retained for ABI
/// stability.
const char* main_path__unused__;
/// The path to the `.packages` file for the project. The string can be
/// collected after the call to `FlutterEngineRun` returns. The string must be
/// NULL terminated.
///
/// @deprecated As of Dart 2, running from Dart source is no longer
/// supported. Dart code should now be compiled to kernel form
/// and will be loaded by from `kernel_blob.bin` in the assets
/// directory. This struct member is retained for ABI
/// stability.
const char* packages_path__unused__;
/// The path to the `icudtl.dat` file for the project. The string can be
/// collected after the call to `FlutterEngineRun` returns. The string must
/// be NULL terminated.
const char* icu_data_path;
/// The command line argument count used to initialize the project.
int command_line_argc;
/// The command line arguments used to initialize the project. The strings can
/// be collected after the call to `FlutterEngineRun` returns. The strings
/// must be `NULL` terminated.
///
/// @attention The first item in the command line (if specified at all) is
/// interpreted as the executable name. So if an engine flag
/// needs to be passed into the same, it needs to not be the
/// very first item in the list.
///
/// The set of engine flags are only meant to control
/// unstable features in the engine. Deployed applications should not pass any
/// command line arguments at all as they may affect engine stability at
/// runtime in the presence of un-sanitized input. The list of currently
/// recognized engine flags and their descriptions can be retrieved from the
/// `switches.h` engine source file.
const char* const* command_line_argv;
/// The callback invoked by the engine in order to give the embedder the
/// chance to respond to platform messages from the Dart application.
/// The callback will be invoked on the thread on which the `FlutterEngineRun`
/// call is made. The second parameter, `user_data`, is supplied when
/// `FlutterEngineRun` or `FlutterEngineInitialize` is called.
FlutterPlatformMessageCallback platform_message_callback;
/// The VM snapshot data buffer used in AOT operation. This buffer must be
/// mapped in as read-only. For more information refer to the documentation on
/// the Wiki at
/// https://github.com/flutter/flutter/wiki/Flutter-engine-operation-in-AOT-Mode
const uint8_t* vm_snapshot_data;
/// The size of the VM snapshot data buffer. If vm_snapshot_data is a symbol
/// reference, 0 may be passed here.
size_t vm_snapshot_data_size;
/// The VM snapshot instructions buffer used in AOT operation. This buffer
/// must be mapped in as read-execute. For more information refer to the
/// documentation on the Wiki at
/// https://github.com/flutter/flutter/wiki/Flutter-engine-operation-in-AOT-Mode
const uint8_t* vm_snapshot_instructions;
/// The size of the VM snapshot instructions buffer. If
/// vm_snapshot_instructions is a symbol reference, 0 may be passed here.
size_t vm_snapshot_instructions_size;
/// The isolate snapshot data buffer used in AOT operation. This buffer must
/// be mapped in as read-only. For more information refer to the documentation
/// on the Wiki at
/// https://github.com/flutter/flutter/wiki/Flutter-engine-operation-in-AOT-Mode
const uint8_t* isolate_snapshot_data;
/// The size of the isolate snapshot data buffer. If isolate_snapshot_data is
/// a symbol reference, 0 may be passed here.
size_t isolate_snapshot_data_size;
/// The isolate snapshot instructions buffer used in AOT operation. This
/// buffer must be mapped in as read-execute. For more information refer to
/// the documentation on the Wiki at
/// https://github.com/flutter/flutter/wiki/Flutter-engine-operation-in-AOT-Mode
const uint8_t* isolate_snapshot_instructions;
/// The size of the isolate snapshot instructions buffer. If
/// isolate_snapshot_instructions is a symbol reference, 0 may be passed here.
size_t isolate_snapshot_instructions_size;
/// The callback invoked by the engine in root isolate scope. Called
/// immediately after the root isolate has been created and marked runnable.
VoidCallback root_isolate_create_callback;
/// The legacy callback invoked by the engine in order to give the embedder
/// the chance to respond to semantics node updates from the Dart application.
/// Semantics node updates are sent in batches terminated by a 'batch end'
/// callback that is passed a sentinel `FlutterSemanticsNode` whose `id` field
/// has the value `kFlutterSemanticsNodeIdBatchEnd`.
///
/// The callback will be invoked on the thread on which the `FlutterEngineRun`
/// call is made.
///
/// @deprecated Use `update_semantics_callback2` instead. Only one of
/// `update_semantics_node_callback`,
/// `update_semantics_callback`, and
/// `update_semantics_callback2` may be provided; the others
/// should be set to null.
FlutterUpdateSemanticsNodeCallback update_semantics_node_callback;
/// The legacy callback invoked by the engine in order to give the embedder
/// the chance to respond to updates to semantics custom actions from the Dart
/// application. Custom action updates are sent in batches terminated by a
/// 'batch end' callback that is passed a sentinel
/// `FlutterSemanticsCustomAction` whose `id` field has the value
/// `kFlutterSemanticsCustomActionIdBatchEnd`.
///
/// The callback will be invoked on the thread on which the `FlutterEngineRun`
/// call is made.
///
/// @deprecated Use `update_semantics_callback2` instead. Only one of
/// `update_semantics_node_callback`,
/// `update_semantics_callback`, and
/// `update_semantics_callback2` may be provided; the others
/// should be set to null.
FlutterUpdateSemanticsCustomActionCallback
update_semantics_custom_action_callback;
/// Path to a directory used to store data that is cached across runs of a
/// Flutter application (such as compiled shader programs used by Skia).
/// This is optional. The string must be NULL terminated.
///
// This is different from the cache-path-dir argument defined in switches.h,
// which is used in `flutter::Settings` as `temp_directory_path`.
const char* persistent_cache_path;
/// If true, the engine would only read the existing cache, but not write new
/// ones.
bool is_persistent_cache_read_only;
/// A callback that gets invoked by the engine when it attempts to wait for a
/// platform vsync event. The engine will give the platform a baton that needs
/// to be returned back to the engine via `FlutterEngineOnVsync`. All batons
/// must be retured to the engine before initializing a
/// `FlutterEngineShutdown`. Not doing the same will result in a memory leak.
/// While the call to `FlutterEngineOnVsync` must occur on the thread that
/// made the call to `FlutterEngineRun`, the engine will make this callback on
/// an internal engine-managed thread. If the components accessed on the
/// embedder are not thread safe, the appropriate re-threading must be done.
VsyncCallback vsync_callback;
/// The name of a custom Dart entrypoint. This is optional and specifying a
/// null or empty entrypoint makes the engine look for a method named "main"
/// in the root library of the application.
///
/// Care must be taken to ensure that the custom entrypoint is not tree-shaken
/// away. Usually, this is done using the `@pragma('vm:entry-point')`
/// decoration.
const char* custom_dart_entrypoint;
/// Typically the Flutter engine create and manages its internal threads. This
/// optional argument allows for the specification of task runner interfaces
/// to event loops managed by the embedder on threads it creates.
const FlutterCustomTaskRunners* custom_task_runners;
/// All `FlutterEngine` instances in the process share the same Dart VM. When
/// the first engine is launched, it starts the Dart VM as well. It used to be
/// the case that it was not possible to shutdown the Dart VM cleanly and
/// start it back up in the process in a safe manner. This issue has since
/// been patched. Unfortunately, applications already began to make use of the
/// fact that shutting down the Flutter engine instance left a running VM in
/// the process. Since a Flutter engine could be launched on any thread,
/// applications would "warm up" the VM on another thread by launching
/// an engine with no isolates and then shutting it down immediately. The main
/// Flutter application could then be started on the main thread without
/// having to incur the Dart VM startup costs at that time. With the new
/// behavior, this "optimization" immediately becomes massive performance
/// pessimization as the VM would be started up in the "warm up" phase, shut
/// down there and then started again on the main thread. Changing this
/// behavior was deemed to be an unacceptable breaking change. Embedders that
/// wish to shutdown the Dart VM when the last engine is terminated in the
/// process should opt into this behavior by setting this flag to true.
bool shutdown_dart_vm_when_done;
/// Typically, Flutter renders the layer hierarchy into a single root surface.
/// However, when embedders need to interleave their own contents within the
/// Flutter layer hierarchy, their applications can push platform views within
/// the Flutter scene. This is done using the `SceneBuilder.addPlatformView`
/// call. When this happens, the Flutter rasterizer divides the effective view
/// hierarchy into multiple layers. Each layer gets its own backing store and
/// Flutter renders into the same. Once the layers contents have been
/// fulfilled, the embedder is asked to composite these layers on-screen. At
/// this point, it can interleave its own contents within the effective
/// hierarchy. The interface for the specification of these layer backing
/// stores and the hooks to listen for the composition of layers on-screen can
/// be controlled using this field. This field is completely optional. In its
/// absence, platforms views in the scene are ignored and Flutter renders to
/// the root surface as normal.
const FlutterCompositor* compositor;
/// Max size of the old gen heap for the Dart VM in MB, or 0 for unlimited, -1
/// for default value.
///
/// See also:
/// https://github.com/dart-lang/sdk/blob/ca64509108b3e7219c50d6c52877c85ab6a35ff2/runtime/vm/flag_list.h#L150
int64_t dart_old_gen_heap_size;
/// The AOT data to be used in AOT operation.
///
/// Embedders should instantiate and destroy this object via the
/// FlutterEngineCreateAOTData and FlutterEngineCollectAOTData methods.
///
/// Embedders can provide either snapshot buffers or aot_data, but not both.
FlutterEngineAOTData aot_data;
/// A callback that computes the locale the platform would natively resolve
/// to.
///
/// The input parameter is an array of FlutterLocales which represent the
/// locales supported by the app. One of the input supported locales should
/// be selected and returned to best match with the user/device's preferred
/// locale. The implementation should produce a result that as closely
/// matches what the platform would natively resolve to as possible.
FlutterComputePlatformResolvedLocaleCallback
compute_platform_resolved_locale_callback;
/// The command line argument count for arguments passed through to the Dart
/// entrypoint.
int dart_entrypoint_argc;
/// The command line arguments passed through to the Dart entrypoint. The
/// strings must be `NULL` terminated.
///
/// The strings will be copied out and so any strings passed in here can
/// be safely collected after initializing the engine with
/// `FlutterProjectArgs`.
const char* const* dart_entrypoint_argv;
// Logging callback for Dart application messages.
//
// This callback is used by embedder to log print messages from the running
// Flutter application. This callback is made on an internal engine managed
// thread and embedders must re-thread if necessary. Performing blocking calls
// in this callback may introduce application jank.
FlutterLogMessageCallback log_message_callback;
// A tag string associated with application log messages.
//
// A log message tag string that can be used convey application, subsystem,
// or component name to embedder's logger. This string will be passed to to
// callbacks on `log_message_callback`. Defaults to "flutter" if unspecified.
const char* log_tag;
// A callback that is invoked right before the engine is restarted.
//
// This optional callback is typically used to reset states to as if the
// engine has just been started, and usually indicates the user has requested
// a hot restart (Shift-R in the Flutter CLI.) It is not called the first time
// the engine starts.
//
// The first argument is the `user_data` from `FlutterEngineInitialize`.
OnPreEngineRestartCallback on_pre_engine_restart_callback;
/// The callback invoked by the engine in order to give the embedder the
/// chance to respond to updates to semantics nodes and custom actions from
/// the Dart application.
///
/// The callback will be invoked on the thread on which the `FlutterEngineRun`
/// call is made.
///
/// @deprecated Use `update_semantics_callback2` instead. Only one of
/// `update_semantics_node_callback`,
/// `update_semantics_callback`, and
/// `update_semantics_callback2` may be provided; the others
/// must be set to null.
FlutterUpdateSemanticsCallback update_semantics_callback;
/// The callback invoked by the engine in order to give the embedder the
/// chance to respond to updates to semantics nodes and custom actions from
/// the Dart application.
///
/// The callback will be invoked on the thread on which the `FlutterEngineRun`
/// call is made.
///
/// Only one of `update_semantics_node_callback`, `update_semantics_callback`,
/// and `update_semantics_callback2` may be provided; the others must be set
/// to null.
FlutterUpdateSemanticsCallback2 update_semantics_callback2;
/// The callback invoked by the engine in response to a channel listener
/// being registered on the framework side. The callback is invoked from
/// a task posted to the platform thread.
FlutterChannelUpdateCallback channel_update_callback;
} FlutterProjectArgs;
#ifndef FLUTTER_ENGINE_NO_PROTOTYPES
// NOLINTBEGIN(google-objc-function-naming)
//------------------------------------------------------------------------------
/// @brief Creates the necessary data structures to launch a Flutter Dart
/// application in AOT mode. The data may only be collected after
/// all FlutterEngine instances launched using this data have been
/// terminated.
///
/// @param[in] source The source of the AOT data.
/// @param[out] data_out The AOT data on success. Unchanged on failure.
///
/// @return Returns if the AOT data could be successfully resolved.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineCreateAOTData(
const FlutterEngineAOTDataSource* source,
FlutterEngineAOTData* data_out);
//------------------------------------------------------------------------------
/// @brief Collects the AOT data.
///
/// @warning The embedder must ensure that this call is made only after all
/// FlutterEngine instances launched using this data have been
/// terminated, and that all of those instances were launched with
/// the FlutterProjectArgs::shutdown_dart_vm_when_done flag set to
/// true.
///
/// @param[in] data The data to collect.
///
/// @return Returns if the AOT data was successfully collected.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data);
//------------------------------------------------------------------------------
/// @brief Initialize and run a Flutter engine instance and return a handle
/// to it. This is a convenience method for the pair of calls to
/// `FlutterEngineInitialize` and `FlutterEngineRunInitialized`.
///
/// @note This method of running a Flutter engine works well except in
/// cases where the embedder specifies custom task runners via
/// `FlutterProjectArgs::custom_task_runners`. In such cases, the
/// engine may need the embedder to post tasks back to it before
/// `FlutterEngineRun` has returned. Embedders can only post tasks
/// to the engine if they have a handle to the engine. In such
/// cases, embedders are advised to get the engine handle via the
/// `FlutterInitializeCall`. Then they can call
/// `FlutterEngineRunInitialized` knowing that they will be able to
/// service custom tasks on other threads with the engine handle.
///
/// @param[in] version The Flutter embedder API version. Must be
/// FLUTTER_ENGINE_VERSION.
/// @param[in] config The renderer configuration.
/// @param[in] args The Flutter project arguments.
/// @param user_data A user data baton passed back to embedders in
/// callbacks.
/// @param[out] engine_out The engine handle on successful engine creation.
///
/// @return The result of the call to run the Flutter engine.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineRun(size_t version,
const FlutterRendererConfig* config,
const FlutterProjectArgs* args,
void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) *
engine_out);
//------------------------------------------------------------------------------
/// @brief Shuts down a Flutter engine instance. The engine handle is no
/// longer valid for any calls in the embedder API after this point.
/// Making additional calls with this handle is undefined behavior.
///
/// @note This de-initializes the Flutter engine instance (via an implicit
/// call to `FlutterEngineDeinitialize`) if necessary.
///
/// @param[in] engine The Flutter engine instance to collect.
///
/// @return The result of the call to shutdown the Flutter engine instance.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine)
engine);
//------------------------------------------------------------------------------
/// @brief Initialize a Flutter engine instance. This does not run the
/// Flutter application code till the `FlutterEngineRunInitialized`
/// call is made. Besides Flutter application code, no tasks are
/// scheduled on embedder managed task runners either. This allows
/// embedders providing custom task runners to the Flutter engine to
/// obtain a handle to the Flutter engine before the engine can post
/// tasks on these task runners.
///
/// @param[in] version The Flutter embedder API version. Must be
/// FLUTTER_ENGINE_VERSION.
/// @param[in] config The renderer configuration.
/// @param[in] args The Flutter project arguments.
/// @param user_data A user data baton passed back to embedders in
/// callbacks.
/// @param[out] engine_out The engine handle on successful engine creation.
///
/// @return The result of the call to initialize the Flutter engine.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineInitialize(size_t version,
const FlutterRendererConfig* config,
const FlutterProjectArgs* args,
void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) *
engine_out);
//------------------------------------------------------------------------------
/// @brief Stops running the Flutter engine instance. After this call, the
/// embedder is also guaranteed that no more calls to post tasks
/// onto custom task runners specified by the embedder are made. The
/// Flutter engine handle still needs to be collected via a call to
/// `FlutterEngineShutdown`.
///
/// @param[in] engine The running engine instance to de-initialize.
///
/// @return The result of the call to de-initialize the Flutter engine.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine)
engine);
//------------------------------------------------------------------------------
/// @brief Runs an initialized engine instance. An engine can be
/// initialized via `FlutterEngineInitialize`. An initialized
/// instance can only be run once. During and after this call,
/// custom task runners supplied by the embedder are expected to
/// start servicing tasks.
///
/// @param[in] engine An initialized engine instance that has not previously
/// been run.
///
/// @return The result of the call to run the initialized Flutter
/// engine instance.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineRunInitialized(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
//------------------------------------------------------------------------------
/// @brief Removes a view.
///
/// This is an asynchronous operation. The view's resources must not
/// be cleaned up until the |remove_view_callback| is invoked with
/// a |removed| value of `true`.
///
/// @param[in] engine A running engine instance.
/// @param[in] info The remove view arguments. This can be deallocated
/// once |FlutterEngineRemoveView| returns, before
/// |remove_view_callback| is invoked.
///
/// @return The result of *starting* the asynchronous operation. If
/// `kSuccess`, the |remove_view_callback| will be invoked.
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineRemoveView(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterRemoveViewInfo* info);
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSendWindowMetricsEvent(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterWindowMetricsEvent* event);
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSendPointerEvent(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPointerEvent* events,
size_t events_count);
//------------------------------------------------------------------------------
/// @brief Sends a key event to the engine. The framework will decide
/// whether to handle this event in a synchronous fashion, although
/// due to technical limitation, the result is always reported
/// asynchronously. The `callback` is guaranteed to be called
/// exactly once.
///
/// @param[in] engine A running engine instance.
/// @param[in] event The event data to be sent. This function will no
/// longer access `event` after returning.
/// @param[in] callback The callback invoked by the engine when the
/// Flutter application has decided whether it
/// handles this event. Accepts nullptr.
/// @param[in] user_data The context associated with the callback. The
/// exact same value will used to invoke `callback`.
/// Accepts nullptr.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data);
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSendPlatformMessage(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessage* message);
//------------------------------------------------------------------------------
/// @brief Creates a platform message response handle that allows the
/// embedder to set a native callback for a response to a message.
/// This handle may be set on the `response_handle` field of any
/// `FlutterPlatformMessage` sent to the engine.
///
/// The handle must be collected via a call to
/// `FlutterPlatformMessageReleaseResponseHandle`. This may be done
/// immediately after a call to `FlutterEngineSendPlatformMessage`
/// with a platform message whose response handle contains the handle
/// created using this call. In case a handle is created but never
/// sent in a message, the release call must still be made. Not
/// calling release on the handle results in a small memory leak.
///
/// The user data baton passed to the data callback is the one
/// specified in this call as the third argument.
///
/// @see FlutterPlatformMessageReleaseResponseHandle()
///
/// @param[in] engine A running engine instance.
/// @param[in] data_callback The callback invoked by the engine when the
/// Flutter application send a response on the
/// handle.
/// @param[in] user_data The user data associated with the data callback.
/// @param[out] response_out The response handle created when this call is
/// successful.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterPlatformMessageCreateResponseHandle(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterDataCallback data_callback,
void* user_data,
FlutterPlatformMessageResponseHandle** response_out);
//------------------------------------------------------------------------------
/// @brief Collects the handle created using
/// `FlutterPlatformMessageCreateResponseHandle`.
///
/// @see FlutterPlatformMessageCreateResponseHandle()
///
/// @param[in] engine A running engine instance.
/// @param[in] response The platform message response handle to collect.
/// These handles are created using
/// `FlutterPlatformMessageCreateResponseHandle()`.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterPlatformMessageResponseHandle* response);
//------------------------------------------------------------------------------
/// @brief Send a response from the native side to a platform message from
/// the Dart Flutter application.
///
/// @param[in] engine The running engine instance.
/// @param[in] handle The platform message response handle.
/// @param[in] data The data to associate with the platform message
/// response.
/// @param[in] data_length The length of the platform message response data.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSendPlatformMessageResponse(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length);
//------------------------------------------------------------------------------
/// @brief This API is only meant to be used by platforms that need to
/// flush tasks on a message loop not controlled by the Flutter
/// engine.
///
/// @deprecated This API will be deprecated and is not part of the stable API.
/// Please use the custom task runners API by setting an
/// appropriate `FlutterProjectArgs::custom_task_runners`
/// interface. This will yield better performance and the
/// interface is stable.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult __FlutterEngineFlushPendingTasksNow();
//------------------------------------------------------------------------------
/// @brief Register an external texture with a unique (per engine)
/// identifier. Only rendering backends that support external
/// textures accept external texture registrations. After the
/// external texture is registered, the application can mark that a
/// frame is available by calling
/// `FlutterEngineMarkExternalTextureFrameAvailable`.
///
/// @see FlutterEngineUnregisterExternalTexture()
/// @see FlutterEngineMarkExternalTextureFrameAvailable()
///
/// @param[in] engine A running engine instance.
/// @param[in] texture_identifier The identifier of the texture to register
/// with the engine. The embedder may supply new
/// frames to this texture using the same
/// identifier.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineRegisterExternalTexture(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier);
//------------------------------------------------------------------------------
/// @brief Unregister a previous texture registration.
///
/// @see FlutterEngineRegisterExternalTexture()
/// @see FlutterEngineMarkExternalTextureFrameAvailable()
///
/// @param[in] engine A running engine instance.
/// @param[in] texture_identifier The identifier of the texture for which new
/// frame will not be available.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineUnregisterExternalTexture(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier);
//------------------------------------------------------------------------------
/// @brief Mark that a new texture frame is available for a given texture
/// identifier.
///
/// @see FlutterEngineRegisterExternalTexture()
/// @see FlutterEngineUnregisterExternalTexture()
///
/// @param[in] engine A running engine instance.
/// @param[in] texture_identifier The identifier of the texture whose frame
/// has been updated.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier);
//------------------------------------------------------------------------------
/// @brief Enable or disable accessibility semantics.
///
/// @param[in] engine A running engine instance.
/// @param[in] enabled When enabled, changes to the semantic contents of the
/// window are sent via the
/// `FlutterUpdateSemanticsCallback2` registered to
/// `update_semantics_callback2` in
/// `FlutterProjectArgs`.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineUpdateSemanticsEnabled(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
bool enabled);
//------------------------------------------------------------------------------
/// @brief Sets additional accessibility features.
///
/// @param[in] engine A running engine instance
/// @param[in] features The accessibility features to set.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature features);
//------------------------------------------------------------------------------
/// @brief Dispatch a semantics action to the specified semantics node.
///
/// @param[in] engine A running engine instance.
/// @param[in] node_id The semantics node identifier.
/// @param[in] action The semantics action.
/// @param[in] data Data associated with the action.
/// @param[in] data_length The data length.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineDispatchSemanticsAction(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
uint64_t node_id,
FlutterSemanticsAction action,
const uint8_t* data,
size_t data_length);
//------------------------------------------------------------------------------
/// @brief Notify the engine that a vsync event occurred. A baton passed to
/// the platform via the vsync callback must be returned. This call
/// must be made on the thread on which the call to
/// `FlutterEngineRun` was made.
///
/// @see FlutterEngineGetCurrentTime()
///
/// @attention That frame timepoints are in nanoseconds.
///
/// @attention The system monotonic clock is used as the timebase.
///
/// @param[in] engine. A running engine instance.
/// @param[in] baton The baton supplied by the engine.
/// @param[in] frame_start_time_nanos The point at which the vsync event
/// occurred or will occur. If the time
/// point is in the future, the engine will
/// wait till that point to begin its frame
/// workload.
/// @param[in] frame_target_time_nanos The point at which the embedder
/// anticipates the next vsync to occur.
/// This is a hint the engine uses to
/// schedule Dart VM garbage collection in
/// periods in which the various threads
/// are most likely to be idle. For
/// example, for a 60Hz display, embedders
/// should add 16.6 * 1e6 to the frame time
/// field.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineOnVsync(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
intptr_t baton,
uint64_t frame_start_time_nanos,
uint64_t frame_target_time_nanos);
//------------------------------------------------------------------------------
/// @brief Reloads the system fonts in engine.
///
/// @param[in] engine. A running engine instance.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineReloadSystemFonts(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
//------------------------------------------------------------------------------
/// @brief A profiling utility. Logs a trace duration begin event to the
/// timeline. If the timeline is unavailable or disabled, this has
/// no effect. Must be balanced with an duration end event (via
/// `FlutterEngineTraceEventDurationEnd`) with the same name on the
/// same thread. Can be called on any thread. Strings passed into
/// the function will NOT be copied when added to the timeline. Only
/// string literals may be passed in.
///
/// @param[in] name The name of the trace event.
///
FLUTTER_EXPORT
void FlutterEngineTraceEventDurationBegin(const char* name);
//-----------------------------------------------------------------------------
/// @brief A profiling utility. Logs a trace duration end event to the
/// timeline. If the timeline is unavailable or disabled, this has
/// no effect. This call must be preceded by a trace duration begin
/// call (via `FlutterEngineTraceEventDurationBegin`) with the same
/// name on the same thread. Can be called on any thread. Strings
/// passed into the function will NOT be copied when added to the
/// timeline. Only string literals may be passed in.
///
/// @param[in] name The name of the trace event.
///
FLUTTER_EXPORT
void FlutterEngineTraceEventDurationEnd(const char* name);
//-----------------------------------------------------------------------------
/// @brief A profiling utility. Logs a trace duration instant event to the
/// timeline. If the timeline is unavailable or disabled, this has
/// no effect. Can be called on any thread. Strings passed into the
/// function will NOT be copied when added to the timeline. Only
/// string literals may be passed in.
///
/// @param[in] name The name of the trace event.
///
FLUTTER_EXPORT
void FlutterEngineTraceEventInstant(const char* name);
//------------------------------------------------------------------------------
/// @brief Posts a task onto the Flutter render thread. Typically, this may
/// be called from any thread as long as a `FlutterEngineShutdown`
/// on the specific engine has not already been initiated.
///
/// @param[in] engine A running engine instance.
/// @param[in] callback The callback to execute on the render thread.
/// @param callback_data The callback context.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEnginePostRenderThreadTask(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
VoidCallback callback,
void* callback_data);
//------------------------------------------------------------------------------
/// @brief Get the current time in nanoseconds from the clock used by the
/// flutter engine. This is the system monotonic clock.
///
/// @return The current time in nanoseconds.
///
FLUTTER_EXPORT
uint64_t FlutterEngineGetCurrentTime();
//------------------------------------------------------------------------------
/// @brief Inform the engine to run the specified task. This task has been
/// given to the engine via the
/// `FlutterTaskRunnerDescription.post_task_callback`. This call
/// must only be made at the target time specified in that callback.
/// Running the task before that time is undefined behavior.
///
/// @param[in] engine A running engine instance.
/// @param[in] task the task handle.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterTask* task);
//------------------------------------------------------------------------------
/// @brief Notify a running engine instance that the locale has been
/// updated. The preferred locale must be the first item in the list
/// of locales supplied. The other entries will be used as a
/// fallback.
///
/// @param[in] engine A running engine instance.
/// @param[in] locales The updated locales in the order of preference.
/// @param[in] locales_count The count of locales supplied.
///
/// @return Whether the locale updates were applied.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterLocale** locales,
size_t locales_count);
//------------------------------------------------------------------------------
/// @brief Returns if the Flutter engine instance will run AOT compiled
/// Dart code. This call has no threading restrictions.
///
/// For embedder code that is configured for both AOT and JIT mode
/// Dart execution based on the Flutter engine being linked to, this
/// runtime check may be used to appropriately configure the
/// `FlutterProjectArgs`. In JIT mode execution, the kernel
/// snapshots must be present in the Flutter assets directory
/// specified in the `FlutterProjectArgs`. For AOT execution, the
/// fields `vm_snapshot_data`, `vm_snapshot_instructions`,
/// `isolate_snapshot_data` and `isolate_snapshot_instructions`
/// (along with their size fields) must be specified in
/// `FlutterProjectArgs`.
///
/// @return True, if AOT Dart code is run. JIT otherwise.
///
FLUTTER_EXPORT
bool FlutterEngineRunsAOTCompiledDartCode(void);
//------------------------------------------------------------------------------
/// @brief Posts a Dart object to specified send port. The corresponding
/// receive port for send port can be in any isolate running in the
/// VM. This isolate can also be the root isolate for an
/// unrelated engine. The engine parameter is necessary only to
/// ensure the call is not made when no engine (and hence no VM) is
/// running.
///
/// Unlike the platform messages mechanism, there are no threading
/// restrictions when using this API. Message can be posted on any
/// thread and they will be made available to isolate on which the
/// corresponding send port is listening.
///
/// However, it is the embedders responsibility to ensure that the
/// call is not made during an ongoing call the
/// `FlutterEngineDeinitialize` or `FlutterEngineShutdown` on
/// another thread.
///
/// @param[in] engine A running engine instance.
/// @param[in] port The send port to send the object to.
/// @param[in] object The object to send to the isolate with the
/// corresponding receive port.
///
/// @return If the message was posted to the send port.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEnginePostDartObject(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterEngineDartPort port,
const FlutterEngineDartObject* object);
//------------------------------------------------------------------------------
/// @brief Posts a low memory notification to a running engine instance.
/// The engine will do its best to release non-critical resources in
/// response. It is not guaranteed that the resource would have been
/// collected by the time this call returns however. The
/// notification is posted to engine subsystems that may be
/// operating on other threads.
///
/// Flutter applications can respond to these notifications by
/// setting `WidgetsBindingObserver.didHaveMemoryPressure`
/// observers.
///
/// @param[in] engine A running engine instance.
///
/// @return If the low memory notification was sent to the running engine
/// instance.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineNotifyLowMemoryWarning(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
//------------------------------------------------------------------------------
/// @brief Schedule a callback to be run on all engine managed threads.
/// The engine will attempt to service this callback the next time
/// the message loop for each managed thread is idle. Since the
/// engine manages the entire lifecycle of multiple threads, there
/// is no opportunity for the embedders to finely tune the
/// priorities of threads directly, or, perform other thread
/// specific configuration (for example, setting thread names for
/// tracing). This callback gives embedders a chance to affect such
/// tuning.
///
/// @attention This call is expensive and must be made as few times as
/// possible. The callback must also return immediately as not doing
/// so may risk performance issues (especially for callbacks of type
/// kFlutterNativeThreadTypeUI and kFlutterNativeThreadTypeRender).
///
/// @attention Some callbacks (especially the ones of type
/// kFlutterNativeThreadTypeWorker) may be called after the
/// FlutterEngine instance has shut down. Embedders must be careful
/// in handling the lifecycle of objects associated with the user
/// data baton.
///
/// @attention In case there are multiple running Flutter engine instances,
/// their workers are shared.
///
/// @param[in] engine A running engine instance.
/// @param[in] callback The callback that will get called multiple times on
/// each engine managed thread.
/// @param[in] user_data A baton passed by the engine to the callback. This
/// baton is not interpreted by the engine in any way.
///
/// @return Returns if the callback was successfully posted to all threads.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEnginePostCallbackOnAllNativeThreads(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterNativeThreadCallback callback,
void* user_data);
//------------------------------------------------------------------------------
/// @brief Posts updates corresponding to display changes to a running engine
/// instance.
///
/// @param[in] update_type The type of update pushed to the engine.
/// @param[in] displays The displays affected by this update.
/// @param[in] display_count Size of the displays array, must be at least 1.
///
/// @return the result of the call made to the engine.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineNotifyDisplayUpdate(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* displays,
size_t display_count);
//------------------------------------------------------------------------------
/// @brief Schedule a new frame to redraw the content.
///
/// @param[in] engine A running engine instance.
///
/// @return the result of the call made to the engine.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineScheduleFrame(FLUTTER_API_SYMBOL(FlutterEngine)
engine);
//------------------------------------------------------------------------------
/// @brief Schedule a callback to be called after the next frame is drawn.
/// This must be called from the platform thread. The callback is
/// executed only once from the raster thread; embedders must
/// re-thread if necessary. Performing blocking calls
/// in this callback may introduce application jank.
///
/// @param[in] engine A running engine instance.
/// @param[in] callback The callback to execute.
/// @param[in] user_data A baton passed by the engine to the callback. This
/// baton is not interpreted by the engine in any way.
///
/// @return The result of the call.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSetNextFrameCallback(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
VoidCallback callback,
void* user_data);
#endif // !FLUTTER_ENGINE_NO_PROTOTYPES
// Typedefs for the function pointers in FlutterEngineProcTable.
typedef FlutterEngineResult (*FlutterEngineCreateAOTDataFnPtr)(
const FlutterEngineAOTDataSource* source,
FlutterEngineAOTData* data_out);
typedef FlutterEngineResult (*FlutterEngineCollectAOTDataFnPtr)(
FlutterEngineAOTData data);
typedef FlutterEngineResult (*FlutterEngineRunFnPtr)(
size_t version,
const FlutterRendererConfig* config,
const FlutterProjectArgs* args,
void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) * engine_out);
typedef FlutterEngineResult (*FlutterEngineShutdownFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
typedef FlutterEngineResult (*FlutterEngineInitializeFnPtr)(
size_t version,
const FlutterRendererConfig* config,
const FlutterProjectArgs* args,
void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) * engine_out);
typedef FlutterEngineResult (*FlutterEngineDeinitializeFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
typedef FlutterEngineResult (*FlutterEngineRunInitializedFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
typedef FlutterEngineResult (*FlutterEngineSendWindowMetricsEventFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterWindowMetricsEvent* event);
typedef FlutterEngineResult (*FlutterEngineSendPointerEventFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPointerEvent* events,
size_t events_count);
typedef FlutterEngineResult (*FlutterEngineSendKeyEventFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data);
typedef FlutterEngineResult (*FlutterEngineSendPlatformMessageFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessage* message);
typedef FlutterEngineResult (
*FlutterEnginePlatformMessageCreateResponseHandleFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterDataCallback data_callback,
void* user_data,
FlutterPlatformMessageResponseHandle** response_out);
typedef FlutterEngineResult (
*FlutterEnginePlatformMessageReleaseResponseHandleFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterPlatformMessageResponseHandle* response);
typedef FlutterEngineResult (*FlutterEngineSendPlatformMessageResponseFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length);
typedef FlutterEngineResult (*FlutterEngineRegisterExternalTextureFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier);
typedef FlutterEngineResult (*FlutterEngineUnregisterExternalTextureFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier);
typedef FlutterEngineResult (
*FlutterEngineMarkExternalTextureFrameAvailableFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier);
typedef FlutterEngineResult (*FlutterEngineUpdateSemanticsEnabledFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
bool enabled);
typedef FlutterEngineResult (*FlutterEngineUpdateAccessibilityFeaturesFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature features);
typedef FlutterEngineResult (*FlutterEngineDispatchSemanticsActionFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
uint64_t id,
FlutterSemanticsAction action,
const uint8_t* data,
size_t data_length);
typedef FlutterEngineResult (*FlutterEngineOnVsyncFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
intptr_t baton,
uint64_t frame_start_time_nanos,
uint64_t frame_target_time_nanos);
typedef FlutterEngineResult (*FlutterEngineReloadSystemFontsFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
typedef void (*FlutterEngineTraceEventDurationBeginFnPtr)(const char* name);
typedef void (*FlutterEngineTraceEventDurationEndFnPtr)(const char* name);
typedef void (*FlutterEngineTraceEventInstantFnPtr)(const char* name);
typedef FlutterEngineResult (*FlutterEnginePostRenderThreadTaskFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
VoidCallback callback,
void* callback_data);
typedef uint64_t (*FlutterEngineGetCurrentTimeFnPtr)();
typedef FlutterEngineResult (*FlutterEngineRunTaskFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterTask* task);
typedef FlutterEngineResult (*FlutterEngineUpdateLocalesFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterLocale** locales,
size_t locales_count);
typedef bool (*FlutterEngineRunsAOTCompiledDartCodeFnPtr)(void);
typedef FlutterEngineResult (*FlutterEnginePostDartObjectFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterEngineDartPort port,
const FlutterEngineDartObject* object);
typedef FlutterEngineResult (*FlutterEngineNotifyLowMemoryWarningFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
typedef FlutterEngineResult (*FlutterEnginePostCallbackOnAllNativeThreadsFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterNativeThreadCallback callback,
void* user_data);
typedef FlutterEngineResult (*FlutterEngineNotifyDisplayUpdateFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterEngineDisplaysUpdateType update_type,
const FlutterEngineDisplay* displays,
size_t display_count);
typedef FlutterEngineResult (*FlutterEngineScheduleFrameFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine);
typedef FlutterEngineResult (*FlutterEngineSetNextFrameCallbackFnPtr)(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
VoidCallback callback,
void* user_data);
/// Function-pointer-based versions of the APIs above.
typedef struct {
/// The size of this struct. Must be sizeof(FlutterEngineProcs).
size_t struct_size;
FlutterEngineCreateAOTDataFnPtr CreateAOTData;
FlutterEngineCollectAOTDataFnPtr CollectAOTData;
FlutterEngineRunFnPtr Run;
FlutterEngineShutdownFnPtr Shutdown;
FlutterEngineInitializeFnPtr Initialize;
FlutterEngineDeinitializeFnPtr Deinitialize;
FlutterEngineRunInitializedFnPtr RunInitialized;
FlutterEngineSendWindowMetricsEventFnPtr SendWindowMetricsEvent;
FlutterEngineSendPointerEventFnPtr SendPointerEvent;
FlutterEngineSendKeyEventFnPtr SendKeyEvent;
FlutterEngineSendPlatformMessageFnPtr SendPlatformMessage;
FlutterEnginePlatformMessageCreateResponseHandleFnPtr
PlatformMessageCreateResponseHandle;
FlutterEnginePlatformMessageReleaseResponseHandleFnPtr
PlatformMessageReleaseResponseHandle;
FlutterEngineSendPlatformMessageResponseFnPtr SendPlatformMessageResponse;
FlutterEngineRegisterExternalTextureFnPtr RegisterExternalTexture;
FlutterEngineUnregisterExternalTextureFnPtr UnregisterExternalTexture;
FlutterEngineMarkExternalTextureFrameAvailableFnPtr
MarkExternalTextureFrameAvailable;
FlutterEngineUpdateSemanticsEnabledFnPtr UpdateSemanticsEnabled;
FlutterEngineUpdateAccessibilityFeaturesFnPtr UpdateAccessibilityFeatures;
FlutterEngineDispatchSemanticsActionFnPtr DispatchSemanticsAction;
FlutterEngineOnVsyncFnPtr OnVsync;
FlutterEngineReloadSystemFontsFnPtr ReloadSystemFonts;
FlutterEngineTraceEventDurationBeginFnPtr TraceEventDurationBegin;
FlutterEngineTraceEventDurationEndFnPtr TraceEventDurationEnd;
FlutterEngineTraceEventInstantFnPtr TraceEventInstant;
FlutterEnginePostRenderThreadTaskFnPtr PostRenderThreadTask;
FlutterEngineGetCurrentTimeFnPtr GetCurrentTime;
FlutterEngineRunTaskFnPtr RunTask;
FlutterEngineUpdateLocalesFnPtr UpdateLocales;
FlutterEngineRunsAOTCompiledDartCodeFnPtr RunsAOTCompiledDartCode;
FlutterEnginePostDartObjectFnPtr PostDartObject;
FlutterEngineNotifyLowMemoryWarningFnPtr NotifyLowMemoryWarning;
FlutterEnginePostCallbackOnAllNativeThreadsFnPtr
PostCallbackOnAllNativeThreads;
FlutterEngineNotifyDisplayUpdateFnPtr NotifyDisplayUpdate;
FlutterEngineScheduleFrameFnPtr ScheduleFrame;
FlutterEngineSetNextFrameCallbackFnPtr SetNextFrameCallback;
} FlutterEngineProcTable;
//------------------------------------------------------------------------------
/// @brief Gets the table of engine function pointers.
///
/// @param[out] table The table to fill with pointers. This should be
/// zero-initialized, except for struct_size.
///
/// @return Returns whether the table was successfully populated.
///
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineGetProcAddresses(
FlutterEngineProcTable* table);
// NOLINTEND(google-objc-function-naming)
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_H_
| engine/shell/platform/embedder/embedder.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder.h",
"repo_id": "engine",
"token_count": 44269
} | 375 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/embedder_layers.h"
#include <algorithm>
namespace flutter {
EmbedderLayers::EmbedderLayers(SkISize frame_size,
double device_pixel_ratio,
SkMatrix root_surface_transformation,
uint64_t presentation_time)
: frame_size_(frame_size),
device_pixel_ratio_(device_pixel_ratio),
root_surface_transformation_(root_surface_transformation),
presentation_time_(presentation_time) {}
EmbedderLayers::~EmbedderLayers() = default;
void EmbedderLayers::PushBackingStoreLayer(
const FlutterBackingStore* store,
const std::vector<SkIRect>& paint_region_vec) {
FlutterLayer layer = {};
layer.struct_size = sizeof(FlutterLayer);
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = store;
const auto layer_bounds =
SkRect::MakeWH(frame_size_.width(), frame_size_.height());
const auto transformed_layer_bounds =
root_surface_transformation_.mapRect(layer_bounds);
layer.offset.x = transformed_layer_bounds.x();
layer.offset.y = transformed_layer_bounds.y();
layer.size.width = transformed_layer_bounds.width();
layer.size.height = transformed_layer_bounds.height();
auto paint_region_rects = std::make_unique<std::vector<FlutterRect>>();
paint_region_rects->reserve(paint_region_vec.size());
for (const auto& rect : paint_region_vec) {
auto transformed_rect =
root_surface_transformation_.mapRect(SkRect::Make(rect));
paint_region_rects->push_back(FlutterRect{
transformed_rect.x(),
transformed_rect.y(),
transformed_rect.right(),
transformed_rect.bottom(),
});
}
auto paint_region = std::make_unique<FlutterRegion>();
paint_region->struct_size = sizeof(FlutterRegion);
paint_region->rects = paint_region_rects->data();
paint_region->rects_count = paint_region_rects->size();
rects_referenced_.push_back(std::move(paint_region_rects));
auto present_info = std::make_unique<FlutterBackingStorePresentInfo>();
present_info->struct_size = sizeof(FlutterBackingStorePresentInfo);
present_info->paint_region = paint_region.get();
regions_referenced_.push_back(std::move(paint_region));
layer.backing_store_present_info = present_info.get();
layer.presentation_time = presentation_time_;
present_info_referenced_.push_back(std::move(present_info));
presented_layers_.push_back(layer);
}
static std::unique_ptr<FlutterPlatformViewMutation> ConvertMutation(
double opacity) {
FlutterPlatformViewMutation mutation = {};
mutation.type = kFlutterPlatformViewMutationTypeOpacity;
mutation.opacity = opacity;
return std::make_unique<FlutterPlatformViewMutation>(mutation);
}
static std::unique_ptr<FlutterPlatformViewMutation> ConvertMutation(
const SkRect& rect) {
FlutterPlatformViewMutation mutation = {};
mutation.type = kFlutterPlatformViewMutationTypeClipRect;
mutation.clip_rect.left = rect.left();
mutation.clip_rect.top = rect.top();
mutation.clip_rect.right = rect.right();
mutation.clip_rect.bottom = rect.bottom();
return std::make_unique<FlutterPlatformViewMutation>(mutation);
}
static FlutterSize VectorToSize(const SkVector& vector) {
FlutterSize size = {};
size.width = vector.x();
size.height = vector.y();
return size;
}
static std::unique_ptr<FlutterPlatformViewMutation> ConvertMutation(
const SkRRect& rrect) {
FlutterPlatformViewMutation mutation = {};
mutation.type = kFlutterPlatformViewMutationTypeClipRoundedRect;
const auto& rect = rrect.rect();
mutation.clip_rounded_rect.rect.left = rect.left();
mutation.clip_rounded_rect.rect.top = rect.top();
mutation.clip_rounded_rect.rect.right = rect.right();
mutation.clip_rounded_rect.rect.bottom = rect.bottom();
mutation.clip_rounded_rect.upper_left_corner_radius =
VectorToSize(rrect.radii(SkRRect::Corner::kUpperLeft_Corner));
mutation.clip_rounded_rect.upper_right_corner_radius =
VectorToSize(rrect.radii(SkRRect::Corner::kUpperRight_Corner));
mutation.clip_rounded_rect.lower_right_corner_radius =
VectorToSize(rrect.radii(SkRRect::Corner::kLowerRight_Corner));
mutation.clip_rounded_rect.lower_left_corner_radius =
VectorToSize(rrect.radii(SkRRect::Corner::kLowerLeft_Corner));
return std::make_unique<FlutterPlatformViewMutation>(mutation);
}
static std::unique_ptr<FlutterPlatformViewMutation> ConvertMutation(
const SkMatrix& matrix) {
FlutterPlatformViewMutation mutation = {};
mutation.type = kFlutterPlatformViewMutationTypeTransformation;
mutation.transformation.scaleX = matrix[SkMatrix::kMScaleX];
mutation.transformation.skewX = matrix[SkMatrix::kMSkewX];
mutation.transformation.transX = matrix[SkMatrix::kMTransX];
mutation.transformation.skewY = matrix[SkMatrix::kMSkewY];
mutation.transformation.scaleY = matrix[SkMatrix::kMScaleY];
mutation.transformation.transY = matrix[SkMatrix::kMTransY];
mutation.transformation.pers0 = matrix[SkMatrix::kMPersp0];
mutation.transformation.pers1 = matrix[SkMatrix::kMPersp1];
mutation.transformation.pers2 = matrix[SkMatrix::kMPersp2];
return std::make_unique<FlutterPlatformViewMutation>(mutation);
}
void EmbedderLayers::PushPlatformViewLayer(
FlutterPlatformViewIdentifier identifier,
const EmbeddedViewParams& params) {
{
FlutterPlatformView view = {};
view.struct_size = sizeof(FlutterPlatformView);
view.identifier = identifier;
const auto& mutators = params.mutatorsStack();
std::vector<const FlutterPlatformViewMutation*> mutations_array;
for (auto i = mutators.Bottom(); i != mutators.Top(); ++i) {
const auto& mutator = *i;
switch (mutator->GetType()) {
case MutatorType::kClipRect: {
mutations_array.push_back(
mutations_referenced_
.emplace_back(ConvertMutation(mutator->GetRect()))
.get());
} break;
case MutatorType::kClipRRect: {
mutations_array.push_back(
mutations_referenced_
.emplace_back(ConvertMutation(mutator->GetRRect()))
.get());
} break;
case MutatorType::kClipPath: {
// Unsupported mutation.
} break;
case MutatorType::kTransform: {
const auto& matrix = mutator->GetMatrix();
if (!matrix.isIdentity()) {
mutations_array.push_back(
mutations_referenced_.emplace_back(ConvertMutation(matrix))
.get());
}
} break;
case MutatorType::kOpacity: {
const double opacity =
std::clamp(mutator->GetAlphaFloat(), 0.0f, 1.0f);
if (opacity < 1.0) {
mutations_array.push_back(
mutations_referenced_.emplace_back(ConvertMutation(opacity))
.get());
}
} break;
case MutatorType::kBackdropFilter:
break;
}
}
if (!mutations_array.empty()) {
// If there are going to be any mutations, they must first take into
// account the root surface transformation.
if (!root_surface_transformation_.isIdentity()) {
mutations_array.push_back(
mutations_referenced_
.emplace_back(ConvertMutation(root_surface_transformation_))
.get());
}
auto mutations =
std::make_unique<std::vector<const FlutterPlatformViewMutation*>>(
mutations_array.rbegin(), mutations_array.rend());
mutations_arrays_referenced_.emplace_back(std::move(mutations));
view.mutations_count = mutations_array.size();
view.mutations = mutations_arrays_referenced_.back().get()->data();
}
platform_views_referenced_.emplace_back(
std::make_unique<FlutterPlatformView>(view));
}
FlutterLayer layer = {};
layer.struct_size = sizeof(FlutterLayer);
layer.type = kFlutterLayerContentTypePlatformView;
layer.platform_view = platform_views_referenced_.back().get();
const auto layer_bounds =
SkRect::MakeXYWH(params.finalBoundingRect().x(), //
params.finalBoundingRect().y(), //
params.sizePoints().width() * device_pixel_ratio_, //
params.sizePoints().height() * device_pixel_ratio_ //
);
const auto transformed_layer_bounds =
root_surface_transformation_.mapRect(layer_bounds);
layer.offset.x = transformed_layer_bounds.x();
layer.offset.y = transformed_layer_bounds.y();
layer.size.width = transformed_layer_bounds.width();
layer.size.height = transformed_layer_bounds.height();
layer.presentation_time = presentation_time_;
presented_layers_.push_back(layer);
}
void EmbedderLayers::InvokePresentCallback(
FlutterViewId view_id,
const PresentCallback& callback) const {
std::vector<const FlutterLayer*> presented_layers_pointers;
presented_layers_pointers.reserve(presented_layers_.size());
for (const auto& layer : presented_layers_) {
presented_layers_pointers.push_back(&layer);
}
callback(view_id, presented_layers_pointers);
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_layers.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_layers.cc",
"repo_id": "engine",
"token_count": 3605
} | 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_EMBEDDER_EMBEDDER_SURFACE_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_H_
#include <memory>
#include "flutter/flow/embedded_views.h"
#include "flutter/flow/surface.h"
#include "flutter/fml/macros.h"
namespace flutter {
class EmbedderSurface {
public:
EmbedderSurface();
virtual ~EmbedderSurface();
virtual bool IsValid() const = 0;
virtual std::unique_ptr<Surface> CreateGPUSurface() = 0;
virtual std::shared_ptr<impeller::Context> CreateImpellerContext() const;
virtual sk_sp<GrDirectContext> CreateResourceContext() const;
private:
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurface);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_H_
| engine/shell/platform/embedder/embedder_surface.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_surface.h",
"repo_id": "engine",
"token_count": 332
} | 377 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_THREAD_HOST_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_THREAD_HOST_H_
#include <map>
#include <memory>
#include <set>
#include "flutter/common/task_runners.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/embedder_task_runner.h"
namespace flutter {
class EmbedderThreadHost {
public:
static std::unique_ptr<EmbedderThreadHost>
CreateEmbedderOrEngineManagedThreadHost(
const FlutterCustomTaskRunners* custom_task_runners,
const flutter::ThreadConfigSetter& config_setter =
fml::Thread::SetCurrentThreadName);
EmbedderThreadHost(
ThreadHost host,
const flutter::TaskRunners& runners,
const std::set<fml::RefPtr<EmbedderTaskRunner>>& embedder_task_runners);
~EmbedderThreadHost();
bool IsValid() const;
const flutter::TaskRunners& GetTaskRunners() const;
bool PostTask(int64_t runner, uint64_t task) const;
private:
ThreadHost host_;
flutter::TaskRunners runners_;
std::map<int64_t, fml::RefPtr<EmbedderTaskRunner>> runners_map_;
static std::unique_ptr<EmbedderThreadHost> CreateEmbedderManagedThreadHost(
const FlutterCustomTaskRunners* custom_task_runners,
const flutter::ThreadConfigSetter& config_setter =
fml::Thread::SetCurrentThreadName);
static std::unique_ptr<EmbedderThreadHost> CreateEngineManagedThreadHost(
const flutter::ThreadConfigSetter& config_setter =
fml::Thread::SetCurrentThreadName);
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderThreadHost);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_THREAD_HOST_H_
| engine/shell/platform/embedder/embedder_thread_host.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_thread_host.h",
"repo_id": "engine",
"token_count": 704
} | 378 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:core';
import 'dart:ffi' as ffi;
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'dart:ui';
void main() {}
@pragma('vm:entry-point')
void customEntrypoint() {
sayHiFromCustomEntrypoint();
}
@pragma('vm:external-name', 'SayHiFromCustomEntrypoint')
external void sayHiFromCustomEntrypoint();
@pragma('vm:entry-point')
void customEntrypoint1() {
sayHiFromCustomEntrypoint1();
sayHiFromCustomEntrypoint2();
sayHiFromCustomEntrypoint3();
}
@pragma('vm:external-name', 'SayHiFromCustomEntrypoint1')
external void sayHiFromCustomEntrypoint1();
@pragma('vm:external-name', 'SayHiFromCustomEntrypoint2')
external void sayHiFromCustomEntrypoint2();
@pragma('vm:external-name', 'SayHiFromCustomEntrypoint3')
external void sayHiFromCustomEntrypoint3();
@pragma('vm:entry-point')
void terminateExitCodeHandler() {
final ProcessResult result = Process.runSync('ls', <String>[]);
}
@pragma('vm:entry-point')
void executableNameNotNull() {
notifyStringValue(Platform.executable);
}
@pragma('vm:entry-point')
void implicitViewNotNull() {
notifyBoolValue(PlatformDispatcher.instance.implicitView != null);
}
@pragma('vm:external-name', 'NotifyStringValue')
external void notifyStringValue(String value);
@pragma('vm:external-name', 'NotifyBoolValue')
external void notifyBoolValue(bool value);
@pragma('vm:entry-point')
void invokePlatformTaskRunner() {
PlatformDispatcher.instance.sendPlatformMessage('OhHi', null, null);
}
Float64List kTestTransform = () {
final Float64List values = Float64List(16);
values[0] = 1.0; // scaleX
values[4] = 2.0; // skewX
values[12] = 3.0; // transX
values[1] = 4.0; // skewY
values[5] = 5.0; // scaleY
values[13] = 6.0; // transY
values[3] = 7.0; // pers0
values[7] = 8.0; // pers1
values[15] = 9.0; // pers2
return values;
}();
@pragma('vm:external-name', 'SignalNativeTest')
external void signalNativeTest();
@pragma('vm:external-name', 'SignalNativeCount')
external void signalNativeCount(int count);
@pragma('vm:external-name', 'SignalNativeMessage')
external void signalNativeMessage(String message);
@pragma('vm:external-name', 'NotifySemanticsEnabled')
external void notifySemanticsEnabled(bool enabled);
@pragma('vm:external-name', 'NotifyAccessibilityFeatures')
external void notifyAccessibilityFeatures(bool reduceMotion);
@pragma('vm:external-name', 'NotifySemanticsAction')
external void notifySemanticsAction(int nodeId, int action, List<int> data);
/// Returns a future that completes when
/// `PlatformDispatcher.instance.onSemanticsEnabledChanged` fires.
Future<void> get semanticsChanged {
final Completer<void> semanticsChanged = Completer<void>();
PlatformDispatcher.instance.onSemanticsEnabledChanged =
semanticsChanged.complete;
return semanticsChanged.future;
}
/// Returns a future that completes when
/// `PlatformDispatcher.instance.onAccessibilityFeaturesChanged` fires.
Future<void> get accessibilityFeaturesChanged {
final Completer<void> featuresChanged = Completer<void>();
PlatformDispatcher.instance.onAccessibilityFeaturesChanged =
featuresChanged.complete;
return featuresChanged.future;
}
Future<SemanticsActionEvent> get semanticsActionEvent {
final Completer<SemanticsActionEvent> actionReceived =
Completer<SemanticsActionEvent>();
PlatformDispatcher.instance.onSemanticsActionEvent =
(SemanticsActionEvent action) {
actionReceived.complete(action);
};
return actionReceived.future;
}
@pragma('vm:entry-point')
Future<void> a11y_main() async {
// 1: Return initial state (semantics disabled).
notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled);
// 2: Await semantics enabled from embedder.
await semanticsChanged;
notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled);
// 3: Return initial state of accessibility features.
notifyAccessibilityFeatures(
PlatformDispatcher.instance.accessibilityFeatures.reduceMotion);
// 4: Await accessibility features changed from embedder.
await accessibilityFeaturesChanged;
notifyAccessibilityFeatures(
PlatformDispatcher.instance.accessibilityFeatures.reduceMotion);
// 5: Fire semantics update.
final SemanticsUpdateBuilder builder = SemanticsUpdateBuilder()
..updateNode(
id: 42,
identifier: '',
label: 'A: root',
labelAttributes: <StringAttribute>[],
rect: Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
transform: kTestTransform,
childrenInTraversalOrder: Int32List.fromList(<int>[84, 96]),
childrenInHitTestOrder: Int32List.fromList(<int>[96, 84]),
actions: 0,
flags: 0,
maxValueLength: 0,
currentValueLength: 0,
textSelectionBase: 0,
textSelectionExtent: 0,
platformViewId: 0,
scrollChildren: 0,
scrollIndex: 0,
scrollPosition: 0.0,
scrollExtentMax: 0.0,
scrollExtentMin: 0.0,
elevation: 0.0,
thickness: 0.0,
hint: '',
hintAttributes: <StringAttribute>[],
value: '',
valueAttributes: <StringAttribute>[],
increasedValue: '',
increasedValueAttributes: <StringAttribute>[],
decreasedValue: '',
decreasedValueAttributes: <StringAttribute>[],
tooltip: 'tooltip',
textDirection: TextDirection.ltr,
additionalActions: Int32List(0),
)
..updateNode(
id: 84,
identifier: '',
label: 'B: leaf',
labelAttributes: <StringAttribute>[],
rect: Rect.fromLTRB(40.0, 40.0, 80.0, 80.0),
transform: kTestTransform,
actions: 0,
flags: 0,
maxValueLength: 0,
currentValueLength: 0,
textSelectionBase: 0,
textSelectionExtent: 0,
platformViewId: 0,
scrollChildren: 0,
scrollIndex: 0,
scrollPosition: 0.0,
scrollExtentMax: 0.0,
scrollExtentMin: 0.0,
elevation: 0.0,
thickness: 0.0,
hint: '',
hintAttributes: <StringAttribute>[],
value: '',
valueAttributes: <StringAttribute>[],
increasedValue: '',
increasedValueAttributes: <StringAttribute>[],
decreasedValue: '',
decreasedValueAttributes: <StringAttribute>[],
tooltip: 'tooltip',
textDirection: TextDirection.ltr,
additionalActions: Int32List(0),
childrenInHitTestOrder: Int32List(0),
childrenInTraversalOrder: Int32List(0),
)
..updateNode(
id: 96,
identifier: '',
label: 'C: branch',
labelAttributes: <StringAttribute>[],
rect: Rect.fromLTRB(40.0, 40.0, 80.0, 80.0),
transform: kTestTransform,
childrenInTraversalOrder: Int32List.fromList(<int>[128]),
childrenInHitTestOrder: Int32List.fromList(<int>[128]),
actions: 0,
flags: 0,
maxValueLength: 0,
currentValueLength: 0,
textSelectionBase: 0,
textSelectionExtent: 0,
platformViewId: 0,
scrollChildren: 0,
scrollIndex: 0,
scrollPosition: 0.0,
scrollExtentMax: 0.0,
scrollExtentMin: 0.0,
elevation: 0.0,
thickness: 0.0,
hint: '',
hintAttributes: <StringAttribute>[],
value: '',
valueAttributes: <StringAttribute>[],
increasedValue: '',
increasedValueAttributes: <StringAttribute>[],
decreasedValue: '',
decreasedValueAttributes: <StringAttribute>[],
tooltip: 'tooltip',
textDirection: TextDirection.ltr,
additionalActions: Int32List(0),
)
..updateNode(
id: 128,
identifier: '',
label: 'D: leaf',
labelAttributes: <StringAttribute>[],
rect: Rect.fromLTRB(40.0, 40.0, 80.0, 80.0),
transform: kTestTransform,
additionalActions: Int32List.fromList(<int>[21]),
platformViewId: 0x3f3,
actions: 0,
flags: 0,
maxValueLength: 0,
currentValueLength: 0,
textSelectionBase: 0,
textSelectionExtent: 0,
scrollChildren: 0,
scrollIndex: 0,
scrollPosition: 0.0,
scrollExtentMax: 0.0,
scrollExtentMin: 0.0,
elevation: 0.0,
thickness: 0.0,
hint: '',
hintAttributes: <StringAttribute>[],
value: '',
valueAttributes: <StringAttribute>[],
increasedValue: '',
increasedValueAttributes: <StringAttribute>[],
decreasedValue: '',
decreasedValueAttributes: <StringAttribute>[],
tooltip: 'tooltip',
textDirection: TextDirection.ltr,
childrenInHitTestOrder: Int32List(0),
childrenInTraversalOrder: Int32List(0),
)
..updateCustomAction(
id: 21,
label: 'Archive',
hint: 'archive message',
);
PlatformDispatcher.instance.views.first.updateSemantics(builder.build());
signalNativeTest();
// 6: Await semantics action from embedder.
final SemanticsActionEvent data = await semanticsActionEvent;
final List<int> actionArgs = <int>[
(data.arguments! as ByteData).getInt8(0),
(data.arguments! as ByteData).getInt8(1)
];
notifySemanticsAction(data.nodeId, data.type.index, actionArgs);
// 7: Await semantics disabled from embedder.
await semanticsChanged;
notifySemanticsEnabled(PlatformDispatcher.instance.semanticsEnabled);
}
@pragma('vm:entry-point')
Future<void> a11y_string_attributes() async {
// 1: Wait until semantics are enabled.
if (!PlatformDispatcher.instance.semanticsEnabled) {
await semanticsChanged;
}
// 2: Update semantics with string attributes.
final SemanticsUpdateBuilder builder = SemanticsUpdateBuilder()
..updateNode(
id: 42,
identifier: 'identifier',
label: 'What is the meaning of life?',
labelAttributes: <StringAttribute>[
LocaleStringAttribute(
range: TextRange(start: 0, end: 'What is the meaning of life?'.length),
locale: Locale('en'),
),
SpellOutStringAttribute(
range: TextRange(start: 0, end: 1),
),
],
rect: Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
transform: kTestTransform,
childrenInTraversalOrder: Int32List.fromList(<int>[84, 96]),
childrenInHitTestOrder: Int32List.fromList(<int>[96, 84]),
actions: 0,
flags: 0,
maxValueLength: 0,
currentValueLength: 0,
textSelectionBase: 0,
textSelectionExtent: 0,
platformViewId: 0,
scrollChildren: 0,
scrollIndex: 0,
scrollPosition: 0.0,
scrollExtentMax: 0.0,
scrollExtentMin: 0.0,
elevation: 0.0,
thickness: 0.0,
hint: "It's a number",
hintAttributes: <StringAttribute>[
LocaleStringAttribute(
range: TextRange(start: 0, end: 1),
locale: Locale('en'),
),
LocaleStringAttribute(
range: TextRange(start: 2, end: 3),
locale: Locale('fr'),
),
],
value: '42',
valueAttributes: <StringAttribute>[
LocaleStringAttribute(
range: TextRange(start: 0, end: '42'.length),
locale: Locale('en', 'US'),
),
],
increasedValue: '43',
increasedValueAttributes: <StringAttribute>[
SpellOutStringAttribute(
range: TextRange(start: 0, end: 1),
),
SpellOutStringAttribute(
range: TextRange(start: 1, end: 2),
),
],
decreasedValue: '41',
decreasedValueAttributes: <StringAttribute>[],
tooltip: 'tooltip',
textDirection: TextDirection.ltr,
additionalActions: Int32List(0),
);
PlatformDispatcher.instance.views.first.updateSemantics(builder.build());
signalNativeTest();
}
@pragma('vm:entry-point')
void platform_messages_response() {
PlatformDispatcher.instance.onPlatformMessage =
(String name, ByteData? data, PlatformMessageResponseCallback? callback) {
callback!(data);
};
signalNativeTest();
}
@pragma('vm:entry-point')
void platform_messages_no_response() {
PlatformDispatcher.instance.onPlatformMessage =
(String name, ByteData? data, PlatformMessageResponseCallback? callback) {
final Uint8List list = data!.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
signalNativeMessage(utf8.decode(list));
// This does nothing because no one is listening on the other side. But complete the loop anyway
// to make sure all null checking on response handles in the engine is in place.
callback!(data);
};
signalNativeTest();
}
@pragma('vm:entry-point')
void null_platform_messages() {
PlatformDispatcher.instance.onPlatformMessage =
(String name, ByteData? data, PlatformMessageResponseCallback? callback) {
// This checks if the platform_message null data is converted to Flutter null.
signalNativeMessage((null == data).toString());
callback!(data);
};
signalNativeTest();
}
Picture CreateSimplePicture() {
final Paint blackPaint = Paint();
final Paint whitePaint = Paint()..color = Color.fromARGB(255, 255, 255, 255);
final PictureRecorder baseRecorder = PictureRecorder();
final Canvas canvas = Canvas(baseRecorder);
canvas.drawRect(Rect.fromLTRB(0.0, 0.0, 1000.0, 1000.0), blackPaint);
canvas.drawRect(Rect.fromLTRB(10.0, 10.0, 990.0, 990.0), whitePaint);
return baseRecorder.endRecording();
}
@pragma('vm:entry-point')
void can_composite_platform_views() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.addPicture(Offset(1.0, 1.0), CreateSimplePicture());
builder.pushOffset(1.0, 2.0);
builder.addPlatformView(42, width: 123.0, height: 456.0);
builder.addPicture(Offset(1.0, 1.0), CreateSimplePicture());
builder.pop(); // offset
signalNativeTest(); // Signal 2
PlatformDispatcher.instance.views.first.render(builder.build());
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_composite_platform_views_with_opacity() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
// Root node
builder.pushOffset(1.0, 2.0);
// First sibling layer (no platform view, should be cached)
builder.pushOpacity(127);
builder.addPicture(Offset(1.0, 1.0), CreateSimplePicture());
builder.pop();
// Second sibling layer (platform view, should not be cached)
builder.pushOpacity(127);
builder.addPlatformView(42, width: 123.0, height: 456.0);
builder.pop();
// Third sibling layer (no platform view, should be cached)
builder.pushOpacity(127);
builder.addPicture(Offset(2.0, 1.0), CreateSimplePicture());
builder.pop();
signalNativeTest(); // Signal 2
PlatformDispatcher.instance.views.first.render(builder.build());
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_composite_with_opacity() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOpacity(127);
builder.addPicture(Offset(1.0, 1.0), CreateSimplePicture());
builder.pop(); // offset
signalNativeTest(); // Signal 2
PlatformDispatcher.instance.views.first.render(builder.build());
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
Picture CreateColoredBox(Color color, Size size) {
final Paint paint = Paint();
paint.color = color;
final PictureRecorder baseRecorder = PictureRecorder();
final Canvas canvas = Canvas(baseRecorder);
canvas.drawRect(Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint);
return baseRecorder.endRecording();
}
@pragma('vm:entry-point')
void can_composite_platform_views_with_known_scene() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Color blue = Color.fromARGB(127, 0, 0, 255);
final Color gray = Color.fromARGB(127, 127, 127, 127);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
// 10 (Index 0)
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pushOffset(20.0, 20.0);
// 20 (Index 1)
builder.addPlatformView(1,
width: size.width, height: size.height); // green - platform
builder.pop();
// 30 (Index 2)
builder.addPicture(
Offset(30.0, 30.0), CreateColoredBox(blue, size)); // blue - flutter
builder.pushOffset(40.0, 40.0);
// 40 (Index 3)
builder.addPlatformView(2,
width: size.width, height: size.height); // magenta - platform
builder.pop();
// 50 (Index 4)
builder.addPicture(
Offset(50.0, 50.0), CreateColoredBox(gray, size)); // gray - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest(); // Signal 2
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_composite_platform_views_transparent_overlay() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Color blue = Color.fromARGB(127, 0, 0, 255);
final Color transparent = Color(0xFFFFFF);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
// 10 (Index 0)
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pushOffset(20.0, 20.0);
// 20 (Index 1)
builder.addPlatformView(1,
width: size.width, height: size.height); // green - platform
builder.pop();
// 30 (Index 2)
builder.addPicture(
Offset(30.0, 30.0), CreateColoredBox(transparent, size)); // transparent picture, no layer should be created.
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest(); // Signal 2
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_composite_platform_views_no_overlay() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Color blue = Color.fromARGB(127, 0, 0, 255);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
// 10 (Index 0)
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pushOffset(20.0, 20.0);
// 20 (Index 1)
builder.addPlatformView(1,
width: size.width, height: size.height); // green - platform
builder.pop();
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest(); // Signal 2
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_composite_platform_views_with_root_layer_only() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
// 10 (Index 0)
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest(); // Signal 2
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_composite_platform_views_with_platform_layer_on_bottom() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
// 10 (Index 0)
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pushOffset(20.0, 20.0);
// 20 (Index 1)
builder.addPlatformView(1,
width: size.width, height: size.height); // green - platform
builder.pop();
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest(); // Signal 2
};
signalNativeTest(); // Signal 1
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:external-name', 'SignalBeginFrame')
external void signalBeginFrame();
@pragma('vm:entry-point')
Future<void> texture_destruction_callback_called_without_custom_compositor() async {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_render_scene_without_custom_compositor() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Color green = Color.fromARGB(127, 0, 255, 0);
final Color blue = Color.fromARGB(127, 0, 0, 255);
final Color magenta = Color.fromARGB(127, 255, 0, 255);
final Color gray = Color.fromARGB(127, 127, 127, 127);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.addPicture(
Offset(20.0, 20.0), CreateColoredBox(green, size)); // green - flutter
builder.addPicture(
Offset(30.0, 30.0), CreateColoredBox(blue, size)); // blue - flutter
builder.addPicture(Offset(40.0, 40.0),
CreateColoredBox(magenta, size)); // magenta - flutter
builder.addPicture(
Offset(50.0, 50.0), CreateColoredBox(gray, size)); // gray - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
Picture CreateGradientBox(Size size) {
final Paint paint = Paint();
final List<Color> rainbow = <Color>[
Color.fromARGB(255, 255, 0, 0), // red
Color.fromARGB(255, 255, 165, 0), // orange
Color.fromARGB(255, 255, 255, 0), // yellow
Color.fromARGB(255, 0, 255, 0), // green
Color.fromARGB(255, 0, 0, 255), // blue
Color.fromARGB(255, 75, 0, 130), // indigo
Color.fromARGB(255, 238, 130, 238), // violet
];
final List<double> stops = <double>[
(1.0 / 7.0),
(2.0 / 7.0),
(3.0 / 7.0),
(4.0 / 7.0),
(5.0 / 7.0),
(6.0 / 7.0),
(7.0 / 7.0),
];
paint.shader = Gradient.linear(
Offset(0.0, 0.0), Offset(size.width, size.height), rainbow, stops);
final PictureRecorder baseRecorder = PictureRecorder();
final Canvas canvas = Canvas(baseRecorder);
canvas.drawRect(Rect.fromLTRB(0.0, 0.0, size.width, size.height), paint);
return baseRecorder.endRecording();
}
@pragma('vm:external-name', 'EchoKeyEvent')
external void _echoKeyEvent(int change, int timestamp, int physical,
int logical, int charCode, bool synthesized, int deviceType);
// Convert `kind` in enum form to its integer form.
//
// It performs a reversed mapping from `UnserializeKeyEventType`
// in shell/platform/embedder/tests/embedder_unittests.cc.
int _serializeKeyEventType(KeyEventType change) {
switch (change) {
case KeyEventType.up:
return 1;
case KeyEventType.down:
return 2;
case KeyEventType.repeat:
return 3;
}
}
// Convert `deviceType` in enum form to its integer form.
//
// It performs a reversed mapping from `UnserializeKeyEventDeviceType`
// in shell/platform/embedder/tests/embedder_unittests.cc.
int _serializeKeyEventDeviceType(KeyEventDeviceType deviceType) {
switch (deviceType) {
case KeyEventDeviceType.keyboard:
return 1;
case KeyEventDeviceType.directionalPad:
return 2;
case KeyEventDeviceType.gamepad:
return 3;
case KeyEventDeviceType.joystick:
return 4;
case KeyEventDeviceType.hdmi:
return 5;
}
}
// Echo the event data with `_echoKeyEvent`, and returns synthesized as handled.
@pragma('vm:entry-point')
Future<void> key_data_echo() async {
PlatformDispatcher.instance.onKeyData = (KeyData data) {
_echoKeyEvent(
_serializeKeyEventType(data.type),
data.timeStamp.inMicroseconds,
data.physical,
data.logical,
data.character == null ? 0 : data.character!.codeUnitAt(0),
data.synthesized,
_serializeKeyEventDeviceType(data.deviceType),
);
return data.synthesized;
};
signalNativeTest();
}
// After platform channel 'test/starts_echo' receives a message, starts echoing
// the event data with `_echoKeyEvent`, and returns synthesized as handled.
@pragma('vm:entry-point')
Future<void> key_data_late_echo() async {
channelBuffers.setListener('test/starts_echo',
(ByteData? data, PlatformMessageResponseCallback callback) {
PlatformDispatcher.instance.onKeyData = (KeyData data) {
_echoKeyEvent(
_serializeKeyEventType(data.type),
data.timeStamp.inMicroseconds,
data.physical,
data.logical,
data.character == null ? 0 : data.character!.codeUnitAt(0),
data.synthesized,
_serializeKeyEventDeviceType(data.deviceType),
);
return data.synthesized;
};
callback(null);
});
signalNativeTest();
}
@pragma('vm:entry-point')
void render_implicit_view() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Size size = Size(800.0, 600.0);
final Color red = Color.fromARGB(127, 255, 0, 0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset(0.0, 0.0), CreateColoredBox(red, size));
builder.pop();
PlatformDispatcher.instance.implicitView?.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void render_gradient() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Size size = Size(800.0, 600.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset(0.0, 0.0), CreateGradientBox(size)); // gradient - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void render_texture() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Size size = Size(800.0, 600.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addTexture(/*textureId*/ 1, width: size.width, height: size.height);
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void render_gradient_on_non_root_backing_store() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Size size = Size(800.0, 600.0);
final Color red = Color.fromARGB(127, 255, 0, 0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
// Even though this is occluded, add something so it is not elided.
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.addPlatformView(1, width: 100, height: 200); // undefined - platform
builder.addPicture(
Offset(0.0, 0.0), CreateGradientBox(size)); // gradient - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void verify_b141980393() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
// The platform view in the test case is screen sized but with margins of 31
// and 37 points from the top and bottom.
const double topMargin = 31.0;
const double bottomMargin = 37.0;
final Size platformViewSize = Size(800.0, 600.0 - topMargin - bottomMargin);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(
0.0, // x
topMargin // y
);
// The web view in example.
builder.addPlatformView(1337,
width: platformViewSize.width, height: platformViewSize.height);
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_display_platform_view_with_pixel_ratio() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushTransform(Float64List.fromList(<double>[
2.0,
0.0,
0.0,
0.0,
0.0,
2.0,
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
0.0,
0.0,
0.0,
1.0
])); // base
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(400.0, 300.0)));
builder.pushOffset(0.0, 20.0); // offset
builder.addPlatformView(42, width: 400.0, height: 280.0);
builder.pop(); // offset
builder.addPicture(Offset(0.0, 0.0),
CreateColoredBox(Color.fromARGB(128, 255, 0, 0), Size(400.0, 300.0)));
builder.pop(); // base
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_receive_locale_updates() {
PlatformDispatcher.instance.onLocaleChanged = () {
signalNativeCount(PlatformDispatcher.instance.locales.length);
};
signalNativeTest();
}
// Verifies behavior tracked in https://github.com/flutter/flutter/issues/43732
@pragma('vm:entry-point')
void verify_b143464703() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0); // base
// Background
builder.addPicture(
Offset(0.0, 0.0),
CreateColoredBox(
Color.fromARGB(255, 128, 128, 128), Size(1024.0, 600.0)));
builder.pushOpacity(128);
builder.addPicture(Offset(10.0, 10.0),
CreateColoredBox(Color.fromARGB(255, 0, 0, 255), Size(25.0, 25.0)));
builder.pop(); // opacity 128
// The top bar and the platform view are pushed to the side.
builder.pushOffset(135.0, 0.0); // 1
builder.pushOpacity(128); // opacity
// Platform view offset from the top
builder.pushOffset(0.0, 60.0); // 2
builder.addPlatformView(42, width: 1024.0, height: 540.0);
builder.pop(); // 2
// Top bar
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(1024.0, 60.0)));
builder.pop(); // opacity
builder.pop(); // 1
builder.pop(); // base
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void push_frames_over_and_over() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset(0.0, 0.0),
CreateColoredBox(
Color.fromARGB(255, 128, 128, 128), Size(1024.0, 600.0)));
builder.pushOpacity(128);
builder.addPlatformView(42, width: 1024.0, height: 540.0);
builder.pop();
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest();
PlatformDispatcher.instance.scheduleFrame();
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void platform_view_mutators() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0); // base
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(800.0, 600.0)));
builder.pushOpacity(128);
builder.pushClipRect(Rect.fromLTWH(10.0, 10.0, 800.0 - 20.0, 600.0 - 20.0));
builder.pushClipRRect(RRect.fromLTRBR(
10.0, 10.0, 800.0 - 10.0, 600.0 - 10.0, Radius.circular(14.0)));
builder.addPlatformView(42, width: 800.0, height: 600.0);
builder.pop(); // clip rrect
builder.pop(); // clip rect
builder.pop(); // opacity
builder.pop(); // base
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void platform_view_mutators_with_pixel_ratio() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0); // base
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(400.0, 300.0)));
builder.pushOpacity(128);
builder.pushClipRect(Rect.fromLTWH(5.0, 5.0, 400.0 - 10.0, 300.0 - 10.0));
builder.pushClipRRect(RRect.fromLTRBR(
5.0, 5.0, 400.0 - 5.0, 300.0 - 5.0, Radius.circular(7.0)));
builder.addPlatformView(42, width: 400.0, height: 300.0);
builder.pop(); // clip rrect
builder.pop(); // clip rect
builder.pop(); // opacity
builder.pop(); // base
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void empty_scene() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
PlatformDispatcher.instance.views.first.render(SceneBuilder().build());
signalNativeTest();
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void scene_with_no_container() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(400.0, 300.0)));
PlatformDispatcher.instance.views.first.render(builder.build());
signalNativeTest();
};
PlatformDispatcher.instance.scheduleFrame();
}
Picture CreateArcEndCapsPicture() {
final PictureRecorder baseRecorder = PictureRecorder();
final Canvas canvas = Canvas(baseRecorder);
final style = Paint()
..strokeWidth = 12.0
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.miter;
style.color = Color.fromARGB(255, 255, 0, 0);
canvas.drawArc(
Rect.fromLTRB(0.0, 0.0, 500.0, 500.0), 1.57, 1.0, false, style);
return baseRecorder.endRecording();
}
@pragma('vm:entry-point')
void arc_end_caps_correct() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.addPicture(Offset(0.0, 0.0), CreateArcEndCapsPicture());
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void scene_builder_with_clips() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushClipRect(Rect.fromLTRB(10.0, 10.0, 390.0, 290.0));
builder.addPlatformView(42, width: 400.0, height: 300.0);
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(400.0, 300.0)));
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void scene_builder_with_complex_clips() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushClipRect(Rect.fromLTRB(0.0, 0.0, 1024.0, 600.0));
builder.pushOffset(512.0, 0.0);
builder.pushClipRect(Rect.fromLTRB(0.0, 0.0, 512.0, 600.0));
builder.pushOffset(-256.0, 0.0);
builder.pushClipRect(Rect.fromLTRB(0.0, 0.0, 1024.0, 600.0));
builder.addPlatformView(42, width: 1024.0, height: 600.0);
builder.addPicture(
Offset(0.0, 0.0), CreateGradientBox(Size(1024.0, 600.0)));
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:external-name', 'SendObjectToNativeCode')
external void sendObjectToNativeCode(dynamic object);
@pragma('vm:entry-point')
void objects_can_be_posted() {
final ReceivePort port = ReceivePort();
port.listen((dynamic message) {
sendObjectToNativeCode(message);
});
signalNativeCount(port.sendPort.nativePort);
}
@pragma('vm:entry-point')
void empty_scene_posts_zero_layers_to_compositor() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
// Should not render anything.
builder.pushClipRect(Rect.fromLTRB(0.0, 0.0, 300.0, 200.0));
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void compositor_can_post_only_platform_views() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.addPlatformView(42, width: 300.0, height: 200.0);
builder.addPlatformView(24, width: 300.0, height: 200.0);
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void render_targets_are_recycled() {
int frameCount = 0;
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
for (int i = 0; i < 10; i++) {
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(30.0, 20.0)));
builder.addPlatformView(42 + i, width: 30.0, height: 20.0);
}
PlatformDispatcher.instance.views.first.render(builder.build());
frameCount++;
if (frameCount == 8) {
signalNativeTest();
} else {
PlatformDispatcher.instance.scheduleFrame();
}
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void render_targets_are_in_stable_order() {
int frameCount = 0;
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
for (int i = 0; i < 10; i++) {
builder.addPicture(Offset(0.0, 0.0), CreateGradientBox(Size(30.0, 20.0)));
builder.addPlatformView(42 + i, width: 30.0, height: 20.0);
}
PlatformDispatcher.instance.views.first.render(builder.build());
PlatformDispatcher.instance.scheduleFrame();
frameCount++;
if (frameCount == 8) {
signalNativeTest();
}
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:external-name', 'NativeArgumentsCallback')
external void nativeArgumentsCallback(List<String> args);
@pragma('vm:entry-point')
void custom_logger(List<String> args) {
print('hello world');
}
@pragma('vm:entry-point')
void dart_entrypoint_args(List<String> args) {
nativeArgumentsCallback(args);
}
@pragma('vm:external-name', 'SnapshotsCallback')
external void snapshotsCallback(Image bigImage, Image smallImage);
@pragma('vm:entry-point')
Future<void> snapshot_large_scene(int maxSize) async {
// Set width to double the max size, which will result in height being half the max size after scaling.
double width = maxSize * 2.0, height = maxSize.toDouble();
PictureRecorder recorder = PictureRecorder();
{
final Canvas canvas = Canvas(recorder, Rect.fromLTWH(0, 0, width, height));
final Paint paint = Paint();
// Bottom left
paint.color = Color.fromARGB(255, 100, 255, 100);
canvas.drawRect(Rect.fromLTWH(0, height / 2, width / 2, height / 2), paint);
// Top right
paint.color = Color.fromARGB(255, 100, 100, 255);
canvas.drawRect(Rect.fromLTWH(width / 2, 0, width / 2, height / 2), paint);
}
Picture picture = recorder.endRecording();
final Image bigImage = await picture.toImage(width.toInt(), height.toInt());
// The max size varies across hardware/drivers, so normalize the result to a smaller target size in
// order to reliably test against an image fixture.
double smallWidth = 128, smallHeight = 64;
recorder = PictureRecorder();
{
final Canvas canvas =
Canvas(recorder, Rect.fromLTWH(0, 0, smallWidth, smallHeight));
canvas.scale(smallWidth / bigImage.width);
canvas.drawImage(bigImage, Offset.zero, Paint());
}
picture = recorder.endRecording();
final Image smallImage =
await picture.toImage(smallWidth.toInt(), smallHeight.toInt());
snapshotsCallback(bigImage, smallImage);
}
@pragma('vm:entry-point')
void invalid_backingstore() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Color red = Color.fromARGB(127, 255, 0, 0);
final Size size = Size(50.0, 150.0);
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset(10.0, 10.0), CreateColoredBox(red, size)); // red - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.onDrawFrame = () {
signalNativeTest();
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void can_schedule_frame() {
PlatformDispatcher.instance.onBeginFrame = (Duration beginTime) {
signalNativeCount(beginTime.inMicroseconds);
};
signalNativeTest();
}
void drawSolidColor(Color c) {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
builder.addPicture(
Offset.zero,
CreateColoredBox(
c, PlatformDispatcher.instance.views.first.physicalSize));
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void draw_solid_red() {
drawSolidColor(const Color.fromARGB(255, 255, 0, 0));
}
@pragma('vm:entry-point')
void draw_solid_green() {
drawSolidColor(const Color.fromARGB(255, 0, 255, 0));
}
@pragma('vm:entry-point')
void draw_solid_blue() {
drawSolidColor(const Color.fromARGB(255, 0, 0, 255));
}
@pragma('vm:entry-point')
void pointer_data_packet() {
PlatformDispatcher.instance.onPointerDataPacket =
(PointerDataPacket packet) {
signalNativeCount(packet.data.length);
for (final PointerData pointerData in packet.data) {
signalNativeMessage(pointerData.toString());
}
};
signalNativeTest();
}
@pragma('vm:entry-point')
void pointer_data_packet_view_id() {
PlatformDispatcher.instance.onPointerDataPacket = (PointerDataPacket packet) {
assert(packet.data.length == 1);
for (final PointerData pointerData in packet.data) {
signalNativeMessage('ViewID: ${pointerData.viewId}');
}
};
signalNativeTest();
}
Map<int, Size> _getAllViewSizes() {
final Map<int, Size> result = <int, Size>{};
for (final FlutterView view in PlatformDispatcher.instance.views) {
result[view.viewId] = view.physicalSize;
}
return result;
}
List<int> _findDifferences(Map<int, Size> a, Map<int, Size> b) {
final Set<int> result = <int>{};
a.forEach((int viewId, Size sizeA) {
if (!b.containsKey(viewId) || b[viewId] != sizeA) {
result.add(viewId);
}
});
b.forEach((int viewId, Size sizeB) {
if (!a.containsKey(viewId)) {
result.add(viewId);
}
});
return result.toList()..sort();
}
@pragma('vm:entry-point')
void window_metrics_event_view_id() {
Map<int, Size> sizes = _getAllViewSizes();
PlatformDispatcher.instance.onMetricsChanged = () {
final Map<int, Size> newSizes = _getAllViewSizes();
final List<int> differences = _findDifferences(sizes, newSizes);
sizes = newSizes;
signalNativeMessage('Changed: $differences');
};
signalNativeTest();
}
@pragma('vm:entry-point')
Future<void> channel_listener_response() async {
channelBuffers.setListener('test/listen',
(ByteData? data, PlatformMessageResponseCallback callback) {
callback(null);
});
signalNativeTest();
}
@pragma('vm:entry-point')
void render_gradient_retained() {
OffsetEngineLayer? offsetLayer; // Retain the offset layer.
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final Size size = Size(800.0, 600.0);
final SceneBuilder builder = SceneBuilder();
offsetLayer = builder.pushOffset(0.0, 0.0, oldLayer: offsetLayer);
// display_list_layer will comparing the display_list
// no need to retain the picture
builder.addPicture(
Offset(0.0, 0.0), CreateGradientBox(size)); // gradient - flutter
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
@pragma('vm:entry-point')
void render_impeller_gl_test() {
PlatformDispatcher.instance.onBeginFrame = (Duration duration) {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(0.0, 0.0);
final Paint paint = Paint();
paint.color = Color.fromARGB(255, 0, 0, 255);
final PictureRecorder baseRecorder = PictureRecorder();
final Canvas canvas = Canvas(baseRecorder);
canvas.drawPaint(Paint()..color = Color.fromARGB(255, 255, 0, 0));
canvas.drawRect(Rect.fromLTRB(20.0, 20.0, 200.0, 150.0), paint);
builder.addPicture(Offset.zero, baseRecorder.endRecording());
builder.pop();
PlatformDispatcher.instance.views.first.render(builder.build());
};
PlatformDispatcher.instance.scheduleFrame();
}
| engine/shell/platform/embedder/fixtures/main.dart/0 | {
"file_path": "engine/shell/platform/embedder/fixtures/main.dart",
"repo_id": "engine",
"token_count": 17006
} | 379 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_ASSERTIONS_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_ASSERTIONS_H_
#include <sstream>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/embedder_engine.h"
#include "flutter/testing/assertions.h"
#include "gtest/gtest.h"
#include "third_party/skia/include/core/SkPoint.h"
#include "third_party/skia/include/core/SkSize.h"
// NOLINTBEGIN(google-objc-function-naming)
//------------------------------------------------------------------------------
// Equality
//------------------------------------------------------------------------------
inline bool operator==(const FlutterPoint& a, const FlutterPoint& b) {
return flutter::testing::NumberNear(a.x, b.x) &&
flutter::testing::NumberNear(a.y, b.y);
}
inline bool operator==(const FlutterRect& a, const FlutterRect& b) {
return flutter::testing::NumberNear(a.left, b.left) &&
flutter::testing::NumberNear(a.top, b.top) &&
flutter::testing::NumberNear(a.right, b.right) &&
flutter::testing::NumberNear(a.bottom, b.bottom);
}
inline bool operator==(const FlutterSize& a, const FlutterSize& b) {
return flutter::testing::NumberNear(a.width, b.width) &&
flutter::testing::NumberNear(a.height, b.height);
}
inline bool operator==(const FlutterRoundedRect& a,
const FlutterRoundedRect& b) {
return a.rect == b.rect &&
a.upper_left_corner_radius == b.upper_left_corner_radius &&
a.upper_right_corner_radius == b.upper_right_corner_radius &&
a.lower_right_corner_radius == b.lower_right_corner_radius &&
a.lower_left_corner_radius == b.lower_left_corner_radius;
}
inline bool operator==(const FlutterTransformation& a,
const FlutterTransformation& b) {
return a.scaleX == b.scaleX && a.skewX == b.skewX && a.transX == b.transX &&
a.skewY == b.skewY && a.scaleY == b.scaleY && a.transY == b.transY &&
a.pers0 == b.pers0 && a.pers1 == b.pers1 && a.pers2 == b.pers2;
}
inline bool operator==(const FlutterOpenGLTexture& a,
const FlutterOpenGLTexture& b) {
return a.target == b.target && a.name == b.name && a.format == b.format &&
a.user_data == b.user_data &&
a.destruction_callback == b.destruction_callback;
}
inline bool operator==(const FlutterOpenGLFramebuffer& a,
const FlutterOpenGLFramebuffer& b) {
return a.target == b.target && a.name == b.name &&
a.user_data == b.user_data &&
a.destruction_callback == b.destruction_callback;
}
inline bool operator==(const FlutterMetalTexture& a,
const FlutterMetalTexture& b) {
return a.texture_id == b.texture_id && a.texture == b.texture;
}
inline bool operator==(const FlutterVulkanImage& a,
const FlutterVulkanImage& b) {
return a.image == b.image && a.format == b.format;
}
inline bool operator==(const FlutterVulkanBackingStore& a,
const FlutterVulkanBackingStore& b) {
return a.image == b.image;
}
inline bool operator==(const FlutterMetalBackingStore& a,
const FlutterMetalBackingStore& b) {
return a.texture == b.texture;
}
inline bool operator==(const FlutterOpenGLBackingStore& a,
const FlutterOpenGLBackingStore& b) {
if (!(a.type == b.type)) {
return false;
}
switch (a.type) {
case kFlutterOpenGLTargetTypeTexture:
return a.texture == b.texture;
case kFlutterOpenGLTargetTypeFramebuffer:
return a.framebuffer == b.framebuffer;
}
return false;
}
inline bool operator==(const FlutterSoftwareBackingStore& a,
const FlutterSoftwareBackingStore& b) {
return a.allocation == b.allocation && a.row_bytes == b.row_bytes &&
a.height == b.height && a.user_data == b.user_data &&
a.destruction_callback == b.destruction_callback;
}
inline bool operator==(const FlutterSoftwareBackingStore2& a,
const FlutterSoftwareBackingStore2& b) {
return a.allocation == b.allocation && a.row_bytes == b.row_bytes &&
a.height == b.height && a.user_data == b.user_data &&
a.destruction_callback == b.destruction_callback &&
a.pixel_format == b.pixel_format;
}
inline bool operator==(const FlutterRegion& a, const FlutterRegion& b) {
if (a.struct_size != b.struct_size || a.rects_count != b.rects_count) {
return false;
}
for (size_t i = 0; i < a.rects_count; i++) {
if (!(a.rects[i] == b.rects[i])) {
return false;
}
}
return true;
}
inline bool operator==(const FlutterBackingStorePresentInfo& a,
const FlutterBackingStorePresentInfo& b) {
return a.struct_size == b.struct_size && *a.paint_region == *b.paint_region;
}
inline bool operator==(const FlutterBackingStore& a,
const FlutterBackingStore& b) {
if (!(a.struct_size == b.struct_size && a.user_data == b.user_data &&
a.type == b.type && a.did_update == b.did_update)) {
return false;
}
switch (a.type) {
case kFlutterBackingStoreTypeOpenGL:
return a.open_gl == b.open_gl;
case kFlutterBackingStoreTypeSoftware:
return a.software == b.software;
case kFlutterBackingStoreTypeMetal:
return a.metal == b.metal;
case kFlutterBackingStoreTypeVulkan:
return a.vulkan == b.vulkan;
case kFlutterBackingStoreTypeSoftware2:
return a.software2 == b.software2;
}
return false;
}
inline bool operator==(const FlutterPlatformViewMutation& a,
const FlutterPlatformViewMutation& b) {
if (a.type != b.type) {
return false;
}
switch (a.type) {
case kFlutterPlatformViewMutationTypeOpacity:
return flutter::testing::NumberNear(a.opacity, b.opacity);
case kFlutterPlatformViewMutationTypeClipRect:
return a.clip_rect == b.clip_rect;
case kFlutterPlatformViewMutationTypeClipRoundedRect:
return a.clip_rounded_rect == b.clip_rounded_rect;
case kFlutterPlatformViewMutationTypeTransformation:
return a.transformation == b.transformation;
}
return false;
}
inline bool operator==(const FlutterPlatformView& a,
const FlutterPlatformView& b) {
if (!(a.struct_size == b.struct_size && a.identifier == b.identifier &&
a.mutations_count == b.mutations_count)) {
return false;
}
for (size_t i = 0; i < a.mutations_count; ++i) {
if (!(*a.mutations[i] == *b.mutations[i])) {
return false;
}
}
return true;
}
inline bool operator==(const FlutterLayer& a, const FlutterLayer& b) {
if (!(a.struct_size == b.struct_size && a.type == b.type &&
a.offset == b.offset && a.size == b.size)) {
return false;
}
switch (a.type) {
case kFlutterLayerContentTypeBackingStore:
return *a.backing_store == *b.backing_store &&
*a.backing_store_present_info == *b.backing_store_present_info;
case kFlutterLayerContentTypePlatformView:
return *a.platform_view == *b.platform_view;
}
return false;
}
//------------------------------------------------------------------------------
// Printing
//------------------------------------------------------------------------------
inline std::ostream& operator<<(std::ostream& out, const FlutterPoint& point) {
return out << "(" << point.x << ", " << point.y << ")";
}
inline std::ostream& operator<<(std::ostream& out, const FlutterRect& r) {
return out << "LTRB (" << r.left << ", " << r.top << ", " << r.right << ", "
<< r.bottom << ")";
}
inline std::ostream& operator<<(std::ostream& out, const FlutterSize& size) {
return out << "(" << size.width << ", " << size.height << ")";
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterRoundedRect& r) {
out << "Rect: " << r.rect << ", ";
out << "Upper Left Corner Radius: " << r.upper_left_corner_radius << ", ";
out << "Upper Right Corner Radius: " << r.upper_right_corner_radius << ", ";
out << "Lower Right Corner Radius: " << r.lower_right_corner_radius << ", ";
out << "Lower Left Corner Radius: " << r.lower_left_corner_radius;
return out;
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterTransformation& t) {
out << "Scale X: " << t.scaleX << ", ";
out << "Skew X: " << t.skewX << ", ";
out << "Trans X: " << t.transX << ", ";
out << "Skew Y: " << t.skewY << ", ";
out << "Scale Y: " << t.scaleY << ", ";
out << "Trans Y: " << t.transY << ", ";
out << "Pers 0: " << t.pers0 << ", ";
out << "Pers 1: " << t.pers1 << ", ";
out << "Pers 2: " << t.pers2;
return out;
}
inline std::string FlutterLayerContentTypeToString(
FlutterLayerContentType type) {
switch (type) {
case kFlutterLayerContentTypeBackingStore:
return "kFlutterLayerContentTypeBackingStore";
case kFlutterLayerContentTypePlatformView:
return "kFlutterLayerContentTypePlatformView";
}
return "Unknown";
}
inline std::string FlutterBackingStoreTypeToString(
FlutterBackingStoreType type) {
switch (type) {
case kFlutterBackingStoreTypeOpenGL:
return "kFlutterBackingStoreTypeOpenGL";
case kFlutterBackingStoreTypeSoftware:
return "kFlutterBackingStoreTypeSoftware";
case kFlutterBackingStoreTypeMetal:
return "kFlutterBackingStoreTypeMetal";
case kFlutterBackingStoreTypeVulkan:
return "kFlutterBackingStoreTypeVulkan";
case kFlutterBackingStoreTypeSoftware2:
return "kFlutterBackingStoreTypeSoftware2";
}
return "Unknown";
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterOpenGLTexture& item) {
return out << "(FlutterOpenGLTexture) Target: 0x" << std::hex << item.target
<< std::dec << " Name: " << item.name << " Format: " << item.format
<< " User Data: " << item.user_data << " Destruction Callback: "
<< reinterpret_cast<void*>(item.destruction_callback);
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterOpenGLFramebuffer& item) {
return out << "(FlutterOpenGLFramebuffer) Target: 0x" << std::hex
<< item.target << std::dec << " Name: " << item.name
<< " User Data: " << item.user_data << " Destruction Callback: "
<< reinterpret_cast<void*>(item.destruction_callback);
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterMetalTexture& item) {
return out << "(FlutterMetalTexture) Texture ID: " << std::hex
<< item.texture_id << std::dec << " Handle: 0x" << std::hex
<< item.texture;
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterVulkanImage& item) {
return out << "(FlutterVulkanTexture) Image Handle: " << std::hex
<< item.image << std::dec << " Format: " << item.format;
}
inline std::string FlutterPlatformViewMutationTypeToString(
FlutterPlatformViewMutationType type) {
switch (type) {
case kFlutterPlatformViewMutationTypeOpacity:
return "kFlutterPlatformViewMutationTypeOpacity";
case kFlutterPlatformViewMutationTypeClipRect:
return "kFlutterPlatformViewMutationTypeClipRect";
case kFlutterPlatformViewMutationTypeClipRoundedRect:
return "kFlutterPlatformViewMutationTypeClipRoundedRect";
case kFlutterPlatformViewMutationTypeTransformation:
return "kFlutterPlatformViewMutationTypeTransformation";
}
return "Unknown";
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterPlatformViewMutation& m) {
out << "(FlutterPlatformViewMutation) Type: "
<< FlutterPlatformViewMutationTypeToString(m.type) << " ";
switch (m.type) {
case kFlutterPlatformViewMutationTypeOpacity:
out << "Opacity: " << m.opacity;
case kFlutterPlatformViewMutationTypeClipRect:
out << "Clip Rect: " << m.clip_rect;
case kFlutterPlatformViewMutationTypeClipRoundedRect:
out << "Clip Rounded Rect: " << m.clip_rounded_rect;
case kFlutterPlatformViewMutationTypeTransformation:
out << "Transformation: " << m.transformation;
}
return out;
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterPlatformView& platform_view) {
out << "["
<< "(FlutterPlatformView) Struct Size: " << platform_view.struct_size
<< " Identifier: " << platform_view.identifier
<< " Mutations Count: " << platform_view.mutations_count;
if (platform_view.mutations_count > 0) {
out << std::endl;
for (size_t i = 0; i < platform_view.mutations_count; i++) {
out << "Mutation " << i << ": " << *platform_view.mutations[i]
<< std::endl;
}
}
out << "]";
return out;
}
inline std::string FlutterOpenGLTargetTypeToString(
FlutterOpenGLTargetType type) {
switch (type) {
case kFlutterOpenGLTargetTypeTexture:
return "kFlutterOpenGLTargetTypeTexture";
case kFlutterOpenGLTargetTypeFramebuffer:
return "kFlutterOpenGLTargetTypeFramebuffer";
}
return "Unknown";
}
inline std::string FlutterSoftwarePixelFormatToString(
FlutterSoftwarePixelFormat pixfmt) {
switch (pixfmt) {
case kFlutterSoftwarePixelFormatGray8:
return "kFlutterSoftwarePixelFormatGray8";
case kFlutterSoftwarePixelFormatRGB565:
return "kFlutterSoftwarePixelFormatRGB565";
case kFlutterSoftwarePixelFormatRGBA4444:
return "kFlutterSoftwarePixelFormatRGBA4444";
case kFlutterSoftwarePixelFormatRGBA8888:
return "kFlutterSoftwarePixelFormatRGBA8888";
case kFlutterSoftwarePixelFormatRGBX8888:
return "kFlutterSoftwarePixelFormatRGBX8888";
case kFlutterSoftwarePixelFormatBGRA8888:
return "kFlutterSoftwarePixelFormatBGRA8888";
case kFlutterSoftwarePixelFormatNative32:
return "kFlutterSoftwarePixelFormatNative32";
default:
FML_LOG(ERROR) << "Invalid software rendering pixel format";
}
return "Unknown";
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterOpenGLBackingStore& item) {
out << "(FlutterOpenGLBackingStore) Type: "
<< FlutterOpenGLTargetTypeToString(item.type) << " ";
switch (item.type) {
case kFlutterOpenGLTargetTypeTexture:
out << item.texture;
break;
case kFlutterOpenGLTargetTypeFramebuffer:
out << item.framebuffer;
break;
}
return out;
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterSoftwareBackingStore& item) {
return out << "(FlutterSoftwareBackingStore) Allocation: " << item.allocation
<< " Row Bytes: " << item.row_bytes << " Height: " << item.height
<< " User Data: " << item.user_data << " Destruction Callback: "
<< reinterpret_cast<void*>(item.destruction_callback);
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterMetalBackingStore& item) {
return out << "(FlutterMetalBackingStore) Texture: " << item.texture;
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterVulkanBackingStore& item) {
return out << "(FlutterVulkanBackingStore) Image: " << item.image;
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterSoftwareBackingStore2& item) {
return out << "(FlutterSoftwareBackingStore2) Allocation: " << item.allocation
<< " Row Bytes: " << item.row_bytes << " Height: " << item.height
<< " User Data: " << item.user_data << " Destruction Callback: "
<< reinterpret_cast<void*>(item.destruction_callback)
<< " Pixel Format: "
<< FlutterSoftwarePixelFormatToString(item.pixel_format);
}
inline std::ostream& operator<<(std::ostream& out,
const FlutterBackingStore& backing_store) {
out << "(FlutterBackingStore) Struct size: " << backing_store.struct_size
<< " User Data: " << backing_store.user_data
<< " Type: " << FlutterBackingStoreTypeToString(backing_store.type)
<< " ";
switch (backing_store.type) {
case kFlutterBackingStoreTypeOpenGL:
out << backing_store.open_gl;
break;
case kFlutterBackingStoreTypeSoftware:
out << backing_store.software;
break;
case kFlutterBackingStoreTypeMetal:
out << backing_store.metal;
break;
case kFlutterBackingStoreTypeVulkan:
out << backing_store.vulkan;
break;
case kFlutterBackingStoreTypeSoftware2:
out << backing_store.software2;
break;
}
return out;
}
inline std::ostream& operator<<(std::ostream& out, const FlutterLayer& layer) {
out << "(Flutter Layer) Struct size: " << layer.struct_size
<< " Type: " << FlutterLayerContentTypeToString(layer.type);
switch (layer.type) {
case kFlutterLayerContentTypeBackingStore:
out << *layer.backing_store;
break;
case kFlutterLayerContentTypePlatformView:
out << *layer.platform_view;
break;
}
return out << " Offset: " << layer.offset << " Size: " << layer.size;
}
//------------------------------------------------------------------------------
// Factories and Casts
//------------------------------------------------------------------------------
inline FlutterPoint FlutterPointMake(double x, double y) {
FlutterPoint point = {};
point.x = x;
point.y = y;
return point;
}
inline FlutterSize FlutterSizeMake(double width, double height) {
FlutterSize size = {};
size.width = width;
size.height = height;
return size;
}
inline FlutterSize FlutterSizeMake(const SkVector& vector) {
FlutterSize size = {};
size.width = vector.x();
size.height = vector.y();
return size;
}
inline FlutterTransformation FlutterTransformationMake(const SkMatrix& matrix) {
FlutterTransformation transformation = {};
transformation.scaleX = matrix[SkMatrix::kMScaleX];
transformation.skewX = matrix[SkMatrix::kMSkewX];
transformation.transX = matrix[SkMatrix::kMTransX];
transformation.skewY = matrix[SkMatrix::kMSkewY];
transformation.scaleY = matrix[SkMatrix::kMScaleY];
transformation.transY = matrix[SkMatrix::kMTransY];
transformation.pers0 = matrix[SkMatrix::kMPersp0];
transformation.pers1 = matrix[SkMatrix::kMPersp1];
transformation.pers2 = matrix[SkMatrix::kMPersp2];
return transformation;
}
inline SkMatrix SkMatrixMake(const FlutterTransformation& xformation) {
return SkMatrix::MakeAll(xformation.scaleX, //
xformation.skewX, //
xformation.transX, //
xformation.skewY, //
xformation.scaleY, //
xformation.transY, //
xformation.pers0, //
xformation.pers1, //
xformation.pers2 //
);
}
inline flutter::EmbedderEngine* ToEmbedderEngine(const FlutterEngine& engine) {
return reinterpret_cast<flutter::EmbedderEngine*>(engine);
}
inline FlutterRect FlutterRectMake(const SkRect& rect) {
FlutterRect r = {};
r.left = rect.left();
r.top = rect.top();
r.right = rect.right();
r.bottom = rect.bottom();
return r;
}
inline FlutterRect FlutterRectMakeLTRB(double l, double t, double r, double b) {
FlutterRect rect = {};
rect.left = l;
rect.top = t;
rect.right = r;
rect.bottom = b;
return rect;
}
inline SkRect SkRectMake(const FlutterRect& rect) {
return SkRect::MakeLTRB(rect.left, rect.top, rect.right, rect.bottom);
}
inline FlutterRoundedRect FlutterRoundedRectMake(const SkRRect& rect) {
FlutterRoundedRect r = {};
r.rect = FlutterRectMake(rect.rect());
r.upper_left_corner_radius =
FlutterSizeMake(rect.radii(SkRRect::Corner::kUpperLeft_Corner));
r.upper_right_corner_radius =
FlutterSizeMake(rect.radii(SkRRect::Corner::kUpperRight_Corner));
r.lower_right_corner_radius =
FlutterSizeMake(rect.radii(SkRRect::Corner::kLowerRight_Corner));
r.lower_left_corner_radius =
FlutterSizeMake(rect.radii(SkRRect::Corner::kLowerLeft_Corner));
return r;
}
// NOLINTEND(google-objc-function-naming)
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_ASSERTIONS_H_
| engine/shell/platform/embedder/tests/embedder_assertions.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_assertions.h",
"repo_id": "engine",
"token_count": 8186
} | 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_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_METAL_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_METAL_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h"
namespace flutter {
namespace testing {
class EmbedderTestCompositorMetal : public EmbedderTestCompositor {
public:
EmbedderTestCompositorMetal(SkISize surface_size,
sk_sp<GrDirectContext> context);
~EmbedderTestCompositorMetal() override;
private:
bool UpdateOffscrenComposition(const FlutterLayer** layers,
size_t layers_count) override;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorMetal);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_METAL_H_
| engine/shell/platform/embedder/tests/embedder_test_compositor_metal.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor_metal.h",
"repo_id": "engine",
"token_count": 443
} | 381 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/embedder.h"
#include <set>
#include "flutter/testing/testing.h"
#ifdef _WIN32
// winbase.h defines GetCurrentTime as a macro.
#undef GetCurrentTime
#endif
namespace flutter {
namespace testing {
// Verifies that the proc table is fully populated.
TEST(EmbedderProcTable, AllPointersProvided) {
FlutterEngineProcTable procs = {};
procs.struct_size = sizeof(FlutterEngineProcTable);
ASSERT_EQ(FlutterEngineGetProcAddresses(&procs), kSuccess);
void (**proc)() = reinterpret_cast<void (**)()>(&procs.CreateAOTData);
const uintptr_t end_address =
reinterpret_cast<uintptr_t>(&procs) + procs.struct_size;
while (reinterpret_cast<uintptr_t>(proc) < end_address) {
EXPECT_NE(*proc, nullptr);
++proc;
}
}
// Ensures that there are no duplicate pointers in the proc table, to catch
// copy/paste mistakes when adding a new entry to FlutterEngineGetProcAddresses.
TEST(EmbedderProcTable, NoDuplicatePointers) {
FlutterEngineProcTable procs = {};
procs.struct_size = sizeof(FlutterEngineProcTable);
ASSERT_EQ(FlutterEngineGetProcAddresses(&procs), kSuccess);
void (**proc)() = reinterpret_cast<void (**)()>(&procs.CreateAOTData);
const uintptr_t end_address =
reinterpret_cast<uintptr_t>(&procs) + procs.struct_size;
std::set<void (*)()> seen_procs;
while (reinterpret_cast<uintptr_t>(proc) < end_address) {
auto result = seen_procs.insert(*proc);
EXPECT_TRUE(result.second);
++proc;
}
}
// Spot-checks that calling one of the function pointers works.
TEST(EmbedderProcTable, CallProc) {
FlutterEngineProcTable procs = {};
procs.struct_size = sizeof(FlutterEngineProcTable);
ASSERT_EQ(FlutterEngineGetProcAddresses(&procs), kSuccess);
EXPECT_NE(procs.GetCurrentTime(), 0ULL);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/embedder/tests/embedder_unittests_proctable.cc/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_unittests_proctable.cc",
"repo_id": "engine",
"token_count": 705
} | 382 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "natives.h"
#include <zircon/syscalls.h>
#include <cstring>
#include <memory>
#include <vector>
#include "handle.h"
#include "handle_disposition.h"
#include "handle_waiter.h"
#include "system.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_class_library.h"
#include "third_party/tonic/dart_class_provider.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_state.h"
#include "third_party/tonic/logging/dart_invoke.h"
#include "third_party/tonic/typed_data/typed_list.h"
using tonic::ToDart;
namespace zircon {
namespace dart {
namespace {
static tonic::DartLibraryNatives* g_natives;
tonic::DartLibraryNatives* InitNatives() {
tonic::DartLibraryNatives* natives = new tonic::DartLibraryNatives();
HandleDisposition::RegisterNatives(natives);
HandleWaiter::RegisterNatives(natives);
Handle::RegisterNatives(natives);
System::RegisterNatives(natives);
return natives;
}
Dart_NativeFunction NativeLookup(Dart_Handle name,
int argument_count,
bool* auto_setup_scope) {
const char* function_name = nullptr;
Dart_Handle result = Dart_StringToCString(name, &function_name);
if (Dart_IsError(result)) {
Dart_PropagateError(result);
}
FML_DCHECK(function_name != nullptr);
FML_DCHECK(auto_setup_scope != nullptr);
*auto_setup_scope = true;
if (!g_natives)
g_natives = InitNatives();
return g_natives->GetNativeFunction(name, argument_count, auto_setup_scope);
}
const uint8_t* NativeSymbol(Dart_NativeFunction native_function) {
if (!g_natives)
g_natives = InitNatives();
return g_natives->GetSymbol(native_function);
}
} // namespace
void Initialize() {
Dart_Handle library = Dart_LookupLibrary(ToDart("dart:zircon"));
FML_CHECK(!tonic::CheckAndHandleError(library));
Dart_Handle result = Dart_SetNativeResolver(
library, zircon::dart::NativeLookup, zircon::dart::NativeSymbol);
FML_CHECK(!tonic::CheckAndHandleError(result));
auto dart_state = tonic::DartState::Current();
std::unique_ptr<tonic::DartClassProvider> zircon_class_provider(
new tonic::DartClassProvider(dart_state, "dart:zircon"));
dart_state->class_library().add_provider("zircon",
std::move(zircon_class_provider));
}
} // namespace dart
} // namespace zircon
| engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/natives.cc",
"repo_id": "engine",
"token_count": 1017
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_HANDLE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_HANDLE_H_
#include "macros.h"
#include "include/dart_api_dl.h"
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct zircon_dart_handle_t {
uint32_t handle;
} zircon_dart_handle_t;
typedef struct zircon_dart_handle_pair_t {
zircon_dart_handle_t* left;
zircon_dart_handle_t* right;
} zircon_dart_handle_pair_t;
typedef struct zircon_dart_handle_list_t {
// data is of type `std::vector<zircon_handle_t*>*`.
void* data;
uint32_t size;
} zircon_dart_handle_list_t;
// Creates a list.
ZIRCON_FFI_EXPORT zircon_dart_handle_list_t* zircon_dart_handle_list_create();
// Appends to the list.
ZIRCON_FFI_EXPORT void zircon_dart_handle_list_append(
zircon_dart_handle_list_t* list,
zircon_dart_handle_t* handle);
// Frees the list, all the handles passed here must have been released.
ZIRCON_FFI_EXPORT void zircon_dart_handle_list_free(
zircon_dart_handle_list_t* list);
// Returns 1 if the handle is valid.
ZIRCON_FFI_EXPORT int32_t zircon_dart_handle_is_valid(
zircon_dart_handle_t* handle);
// Closes the handle, but doesn't release any ffi-associated memory. Returns 1
// on success.
ZIRCON_FFI_EXPORT int32_t zircon_dart_handle_close(
zircon_dart_handle_t* handle);
// Closes the zircon handle if valid and frees the memory.
ZIRCON_FFI_EXPORT void zircon_dart_handle_free(zircon_dart_handle_t* handle);
// Attach a finalizer for pointer to object, such that `finalizer(pointer)` will
// be called when `object` is collected by the Dart garbage collector.
//
// The external_allocation_size is used by the Dart garbage collector as a hint
// about the size of the external allocation.
//
// Returns 1 on success.
ZIRCON_FFI_EXPORT int zircon_dart_handle_pair_attach_finalizer(
Dart_Handle object,
void* pointer,
intptr_t external_allocation_size);
ZIRCON_FFI_EXPORT int zircon_dart_handle_attach_finalizer(
Dart_Handle object,
void* pointer,
intptr_t external_allocation_size);
// ZIRCON_FFI_EXPORT zircon_dart_handle_t* zircon_dart_duplicate_handle(
// zircon_dart_handle_t* handle,
// uint32_t rights);
#ifdef __cplusplus
}
#endif
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_PKG_ZIRCON_FFI_HANDLE_H_
| engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon_ffi/handle.h",
"repo_id": "engine",
"token_count": 1017
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_
#include <memory>
#include <fuchsia/component/runner/cpp/fidl.h>
#include <fuchsia/test/cpp/fidl.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async/cpp/executor.h>
#include <lib/async/cpp/wait.h>
#include <lib/fdio/namespace.h>
#include <lib/sys/cpp/component_context.h>
#include <lib/sys/cpp/service_directory.h>
#include <lib/zx/timer.h>
#include <lib/fidl/cpp/binding_set.h>
#include "lib/fidl/cpp/binding.h"
#include "runtime/dart/utils/mapped_resource.h"
#include "third_party/dart/runtime/include/dart_api.h"
namespace dart_runner {
/// Starts a Dart test component written in CFv2. It's different from
/// DartComponentController in that it must implement the
/// |fuchsia.test.Suite| protocol. It was forked to avoid a naming clash
/// between the two classes' methods as the Suite protocol requires a Run()
/// method for the test_manager to call on. This way, we avoid an extra layer
/// between the test_manager and actual test execution.
/// TODO(fxb/98369): Look into combining the two component classes once dart
/// testing is stable.
class DartTestComponentController
: public fuchsia::component::runner::ComponentController,
public fuchsia::test::Suite {
using DoneCallback = fit::function<void(DartTestComponentController*)>;
public:
DartTestComponentController(
fuchsia::component::runner::ComponentStartInfo start_info,
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services,
fidl::InterfaceRequest<fuchsia::component::runner::ComponentController>
controller,
DoneCallback done_callback);
~DartTestComponentController() override;
/// Sets up the controller.
///
/// This should be called before |Run|.
void SetUp();
/// |Suite| protocol implementation.
void GetTests(
fidl::InterfaceRequest<fuchsia::test::CaseIterator> iterator) override;
/// |Suite| protocol implementation.
void Run(std::vector<fuchsia::test::Invocation> tests,
fuchsia::test::RunOptions options,
fidl::InterfaceHandle<fuchsia::test::RunListener> listener) override;
fidl::InterfaceRequestHandler<fuchsia::test::Suite> GetHandler() {
return suite_bindings_.GetHandler(this, loop_->dispatcher());
}
private:
/// Helper for actually running the Dart main. Returns a promise.
fpromise::promise<> RunDartMain();
/// Creates and binds the namespace for this component. Returns true if
/// successful, false otherwise.
bool CreateAndBindNamespace();
bool SetUpFromKernel();
bool SetUpFromAppSnapshot();
bool CreateIsolate(const uint8_t* isolate_snapshot_data,
const uint8_t* isolate_snapshot_instructions);
// |ComponentController|
void Kill() override;
void Stop() override;
// Idle notification.
void MessageEpilogue(Dart_Handle result);
void OnIdleTimer(async_dispatcher_t* dispatcher,
async::WaitBase* wait,
zx_status_t status,
const zx_packet_signal* signal);
// |CaseIterator|
class CaseIterator final : public fuchsia::test::CaseIterator {
public:
CaseIterator(fidl::InterfaceRequest<fuchsia::test::CaseIterator> request,
async_dispatcher_t* dispatcher,
std::string test_component_name,
fit::function<void(CaseIterator*)> done_callback);
void GetNext(GetNextCallback callback) override;
private:
bool first_case_ = true;
fidl::Binding<fuchsia::test::CaseIterator> binding_;
std::string test_component_name_;
fit::function<void(CaseIterator*)> done_callback_;
};
std::unique_ptr<CaseIterator> RemoveCaseInterator(CaseIterator*);
// We only need one case_listener currently as dart tests are run as one
// large test file. In future iterations, case_listeners must be
// created per test case.
fidl::InterfacePtr<fuchsia::test::CaseListener> case_listener_;
std::map<CaseIterator*, std::unique_ptr<CaseIterator>> case_iterators_;
// |Suite|
/// Exposes suite protocol on behalf of test component.
std::string test_component_name_;
std::unique_ptr<sys::ComponentContext> suite_context_;
fidl::BindingSet<fuchsia::test::Suite> suite_bindings_;
// The loop must be the first declared member so that it gets destroyed after
// binding_ which expects the existence of a loop.
std::unique_ptr<async::Loop> loop_;
async::Executor executor_;
std::string label_;
std::string url_;
std::shared_ptr<sys::ServiceDirectory> runner_incoming_services_;
std::string data_path_;
std::unique_ptr<sys::ComponentContext> context_;
fuchsia::component::runner::ComponentStartInfo start_info_;
fidl::Binding<fuchsia::component::runner::ComponentController> binding_;
DoneCallback done_callback_;
zx::socket out_, err_, out_client_, err_client_;
fdio_ns_t* namespace_ = nullptr;
int stdout_fd_ = -1;
int stderr_fd_ = -1;
dart_utils::ElfSnapshot elf_snapshot_; // AOT snapshot
dart_utils::MappedResource isolate_snapshot_data_; // JIT snapshot
dart_utils::MappedResource isolate_snapshot_instructions_; // JIT snapshot
std::vector<dart_utils::MappedResource> kernel_peices_;
Dart_Isolate isolate_;
int32_t return_code_ = 0;
zx::time idle_start_{0};
zx::timer idle_timer_;
async::WaitMethod<DartTestComponentController,
&DartTestComponentController::OnIdleTimer>
idle_wait_{this};
// Disallow copy and assignment.
DartTestComponentController(const DartTestComponentController&) = delete;
DartTestComponentController& operator=(const DartTestComponentController&) =
delete;
};
} // namespace dart_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_DART_RUNNER_DART_TEST_COMPONENT_CONTROLLER_H_
| engine/shell/platform/fuchsia/dart_runner/dart_test_component_controller.h/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/dart_test_component_controller.h",
"repo_id": "engine",
"token_count": 2123
} | 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.
{
include: [ "common.shard.cml" ],
program: {
runner: "elf",
binary: "bin/app",
forward_stdout_to: "log",
forward_stderr_to: "log",
},
capabilities: [
{
runner: "dart_aot_product_runner",
path: "/svc/fuchsia.component.runner.ComponentRunner",
},
],
expose: [
{
runner: "dart_aot_product_runner",
from: "self",
},
],
}
| engine/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/meta/dart_aot_product_runner.cml",
"repo_id": "engine",
"token_count": 295
} | 386 |
#!/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.
import argparse
import os
import re
import sys
def main():
parser = argparse.ArgumentParser(
sys.argv[0], description="Generate main file for Fuchsia dart test"
)
parser.add_argument("--out", help="Path to .dart file to generate", required=True)
parser.add_argument("--main-dart", help="Path to main.dart file to import", required=True)
args = parser.parse_args()
out_dir = os.path.dirname(args.out)
assert os.path.isfile(os.path.join(os.path.dirname(args.out), args.main_dart))
outfile = open(args.out, 'w')
# Ignores relative lib imports due to a few modules that complain about
# this. It is also possible that a future may be unawaited given that main
# may not always be synchronous across all functions.
outfile.write('''// Generated by ''')
outfile.write(os.path.basename(__file__))
outfile.write(
'''
// ignore_for_file: avoid_relative_lib_imports
import 'dart:async';
import 'package:flutter_driver/driver_extension.dart';
'''
)
outfile.write("import '%s' as flutter_app_main;\n" % args.main_dart)
outfile.write(
'''
void main() async {
assert(await (() async {
// TODO(awdavies): Use the logger instead.
print('Overriding app main method because flutter_driver_extendable '
'is enabled in the build file');
try {
// Enables Flutter Driver VM service extension
//
// This extension is required for tests that use package:flutter_driver
// to drive applications from a separate process.
enableFlutterDriverExtension();
// TODO(awdavies): Use the logger instead.
print('flutter driver extensions enabled.');
//ignore: avoid_catches_without_on_clauses
} catch (e) {
// TODO(awdavies): Use the logger instead.
// Noop.
print('flutter driver extensions not enabled. $e');
}
// Always return true so that the assert succeeds.
return true;
}()));
// Execute the main method of the app under test
var res = (flutter_app_main.main as dynamic)();
if (res != null && res is Future) {
await res;
}
}
'''
)
outfile.close()
if __name__ == '__main__':
main()
| engine/shell/platform/fuchsia/flutter/build/gen_debug_wrapper_main.py/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/build/gen_debug_wrapper_main.py",
"repo_id": "engine",
"token_count": 815
} | 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.
#include "flutter_runner_product_configuration.h"
#include <zircon/assert.h>
#include "flutter/fml/logging.h"
#include "rapidjson/document.h"
namespace flutter_runner {
FlutterRunnerProductConfiguration::FlutterRunnerProductConfiguration(
std::string json_string) {
rapidjson::Document document;
document.Parse(json_string);
if (!document.IsObject()) {
FML_LOG(ERROR) << "Failed to parse configuration; using defaults: "
<< json_string;
return;
}
// Parse out all values we're expecting.
if (document.HasMember("intercept_all_input")) {
auto& val = document["intercept_all_input"];
if (val.IsBool()) {
intercept_all_input_ = val.GetBool();
}
}
if (document.HasMember("software_rendering")) {
auto& val = document["software_rendering"];
if (val.IsBool()) {
software_rendering_ = val.GetBool();
}
}
if (document.HasMember("enable_shader_warmup")) {
auto& val = document["enable_shader_warmup"];
if (val.IsBool()) {
enable_shader_warmup_ = val.GetBool();
}
}
if (document.HasMember("enable_shader_warmup_dart_hooks")) {
auto& val = document["enable_shader_warmup_dart_hooks"];
if (val.IsBool()) {
enable_shader_warmup_dart_hooks_ = val.GetBool();
}
}
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/flutter_runner_product_configuration.cc",
"repo_id": "engine",
"token_count": 562
} | 388 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/fuchsia/flutter/keyboard.h"
#include <fuchsia/input/cpp/fidl.h>
#include <fuchsia/ui/input/cpp/fidl.h>
#include <fuchsia/ui/input3/cpp/fidl.h>
#include <iostream>
namespace flutter_runner {
using fuchsia::input::Key;
using fuchsia::ui::input::kModifierCapsLock;
using fuchsia::ui::input::kModifierLeftAlt;
using fuchsia::ui::input::kModifierLeftControl;
using fuchsia::ui::input::kModifierLeftShift;
using fuchsia::ui::input::kModifierNone;
using fuchsia::ui::input::kModifierRightAlt;
using fuchsia::ui::input::kModifierRightControl;
using fuchsia::ui::input::kModifierRightShift;
using fuchsia::ui::input3::KeyEvent;
using fuchsia::ui::input3::KeyEventType;
namespace {
// A simple keymap from a QWERTY keyboard to code points. A value 0 means no
// code point has been assigned for the respective keypress. Column 0 is the
// code point without a level modifier active, and Column 1 is the code point
// with a level modifier (e.g. Shift key) active.
static const uint32_t QWERTY_TO_CODE_POINTS[][2] = {
// 0x00
{},
{},
{},
{},
// 0x04,
{'a', 'A'},
{'b', 'B'},
{'c', 'C'},
{'d', 'D'},
// 0x08
{'e', 'E'},
{'f', 'F'},
{'g', 'G'},
{'h', 'H'},
// 0x0c
{'i', 'I'},
{'j', 'J'},
{'k', 'K'},
{'l', 'L'},
// 0x10
{'m', 'M'},
{'n', 'N'},
{'o', 'O'},
{'p', 'P'},
// 0x14
{'q', 'Q'},
{'r', 'R'},
{'s', 'S'},
{'t', 'T'},
// 0x18
{'u', 'U'},
{'v', 'V'},
{'w', 'W'},
{'x', 'X'},
// 0x1c
{'y', 'Y'},
{'z', 'Z'},
{'1', '!'},
{'2', '@'},
// 0x20
{'3', '#'},
{'4', '$'},
{'5', '%'},
{'6', '^'},
// 0x24
{'7', '&'},
{'8', '*'},
{'9', '('},
{'0', ')'},
// 0x28
{},
{},
{},
{},
// 0x2c
{' ', ' '},
{'-', '_'},
{'=', '+'},
{'[', '{'},
// 0x30
{']', '}'},
{'\\', '|'},
{},
{';', ':'},
// 0x34
{'\'', '"'},
{'`', '~'},
{',', '<'},
{'.', '>'},
// 0x38
{'/', '?'},
{},
{},
{},
// 0x3c
{},
{},
{},
{},
// 0x40
{},
{},
{},
{},
// 0x44
{},
{},
{},
{},
// 0x48
{},
{},
{},
{},
// 0x4c
{},
{},
{},
{},
// 0x50
{},
{},
{},
{},
// 0x54
{'/', 0},
{'*', 0},
{'-', 0},
{'+', 0},
// 0x58
{},
{'1', 0},
{'2', 0},
{'3', 0},
// 0x5c
{'4', 0},
{'5', 0},
{'6', 0},
{'7', 0},
// 0x60
{'8', 0},
{'9', 0},
{'0', 0},
{'.', 0},
};
} // namespace
Keyboard::Keyboard()
: any_events_received_(false),
stateful_caps_lock_(false),
left_shift_(false),
right_shift_(false),
left_alt_(false),
right_alt_(false),
left_ctrl_(false),
right_ctrl_(false),
last_event_() {}
bool Keyboard::ConsumeEvent(KeyEvent event) {
if (!event.has_type()) {
return false;
}
if (!event.has_key() && !event.has_key_meaning()) {
return false;
}
// Check if the time sequence of the events is correct.
last_event_ = std::move(event);
any_events_received_ = true;
if (!event.has_key()) {
// The key only has key meaning. Key meaning currently can not
// update the modifier state, so we just short-circuit the table
// below.
return true;
}
const Key& key = last_event_.key();
const KeyEventType& event_type = last_event_.type();
switch (event_type) {
// For modifier keys, a SYNC is the same as a press.
case KeyEventType::SYNC:
switch (key) {
case Key::CAPS_LOCK:
stateful_caps_lock_ = true;
break;
case Key::LEFT_ALT:
left_alt_ = true;
break;
case Key::LEFT_CTRL:
left_ctrl_ = true;
break;
case Key::LEFT_SHIFT:
left_shift_ = true;
break;
case Key::RIGHT_ALT:
right_alt_ = true;
break;
case Key::RIGHT_CTRL:
right_ctrl_ = true;
break;
case Key::RIGHT_SHIFT:
right_shift_ = true;
break;
default:
// no-op
break;
}
break;
case KeyEventType::PRESSED:
switch (key) {
case Key::CAPS_LOCK:
stateful_caps_lock_ = !stateful_caps_lock_;
break;
case Key::LEFT_ALT:
left_alt_ = true;
break;
case Key::LEFT_CTRL:
left_ctrl_ = true;
break;
case Key::LEFT_SHIFT:
left_shift_ = true;
break;
case Key::RIGHT_ALT:
right_alt_ = true;
break;
case Key::RIGHT_CTRL:
right_ctrl_ = true;
break;
case Key::RIGHT_SHIFT:
right_shift_ = true;
break;
default:
// No-op
break;
}
break;
case KeyEventType::RELEASED:
switch (key) {
case Key::CAPS_LOCK:
// No-op.
break;
case Key::LEFT_ALT:
left_alt_ = false;
break;
case Key::LEFT_CTRL:
left_ctrl_ = false;
break;
case Key::LEFT_SHIFT:
left_shift_ = false;
break;
case Key::RIGHT_ALT:
right_alt_ = false;
break;
case Key::RIGHT_CTRL:
right_ctrl_ = false;
break;
case Key::RIGHT_SHIFT:
right_shift_ = false;
break;
default:
// No-op
break;
}
break;
case KeyEventType::CANCEL:
// No-op?
break;
default:
// No-op
break;
}
return true;
}
bool Keyboard::IsShift() {
return left_shift_ | right_shift_ | stateful_caps_lock_;
}
bool Keyboard::IsKeys() {
return LastHIDUsagePage() == 0x7;
}
uint32_t Keyboard::Modifiers() {
return kModifierNone + (kModifierLeftShift * left_shift_) +
(kModifierLeftAlt * left_alt_) + (kModifierLeftControl * left_ctrl_) +
(kModifierRightShift * right_shift_) +
(kModifierRightAlt * right_alt_) +
(kModifierRightControl * right_ctrl_) +
(kModifierCapsLock * stateful_caps_lock_);
}
uint32_t Keyboard::LastCodePoint() {
// If the key has a meaning, and if the meaning is a code point, always have
// that code point take precedence over any other keymap.
if (last_event_.has_key_meaning()) {
const auto& key_meaning = last_event_.key_meaning();
if (key_meaning.is_codepoint()) {
return key_meaning.codepoint();
}
}
static const int qwerty_map_size =
sizeof(QWERTY_TO_CODE_POINTS) / sizeof(QWERTY_TO_CODE_POINTS[0]);
if (!IsKeys()) {
return 0;
}
const auto usage = LastHIDUsageID();
if (usage < qwerty_map_size) {
return QWERTY_TO_CODE_POINTS[usage][IsShift() & 1];
}
// Any other keys don't have a code point.
return 0;
}
uint32_t Keyboard::GetLastKey() {
// For logical key determination, the physical key does not matter as long
// as code point is set.
// https://github.com/flutter/flutter/blob/570e39d38b799e91abe4f73f120ce494049c4ff0/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart#L71
// It is not quite clear what happens to the physical key, though:
// https://github.com/flutter/flutter/blob/570e39d38b799e91abe4f73f120ce494049c4ff0/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart#L88
if (!last_event_.has_key()) {
return 0;
}
return static_cast<uint32_t>(last_event_.key());
}
uint32_t Keyboard::LastHIDUsage() {
return GetLastKey() & 0xFFFFFFFF;
}
uint16_t Keyboard::LastHIDUsageID() {
return GetLastKey() & 0xFFFF;
}
uint16_t Keyboard::LastHIDUsagePage() {
return (GetLastKey() >> 16) & 0xFFFF;
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/keyboard.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/keyboard.cc",
"repo_id": "engine",
"token_count": 3984
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_INJECTOR_DELEGATE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_INJECTOR_DELEGATE_H_
#include <fuchsia/ui/pointerinjector/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <queue>
#include <unordered_map>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
#include "flutter/lib/ui/window/platform_message.h"
#include "third_party/rapidjson/include/rapidjson/document.h"
namespace flutter_runner {
// This class is responsible for handling the platform messages related to
// pointer events and managing the lifecycle of
// |fuchsia.ui.pointerinjector.Device| client side endpoint for embedded views.
class PointerInjectorDelegate {
public:
static constexpr auto kPointerInjectorMethodPrefix =
"View.pointerinjector.inject";
PointerInjectorDelegate(fuchsia::ui::pointerinjector::RegistryHandle registry,
fuchsia::ui::views::ViewRef host_view_ref)
: registry_(std::make_shared<fuchsia::ui::pointerinjector::RegistryPtr>(
registry.Bind())),
host_view_ref_(std::make_shared<fuchsia::ui::views::ViewRef>(
std::move(host_view_ref))) {}
// Handles the following pointer event related platform message requests:
// View.Pointerinjector.inject
// - Attempts to dispatch a pointer event to the given viewRef. Completes
// with [0] when the pointer event is sent to the given viewRef.
bool HandlePlatformMessage(
rapidjson::Value request,
fml::RefPtr<flutter::PlatformMessageResponse> response);
// Adds an endpoint for |view_id| in |valid_views_| for lifecycle management.
// Called in |PlatformView::OnChildViewViewRef()|.
void OnCreateView(
uint64_t view_id,
std::optional<fuchsia::ui::views::ViewRef> view_ref = std::nullopt);
// Closes the |fuchsia.ui.pointerinjector.Device| channel for |view_id| and
// cleans up resources.
void OnDestroyView(uint64_t view_id) { valid_views_.erase(view_id); }
private:
using ViewId = int64_t;
struct PointerInjectorRequest {
// The position of the pointer event in viewport's coordinate system.
float x = 0.f, y = 0.f;
// |fuchsia.ui.pointerinjector.PointerSample.pointer_id|.
uint32_t pointer_id = 0;
// |fuchsia.ui.pointerinjector.PointerSample.phase|.
fuchsia::ui::pointerinjector::EventPhase phase =
fuchsia::ui::pointerinjector::EventPhase::ADD;
// |fuchsia.ui.pointerinjector.Event.trace_flow_id|.
uint64_t trace_flow_id = 0;
// Logical size of the view's coordinate system.
std::array<float, 2> logical_size = {0.f, 0.f};
// |fuchsia.ui.pointerinjector.Event.timestamp|.
zx_time_t timestamp = 0;
};
// This class is responsible for dispatching pointer events to a view by first
// registering the injector device using
// |fuchsia.ui.pointerinjector.Registry.Register| and then injecting the
// pointer event using |fuchsia.ui.pointerinjector.Device.Inject|.
class PointerInjectorEndpoint {
public:
PointerInjectorEndpoint(
std::shared_ptr<fuchsia::ui::pointerinjector::RegistryPtr> registry,
std::shared_ptr<fuchsia::ui::views::ViewRef> host_view_ref,
std::optional<fuchsia::ui::views::ViewRef> view_ref)
: registry_(std::move(registry)),
host_view_ref_(std::move(host_view_ref)),
view_ref_(std::move(view_ref)),
weak_factory_(this) {
// Try to re-register the |device_| if the |device_| gets closed due to
// some error.
device_.set_error_handler(
[weak = weak_factory_.GetWeakPtr()](auto status) {
FML_LOG(WARNING)
<< "fuchsia.ui.pointerinjector.Device closed " << status;
if (!weak) {
return;
}
// Clear all the stale pointer events in |injector_events_| and
// reset the state of |weak| so that any future calls do not inject
// any stale pointer events.
weak->Reset();
});
}
// Registers |device_| if it has not been registered and calls
// |DispatchPendingEvents()| to dispatch |request| to the view.
void InjectEvent(PointerInjectorRequest request);
private:
// Registers with the pointer injector service.
//
// Sets |registered_| to true immediately after submitting the registration
// request. This means that the registration request may still be in-flight
// on the server side when the function returns. Events can safely be
// injected into the channel while registration is pending ("feed forward").
void RegisterInjector(const PointerInjectorRequest& request);
// Recursively calls |fuchsia.ui.pointerinjector.Device.Inject| to dispatch
// the pointer events in |injector_events_| to the view.
void DispatchPendingEvents();
void EnqueueEvent(fuchsia::ui::pointerinjector::Event event);
// Resets |registered_|, |injection_in_flight_| and |injector_events_| so
// that |device_| can be re-registered and future calls to
// |fuchsia.ui.pointerinjector.Device.Inject| do not include any stale
// pointer events.
void Reset();
// Set to true if there is a |fuchsia.ui.pointerinjector.Device.Inject| call
// in progress. If true, the |fuchsia.ui.pointerinjector.Event| is buffered
// in |injector_events_|.
bool injection_in_flight_ = false;
// Set to true if |device_| has been registered using
// |fuchsia.ui.pointerinjector.Registry.Register|. False otherwise.
bool registered_ = false;
std::shared_ptr<fuchsia::ui::pointerinjector::RegistryPtr> registry_;
// ViewRef for the main flutter app launching the embedded child views.
std::shared_ptr<fuchsia::ui::views::ViewRef> host_view_ref_;
// ViewRef for a flatland view.
// Set in |OnCreateView|.
std::optional<fuchsia::ui::views::ViewRef> view_ref_;
fuchsia::ui::pointerinjector::DevicePtr device_;
// A queue containing all the pending |fuchsia.ui.pointerinjector.Event|s
// which have to be dispatched to the view.
// Note: The size of a vector inside |injector_events_| should not exceed
// |fuchsia.ui.pointerinjector.MAX_INJECT|.
std::queue<std::vector<fuchsia::ui::pointerinjector::Event>>
injector_events_;
fml::WeakPtrFactory<PointerInjectorEndpoint>
weak_factory_; // Must be the last member.
FML_DISALLOW_COPY_AND_ASSIGN(PointerInjectorEndpoint);
};
void Complete(fml::RefPtr<flutter::PlatformMessageResponse> response,
std::string value);
// Generates a |fuchsia.ui.pointerinjector.Event| from |request| by extracting
// information like timestamp, trace flow id and pointer sample from
// |request|.
static fuchsia::ui::pointerinjector::Event ExtractPointerEvent(
PointerInjectorRequest request);
// A map of valid views keyed by its view id. A view can receive pointer
// events only if it is present in |valid_views_|.
std::unordered_map<ViewId, PointerInjectorEndpoint> valid_views_;
std::shared_ptr<fuchsia::ui::pointerinjector::RegistryPtr> registry_;
// ViewRef for the main flutter app launching the embedded child views.
std::shared_ptr<fuchsia::ui::views::ViewRef> host_view_ref_;
FML_DISALLOW_COPY_AND_ASSIGN(PointerInjectorDelegate);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_POINTER_INJECTOR_DELEGATE_H_
| engine/shell/platform/fuchsia/flutter/pointer_injector_delegate.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/pointer_injector_delegate.h",
"repo_id": "engine",
"token_count": 2798
} | 390 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_H_
#include "flutter/flow/surface.h"
#include "flutter/fml/macros.h"
#include "flutter/fml/memory/weak_ptr.h"
namespace flutter_runner {
// The interface between the Flutter rasterizer and the underlying platform. May
// be constructed on any thread but will be used by the engine only on the
// raster thread.
class Surface final : public flutter::Surface {
public:
Surface(std::string debug_label,
std::shared_ptr<flutter::ExternalViewEmbedder> view_embedder,
GrDirectContext* gr_context);
~Surface() override;
private:
const std::string debug_label_;
std::shared_ptr<flutter::ExternalViewEmbedder> view_embedder_;
GrDirectContext* gr_context_;
// |flutter::Surface|
bool IsValid() override;
// |flutter::Surface|
std::unique_ptr<flutter::SurfaceFrame> AcquireFrame(
const SkISize& size) override;
// |flutter::Surface|
GrDirectContext* GetContext() override;
// |flutter::Surface|
SkMatrix GetRootTransformation() const override;
FML_DISALLOW_COPY_AND_ASSIGN(Surface);
};
} // namespace flutter_runner
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_SURFACE_H_
| engine/shell/platform/fuchsia/flutter/surface.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/surface.h",
"repo_id": "engine",
"token_count": 496
} | 391 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_TYPES_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_TYPES_H_
#include <fuchsia/math/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl.h>
#include <fuchsia/ui/composition/cpp/fidl_test_base.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/fidl/cpp/binding.h>
#include <lib/fidl/cpp/interface_handle.h>
#include <lib/fidl/cpp/interface_ptr.h>
#include <lib/fidl/cpp/interface_request.h>
#include <zircon/types.h>
#include <algorithm>
#include <cfloat>
#include <cstdint>
#include <optional>
#include <unordered_map>
#include <variant>
#include <vector>
#include "flutter/fml/macros.h"
namespace fuchsia {
namespace math {
inline bool operator==(const fuchsia::math::SizeU& a,
const fuchsia::math::SizeU& b) {
return a.width == b.width && a.height == b.height;
}
inline bool operator==(const fuchsia::math::Inset& a,
const fuchsia::math::Inset& b) {
return a.top == b.top && a.left == b.left && a.right == b.right &&
a.bottom == b.bottom;
}
inline bool operator==(const fuchsia::math::Vec& a,
const fuchsia::math::Vec& b) {
return a.x == b.x && a.y == b.y;
}
inline bool operator==(const fuchsia::math::VecF& a,
const fuchsia::math::VecF& b) {
return a.x == b.x && a.y == b.y;
}
inline bool operator==(const fuchsia::math::Rect& a,
const fuchsia::math::Rect& b) {
return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height;
}
inline bool operator==(const fuchsia::math::RectF& a,
const fuchsia::math::RectF& b) {
return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height;
}
inline bool operator==(const std::optional<fuchsia::math::Rect>& a,
const std::optional<fuchsia::math::Rect>& b) {
if (a.has_value() != b.has_value()) {
return false;
}
if (!a.has_value()) {
}
return a.value() == b.value();
}
} // namespace math
namespace ui::composition {
inline bool operator==(const fuchsia::ui::composition::ContentId& a,
const fuchsia::ui::composition::ContentId& b) {
return a.value == b.value;
}
inline bool operator==(const fuchsia::ui::composition::TransformId& a,
const fuchsia::ui::composition::TransformId& b) {
return a.value == b.value;
}
inline bool operator==(const fuchsia::ui::composition::ViewportProperties& a,
const fuchsia::ui::composition::ViewportProperties& b) {
if (a.has_logical_size() != b.has_logical_size()) {
return false;
}
bool logical_size_equal = true;
if (a.has_logical_size()) {
const fuchsia::math::SizeU& a_logical_size = a.logical_size();
const fuchsia::math::SizeU& b_logical_size = b.logical_size();
logical_size_equal = (a_logical_size.width == b_logical_size.width &&
a_logical_size.height == b_logical_size.height);
}
return logical_size_equal;
}
inline bool operator==(const fuchsia::ui::composition::ImageProperties& a,
const fuchsia::ui::composition::ImageProperties& b) {
if (a.has_size() != b.has_size()) {
return false;
}
bool size_equal = true;
if (a.has_size()) {
const fuchsia::math::SizeU& a_size = a.size();
const fuchsia::math::SizeU& b_size = b.size();
size_equal =
(a_size.width == b_size.width && a_size.height == b_size.height);
}
return size_equal;
}
inline bool operator==(const fuchsia::ui::composition::HitRegion& a,
const fuchsia::ui::composition::HitRegion& b) {
return a.region == b.region && a.hit_test == b.hit_test;
}
inline bool operator!=(const fuchsia::ui::composition::HitRegion& a,
const fuchsia::ui::composition::HitRegion& b) {
return !(a == b);
}
inline bool operator==(
const std::vector<fuchsia::ui::composition::HitRegion>& a,
const std::vector<fuchsia::ui::composition::HitRegion>& b) {
if (a.size() != b.size())
return false;
for (size_t i = 0; i < a.size(); ++i) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
} // namespace ui::composition
} // namespace fuchsia
namespace flutter_runner::testing {
constexpr static fuchsia::ui::composition::TransformId kInvalidTransformId{0};
constexpr static fuchsia::ui::composition::ContentId kInvalidContentId{0};
constexpr static fuchsia::ui::composition::HitRegion kInfiniteHitRegion = {
.region = {-FLT_MAX, -FLT_MAX, FLT_MAX, FLT_MAX}};
// Convenience structure which allows clients to easily create a valid
// `ViewCreationToken` / `ViewportCreationToken` pair for use with Flatland
// `CreateView` and `CreateViewport`.
struct ViewTokenPair {
static ViewTokenPair New();
fuchsia::ui::views::ViewCreationToken view_token;
fuchsia::ui::views::ViewportCreationToken viewport_token;
};
// Convenience structure which allows clients to easily create a valid
// `BufferCollectionExportToken` / `BufferCollectionImportToken` pair for use
// with Flatland `RegisterBufferCollection` and `CreateImage`.
struct BufferCollectionTokenPair {
static BufferCollectionTokenPair New();
fuchsia::ui::composition::BufferCollectionExportToken export_token;
fuchsia::ui::composition::BufferCollectionImportToken import_token;
};
struct FakeView {
bool operator==(const FakeView& other) const;
zx_koid_t view_token{};
zx_koid_t view_ref{};
zx_koid_t view_ref_control{};
zx_koid_t view_ref_focused{};
zx_koid_t focuser{};
zx_koid_t touch_source{};
zx_koid_t mouse_source{};
zx_koid_t parent_viewport_watcher{};
};
struct FakeViewport {
bool operator==(const FakeViewport& other) const;
constexpr static fuchsia::math::SizeU kDefaultViewportLogicalSize{};
constexpr static fuchsia::math::Inset kDefaultViewportInset{};
fuchsia::ui::composition::ContentId id{kInvalidContentId};
fuchsia::ui::composition::ViewportProperties viewport_properties{};
zx_koid_t viewport_token{};
zx_koid_t child_view_watcher{};
};
struct FakeImage {
bool operator==(const FakeImage& other) const;
constexpr static fuchsia::math::SizeU kDefaultImageSize{};
constexpr static fuchsia::math::RectF kDefaultSampleRegion{};
constexpr static fuchsia::math::SizeU kDefaultDestinationSize{};
constexpr static float kDefaultOpacity{1.f};
constexpr static fuchsia::ui::composition::BlendMode kDefaultBlendMode{
fuchsia::ui::composition::BlendMode::SRC_OVER};
fuchsia::ui::composition::ContentId id{kInvalidContentId};
fuchsia::ui::composition::ImageProperties image_properties{};
fuchsia::math::RectF sample_region{kDefaultSampleRegion};
fuchsia::math::SizeU destination_size{kDefaultDestinationSize};
float opacity{kDefaultOpacity};
fuchsia::ui::composition::BlendMode blend_mode{kDefaultBlendMode};
zx_koid_t import_token{};
uint32_t vmo_index{0};
};
using FakeContent = std::variant<FakeViewport, FakeImage>;
struct FakeTransform {
bool operator==(const FakeTransform& other) const;
constexpr static fuchsia::math::Vec kDefaultTranslation{.x = 0, .y = 0};
constexpr static fuchsia::math::VecF kDefaultScale{.x = 1.0f, .y = 1.0f};
constexpr static fuchsia::ui::composition::Orientation kDefaultOrientation{
fuchsia::ui::composition::Orientation::CCW_0_DEGREES};
constexpr static float kDefaultOpacity = 1.0f;
fuchsia::ui::composition::TransformId id{kInvalidTransformId};
fuchsia::math::Vec translation{kDefaultTranslation};
fuchsia::math::VecF scale{kDefaultScale};
fuchsia::ui::composition::Orientation orientation{kDefaultOrientation};
std::optional<fuchsia::math::Rect> clip_bounds = std::nullopt;
float opacity = kDefaultOpacity;
std::vector<std::shared_ptr<FakeTransform>> children;
std::shared_ptr<FakeContent> content;
std::vector<fuchsia::ui::composition::HitRegion> hit_regions;
};
struct FakeGraph {
using ContentIdKey = decltype(fuchsia::ui::composition::ContentId::value);
using TransformIdKey = decltype(fuchsia::ui::composition::TransformId::value);
bool operator==(const FakeGraph& other) const;
void Clear();
FakeGraph Clone() const;
std::unordered_map<ContentIdKey, std::shared_ptr<FakeContent>> content_map;
std::unordered_map<TransformIdKey, std::shared_ptr<FakeTransform>>
transform_map;
std::shared_ptr<FakeTransform> root_transform;
std::optional<FakeView> view;
};
template <typename ZX>
std::pair<zx_koid_t, zx_koid_t> GetKoids(const ZX& kobj) {
zx_info_handle_basic_t info;
zx_status_t status =
kobj.get_info(ZX_INFO_HANDLE_BASIC, &info, sizeof(info),
/*actual_records*/ nullptr, /*avail_records*/ nullptr);
return status == ZX_OK ? std::make_pair(info.koid, info.related_koid)
: std::make_pair(zx_koid_t{}, zx_koid_t{});
}
template <typename F>
std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fidl::InterfaceHandle<F>& interface_handle) {
return GetKoids(interface_handle.channel());
}
template <typename F>
std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fidl::InterfaceRequest<F>& interface_request) {
return GetKoids(interface_request.channel());
}
template <typename F>
std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fidl::InterfacePtr<F>& interface_ptr) {
return GetKoids(interface_ptr.channel());
}
template <typename F>
std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fidl::Binding<F>& interface_binding) {
return GetKoids(interface_binding.channel());
}
inline std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fuchsia::ui::views::ViewCreationToken& view_token) {
return GetKoids(view_token.value);
}
inline std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fuchsia::ui::views::ViewportCreationToken& viewport_token) {
return GetKoids(viewport_token.value);
}
inline std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fuchsia::ui::views::ViewRef& view_ref) {
return GetKoids(view_ref.reference);
}
inline std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fuchsia::ui::views::ViewRefControl& view_ref_control) {
return GetKoids(view_ref_control.reference);
}
inline std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fuchsia::ui::composition::BufferCollectionExportToken&
buffer_collection_token) {
return GetKoids(buffer_collection_token.value);
}
inline std::pair<zx_koid_t, zx_koid_t> GetKoids(
const fuchsia::ui::composition::BufferCollectionImportToken&
buffer_collection_token) {
return GetKoids(buffer_collection_token.value);
}
}; // namespace flutter_runner::testing
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_SCENIC_FAKE_FLATLAND_TYPES_H_
| engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/scenic/fake_flatland_types.h",
"repo_id": "engine",
"token_count": 4314
} | 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.
{
include: [ "syslog/client.shard.cml" ],
program: {
data: "data/parent-view",
// Always use the jit runner for now.
// TODO(fxbug.dev/106577): Implement manifest merging build rules for V2 components.
runner: "flutter_jit_runner",
},
capabilities: [
{
protocol: [ "fuchsia.ui.app.ViewProvider" ],
},
],
use: [
{
protocol: [
"fuchsia.ui.app.ViewProvider",
],
},
{
directory: "config-data",
rights: [ "r*" ],
path: "/config/data",
},
// See common.shard.cml.
{
directory: "tzdata-icu",
rights: [ "r*" ],
path: "/config/tzdata/icu",
},
],
expose: [
{
protocol: [ "fuchsia.ui.app.ViewProvider" ],
from: "self",
},
],
}
| engine/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/meta/parent-view.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/embedder/parent-view/meta/parent-view.cml",
"repo_id": "engine",
"token_count": 556
} | 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.
#include "portable_ui_test.h"
#include <fuchsia/inspect/cpp/fidl.h>
#include <fuchsia/logger/cpp/fidl.h>
#include <fuchsia/tracing/provider/cpp/fidl.h>
#include <fuchsia/ui/app/cpp/fidl.h>
#include <lib/async/cpp/task.h>
#include <lib/sys/component/cpp/testing/realm_builder.h>
#include <lib/sys/component/cpp/testing/realm_builder_types.h>
#include "check_view.h"
#include "flutter/fml/logging.h"
namespace fuchsia_test_utils {
namespace {
// Types imported for the realm_builder library.
using component_testing::ChildOptions;
using component_testing::ChildRef;
using component_testing::ParentRef;
using component_testing::Protocol;
using component_testing::RealmRoot;
using component_testing::Route;
using fuchsia_test_utils::CheckViewExistsInSnapshot;
} // namespace
void PortableUITest::SetUp(bool build_realm) {
SetUpRealmBase();
ExtendRealm();
if (build_realm) {
BuildRealm();
}
}
void PortableUITest::BuildRealm() {
realm_ = std::make_unique<RealmRoot>(realm_builder_.Build());
}
void PortableUITest::SetUpRealmBase() {
FML_LOG(INFO) << "Setting up realm base";
// Add Flutter JIT runner as a child of the RealmBuilder
realm_builder_.AddChild(kFlutterJitRunner, kFlutterJitRunnerUrl);
// Add environment providing the Flutter JIT runner
fuchsia::component::decl::Environment flutter_runner_environment;
flutter_runner_environment.set_name(kFlutterRunnerEnvironment);
flutter_runner_environment.set_extends(
fuchsia::component::decl::EnvironmentExtends::REALM);
flutter_runner_environment.set_runners({});
auto environment_runners = flutter_runner_environment.mutable_runners();
// Add Flutter JIT runner to the environment
fuchsia::component::decl::RunnerRegistration flutter_jit_runner_reg;
flutter_jit_runner_reg.set_source(fuchsia::component::decl::Ref::WithChild(
fuchsia::component::decl::ChildRef{.name = kFlutterJitRunner}));
flutter_jit_runner_reg.set_source_name(kFlutterJitRunner);
flutter_jit_runner_reg.set_target_name(kFlutterJitRunner);
environment_runners->push_back(std::move(flutter_jit_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(flutter_runner_environment));
realm_builder_.ReplaceRealmDecl(std::move(realm_decl));
// Add test UI stack component.
realm_builder_.AddChild(kTestUIStack, GetTestUIStackUrl());
// // Route base system services to flutter and the test UI stack.
realm_builder_.AddRoute(Route{
.capabilities = {Protocol{fuchsia::logger::LogSink::Name_},
Protocol{fuchsia::inspect::InspectSink::Name_},
Protocol{fuchsia::sysmem::Allocator::Name_},
Protocol{fuchsia::tracing::provider::Registry::Name_},
Protocol{fuchsia::ui::input::ImeService::Name_},
Protocol{kPosixSocketProviderName},
Protocol{kVulkanLoaderServiceName},
component_testing::Directory{"config-data"}},
.source = ParentRef(),
.targets = {kFlutterJitRunnerRef, kTestUIStackRef}});
// Route UI capabilities to test driver and Flutter runner
realm_builder_.AddRoute(Route{
.capabilities = {Protocol{fuchsia::ui::composition::Allocator::Name_},
Protocol{fuchsia::ui::composition::Flatland::Name_},
Protocol{fuchsia::ui::test::input::Registry::Name_},
Protocol{fuchsia::ui::test::scene::Controller::Name_},
Protocol{fuchsia::ui::display::singleton::Info::Name_},
Protocol{kPointerInjectorRegistryName}},
.source = kTestUIStackRef,
.targets = {ParentRef(), kFlutterJitRunnerRef}});
}
void PortableUITest::ProcessViewGeometryResponse(
fuchsia::ui::observation::geometry::WatchResponse response) {
// Process update if no error
if (!response.has_error()) {
std::vector<fuchsia::ui::observation::geometry::ViewTreeSnapshot>* updates =
response.mutable_updates();
if (updates && !updates->empty()) {
last_view_tree_snapshot_ = std::move(updates->back());
}
} else {
// Otherwise process error
const auto& error = response.error();
if (error | fuchsia::ui::observation::geometry::Error::CHANNEL_OVERFLOW) {
FML_LOG(INFO) << "View Tree watcher channel overflowed";
} else if (error |
fuchsia::ui::observation::geometry::Error::BUFFER_OVERFLOW) {
FML_LOG(INFO) << "View Tree watcher buffer overflowed";
} else if (error |
fuchsia::ui::observation::geometry::Error::VIEWS_OVERFLOW) {
// This one indicates some possible data loss, so we log with a high
// severity
FML_LOG(WARNING)
<< "View Tree watcher attempted to report too many views";
}
}
}
void PortableUITest::WatchViewGeometry() {
FML_CHECK(view_tree_watcher_)
<< "View Tree watcher must be registered before calling Watch()";
view_tree_watcher_->Watch([this](auto response) {
ProcessViewGeometryResponse(std::move(response));
WatchViewGeometry();
});
}
bool PortableUITest::HasViewConnected(zx_koid_t view_ref_koid) {
return last_view_tree_snapshot_.has_value() &&
CheckViewExistsInSnapshot(*last_view_tree_snapshot_, view_ref_koid);
}
void PortableUITest::LaunchClient() {
scene_provider_ =
realm_->component().Connect<fuchsia::ui::test::scene::Controller>();
scene_provider_.set_error_handler([](auto) {
FML_LOG(ERROR) << "Error from test scene provider: "
<< &zx_status_get_string;
});
fuchsia::ui::test::scene::ControllerAttachClientViewRequest request;
request.set_view_provider(
realm_->component().Connect<fuchsia::ui::app::ViewProvider>());
scene_provider_->RegisterViewTreeWatcher(view_tree_watcher_.NewRequest(),
[]() {});
scene_provider_->AttachClientView(
std::move(request), [this](auto client_view_ref_koid) {
client_root_view_ref_koid_ = client_view_ref_koid;
});
FML_LOG(INFO) << "Waiting for client view ref koid";
RunLoopUntil([this] { return client_root_view_ref_koid_.has_value(); });
WatchViewGeometry();
FML_LOG(INFO) << "Waiting for client view to connect";
// Wait for the client view to get attached to the view tree.
RunLoopUntil(
[this] { return HasViewConnected(*client_root_view_ref_koid_); });
FML_LOG(INFO) << "Client view has rendered";
}
void PortableUITest::LaunchClientWithEmbeddedView() {
LaunchClient();
// At this point, the parent view must have rendered, so we just need to wait
// for the embedded view.
RunLoopUntil([this] {
if (!last_view_tree_snapshot_.has_value() ||
!last_view_tree_snapshot_->has_views()) {
return false;
}
if (!client_root_view_ref_koid_.has_value()) {
return false;
}
for (const auto& view : last_view_tree_snapshot_->views()) {
if (!view.has_view_ref_koid() ||
view.view_ref_koid() != *client_root_view_ref_koid_) {
continue;
}
if (view.children().empty()) {
return false;
}
// NOTE: We can't rely on the presence of the child view in
// `view.children()` to guarantee that it has rendered. The child view
// also needs to be present in `last_view_tree_snapshot_->views`.
return std::count_if(
last_view_tree_snapshot_->views().begin(),
last_view_tree_snapshot_->views().end(),
[view_to_find =
view.children().back()](const auto& view_to_check) {
return view_to_check.has_view_ref_koid() &&
view_to_check.view_ref_koid() == view_to_find;
}) > 0;
}
return false;
});
FML_LOG(INFO) << "Embedded view has rendered";
}
void PortableUITest::RegisterTouchScreen() {
FML_LOG(INFO) << "Registering fake touch screen";
input_registry_ =
realm_->component().Connect<fuchsia::ui::test::input::Registry>();
input_registry_.set_error_handler([](auto) {
FML_LOG(ERROR) << "Error from input helper: " << &zx_status_get_string;
});
bool touchscreen_registered = false;
fuchsia::ui::test::input::RegistryRegisterTouchScreenRequest request;
request.set_device(fake_touchscreen_.NewRequest());
input_registry_->RegisterTouchScreen(
std::move(request),
[&touchscreen_registered]() { touchscreen_registered = true; });
RunLoopUntil([&touchscreen_registered] { return touchscreen_registered; });
FML_LOG(INFO) << "Touchscreen registered";
}
void PortableUITest::RegisterMouse() {
FML_LOG(INFO) << "Registering fake mouse";
input_registry_ =
realm_->component().Connect<fuchsia::ui::test::input::Registry>();
input_registry_.set_error_handler([](auto) {
FML_LOG(ERROR) << "Error from input helper: " << &zx_status_get_string;
});
bool mouse_registered = false;
fuchsia::ui::test::input::RegistryRegisterMouseRequest request;
request.set_device(fake_mouse_.NewRequest());
input_registry_->RegisterMouse(
std::move(request), [&mouse_registered]() { mouse_registered = true; });
RunLoopUntil([&mouse_registered] { return mouse_registered; });
FML_LOG(INFO) << "Mouse registered";
}
void PortableUITest::RegisterKeyboard() {
FML_LOG(INFO) << "Registering fake keyboard";
input_registry_ =
realm_->component().Connect<fuchsia::ui::test::input::Registry>();
input_registry_.set_error_handler([](auto) {
FML_LOG(ERROR) << "Error from input helper: " << &zx_status_get_string;
});
bool keyboard_registered = false;
fuchsia::ui::test::input::RegistryRegisterKeyboardRequest request;
request.set_device(fake_keyboard_.NewRequest());
input_registry_->RegisterKeyboard(
std::move(request),
[&keyboard_registered]() { keyboard_registered = true; });
RunLoopUntil([&keyboard_registered] { return keyboard_registered; });
FML_LOG(INFO) << "Keyboard registered";
}
void PortableUITest::InjectTap(int32_t x, int32_t y) {
fuchsia::ui::test::input::TouchScreenSimulateTapRequest tap_request;
tap_request.mutable_tap_location()->x = x;
tap_request.mutable_tap_location()->y = y;
FML_LOG(INFO) << "Injecting tap at (" << tap_request.tap_location().x << ", "
<< tap_request.tap_location().y << ")";
fake_touchscreen_->SimulateTap(std::move(tap_request), [this]() {
++touch_injection_request_count_;
FML_LOG(INFO) << "*** Tap injected, count: "
<< touch_injection_request_count_;
});
}
void PortableUITest::SimulateMouseEvent(
std::vector<fuchsia::ui::test::input::MouseButton> pressed_buttons,
int movement_x,
int movement_y) {
fuchsia::ui::test::input::MouseSimulateMouseEventRequest request;
request.set_pressed_buttons(std::move(pressed_buttons));
request.set_movement_x(movement_x);
request.set_movement_y(movement_y);
FML_LOG(INFO) << "Injecting mouse input";
fake_mouse_->SimulateMouseEvent(
std::move(request), [] { FML_LOG(INFO) << "Mouse event injected"; });
}
void PortableUITest::SimulateMouseScroll(
std::vector<fuchsia::ui::test::input::MouseButton> pressed_buttons,
int scroll_x,
int scroll_y,
bool use_physical_units) {
FML_LOG(INFO) << "Requesting mouse scroll";
fuchsia::ui::test::input::MouseSimulateMouseEventRequest request;
request.set_pressed_buttons(std::move(pressed_buttons));
if (use_physical_units) {
request.set_scroll_h_physical_pixel(scroll_x);
request.set_scroll_v_physical_pixel(scroll_y);
} else {
request.set_scroll_h_detent(scroll_x);
request.set_scroll_v_detent(scroll_y);
}
fake_mouse_->SimulateMouseEvent(std::move(request), [] {
FML_LOG(INFO) << "Mouse scroll event injected";
});
}
void PortableUITest::SimulateTextEntry(std::string text) {
FML_LOG(INFO) << "Sending text request";
bool done = false;
fuchsia::ui::test::input::KeyboardSimulateUsAsciiTextEntryRequest request;
request.set_text(text);
fake_keyboard_->SimulateUsAsciiTextEntry(std::move(request),
[&done]() { done = true; });
RunLoopUntil([&] { return done; });
FML_LOG(INFO) << "Text request sent";
}
} // namespace fuchsia_test_utils
| engine/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/portable_ui_test.cc",
"repo_id": "engine",
"token_count": 4797
} | 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.
#include "vsync_waiter.h"
#include <cstdint>
#include <lib/async/default.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/synchronization/waitable_event.h"
#include "flutter/fml/time/time_delta.h"
#include "flutter/fml/trace_event.h"
#include "flutter_runner_product_configuration.h"
namespace flutter_runner {
VsyncWaiter::VsyncWaiter(AwaitVsyncCallback await_vsync_callback,
AwaitVsyncForSecondaryCallbackCallback
await_vsync_for_secondary_callback_callback,
flutter::TaskRunners task_runners)
: flutter::VsyncWaiter(task_runners),
await_vsync_callback_(await_vsync_callback),
await_vsync_for_secondary_callback_callback_(
await_vsync_for_secondary_callback_callback),
weak_factory_ui_(nullptr),
weak_factory_(this) {
fire_callback_callback_ = [this](fml::TimePoint frame_start,
fml::TimePoint frame_end) {
task_runners_.GetUITaskRunner()->PostTaskForTime(
[frame_start, frame_end, weak_this = weak_ui_]() {
if (weak_this) {
// Note: It is VERY important to set |pause_secondary_tasks| to
// false, else Animator will almost immediately crash on Fuchsia.
// FML_LOG(INFO) << "CRASH:: VsyncWaiter about to FireCallback";
weak_this->FireCallback(frame_start, frame_end,
/*pause_secondary_tasks*/ false);
}
},
frame_start);
};
// Generate a WeakPtrFactory for use with the UI thread. This does not need
// to wait on a latch because we only ever use the WeakPtrFactory on the UI
// thread so we have ordering guarantees (see ::AwaitVSync())
fml::TaskRunner::RunNowOrPostTask(
task_runners_.GetUITaskRunner(), fml::MakeCopyable([this]() mutable {
weak_factory_ui_ =
std::make_unique<fml::WeakPtrFactory<VsyncWaiter>>(this);
weak_ui_ = weak_factory_ui_->GetWeakPtr();
}));
}
VsyncWaiter::~VsyncWaiter() {
fml::AutoResetWaitableEvent ui_latch;
fml::TaskRunner::RunNowOrPostTask(
task_runners_.GetUITaskRunner(),
fml::MakeCopyable(
[weak_factory_ui = std::move(weak_factory_ui_), &ui_latch]() mutable {
weak_factory_ui.reset();
ui_latch.Signal();
}));
ui_latch.Wait();
}
void VsyncWaiter::AwaitVSync() {
await_vsync_callback_(fire_callback_callback_);
}
void VsyncWaiter::AwaitVSyncForSecondaryCallback() {
await_vsync_for_secondary_callback_callback_(fire_callback_callback_);
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/vsync_waiter.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/vsync_waiter.cc",
"repo_id": "engine",
"token_count": 1207
} | 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.
#include "build_info.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <lib/async-loop/cpp/loop.h>
#include <lib/async-loop/default.h>
#include <lib/inspect/cpp/reader.h>
const std::string& inspect_node_name = "build_info_unittests";
void checkProperty(inspect::Hierarchy& root,
const std::string& name,
const std::string& expected_value) {
const inspect::Hierarchy* build_info = root.GetByPath({inspect_node_name});
EXPECT_TRUE(build_info != nullptr);
auto* actual_value =
build_info->node().get_property<inspect::StringPropertyValue>(name);
EXPECT_TRUE(actual_value != nullptr);
EXPECT_EQ(actual_value->value(), expected_value);
}
namespace dart_utils {
class BuildInfoTest : public ::testing::Test {
public:
static void SetUpTestSuite() {
async::Loop loop(&kAsyncLoopConfigAttachToCurrentThread);
auto context = sys::ComponentContext::Create();
RootInspectNode::Initialize(context.get());
}
};
TEST_F(BuildInfoTest, AllPropertiesAreDefined) {
EXPECT_NE(BuildInfo::DartSdkGitRevision(), "{{DART_SDK_GIT_REVISION}}");
EXPECT_NE(BuildInfo::DartSdkSemanticVersion(),
"{{DART_SDK_SEMANTIC_VERSION}}");
EXPECT_NE(BuildInfo::FlutterEngineGitRevision(),
"{{FLUTTER_ENGINE_GIT_REVISION}}");
EXPECT_NE(BuildInfo::FuchsiaSdkVersion(), "{{FUCHSIA_SDK_VERSION}}");
}
TEST_F(BuildInfoTest, AllPropertiesAreDumped) {
inspect::Node node =
dart_utils::RootInspectNode::CreateRootChild(inspect_node_name);
BuildInfo::Dump(node);
inspect::Hierarchy root =
inspect::ReadFromVmo(
std::move(
dart_utils::RootInspectNode::GetInspector()->DuplicateVmo()))
.take_value();
checkProperty(root, "dart_sdk_git_revision", BuildInfo::DartSdkGitRevision());
checkProperty(root, "dart_sdk_semantic_version",
BuildInfo::DartSdkSemanticVersion());
checkProperty(root, "flutter_engine_git_revision",
BuildInfo::FlutterEngineGitRevision());
checkProperty(root, "fuchsia_sdk_version", BuildInfo::FuchsiaSdkVersion());
}
} // namespace dart_utils
| engine/shell/platform/fuchsia/runtime/dart/utils/build_info_unittests.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/build_info_unittests.cc",
"repo_id": "engine",
"token_count": 901
} | 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 "vmservice_object.h"
#include <dirent.h>
#include <fuchsia/io/cpp/fidl.h>
#include <zircon/status.h>
#include <cerrno>
#include <string>
#include "flutter/fml/logging.h"
namespace {
bool ReadDirContents(const std::string& path, std::vector<std::string>* out) {
out->clear();
DIR* dir = opendir(path.c_str());
if (!dir) {
return false;
}
struct dirent* de;
errno = 0;
while ((de = readdir(dir)) != nullptr) {
out->push_back(de->d_name);
}
closedir(dir);
return !errno;
}
} // namespace
namespace dart_utils {
void VMServiceObject::GetContents(LazyEntryVector* out_vector) const {
// List /tmp/dart.services if it exists, and push its contents as
// the contents of this directory.
std::vector<std::string> files;
if (!ReadDirContents(kPortDir, &files)) {
FML_LOG(ERROR) << "Failed to read Dart VM service port directory '"
<< kPortDir << "': " << strerror(errno);
return;
}
for (const auto& file : files) {
if ((file == ".") || (file == "..")) {
continue;
}
out_vector->push_back({std::stoul(file) + GetStartingId(), file,
fuchsia::io::MODE_TYPE_FILE});
}
}
zx_status_t VMServiceObject::GetFile(Node** out_node,
uint64_t id,
std::string name) const {
return ZX_ERR_NOT_FOUND;
}
} // namespace dart_utils
| engine/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/vmservice_object.cc",
"repo_id": "engine",
"token_count": 671
} | 397 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_
#include <memory>
#include "flutter/shell/platform/glfw/public/flutter_glfw.h"
namespace flutter {
namespace testing {
// Base class for a object that provides test implementations of the APIs in
// the headers in platform/glfw/public/.
// Linking this class into a test binary will provide dummy forwarding
// implementations of that C API, so that the wrapper can be tested separately
// from the actual library.
class StubFlutterGlfwApi {
public:
// Sets |stub| as the instance to which calls to the Flutter library C APIs
// will be forwarded.
static void SetTestStub(StubFlutterGlfwApi* stub);
// Returns the current stub, as last set by SetTestFlutterStub.
static StubFlutterGlfwApi* GetTestStub();
virtual ~StubFlutterGlfwApi() {}
// Called for FlutterDesktopInit.
virtual bool Init() { return true; }
// Called for FlutterDesktopTerminate.
virtual void Terminate() {}
// Called for FlutterDesktopCreateWindow.
virtual FlutterDesktopWindowControllerRef CreateWindow(
const FlutterDesktopWindowProperties& window_properties,
const FlutterDesktopEngineProperties& engine_properties) {
return nullptr;
}
// Called for FlutterDesktopDestroyWindow
virtual void DestroyWindow() {}
// Called for FlutterDesktopWindowSetHoverEnabled.
virtual void SetHoverEnabled(bool enabled) {}
// Called for FlutterDesktopWindowSetTitle.
virtual void SetWindowTitle(const char* title) {}
// Called for FlutterDesktopWindowSetIcon.
virtual void SetWindowIcon(uint8_t* pixel_data, int width, int height) {}
// Called for FlutterDesktopWindowGetFrame.
virtual void GetWindowFrame(int* x, int* y, int* width, int* height) {
x = y = width = height = 0;
}
// Called for FlutterDesktopWindowGetFrame.
virtual void SetWindowFrame(int x, int y, int width, int height) {}
// Called for FlutterDesktopWindowGetScaleFactor.
virtual double GetWindowScaleFactor() { return 1.0; }
// Called for FlutterDesktopWindowSetPixelRatioOverride.
virtual void SetPixelRatioOverride(double pixel_ratio) {}
// Called for FlutterDesktopWindowSetSizeLimits.
virtual void SetSizeLimits(FlutterDesktopSize minimum_size,
FlutterDesktopSize maximum_size) {}
// Called for FlutterDesktopRunWindowEventLoopWithTimeout.
virtual bool RunWindowEventLoopWithTimeout(uint32_t millisecond_timeout) {
return true;
}
// Called for FlutterDesktopRunEngine.
virtual FlutterDesktopEngineRef RunEngine(
const FlutterDesktopEngineProperties& properties) {
return nullptr;
}
// Called for FlutterDesktopRunEngineEventLoopWithTimeout.
virtual void RunEngineEventLoopWithTimeout(uint32_t millisecond_timeout) {}
// Called for FlutterDesktopShutDownEngine.
virtual bool ShutDownEngine() { return true; }
// Called for FlutterDesktopPluginRegistrarEnableInputBlocking.
virtual void PluginRegistrarEnableInputBlocking(const char* channel) {}
};
// A test helper that owns a stub implementation, making it the test stub for
// the lifetime of the object, then restoring the previous value.
class ScopedStubFlutterGlfwApi {
public:
// Calls SetTestFlutterStub with |stub|.
explicit ScopedStubFlutterGlfwApi(std::unique_ptr<StubFlutterGlfwApi> stub);
// Restores the previous test stub.
~ScopedStubFlutterGlfwApi();
StubFlutterGlfwApi* stub() { return stub_.get(); }
private:
std::unique_ptr<StubFlutterGlfwApi> stub_;
// The previous stub.
StubFlutterGlfwApi* previous_stub_;
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_CLIENT_WRAPPER_TESTING_STUB_FLUTTER_GLFW_API_H_
| engine/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h/0 | {
"file_path": "engine/shell/platform/glfw/client_wrapper/testing/stub_flutter_glfw_api.h",
"repo_id": "engine",
"token_count": 1238
} | 398 |
// 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_SYSTEM_UTILS_H_
#define FLUTTER_SHELL_PLATFORM_GLFW_SYSTEM_UTILS_H_
#include <string>
#include <vector>
#include "flutter/shell/platform/embedder/embedder.h"
namespace flutter {
// Components of a system language/locale.
struct LanguageInfo {
std::string language;
std::string territory;
std::string codeset;
std::string modifier;
};
// Returns the list of user-preferred languages, in preference order,
// parsed into LanguageInfo structures.
std::vector<LanguageInfo> GetPreferredLanguageInfo();
// Converts a vector of LanguageInfo structs to a vector of FlutterLocale
// structs. |languages| must outlive the returned value, since the returned
// elements have pointers into it.
std::vector<FlutterLocale> ConvertToFlutterLocale(
const std::vector<LanguageInfo>& languages);
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_GLFW_SYSTEM_UTILS_H_
| engine/shell/platform/glfw/system_utils.h/0 | {
"file_path": "engine/shell/platform/glfw/system_utils.h",
"repo_id": "engine",
"token_count": 337
} | 399 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_codec.h"
#include <gmodule.h>
G_DEFINE_QUARK(fl_binary_codec_error_quark, fl_binary_codec_error)
struct _FlBinaryCodec {
FlMessageCodec parent_instance;
};
G_DEFINE_TYPE(FlBinaryCodec, fl_binary_codec, fl_message_codec_get_type())
// Implements FlMessageCodec::encode_message.
static GBytes* fl_binary_codec_encode_message(FlMessageCodec* codec,
FlValue* value,
GError** error) {
if (fl_value_get_type(value) != FL_VALUE_TYPE_UINT8_LIST) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE,
"Only uint8[] values supported");
return nullptr;
}
return g_bytes_new(fl_value_get_uint8_list(value),
fl_value_get_length(value));
}
// Implements FlMessageCodec::decode_message.
static FlValue* fl_binary_codec_decode_message(FlMessageCodec* codec,
GBytes* message,
GError** error) {
gsize data_length;
const uint8_t* data =
static_cast<const uint8_t*>(g_bytes_get_data(message, &data_length));
return fl_value_new_uint8_list(data, data_length);
}
static void fl_binary_codec_class_init(FlBinaryCodecClass* klass) {
FL_MESSAGE_CODEC_CLASS(klass)->encode_message =
fl_binary_codec_encode_message;
FL_MESSAGE_CODEC_CLASS(klass)->decode_message =
fl_binary_codec_decode_message;
}
static void fl_binary_codec_init(FlBinaryCodec* self) {}
G_MODULE_EXPORT FlBinaryCodec* fl_binary_codec_new() {
return static_cast<FlBinaryCodec*>(
g_object_new(fl_binary_codec_get_type(), nullptr));
}
| engine/shell/platform/linux/fl_binary_codec.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_binary_codec.cc",
"repo_id": "engine",
"token_count": 907
} | 400 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h"
#include <gmodule.h>
#include <cstring>
#include "rapidjson/reader.h"
#include "rapidjson/writer.h"
G_DEFINE_QUARK(fl_json_message_codec_error_quark, fl_json_message_codec_error)
struct _FlJsonMessageCodec {
FlMessageCodec parent_instance;
};
G_DEFINE_TYPE(FlJsonMessageCodec,
fl_json_message_codec,
fl_message_codec_get_type())
// Recursively writes #FlValue objects using rapidjson.
static gboolean write_value(rapidjson::Writer<rapidjson::StringBuffer>& writer,
FlValue* value,
GError** error) {
if (value == nullptr) {
writer.Null();
return TRUE;
}
switch (fl_value_get_type(value)) {
case FL_VALUE_TYPE_NULL:
writer.Null();
break;
case FL_VALUE_TYPE_BOOL:
writer.Bool(fl_value_get_bool(value));
break;
case FL_VALUE_TYPE_INT:
writer.Int64(fl_value_get_int(value));
break;
case FL_VALUE_TYPE_FLOAT:
writer.Double(fl_value_get_float(value));
break;
case FL_VALUE_TYPE_STRING:
writer.String(fl_value_get_string(value));
break;
case FL_VALUE_TYPE_UINT8_LIST: {
writer.StartArray();
const uint8_t* data = fl_value_get_uint8_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
writer.Int(data[i]);
}
writer.EndArray();
break;
}
case FL_VALUE_TYPE_INT32_LIST: {
writer.StartArray();
const int32_t* data = fl_value_get_int32_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
writer.Int(data[i]);
}
writer.EndArray();
break;
}
case FL_VALUE_TYPE_INT64_LIST: {
writer.StartArray();
const int64_t* data = fl_value_get_int64_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
writer.Int64(data[i]);
}
writer.EndArray();
break;
}
case FL_VALUE_TYPE_FLOAT_LIST: {
writer.StartArray();
const double* data = fl_value_get_float_list(value);
for (size_t i = 0; i < fl_value_get_length(value); i++) {
writer.Double(data[i]);
}
writer.EndArray();
break;
}
case FL_VALUE_TYPE_LIST: {
writer.StartArray();
for (size_t i = 0; i < fl_value_get_length(value); i++) {
if (!write_value(writer, fl_value_get_list_value(value, i), error)) {
return FALSE;
}
}
writer.EndArray();
break;
}
case FL_VALUE_TYPE_MAP: {
writer.StartObject();
for (size_t i = 0; i < fl_value_get_length(value); i++) {
FlValue* key = fl_value_get_map_key(value, i);
if (fl_value_get_type(key) != FL_VALUE_TYPE_STRING) {
g_set_error(error, FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_OBJECT_KEY_TYPE,
"Invalid object key type");
return FALSE;
}
writer.Key(fl_value_get_string(key));
if (!write_value(writer, fl_value_get_map_value(value, i), error)) {
return FALSE;
}
}
writer.EndObject();
break;
}
default:
g_set_error(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE,
"Unexpected FlValue type %d", fl_value_get_type(value));
return FALSE;
}
return TRUE;
}
// Handler to parse JSON using rapidjson in SAX mode.
struct FlValueHandler {
GPtrArray* stack;
FlValue* key;
GError* error;
FlValueHandler() {
stack = g_ptr_array_new_with_free_func(
reinterpret_cast<GDestroyNotify>(fl_value_unref));
key = nullptr;
error = nullptr;
}
~FlValueHandler() {
g_ptr_array_unref(stack);
if (key != nullptr) {
fl_value_unref(key);
}
if (error != nullptr) {
g_error_free(error);
}
}
// Gets the current head of the stack.
FlValue* get_head() {
if (stack->len == 0) {
return nullptr;
}
return static_cast<FlValue*>(g_ptr_array_index(stack, stack->len - 1));
}
// Pushes a value onto the stack.
void push(FlValue* value) { g_ptr_array_add(stack, fl_value_ref(value)); }
// Pops the stack.
void pop() { g_ptr_array_remove_index(stack, stack->len - 1); }
// Adds a new value to the stack.
bool add(FlValue* value) {
g_autoptr(FlValue) owned_value = value;
FlValue* head = get_head();
if (head == nullptr) {
push(owned_value);
} else if (fl_value_get_type(head) == FL_VALUE_TYPE_LIST) {
fl_value_append(head, owned_value);
} else if (fl_value_get_type(head) == FL_VALUE_TYPE_MAP) {
fl_value_set_take(head, key, fl_value_ref(owned_value));
key = nullptr;
} else {
g_set_error(&error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Can't add value to non container");
return false;
}
if (fl_value_get_type(owned_value) == FL_VALUE_TYPE_LIST ||
fl_value_get_type(owned_value) == FL_VALUE_TYPE_MAP) {
push(value);
}
return true;
}
// The following implements the rapidjson SAX API.
bool Null() { return add(fl_value_new_null()); }
bool Bool(bool b) { return add(fl_value_new_bool(b)); }
bool Int(int i) { return add(fl_value_new_int(i)); }
bool Uint(unsigned i) { return add(fl_value_new_int(i)); }
bool Int64(int64_t i) { return add(fl_value_new_int(i)); }
bool Uint64(uint64_t i) {
// For some reason (bug in rapidjson?) this is not returned in Int64.
if (i == G_MAXINT64) {
return add(fl_value_new_int(i));
} else {
return add(fl_value_new_float(i));
}
}
bool Double(double d) { return add(fl_value_new_float(d)); }
bool RawNumber(const char* str, rapidjson::SizeType length, bool copy) {
g_set_error(&error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"RawNumber not supported");
return false;
}
bool String(const char* str, rapidjson::SizeType length, bool copy) {
FlValue* v = fl_value_new_string_sized(str, length);
return add(v);
}
bool StartObject() { return add(fl_value_new_map()); }
bool Key(const char* str, rapidjson::SizeType length, bool copy) {
if (key != nullptr) {
fl_value_unref(key);
}
key = fl_value_new_string_sized(str, length);
return true;
}
bool EndObject(rapidjson::SizeType memberCount) {
pop();
return true;
}
bool StartArray() { return add(fl_value_new_list()); }
bool EndArray(rapidjson::SizeType elementCount) {
pop();
return true;
}
};
// Implements FlMessageCodec:encode_message.
static GBytes* fl_json_message_codec_encode_message(FlMessageCodec* codec,
FlValue* message,
GError** error) {
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
if (!write_value(writer, message, error)) {
return nullptr;
}
const gchar* text = buffer.GetString();
return g_bytes_new(text, strlen(text));
}
// Implements FlMessageCodec:decode_message.
static FlValue* fl_json_message_codec_decode_message(FlMessageCodec* codec,
GBytes* message,
GError** error) {
gsize data_length;
const gchar* data =
static_cast<const char*>(g_bytes_get_data(message, &data_length));
if (!g_utf8_validate(data, data_length, nullptr)) {
g_set_error(error, FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_UTF8,
"Message is not valid UTF8");
return nullptr;
}
FlValueHandler handler;
rapidjson::Reader reader;
rapidjson::MemoryStream ss(data, data_length);
if (!reader.Parse(ss, handler)) {
if (handler.error != nullptr) {
g_propagate_error(error, handler.error);
handler.error = nullptr;
} else {
g_set_error(error, FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON,
"Message is not valid JSON");
}
return nullptr;
}
FlValue* value = handler.get_head();
if (value == nullptr) {
g_set_error(error, FL_JSON_MESSAGE_CODEC_ERROR,
FL_JSON_MESSAGE_CODEC_ERROR_INVALID_JSON,
"Message is not valid JSON");
return nullptr;
}
return fl_value_ref(value);
}
static void fl_json_message_codec_class_init(FlJsonMessageCodecClass* klass) {
FL_MESSAGE_CODEC_CLASS(klass)->encode_message =
fl_json_message_codec_encode_message;
FL_MESSAGE_CODEC_CLASS(klass)->decode_message =
fl_json_message_codec_decode_message;
}
static void fl_json_message_codec_init(FlJsonMessageCodec* self) {}
G_MODULE_EXPORT FlJsonMessageCodec* fl_json_message_codec_new() {
return static_cast<FlJsonMessageCodec*>(
g_object_new(fl_json_message_codec_get_type(), nullptr));
}
G_MODULE_EXPORT gchar* fl_json_message_codec_encode(FlJsonMessageCodec* codec,
FlValue* value,
GError** error) {
g_return_val_if_fail(FL_IS_JSON_CODEC(codec), nullptr);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
if (!write_value(writer, value, error)) {
return nullptr;
}
return g_strdup(buffer.GetString());
}
G_MODULE_EXPORT FlValue* fl_json_message_codec_decode(FlJsonMessageCodec* codec,
const gchar* text,
GError** error) {
g_return_val_if_fail(FL_IS_JSON_CODEC(codec), nullptr);
g_autoptr(GBytes) data = g_bytes_new_static(text, strlen(text));
g_autoptr(FlValue) value = fl_json_message_codec_decode_message(
FL_MESSAGE_CODEC(codec), data, error);
if (value == nullptr) {
return nullptr;
}
return fl_value_ref(value);
}
| engine/shell/platform/linux/fl_json_message_codec.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_json_message_codec.cc",
"repo_id": "engine",
"token_count": 4719
} | 401 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_KEYBOARD_MANAGER_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_KEYBOARD_MANAGER_H_
#include <gdk/gdk.h>
#include "flutter/shell/platform/linux/fl_keyboard_view_delegate.h"
G_BEGIN_DECLS
#define FL_TYPE_KEYBOARD_MANAGER fl_keyboard_manager_get_type()
G_DECLARE_FINAL_TYPE(FlKeyboardManager,
fl_keyboard_manager,
FL,
KEYBOARD_MANAGER,
GObject);
/**
* FlKeyboardManager:
*
* Processes keyboard events and cooperate with `TextInputPlugin`.
*
* A keyboard event goes through a few sections, each can choose to handle the
* event, and only unhandled events can move to the next section:
*
* - Keyboard: Dispatch to the embedder responder and the channel responder
* simultaneously. After both responders have responded (asynchronously), the
* event is considered handled if either responder handles it.
* - Text input: Events are sent to IM filter (usually owned by
* `TextInputPlugin`) and are handled synchronously.
* - Redispatching: Events are inserted back to the system for redispatching.
*/
/**
* fl_keyboard_manager_new:
* @view_delegate: An interface that the manager requires to communicate with
* the platform. Usually implemented by FlView.
*
* Create a new #FlKeyboardManager.
*
* Returns: a new #FlKeyboardManager.
*/
FlKeyboardManager* fl_keyboard_manager_new(
FlBinaryMessenger* messenger,
FlKeyboardViewDelegate* view_delegate);
/**
* fl_keyboard_manager_handle_event:
* @manager: the #FlKeyboardManager self.
* @event: the event to be dispatched. It is usually a wrap of a GdkEventKey.
* This event will be managed and released by #FlKeyboardManager.
*
* Make the manager process a system key event. This might eventually send
* messages to the framework, trigger text input effects, or redispatch the
* event back to the system.
*/
gboolean fl_keyboard_manager_handle_event(FlKeyboardManager* manager,
FlKeyEvent* event);
/**
* fl_keyboard_manager_is_state_clear:
* @manager: the #FlKeyboardManager self.
*
* A debug-only method that queries whether the manager's various states are
* cleared, i.e. no pending events for redispatching or for responding.
*
* Returns: true if the manager's various states are cleared.
*/
gboolean fl_keyboard_manager_is_state_clear(FlKeyboardManager* manager);
/**
* fl_keyboard_manager_sync_modifier_if_needed:
* @manager: the #FlKeyboardManager self.
* @state: the state of the modifiers mask.
* @event_time: the time attribute of the incoming GDK event.
*
* If needed, synthesize modifier keys up and down event by comparing their
* current pressing states with the given modifiers mask.
*/
void fl_keyboard_manager_sync_modifier_if_needed(FlKeyboardManager* manager,
guint state,
double event_time);
/**
* fl_keyboard_manager_get_pressed_state:
* @manager: the #FlKeyboardManager self.
*
* 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_keyboard_manager_get_pressed_state(FlKeyboardManager* manager);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_KEYBOARD_MANAGER_H_
| engine/shell/platform/linux/fl_keyboard_manager.h/0 | {
"file_path": "engine/shell/platform/linux/fl_keyboard_manager.h",
"repo_id": "engine",
"token_count": 1224
} | 402 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/fl_mouse_cursor_plugin.h"
#include <gtk/gtk.h>
#include <cstring>
#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"
static constexpr char kChannelName[] = "flutter/mousecursor";
static constexpr char kBadArgumentsError[] = "Bad Arguments";
static constexpr char kActivateSystemCursorMethod[] = "activateSystemCursor";
static constexpr char kKindKey[] = "kind";
static constexpr char kFallbackCursor[] = "default";
struct _FlMouseCursorPlugin {
GObject parent_instance;
FlMethodChannel* channel;
FlView* view;
GHashTable* system_cursor_table;
};
G_DEFINE_TYPE(FlMouseCursorPlugin, fl_mouse_cursor_plugin, G_TYPE_OBJECT)
// Insert a new entry into a hashtable from strings to strings.
//
// Returns whether the newly added value was already in the hash table or not.
static bool define_system_cursor(GHashTable* table,
const gchar* key,
const gchar* value) {
return g_hash_table_insert(
table, reinterpret_cast<gpointer>(const_cast<gchar*>(key)),
reinterpret_cast<gpointer>(const_cast<gchar*>(value)));
}
// Populate the hash table so that it maps from Flutter's cursor kinds to GTK's
// cursor values.
//
// The table must have been created as a hashtable from strings to strings.
static void populate_system_cursor_table(GHashTable* table) {
// The following mapping must be kept in sync with Flutter framework's
// mouse_cursor.dart.
define_system_cursor(table, "alias", "alias");
define_system_cursor(table, "allScroll", "all-scroll");
define_system_cursor(table, "basic", "default");
define_system_cursor(table, "cell", "cell");
define_system_cursor(table, "click", "pointer");
define_system_cursor(table, "contextMenu", "context-menu");
define_system_cursor(table, "copy", "copy");
define_system_cursor(table, "forbidden", "not-allowed");
define_system_cursor(table, "grab", "grab");
define_system_cursor(table, "grabbing", "grabbing");
define_system_cursor(table, "help", "help");
define_system_cursor(table, "move", "move");
define_system_cursor(table, "none", "none");
define_system_cursor(table, "noDrop", "no-drop");
define_system_cursor(table, "precise", "crosshair");
define_system_cursor(table, "progress", "progress");
define_system_cursor(table, "text", "text");
define_system_cursor(table, "resizeColumn", "col-resize");
define_system_cursor(table, "resizeDown", "s-resize");
define_system_cursor(table, "resizeDownLeft", "sw-resize");
define_system_cursor(table, "resizeDownRight", "se-resize");
define_system_cursor(table, "resizeLeft", "w-resize");
define_system_cursor(table, "resizeLeftRight", "ew-resize");
define_system_cursor(table, "resizeRight", "e-resize");
define_system_cursor(table, "resizeRow", "row-resize");
define_system_cursor(table, "resizeUp", "n-resize");
define_system_cursor(table, "resizeUpDown", "ns-resize");
define_system_cursor(table, "resizeUpLeft", "nw-resize");
define_system_cursor(table, "resizeUpRight", "ne-resize");
define_system_cursor(table, "resizeUpLeftDownRight", "nwse-resize");
define_system_cursor(table, "resizeUpRightDownLeft", "nesw-resize");
define_system_cursor(table, "verticalText", "vertical-text");
define_system_cursor(table, "wait", "wait");
define_system_cursor(table, "zoomIn", "zoom-in");
define_system_cursor(table, "zoomOut", "zoom-out");
}
// Sets the mouse cursor.
FlMethodResponse* activate_system_cursor(FlMouseCursorPlugin* self,
FlValue* args) {
if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) {
return FL_METHOD_RESPONSE(fl_method_error_response_new(
kBadArgumentsError, "Argument map missing or malformed", nullptr));
}
FlValue* kind_value = fl_value_lookup_string(args, kKindKey);
const gchar* kind = nullptr;
if (fl_value_get_type(kind_value) == FL_VALUE_TYPE_STRING) {
kind = fl_value_get_string(kind_value);
}
if (self->system_cursor_table == nullptr) {
self->system_cursor_table = g_hash_table_new(g_str_hash, g_str_equal);
populate_system_cursor_table(self->system_cursor_table);
}
const gchar* cursor_name = reinterpret_cast<const gchar*>(
g_hash_table_lookup(self->system_cursor_table, kind));
if (cursor_name == nullptr) {
cursor_name = kFallbackCursor;
}
GdkWindow* window =
gtk_widget_get_window(gtk_widget_get_toplevel(GTK_WIDGET(self->view)));
g_autoptr(GdkCursor) cursor =
gdk_cursor_new_from_name(gdk_window_get_display(window), cursor_name);
gdk_window_set_cursor(window, cursor);
return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr));
}
// Called when a method call is received from Flutter.
static void method_call_cb(FlMethodChannel* channel,
FlMethodCall* method_call,
gpointer user_data) {
FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN(user_data);
const gchar* method = fl_method_call_get_name(method_call);
FlValue* args = fl_method_call_get_args(method_call);
g_autoptr(FlMethodResponse) response = nullptr;
if (strcmp(method, kActivateSystemCursorMethod) == 0) {
response = activate_system_cursor(self, args);
} else {
response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new());
}
g_autoptr(GError) error = nullptr;
if (!fl_method_call_respond(method_call, response, &error)) {
g_warning("Failed to send method call response: %s", error->message);
}
}
static void fl_mouse_cursor_plugin_dispose(GObject* object) {
FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN(object);
g_clear_object(&self->channel);
if (self->view != nullptr) {
g_object_remove_weak_pointer(G_OBJECT(self->view),
reinterpret_cast<gpointer*>(&(self->view)));
self->view = nullptr;
}
g_clear_pointer(&self->system_cursor_table, g_hash_table_unref);
G_OBJECT_CLASS(fl_mouse_cursor_plugin_parent_class)->dispose(object);
}
static void fl_mouse_cursor_plugin_class_init(FlMouseCursorPluginClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_mouse_cursor_plugin_dispose;
}
static void fl_mouse_cursor_plugin_init(FlMouseCursorPlugin* self) {}
FlMouseCursorPlugin* fl_mouse_cursor_plugin_new(FlBinaryMessenger* messenger,
FlView* view) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr);
FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN(
g_object_new(fl_mouse_cursor_plugin_get_type(), nullptr));
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
self->channel =
fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec));
fl_method_channel_set_method_call_handler(self->channel, method_call_cb, self,
nullptr);
self->view = view;
if (view != nullptr) {
g_object_add_weak_pointer(G_OBJECT(view),
reinterpret_cast<gpointer*>(&(self->view)));
}
return self;
}
| engine/shell/platform/linux/fl_mouse_cursor_plugin.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_mouse_cursor_plugin.cc",
"repo_id": "engine",
"token_count": 2857
} | 403 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fl_renderer_headless.h"
struct _FlRendererHeadless {
FlRenderer parent_instance;
};
G_DEFINE_TYPE(FlRendererHeadless, fl_renderer_headless, fl_renderer_get_type())
// Implements FlRenderer::make_current.
static void fl_renderer_headless_make_current(FlRenderer* renderer) {}
// Implements FlRenderer::make_resource_current.
static void fl_renderer_headless_make_resource_current(FlRenderer* renderer) {}
// Implements FlRenderer::clear_current.
static void fl_renderer_headless_clear_current(FlRenderer* renderer) {}
static void fl_renderer_headless_class_init(FlRendererHeadlessClass* klass) {
FL_RENDERER_CLASS(klass)->make_current = fl_renderer_headless_make_current;
FL_RENDERER_CLASS(klass)->make_resource_current =
fl_renderer_headless_make_resource_current;
FL_RENDERER_CLASS(klass)->clear_current = fl_renderer_headless_clear_current;
}
static void fl_renderer_headless_init(FlRendererHeadless* self) {}
FlRendererHeadless* fl_renderer_headless_new() {
return FL_RENDERER_HEADLESS(
g_object_new(fl_renderer_headless_get_type(), nullptr));
}
| engine/shell/platform/linux/fl_renderer_headless.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_renderer_headless.cc",
"repo_id": "engine",
"token_count": 452
} | 404 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_message_codec.h"
#include "flutter/shell/platform/linux/testing/fl_test.h"
#include "gtest/gtest.h"
// NOTE(robert-ancell) These test cases assumes a little-endian architecture.
// These tests will need to be updated if tested on a big endian architecture.
// Encodes a message using the supplied codec. Return a hex string with
// the encoded binary output.
static gchar* encode_message_with_codec(FlValue* value, FlMessageCodec* codec) {
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(codec, value, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return bytes_to_hex_string(message);
}
// Encodes a message using a FlStandardMessageCodec. Return a hex string with
// the encoded binary output.
static gchar* encode_message(FlValue* value) {
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
return encode_message_with_codec(value, FL_MESSAGE_CODEC(codec));
}
// Decodes a message using the supplied codec. The binary data is given in
// the form of a hex string.
static FlValue* decode_message_with_codec(const char* hex_string,
FlMessageCodec* codec) {
g_autoptr(GBytes) data = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autoptr(FlValue) value =
fl_message_codec_decode_message(codec, data, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(value, nullptr);
return fl_value_ref(value);
}
// Decodes a message using a FlStandardMessageCodec. The binary data is given in
// the form of a hex string.
static FlValue* decode_message(const char* hex_string) {
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
return decode_message_with_codec(hex_string, FL_MESSAGE_CODEC(codec));
}
// Decodes a message using a FlStandardMessageCodec. The binary data is given in
// the form of a hex string. Expect the given error.
static void decode_error_value(const char* hex_string,
GQuark domain,
gint code) {
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
g_autoptr(GBytes) data = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autoptr(FlValue) value =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), data, &error);
EXPECT_TRUE(value == nullptr);
EXPECT_TRUE(g_error_matches(error, domain, code));
}
TEST(FlStandardMessageCodecTest, EncodeNullptr) {
g_autofree gchar* hex_string = encode_message(nullptr);
EXPECT_STREQ(hex_string, "00");
}
TEST(FlStandardMessageCodecTest, EncodeNull) {
g_autoptr(FlValue) value = fl_value_new_null();
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "00");
}
TEST(FlStandardMessageCodecTest, DecodeNull) {
// Regression test for https://github.com/flutter/flutter/issues/128704.
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
g_autoptr(GBytes) data = g_bytes_new(nullptr, 0);
g_autoptr(GError) error = nullptr;
g_autoptr(FlValue) value =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), data, &error);
EXPECT_FALSE(value == nullptr);
EXPECT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_NULL);
}
static gchar* encode_bool(gboolean value) {
g_autoptr(FlValue) v = fl_value_new_bool(value);
return encode_message(v);
}
TEST(FlStandardMessageCodecTest, EncodeBoolFalse) {
g_autofree gchar* hex_string = encode_bool(FALSE);
EXPECT_STREQ(hex_string, "02");
}
TEST(FlStandardMessageCodecTest, EncodeBoolTrue) {
g_autofree gchar* hex_string = encode_bool(TRUE);
EXPECT_STREQ(hex_string, "01");
}
static gchar* encode_int(int64_t value) {
g_autoptr(FlValue) v = fl_value_new_int(value);
return encode_message(v);
}
TEST(FlStandardMessageCodecTest, EncodeIntZero) {
g_autofree gchar* hex_string = encode_int(0);
EXPECT_STREQ(hex_string, "0300000000");
}
TEST(FlStandardMessageCodecTest, EncodeIntOne) {
g_autofree gchar* hex_string = encode_int(1);
EXPECT_STREQ(hex_string, "0301000000");
}
TEST(FlStandardMessageCodecTest, EncodeInt32) {
g_autofree gchar* hex_string = encode_int(0x01234567);
EXPECT_STREQ(hex_string, "0367452301");
}
TEST(FlStandardMessageCodecTest, EncodeInt32Min) {
g_autofree gchar* hex_string = encode_int(G_MININT32);
EXPECT_STREQ(hex_string, "0300000080");
}
TEST(FlStandardMessageCodecTest, EncodeInt32Max) {
g_autofree gchar* hex_string = encode_int(G_MAXINT32);
EXPECT_STREQ(hex_string, "03ffffff7f");
}
TEST(FlStandardMessageCodecTest, EncodeInt64) {
g_autofree gchar* hex_string = encode_int(0x0123456789abcdef);
EXPECT_STREQ(hex_string, "04efcdab8967452301");
}
TEST(FlStandardMessageCodecTest, EncodeInt64Min) {
g_autofree gchar* hex_string = encode_int(G_MININT64);
EXPECT_STREQ(hex_string, "040000000000000080");
}
TEST(FlStandardMessageCodecTest, EncodeInt64Max) {
g_autofree gchar* hex_string = encode_int(G_MAXINT64);
EXPECT_STREQ(hex_string, "04ffffffffffffff7f");
}
TEST(FlStandardMessageCodecTest, DecodeIntZero) {
g_autoptr(FlValue) value = decode_message("0300000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), 0);
}
TEST(FlStandardMessageCodecTest, DecodeIntOne) {
g_autoptr(FlValue) value = decode_message("0301000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), 1);
}
TEST(FlStandardMessageCodecTest, DecodeInt32) {
g_autoptr(FlValue) value = decode_message("0367452301");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), 0x01234567);
}
TEST(FlStandardMessageCodecTest, DecodeInt32Min) {
g_autoptr(FlValue) value = decode_message("0300000080");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), G_MININT32);
}
TEST(FlStandardMessageCodecTest, DecodeInt32Max) {
g_autoptr(FlValue) value = decode_message("03ffffff7f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), G_MAXINT32);
}
TEST(FlStandardMessageCodecTest, DecodeInt64) {
g_autoptr(FlValue) value = decode_message("04efcdab8967452301");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), 0x0123456789abcdef);
}
TEST(FlStandardMessageCodecTest, DecodeInt64Min) {
g_autoptr(FlValue) value = decode_message("040000000000000080");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), G_MININT64);
}
TEST(FlStandardMessageCodecTest, DecodeInt64Max) {
g_autoptr(FlValue) value = decode_message("04ffffffffffffff7f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(value), G_MAXINT64);
}
TEST(FlStandardMessageCodecTest, DecodeInt32NoData) {
decode_error_value("03", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeIntShortData1) {
decode_error_value("0367", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeIntShortData2) {
decode_error_value("03674523", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt64NoData) {
decode_error_value("04", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt64ShortData1) {
decode_error_value("04ef", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt64ShortData2) {
decode_error_value("04efcdab89674523", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
static gchar* encode_float(double value) {
g_autoptr(FlValue) v = fl_value_new_float(value);
return encode_message(v);
}
TEST(FlStandardMessageCodecTest, EncodeFloatZero) {
g_autofree gchar* hex_string = encode_float(0);
EXPECT_STREQ(hex_string, "06000000000000000000000000000000");
}
TEST(FlStandardMessageCodecTest, EncodeFloatOne) {
g_autofree gchar* hex_string = encode_float(1);
EXPECT_STREQ(hex_string, "0600000000000000000000000000f03f");
}
TEST(FlStandardMessageCodecTest, EncodeFloatMinusOne) {
g_autofree gchar* hex_string = encode_float(-1);
EXPECT_STREQ(hex_string, "0600000000000000000000000000f0bf");
}
TEST(FlStandardMessageCodecTest, EncodeFloatHalf) {
g_autofree gchar* hex_string = encode_float(0.5);
EXPECT_STREQ(hex_string, "0600000000000000000000000000e03f");
}
TEST(FlStandardMessageCodecTest, EncodeFloatFraction) {
g_autofree gchar* hex_string = encode_float(M_PI);
EXPECT_STREQ(hex_string, "0600000000000000182d4454fb210940");
}
TEST(FlStandardMessageCodecTest, EncodeFloatMinusZero) {
g_autofree gchar* hex_string = encode_float(-0.0);
EXPECT_STREQ(hex_string, "06000000000000000000000000000080");
}
TEST(FlStandardMessageCodecTest, EncodeFloatNaN) {
g_autofree gchar* hex_string = encode_float(NAN);
EXPECT_STREQ(hex_string, "0600000000000000000000000000f87f");
}
TEST(FlStandardMessageCodecTest, EncodeFloatInfinity) {
g_autofree gchar* hex_string = encode_float(INFINITY);
EXPECT_STREQ(hex_string, "0600000000000000000000000000f07f");
}
TEST(FlStandardMessageCodecTest, DecodeFloatZero) {
g_autoptr(FlValue) value = decode_message("06000000000000000000000000000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_EQ(fl_value_get_float(value), 0.0);
}
TEST(FlStandardMessageCodecTest, DecodeFloatOne) {
g_autoptr(FlValue) value = decode_message("0600000000000000000000000000f03f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_EQ(fl_value_get_float(value), 1.0);
}
TEST(FlStandardMessageCodecTest, DecodeFloatMinusOne) {
g_autoptr(FlValue) value = decode_message("0600000000000000000000000000f0bf");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_EQ(fl_value_get_float(value), -1.0);
}
TEST(FlStandardMessageCodecTest, DecodeFloatHalf) {
g_autoptr(FlValue) value = decode_message("0600000000000000000000000000e03f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_EQ(fl_value_get_float(value), 0.5);
}
TEST(FlStandardMessageCodecTest, DecodeFloatPi) {
g_autoptr(FlValue) value = decode_message("0600000000000000182d4454fb210940");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_EQ(fl_value_get_float(value), M_PI);
}
TEST(FlStandardMessageCodecTest, DecodeFloatMinusZero) {
g_autoptr(FlValue) value = decode_message("06000000000000000000000000000080");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_EQ(fl_value_get_float(value), -0.0);
}
TEST(FlStandardMessageCodecTest, DecodeFloatNaN) {
g_autoptr(FlValue) value = decode_message("0600000000000000000000000000f87f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_TRUE(isnan(fl_value_get_float(value)));
}
TEST(FlStandardMessageCodecTest, DecodeFloatInfinity) {
g_autoptr(FlValue) value = decode_message("0600000000000000000000000000f07f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT);
EXPECT_TRUE(isinf(fl_value_get_float(value)));
}
TEST(FlStandardMessageCodecTest, DecodeFloatNoData) {
decode_error_value("060000000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloatShortData1) {
decode_error_value("060000000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloatShortData2) {
decode_error_value("060000000000000000000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
static gchar* encode_string(const gchar* value) {
g_autoptr(FlValue) v = fl_value_new_string(value);
return encode_message(v);
}
TEST(FlStandardMessageCodecTest, EncodeStringEmpty) {
g_autofree gchar* hex_string = encode_string("");
EXPECT_STREQ(hex_string, "0700");
}
TEST(FlStandardMessageCodecTest, EncodeStringHello) {
g_autofree gchar* hex_string = encode_string("hello");
EXPECT_STREQ(hex_string, "070568656c6c6f");
}
TEST(FlStandardMessageCodecTest, EncodeStringEmptySized) {
g_autoptr(FlValue) value = fl_value_new_string_sized(nullptr, 0);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0700");
}
TEST(FlStandardMessageCodecTest, EncodeStringHelloSized) {
g_autoptr(FlValue) value = fl_value_new_string_sized("Hello World", 5);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "070548656c6c6f");
}
TEST(FlStandardMessageCodecTest, DecodeStringEmpty) {
g_autoptr(FlValue) value = decode_message("0700");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(value), "");
}
TEST(FlStandardMessageCodecTest, DecodeStringHello) {
g_autoptr(FlValue) value = decode_message("070568656c6c6f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(value), "hello");
}
TEST(FlStandardMessageCodecTest, DecodeStringNoData) {
decode_error_value("07", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeStringLengthNoData) {
decode_error_value("0705", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeStringShortData1) {
decode_error_value("070568", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeStringShortData2) {
decode_error_value("070568656c6c", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeUint8ListEmpty) {
g_autoptr(FlValue) value = fl_value_new_uint8_list(nullptr, 0);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0800");
}
TEST(FlStandardMessageCodecTest, EncodeUint8List) {
uint8_t data[] = {0, 1, 2, 3, 4};
g_autoptr(FlValue) value = fl_value_new_uint8_list(data, 5);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "08050001020304");
}
TEST(FlStandardMessageCodecTest, DecodeUint8ListEmpty) {
g_autoptr(FlValue) value = decode_message("0800");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_UINT8_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeUint8List) {
g_autoptr(FlValue) value = decode_message("08050001020304");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_UINT8_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(5));
const uint8_t* data = fl_value_get_uint8_list(value);
EXPECT_EQ(data[0], 0);
EXPECT_EQ(data[1], 1);
EXPECT_EQ(data[2], 2);
EXPECT_EQ(data[3], 3);
EXPECT_EQ(data[4], 4);
}
TEST(FlStandardMessageCodecTest, DecodeUint8ListNoData) {
decode_error_value("08", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeUint8ListLengthNoData) {
decode_error_value("0805", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeUint8ListShortData1) {
decode_error_value("080500", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeUint8ListShortData2) {
decode_error_value("080500010203", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeInt32ListEmpty) {
g_autoptr(FlValue) value = fl_value_new_int32_list(nullptr, 0);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "09000000");
}
TEST(FlStandardMessageCodecTest, EncodeInt32List) {
int32_t data[] = {0, -1, 2, -3, 4};
g_autoptr(FlValue) value = fl_value_new_int32_list(data, 5);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0905000000000000ffffffff02000000fdffffff04000000");
}
TEST(FlStandardMessageCodecTest, DecodeInt32ListEmpty) {
g_autoptr(FlValue) value = decode_message("09000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT32_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeInt32List) {
g_autoptr(FlValue) value =
decode_message("0905000000000000ffffffff02000000fdffffff04000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT32_LIST);
const int32_t* data = fl_value_get_int32_list(value);
EXPECT_EQ(data[0], 0);
EXPECT_EQ(data[1], -1);
EXPECT_EQ(data[2], 2);
EXPECT_EQ(data[3], -3);
EXPECT_EQ(data[4], 4);
}
TEST(FlStandardMessageCodecTest, DecodeInt32ListNoData) {
decode_error_value("09", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt32ListLengthNoData) {
decode_error_value("09050000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt32ListShortData1) {
decode_error_value("0905000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt32ListShortData2) {
decode_error_value("090500000000ffffffff02000000fdffffff040000",
FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeInt64ListEmpty) {
g_autoptr(FlValue) value = fl_value_new_int64_list(nullptr, 0);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0a00000000000000");
}
TEST(FlStandardMessageCodecTest, EncodeInt64List) {
int64_t data[] = {0, -1, 2, -3, 4};
g_autoptr(FlValue) value = fl_value_new_int64_list(data, 5);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(
hex_string,
"0a050000000000000000000000000000ffffffffffffffff0200000000000000fdffffff"
"ffffffff0400000000000000");
}
TEST(FlStandardMessageCodecTest, DecodeInt64ListEmpty) {
g_autoptr(FlValue) value = decode_message("0a00000000000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT64_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeInt64List) {
g_autoptr(FlValue) value = decode_message(
"0a050000000000000000000000000000ffffffffffffffff0200000000000000fdffffff"
"ffffffff0400000000000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_INT64_LIST);
const int64_t* data = fl_value_get_int64_list(value);
EXPECT_EQ(data[0], 0);
EXPECT_EQ(data[1], -1);
EXPECT_EQ(data[2], 2);
EXPECT_EQ(data[3], -3);
EXPECT_EQ(data[4], 4);
}
TEST(FlStandardMessageCodecTest, DecodeInt64ListNoData) {
decode_error_value("0a", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt64ListLengthNoData) {
decode_error_value("0a05000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt64ListShortData1) {
decode_error_value("0a0500000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeInt64ListShortData2) {
decode_error_value(
"0a050000000000000000000000000000ffffffffffffffff0200000000000000fdffffff"
"ffffffff0400"
"0000000000",
FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeFloat32ListEmpty) {
g_autoptr(FlValue) value = fl_value_new_float32_list(nullptr, 0);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0e000000");
}
TEST(FlStandardMessageCodecTest, EncodeFloat32List) {
float data[] = {0.0f, -0.5f, 0.25f, -0.125f, 0.00625f};
g_autoptr(FlValue) value = fl_value_new_float32_list(data, 5);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0e05000000000000000000bf0000803e000000becdcccc3b");
}
TEST(FlStandardMessageCodecTest, DecodeFloat32ListEmpty) {
g_autoptr(FlValue) value = decode_message("0e000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT32_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeFloat32List) {
g_autoptr(FlValue) value =
decode_message("0e05000000000000000000bf0000803e000000becdcccc3b");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT32_LIST);
const float* data = fl_value_get_float32_list(value);
EXPECT_FLOAT_EQ(data[0], 0.0f);
EXPECT_FLOAT_EQ(data[1], -0.5f);
EXPECT_FLOAT_EQ(data[2], 0.25f);
EXPECT_FLOAT_EQ(data[3], -0.125f);
EXPECT_FLOAT_EQ(data[4], 0.00625f);
}
TEST(FlStandardMessageCodecTest, DecodeFloat32ListNoData) {
decode_error_value("0e", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloat32ListLengthNoData) {
decode_error_value("0e050000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloat32ListShortData1) {
decode_error_value("0e05000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloat32ListShortData2) {
decode_error_value("0e05000000000000000000bf0000803e000000becdcccc",
FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeFloatListEmpty) {
g_autoptr(FlValue) value = fl_value_new_float_list(nullptr, 0);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0b00000000000000");
}
TEST(FlStandardMessageCodecTest, EncodeFloatList) {
double data[] = {0, -0.5, 0.25, -0.125, 0.00625};
g_autoptr(FlValue) value = fl_value_new_float_list(data, 5);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(
hex_string,
"0b050000000000000000000000000000000000000000e0bf000000000000d03f00000000"
"0000c0bf9a9999999999793f");
}
TEST(FlStandardMessageCodecTest, DecodeFloatListEmpty) {
g_autoptr(FlValue) value = decode_message("0b00000000000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeFloatList) {
g_autoptr(FlValue) value = decode_message(
"0b050000000000000000000000000000000000000000e0bf000000000000d03f00000000"
"0000c0bf9a9999999999793f");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_FLOAT_LIST);
const double* data = fl_value_get_float_list(value);
EXPECT_FLOAT_EQ(data[0], 0.0);
EXPECT_FLOAT_EQ(data[1], -0.5);
EXPECT_FLOAT_EQ(data[2], 0.25);
EXPECT_FLOAT_EQ(data[3], -0.125);
EXPECT_FLOAT_EQ(data[4], 0.00625);
}
TEST(FlStandardMessageCodecTest, DecodeFloatListNoData) {
decode_error_value("0b", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloatListLengthNoData) {
decode_error_value("0b05000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloatListShortData1) {
decode_error_value("0b0500000000000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeFloatListShortData2) {
decode_error_value(
"0b050000000000000000000000000000000000000000e0bf000000000000d03f00000000"
"0000c0bf9a99"
"9999999979",
FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeListEmpty) {
g_autoptr(FlValue) value = fl_value_new_list();
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0c00");
}
TEST(FlStandardMessageCodecTest, EncodeListTypes) {
g_autoptr(FlValue) value = fl_value_new_list();
fl_value_append_take(value, fl_value_new_null());
fl_value_append_take(value, fl_value_new_bool(TRUE));
fl_value_append_take(value, fl_value_new_int(42));
fl_value_append_take(value, fl_value_new_float(M_PI));
fl_value_append_take(value, fl_value_new_string("hello"));
fl_value_append_take(value, fl_value_new_list());
fl_value_append_take(value, fl_value_new_map());
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(
hex_string,
"0c070001032a00000006000000000000182d4454fb210940070568656c6c6f0c000d00");
}
TEST(FlStandardMessageCodecTest, EncodeListNested) {
g_autoptr(FlValue) even_numbers = fl_value_new_list();
g_autoptr(FlValue) odd_numbers = fl_value_new_list();
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
fl_value_append_take(even_numbers, fl_value_new_int(i));
} else {
fl_value_append_take(odd_numbers, fl_value_new_int(i));
}
}
g_autoptr(FlValue) value = fl_value_new_list();
fl_value_append(value, even_numbers);
fl_value_append(value, odd_numbers);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string,
"0c020c05030000000003020000000304000000030600000003080000000c"
"0503010000000303000000030500000003070000000309000000");
}
TEST(FlStandardMessageCodecTest, DecodeListEmpty) {
g_autoptr(FlValue) value = decode_message("0c00");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeListTypes) {
g_autoptr(FlValue) value = decode_message(
"0c070001032a00000006000000000000182d4454fb210940070568656c6c6f0c000d00");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(7));
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 0)),
FL_VALUE_TYPE_NULL);
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 1)),
FL_VALUE_TYPE_BOOL);
EXPECT_TRUE(fl_value_get_bool(fl_value_get_list_value(value, 1)));
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 2)),
FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(fl_value_get_list_value(value, 2)), 42);
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 3)),
FL_VALUE_TYPE_FLOAT);
EXPECT_FLOAT_EQ(fl_value_get_float(fl_value_get_list_value(value, 3)), M_PI);
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 4)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_list_value(value, 4)), "hello");
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 5)),
FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(fl_value_get_list_value(value, 5)),
static_cast<size_t>(0));
ASSERT_EQ(fl_value_get_type(fl_value_get_list_value(value, 6)),
FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(fl_value_get_list_value(value, 6)),
static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeListNested) {
g_autoptr(FlValue) value = decode_message(
"0c020c05030000000003020000000304000000030600000003080000000c"
"0503010000000303000000030500000003070000000309000000");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(2));
FlValue* even_list = fl_value_get_list_value(value, 0);
ASSERT_EQ(fl_value_get_type(even_list), FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(even_list), static_cast<size_t>(5));
FlValue* odd_list = fl_value_get_list_value(value, 1);
ASSERT_EQ(fl_value_get_type(odd_list), FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(odd_list), static_cast<size_t>(5));
for (int i = 0; i < 5; i++) {
FlValue* v = fl_value_get_list_value(even_list, i);
ASSERT_EQ(fl_value_get_type(v), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(v), i * 2);
v = fl_value_get_list_value(odd_list, i);
ASSERT_EQ(fl_value_get_type(v), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(v), i * 2 + 1);
}
}
TEST(FlStandardMessageCodecTest, DecodeListNoData) {
decode_error_value("0c", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeListLengthNoData) {
decode_error_value("0c07", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeListShortData1) {
decode_error_value("0c0700", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeListShortData2) {
decode_error_value(
"0c070001032a00000006000000000000182d4454fb210940070568656c6c6f0c000d",
FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeDecodeLargeList) {
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
g_autoptr(FlValue) value = fl_value_new_list();
for (int i = 0; i < 65535; i++) {
fl_value_append_take(value, fl_value_new_int(i));
}
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
g_autoptr(FlValue) decoded_value =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(value, nullptr);
ASSERT_TRUE(fl_value_equal(value, decoded_value));
}
TEST(FlStandardMessageCodecTest, EncodeMapEmpty) {
g_autoptr(FlValue) value = fl_value_new_map();
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string, "0d00");
}
TEST(FlStandardMessageCodecTest, EncodeMapKeyTypes) {
g_autoptr(FlValue) value = fl_value_new_map();
fl_value_set_take(value, fl_value_new_null(), fl_value_new_string("null"));
fl_value_set_take(value, fl_value_new_bool(TRUE),
fl_value_new_string("bool"));
fl_value_set_take(value, fl_value_new_int(42), fl_value_new_string("int"));
fl_value_set_take(value, fl_value_new_float(M_PI),
fl_value_new_string("float"));
fl_value_set_take(value, fl_value_new_string("hello"),
fl_value_new_string("string"));
fl_value_set_take(value, fl_value_new_list(), fl_value_new_string("list"));
fl_value_set_take(value, fl_value_new_map(), fl_value_new_string("map"));
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string,
"0d070007046e756c6c010704626f6f6c032a0000000703696e7406000000000"
"0182d4454fb2109400705666c6f6174070568656c6c6f0706737472696e670c"
"0007046c6973740d0007036d6170");
}
TEST(FlStandardMessageCodecTest, EncodeMapValueTypes) {
g_autoptr(FlValue) value = fl_value_new_map();
fl_value_set_take(value, fl_value_new_string("null"), fl_value_new_null());
fl_value_set_take(value, fl_value_new_string("bool"),
fl_value_new_bool(TRUE));
fl_value_set_take(value, fl_value_new_string("int"), fl_value_new_int(42));
fl_value_set_take(value, fl_value_new_string("float"),
fl_value_new_float(M_PI));
fl_value_set_take(value, fl_value_new_string("string"),
fl_value_new_string("hello"));
fl_value_set_take(value, fl_value_new_string("list"), fl_value_new_list());
fl_value_set_take(value, fl_value_new_string("map"), fl_value_new_map());
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string,
"0d0707046e756c6c000704626f6f6c010703696e74032a0000000705666c6f6"
"17406000000000000182d4454fb2109400706737472696e67070568656c6c6f"
"07046c6973740c0007036d61700d00");
}
TEST(FlStandardMessageCodecTest, EncodeMapNested) {
g_autoptr(FlValue) str_to_int = fl_value_new_map();
g_autoptr(FlValue) int_to_str = fl_value_new_map();
const char* numbers[] = {"zero", "one", "two", "three", nullptr};
for (int i = 0; numbers[i] != nullptr; i++) {
fl_value_set_take(str_to_int, fl_value_new_string(numbers[i]),
fl_value_new_int(i));
fl_value_set_take(int_to_str, fl_value_new_int(i),
fl_value_new_string(numbers[i]));
}
g_autoptr(FlValue) value = fl_value_new_map();
fl_value_set_string(value, "str-to-int", str_to_int);
fl_value_set_string(value, "int-to-str", int_to_str);
g_autofree gchar* hex_string = encode_message(value);
EXPECT_STREQ(hex_string,
"0d02070a7374722d746f2d696e740d0407047a65726f030000000007036f6e6"
"50301000000070374776f0302000000070574687265650303000000070a696e"
"742d746f2d7374720d04030000000007047a65726f030100000007036f6e650"
"302000000070374776f030300000007057468726565");
}
TEST(FlStandardMessageCodecTest, DecodeMapEmpty) {
g_autoptr(FlValue) value = decode_message("0d00");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeMapKeyTypes) {
g_autoptr(FlValue) value = decode_message(
"0d070007046e756c6c010704626f6f6c032a0000000703696e74060000000000182d4454"
"fb2109400705666c6f6174070568656c6c6f0706737472696e670c0007046c6973740d00"
"07036d6170");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(7));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)),
FL_VALUE_TYPE_NULL);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 0)), "null");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 1)),
FL_VALUE_TYPE_BOOL);
EXPECT_TRUE(fl_value_get_bool(fl_value_get_map_key(value, 1)));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 1)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 1)), "bool");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 2)),
FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(fl_value_get_map_key(value, 2)), 42);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 2)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 2)), "int");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 3)),
FL_VALUE_TYPE_FLOAT);
EXPECT_FLOAT_EQ(fl_value_get_float(fl_value_get_map_key(value, 3)), M_PI);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 3)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 3)), "float");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 4)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 4)), "hello");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 4)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 4)), "string");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 5)),
FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(fl_value_get_map_key(value, 5)),
static_cast<size_t>(0));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 5)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 5)), "list");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 6)),
FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(fl_value_get_map_key(value, 6)),
static_cast<size_t>(0));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 6)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 6)), "map");
}
TEST(FlStandardMessageCodecTest, DecodeMapValueTypes) {
g_autoptr(FlValue) value = decode_message(
"0d0707046e756c6c000704626f6f6c010703696e74032a0000000705666c6f6174060000"
"00000000182d4454fb2109400706737472696e67070568656c6c6f07046c6973740c0007"
"036d61700d00");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(7));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 0)), "null");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 0)),
FL_VALUE_TYPE_NULL);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 1)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 1)), "bool");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 1)),
FL_VALUE_TYPE_BOOL);
EXPECT_TRUE(fl_value_get_bool(fl_value_get_map_value(value, 1)));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 2)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 2)), "int");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 2)),
FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(fl_value_get_map_value(value, 2)), 42);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 3)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 3)), "float");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 3)),
FL_VALUE_TYPE_FLOAT);
EXPECT_FLOAT_EQ(fl_value_get_float(fl_value_get_map_value(value, 3)), M_PI);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 4)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 4)), "string");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 4)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(value, 4)), "hello");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 5)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 5)), "list");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 5)),
FL_VALUE_TYPE_LIST);
ASSERT_EQ(fl_value_get_length(fl_value_get_map_value(value, 5)),
static_cast<size_t>(0));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 6)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 6)), "map");
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(value, 6)),
FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(fl_value_get_map_value(value, 6)),
static_cast<size_t>(0));
}
TEST(FlStandardMessageCodecTest, DecodeMapNested) {
g_autoptr(FlValue) value = decode_message(
"0d02070a7374722d746f2d696e740d0407047a65726f030000000007036f6e6503010000"
"00070374776f0302000000070574687265650303000000070a696e742d746f2d7374720d"
"04030000000007047a65726f030100000007036f6e650302000000070374776f03030000"
"0007057468726565");
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(value), static_cast<size_t>(2));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 0)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 0)),
"str-to-int");
FlValue* str_to_int = fl_value_get_map_value(value, 0);
ASSERT_EQ(fl_value_get_type(str_to_int), FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(str_to_int), static_cast<size_t>(4));
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(value, 1)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(value, 1)),
"int-to-str");
FlValue* int_to_str = fl_value_get_map_value(value, 1);
ASSERT_EQ(fl_value_get_type(int_to_str), FL_VALUE_TYPE_MAP);
ASSERT_EQ(fl_value_get_length(int_to_str), static_cast<size_t>(4));
const char* numbers[] = {"zero", "one", "two", "three", nullptr};
for (int i = 0; numbers[i] != nullptr; i++) {
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(str_to_int, i)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_key(str_to_int, i)),
numbers[i]);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(str_to_int, i)),
FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(fl_value_get_map_value(str_to_int, i)), i);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_key(int_to_str, i)),
FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(fl_value_get_map_key(int_to_str, i)), i);
ASSERT_EQ(fl_value_get_type(fl_value_get_map_value(int_to_str, i)),
FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(fl_value_get_map_value(int_to_str, i)),
numbers[i]);
}
}
TEST(FlStandardMessageCodecTest, DecodeMapNoData) {
decode_error_value("0d", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeMapLengthNoData) {
decode_error_value("0d07", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeMapShortData1) {
decode_error_value("0d0707", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, DecodeMapShortData2) {
decode_error_value(
"0d0707046e756c6c000704626f6f6c010703696e74032a0000000705666c6f6174060000"
"00000000182d4454fb2109400706737472696e67070568656c6c6f07046c6973740c0007"
"036d61700d",
FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMessageCodecTest, EncodeDecodeLargeMap) {
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
g_autoptr(FlValue) value = fl_value_new_map();
for (int i = 0; i < 512; i++) {
g_autofree gchar* key = g_strdup_printf("key%d", i);
fl_value_set_string_take(value, key, fl_value_new_int(i));
}
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), value, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
g_autoptr(FlValue) decoded_value =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(value, nullptr);
ASSERT_TRUE(fl_value_equal(value, decoded_value));
}
TEST(FlStandardMessageCodecTest, DecodeUnknownType) {
decode_error_value("0f", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_UNSUPPORTED_TYPE);
}
G_DECLARE_FINAL_TYPE(FlTestStandardMessageCodec,
fl_test_standard_message_codec,
FL,
TEST_STANDARD_MESSAGE_CODEC,
FlStandardMessageCodec)
struct _FlTestStandardMessageCodec {
FlStandardMessageCodec parent_instance;
};
G_DEFINE_TYPE(FlTestStandardMessageCodec,
fl_test_standard_message_codec,
fl_standard_message_codec_get_type())
static gboolean write_custom_value1(FlStandardMessageCodec* codec,
GByteArray* buffer,
FlValue* value,
GError** error) {
const gchar* text =
static_cast<const gchar*>(fl_value_get_custom_value(value));
size_t length = strlen(text);
uint8_t type = 128;
g_byte_array_append(buffer, &type, sizeof(uint8_t));
fl_standard_message_codec_write_size(codec, buffer, length);
g_byte_array_append(buffer, reinterpret_cast<const uint8_t*>(text), length);
return TRUE;
}
static gboolean write_custom_value2(FlStandardMessageCodec* codec,
GByteArray* buffer,
FlValue* value,
GError** error) {
uint8_t type = 129;
g_byte_array_append(buffer, &type, sizeof(uint8_t));
return TRUE;
}
static gboolean fl_test_standard_message_codec_write_value(
FlStandardMessageCodec* codec,
GByteArray* buffer,
FlValue* value,
GError** error) {
if (fl_value_get_type(value) == FL_VALUE_TYPE_CUSTOM &&
fl_value_get_custom_type(value) == 128) {
return write_custom_value1(codec, buffer, value, error);
} else if (fl_value_get_type(value) == FL_VALUE_TYPE_CUSTOM &&
fl_value_get_custom_type(value) == 129) {
return write_custom_value2(codec, buffer, value, error);
} else {
return FL_STANDARD_MESSAGE_CODEC_CLASS(
fl_test_standard_message_codec_parent_class)
->write_value(codec, buffer, value, error);
}
}
static FlValue* read_custom_value1(FlStandardMessageCodec* codec,
GBytes* buffer,
size_t* offset,
GError** error) {
uint32_t length;
if (!fl_standard_message_codec_read_size(codec, buffer, offset, &length,
error)) {
return nullptr;
}
if (*offset + length > g_bytes_get_size(buffer)) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA, "Unexpected end of data");
return nullptr;
}
FlValue* value = fl_value_new_custom(
128,
g_strndup(static_cast<const gchar*>(g_bytes_get_data(buffer, nullptr)) +
*offset,
length),
g_free);
*offset += length;
return value;
}
static FlValue* read_custom_value2(FlStandardMessageCodec* codec,
GBytes* buffer,
size_t* offset,
GError** error) {
return fl_value_new_custom(129, nullptr, nullptr);
}
static FlValue* fl_test_standard_message_codec_read_value_of_type(
FlStandardMessageCodec* codec,
GBytes* buffer,
size_t* offset,
int type,
GError** error) {
if (type == 128) {
return read_custom_value1(codec, buffer, offset, error);
} else if (type == 129) {
return read_custom_value2(codec, buffer, offset, error);
} else {
return FL_STANDARD_MESSAGE_CODEC_CLASS(
fl_test_standard_message_codec_parent_class)
->read_value_of_type(codec, buffer, offset, type, error);
}
}
static void fl_test_standard_message_codec_class_init(
FlTestStandardMessageCodecClass* klass) {
FL_STANDARD_MESSAGE_CODEC_CLASS(klass)->write_value =
fl_test_standard_message_codec_write_value;
FL_STANDARD_MESSAGE_CODEC_CLASS(klass)->read_value_of_type =
fl_test_standard_message_codec_read_value_of_type;
}
static void fl_test_standard_message_codec_init(
FlTestStandardMessageCodec* self) {
// The following line suppresses a warning for unused function
FL_IS_TEST_STANDARD_MESSAGE_CODEC(self);
}
static FlTestStandardMessageCodec* fl_test_standard_message_codec_new() {
return FL_TEST_STANDARD_MESSAGE_CODEC(
g_object_new(fl_test_standard_message_codec_get_type(), nullptr));
}
TEST(FlStandardMessageCodecTest, DecodeCustomType) {
g_autoptr(FlTestStandardMessageCodec) codec =
fl_test_standard_message_codec_new();
g_autoptr(FlValue) value =
decode_message_with_codec("800568656c6c6f", FL_MESSAGE_CODEC(codec));
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_CUSTOM);
ASSERT_EQ(fl_value_get_custom_type(value), 128);
EXPECT_STREQ(static_cast<const gchar*>(fl_value_get_custom_value(value)),
"hello");
}
TEST(FlStandardMessageCodecTest, DecodeCustomTypes) {
g_autoptr(FlTestStandardMessageCodec) codec =
fl_test_standard_message_codec_new();
g_autoptr(FlValue) value = decode_message_with_codec("0c02800568656c6c6f81",
FL_MESSAGE_CODEC(codec));
ASSERT_EQ(fl_value_get_type(value), FL_VALUE_TYPE_LIST);
EXPECT_EQ(fl_value_get_length(value), static_cast<size_t>(2));
FlValue* value1 = fl_value_get_list_value(value, 0);
ASSERT_EQ(fl_value_get_type(value1), FL_VALUE_TYPE_CUSTOM);
ASSERT_EQ(fl_value_get_custom_type(value1), 128);
EXPECT_STREQ(static_cast<const gchar*>(fl_value_get_custom_value(value1)),
"hello");
FlValue* value2 = fl_value_get_list_value(value, 1);
ASSERT_EQ(fl_value_get_type(value2), FL_VALUE_TYPE_CUSTOM);
ASSERT_EQ(fl_value_get_custom_type(value2), 129);
}
TEST(FlStandardMessageCodecTest, EncodeCustomType) {
g_autoptr(FlValue) value = fl_value_new_custom(128, "hello", nullptr);
g_autoptr(FlTestStandardMessageCodec) codec =
fl_test_standard_message_codec_new();
g_autofree gchar* hex_string =
encode_message_with_codec(value, FL_MESSAGE_CODEC(codec));
EXPECT_STREQ(hex_string, "800568656c6c6f");
}
TEST(FlStandardMessageCodecTest, EncodeCustomTypes) {
g_autoptr(FlValue) value = fl_value_new_list();
fl_value_append_take(value, fl_value_new_custom(128, "hello", nullptr));
fl_value_append_take(value, fl_value_new_custom(129, nullptr, nullptr));
g_autoptr(FlTestStandardMessageCodec) codec =
fl_test_standard_message_codec_new();
g_autofree gchar* hex_string =
encode_message_with_codec(value, FL_MESSAGE_CODEC(codec));
EXPECT_STREQ(hex_string, "0c02800568656c6c6f81");
}
TEST(FlStandardMessageCodecTest, EncodeDecode) {
g_autoptr(FlStandardMessageCodec) codec = fl_standard_message_codec_new();
g_autoptr(FlValue) input = fl_value_new_list();
fl_value_append_take(input, fl_value_new_null());
fl_value_append_take(input, fl_value_new_bool(TRUE));
fl_value_append_take(input, fl_value_new_int(42));
fl_value_append_take(input, fl_value_new_float(M_PI));
fl_value_append_take(input, fl_value_new_string("hello"));
fl_value_append_take(input, fl_value_new_list());
fl_value_append_take(input, fl_value_new_map());
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message =
fl_message_codec_encode_message(FL_MESSAGE_CODEC(codec), input, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
g_autoptr(FlValue) output =
fl_message_codec_decode_message(FL_MESSAGE_CODEC(codec), message, &error);
EXPECT_EQ(error, nullptr);
EXPECT_NE(output, nullptr);
ASSERT_TRUE(fl_value_equal(input, output));
}
| engine/shell/platform/linux/fl_standard_message_codec_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_standard_message_codec_test.cc",
"repo_id": "engine",
"token_count": 22827
} | 405 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_PRIVATE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_PRIVATE_H_
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture.h"
G_BEGIN_DECLS
/**
* fl_texture_set_id:
* @texture: an #FlTexture.
* @id: a texture ID.
*
* Set the ID for a texture.
*/
void fl_texture_set_id(FlTexture* texture, int64_t id);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_PRIVATE_H_
| engine/shell/platform/linux/fl_texture_private.h/0 | {
"file_path": "engine/shell/platform/linux/fl_texture_private.h",
"repo_id": "engine",
"token_count": 257
} | 406 |
// 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_BINARY_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_CODEC_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <gmodule.h>
#include "fl_message_codec.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlBinaryCodec,
fl_binary_codec,
FL,
BINARY_CODEC,
FlMessageCodec)
/**
* FlBinaryCodec:
*
* #FlBinaryCodec is an #FlMessageCodec that implements the Flutter binary
* message encoding. This only encodes and decodes #FlValue of type
* #FL_VALUE_TYPE_UINT8_LIST, other types #FlValues will generate an error
* during encoding.
*
* #FlBinaryCodec matches the BinaryCodec class in the Flutter services
* library.
*/
/**
* fl_binary_codec_new:
*
* Creates an #FlBinaryCodec.
*
* Returns: a new #FlBinaryCodec.
*/
FlBinaryCodec* fl_binary_codec_new();
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_BINARY_CODEC_H_
| engine/shell/platform/linux/public/flutter_linux/fl_binary_codec.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_binary_codec.h",
"repo_id": "engine",
"token_count": 567
} | 407 |
// 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_STANDARD_METHOD_CODEC_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_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 <gmodule.h>
#include "fl_method_codec.h"
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlStandardMethodCodec,
fl_standard_method_codec,
FL,
STANDARD_METHOD_CODEC,
FlMethodCodec)
/**
* FlStandardMethodCodec:
*
* #FlStandardMethodCodec is an #FlMethodCodec that implements method calls
* using the Flutter standard message encoding. It should be used with a
* #FlMethodChannel.
*
* #FlStandardMethodCodec matches the StandardMethodCodec class in the Flutter
* services library.
*/
/**
* fl_standard_method_codec_new:
*
* Creates an #FlStandardMethodCodec.
*
* Returns: a new #FlStandardMethodCodec.
*/
FlStandardMethodCodec* fl_standard_method_codec_new();
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_STANDARD_METHOD_CODEC_H_
| engine/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h",
"repo_id": "engine",
"token_count": 556
} | 408 |
// 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_binary_messenger_response_handle.h"
struct _FlMockBinaryMessengerResponseHandle {
FlBinaryMessengerResponseHandle parent_instance;
};
G_DEFINE_TYPE(FlMockBinaryMessengerResponseHandle,
fl_mock_binary_messenger_response_handle,
fl_binary_messenger_response_handle_get_type());
static void fl_mock_binary_messenger_response_handle_class_init(
FlMockBinaryMessengerResponseHandleClass* klass) {}
static void fl_mock_binary_messenger_response_handle_init(
FlMockBinaryMessengerResponseHandle* self) {}
FlMockBinaryMessengerResponseHandle*
fl_mock_binary_messenger_response_handle_new() {
return FL_MOCK_BINARY_MESSENGER_RESPONSE_HANDLE(
g_object_new(fl_mock_binary_messenger_response_handle_get_type(), NULL));
}
| engine/shell/platform/linux/testing/mock_binary_messenger_response_handle.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_binary_messenger_response_handle.cc",
"repo_id": "engine",
"token_count": 344
} | 409 |
// 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_text_input_view_delegate.h"
using namespace flutter::testing;
G_DECLARE_FINAL_TYPE(FlMockTextInputViewDelegate,
fl_mock_text_input_view_delegate,
FL,
MOCK_TEXT_INPUT_VIEW_DELEGATE,
GObject)
struct _FlMockTextInputViewDelegate {
GObject parent_instance;
MockTextInputViewDelegate* mock;
};
static FlTextInputViewDelegate* fl_mock_text_input_view_delegate_new(
MockTextInputViewDelegate* mock) {
FlMockTextInputViewDelegate* self = FL_MOCK_TEXT_INPUT_VIEW_DELEGATE(
g_object_new(fl_mock_text_input_view_delegate_get_type(), nullptr));
self->mock = mock;
return FL_TEXT_INPUT_VIEW_DELEGATE(self);
}
MockTextInputViewDelegate::MockTextInputViewDelegate()
: instance_(fl_mock_text_input_view_delegate_new(this)) {}
MockTextInputViewDelegate::~MockTextInputViewDelegate() {
if (FL_IS_TEXT_INPUT_VIEW_DELEGATE(instance_)) {
g_clear_object(&instance_);
}
}
MockTextInputViewDelegate::operator FlTextInputViewDelegate*() {
return instance_;
}
static void fl_mock_text_input_view_delegate_iface_init(
FlTextInputViewDelegateInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlMockTextInputViewDelegate,
fl_mock_text_input_view_delegate,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_text_input_view_delegate_get_type(),
fl_mock_text_input_view_delegate_iface_init))
static void fl_mock_text_input_view_delegate_class_init(
FlMockTextInputViewDelegateClass* klass) {}
static void fl_mock_text_input_view_delegate_translate_coordinates(
FlTextInputViewDelegate* view_delegate,
gint view_x,
gint view_y,
gint* window_x,
gint* window_y) {
g_return_if_fail(FL_IS_MOCK_TEXT_INPUT_VIEW_DELEGATE(view_delegate));
FlMockTextInputViewDelegate* self =
FL_MOCK_TEXT_INPUT_VIEW_DELEGATE(view_delegate);
self->mock->fl_text_input_view_delegate_translate_coordinates(
view_delegate, view_x, view_y, window_x, window_y);
}
static void fl_mock_text_input_view_delegate_iface_init(
FlTextInputViewDelegateInterface* iface) {
iface->translate_coordinates =
fl_mock_text_input_view_delegate_translate_coordinates;
}
static void fl_mock_text_input_view_delegate_init(
FlMockTextInputViewDelegate* self) {}
| engine/shell/platform/linux/testing/mock_text_input_view_delegate.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_text_input_view_delegate.cc",
"repo_id": "engine",
"token_count": 1054
} | 410 |
// 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 <memory>
#include <string>
#include "flutter/shell/platform/windows/client_wrapper/include/flutter/flutter_view_controller.h"
#include "flutter/shell/platform/windows/client_wrapper/testing/stub_flutter_windows_api.h"
#include "gtest/gtest.h"
namespace flutter {
namespace {
// Stub implementation to validate calls to the API.
class TestWindowsApi : public testing::StubFlutterWindowsApi {
public:
// |flutter::testing::StubFlutterWindowsApi|
FlutterDesktopViewControllerRef ViewControllerCreate(
int width,
int height,
FlutterDesktopEngineRef engine) override {
return reinterpret_cast<FlutterDesktopViewControllerRef>(2);
}
// |flutter::testing::StubFlutterWindowsApi|
void ViewControllerDestroy() override { view_controller_destroyed_ = true; }
// |flutter::testing::StubFlutterWindowsApi|
void ViewControllerForceRedraw() override {
view_controller_force_redrawed_ = true;
}
// |flutter::testing::StubFlutterWindowsApi|
FlutterDesktopEngineRef EngineCreate(
const FlutterDesktopEngineProperties& engine_properties) override {
return reinterpret_cast<FlutterDesktopEngineRef>(1);
}
// |flutter::testing::StubFlutterWindowsApi|
bool EngineDestroy() override {
engine_destroyed_ = true;
return true;
}
bool engine_destroyed() { return engine_destroyed_; }
bool view_controller_destroyed() { return view_controller_destroyed_; }
bool view_controller_force_redrawed() {
return view_controller_force_redrawed_;
}
private:
bool engine_destroyed_ = false;
bool view_controller_destroyed_ = false;
bool view_controller_force_redrawed_ = false;
};
} // namespace
TEST(FlutterViewControllerTest, CreateDestroy) {
DartProject project(L"data");
testing::ScopedStubFlutterWindowsApi scoped_api_stub(
std::make_unique<TestWindowsApi>());
auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub());
{ FlutterViewController controller(100, 100, project); }
EXPECT_TRUE(test_api->view_controller_destroyed());
// Per the C API, once a view controller has taken ownership of an engine
// the engine destruction method should not be called.
EXPECT_FALSE(test_api->engine_destroyed());
}
TEST(FlutterViewControllerTest, GetViewId) {
DartProject project(L"data");
testing::ScopedStubFlutterWindowsApi scoped_api_stub(
std::make_unique<TestWindowsApi>());
auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub());
FlutterViewController controller(100, 100, project);
EXPECT_EQ(controller.view_id(), 1);
}
TEST(FlutterViewControllerTest, GetEngine) {
DartProject project(L"data");
testing::ScopedStubFlutterWindowsApi scoped_api_stub(
std::make_unique<TestWindowsApi>());
auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub());
FlutterViewController controller(100, 100, project);
EXPECT_NE(controller.engine(), nullptr);
}
TEST(FlutterViewControllerTest, GetView) {
DartProject project(L"data");
testing::ScopedStubFlutterWindowsApi scoped_api_stub(
std::make_unique<TestWindowsApi>());
auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub());
FlutterViewController controller(100, 100, project);
EXPECT_NE(controller.view(), nullptr);
}
TEST(FlutterViewControllerTest, ForceRedraw) {
DartProject project(L"data");
testing::ScopedStubFlutterWindowsApi scoped_api_stub(
std::make_unique<TestWindowsApi>());
auto test_api = static_cast<TestWindowsApi*>(scoped_api_stub.stub());
FlutterViewController controller(100, 100, project);
controller.ForceRedraw();
EXPECT_TRUE(test_api->view_controller_force_redrawed());
}
} // namespace flutter
| engine/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/client_wrapper/flutter_view_controller_unittests.cc",
"repo_id": "engine",
"token_count": 1272
} | 411 |
// 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 <memory>
#include <vector>
#include "flutter/shell/platform/windows/compositor_software.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h"
#include "flutter/shell/platform/windows/testing/mock_window_binding_handler.h"
#include "flutter/shell/platform/windows/testing/windows_test.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
using ::testing::Return;
class MockFlutterWindowsView : public FlutterWindowsView {
public:
MockFlutterWindowsView(FlutterWindowsEngine* engine,
std::unique_ptr<WindowBindingHandler> window)
: FlutterWindowsView(kImplicitViewId, engine, std::move(window)) {}
virtual ~MockFlutterWindowsView() = default;
MOCK_METHOD(bool,
PresentSoftwareBitmap,
(const void* allocation, size_t row_bytes, size_t height),
(override));
MOCK_METHOD(bool, ClearSoftwareBitmap, (), (override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockFlutterWindowsView);
};
class CompositorSoftwareTest : public WindowsTest {
public:
CompositorSoftwareTest() = default;
virtual ~CompositorSoftwareTest() = default;
protected:
FlutterWindowsEngine* engine() { return engine_.get(); }
MockFlutterWindowsView* view() { return view_.get(); }
void UseHeadlessEngine() {
FlutterWindowsEngineBuilder builder{GetContext()};
engine_ = builder.Build();
}
void UseEngineWithView() {
FlutterWindowsEngineBuilder builder{GetContext()};
auto window = std::make_unique<MockWindowBindingHandler>();
EXPECT_CALL(*window.get(), SetView).Times(1);
EXPECT_CALL(*window.get(), GetWindowHandle).WillRepeatedly(Return(nullptr));
engine_ = builder.Build();
view_ = std::make_unique<MockFlutterWindowsView>(engine_.get(),
std::move(window));
EngineModifier modifier{engine_.get()};
modifier.SetImplicitView(view_.get());
}
private:
std::unique_ptr<FlutterWindowsEngine> engine_;
std::unique_ptr<MockFlutterWindowsView> view_;
FML_DISALLOW_COPY_AND_ASSIGN(CompositorSoftwareTest);
};
} // namespace
TEST_F(CompositorSoftwareTest, CreateBackingStore) {
UseHeadlessEngine();
auto compositor = CompositorSoftware{engine()};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorSoftwareTest, Present) {
UseEngineWithView();
auto compositor = CompositorSoftware{engine()};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_CALL(*view(), PresentSoftwareBitmap).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorSoftwareTest, PresentEmpty) {
UseEngineWithView();
auto compositor = CompositorSoftware{engine()};
EXPECT_CALL(*view(), ClearSoftwareBitmap).WillOnce(Return(true));
EXPECT_TRUE(compositor.Present(view()->view_id(), nullptr, 0));
}
TEST_F(CompositorSoftwareTest, UnknownViewIgnored) {
UseEngineWithView();
auto compositor = CompositorSoftware{engine()};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
FlutterViewId unknown_view_id = 123;
ASSERT_NE(view()->view_id(), unknown_view_id);
ASSERT_EQ(engine()->view(unknown_view_id), nullptr);
EXPECT_FALSE(compositor.Present(unknown_view_id, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
TEST_F(CompositorSoftwareTest, HeadlessPresentIgnored) {
UseHeadlessEngine();
auto compositor = CompositorSoftware{engine()};
FlutterBackingStoreConfig config = {};
FlutterBackingStore backing_store = {};
ASSERT_TRUE(compositor.CreateBackingStore(config, &backing_store));
FlutterLayer layer = {};
layer.type = kFlutterLayerContentTypeBackingStore;
layer.backing_store = &backing_store;
const FlutterLayer* layer_ptr = &layer;
EXPECT_FALSE(compositor.Present(kImplicitViewId, &layer_ptr, 1));
ASSERT_TRUE(compositor.CollectBackingStore(&backing_store));
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/compositor_software_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/compositor_software_unittests.cc",
"repo_id": "engine",
"token_count": 1752
} | 412 |
// 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/proc_table.h"
#include <EGL/egl.h>
namespace flutter {
namespace egl {
std::shared_ptr<ProcTable> ProcTable::Create() {
auto gl = std::shared_ptr<ProcTable>(new ProcTable());
gl->gen_textures_ =
reinterpret_cast<GenTexturesProc>(::eglGetProcAddress("glGenTextures"));
gl->delete_textures_ = reinterpret_cast<DeleteTexturesProc>(
::eglGetProcAddress("glDeleteTextures"));
gl->bind_texture_ =
reinterpret_cast<BindTextureProc>(::eglGetProcAddress("glBindTexture"));
gl->tex_parameteri_ = reinterpret_cast<TexParameteriProc>(
::eglGetProcAddress("glTexParameteri"));
gl->tex_image_2d_ =
reinterpret_cast<TexImage2DProc>(::eglGetProcAddress("glTexImage2D"));
if (!gl->gen_textures_ || !gl->delete_textures_ || !gl->bind_texture_ ||
!gl->tex_parameteri_ || !gl->tex_image_2d_) {
return nullptr;
}
return gl;
}
ProcTable::ProcTable() = default;
ProcTable::~ProcTable() = default;
void ProcTable::GenTextures(GLsizei n, GLuint* textures) const {
gen_textures_(n, textures);
}
void ProcTable::DeleteTextures(GLsizei n, const GLuint* textures) const {
delete_textures_(n, textures);
}
void ProcTable::BindTexture(GLenum target, GLuint texture) const {
bind_texture_(target, texture);
}
void ProcTable::TexParameteri(GLenum target, GLenum pname, GLint param) const {
tex_parameteri_(target, pname, param);
}
void ProcTable::TexImage2D(GLenum target,
GLint level,
GLint internalformat,
GLsizei width,
GLsizei height,
GLint border,
GLenum format,
GLenum type,
const void* data) const {
tex_image_2d_(target, level, internalformat, width, height, border, format,
type, data);
}
} // namespace egl
} // namespace flutter
| engine/shell/platform/windows/egl/proc_table.cc/0 | {
"file_path": "engine/shell/platform/windows/egl/proc_table.cc",
"repo_id": "engine",
"token_count": 904
} | 413 |
// 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 <oleacc.h>
#include "flutter/shell/platform/windows/flutter_platform_node_delegate_windows.h"
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/windows/accessibility_bridge_windows.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/third_party/accessibility/ax/ax_clipping_behavior.h"
#include "flutter/third_party/accessibility/ax/ax_coordinate_system.h"
#include "flutter/third_party/accessibility/ax/platform/ax_fragment_root_win.h"
namespace flutter {
FlutterPlatformNodeDelegateWindows::FlutterPlatformNodeDelegateWindows(
std::weak_ptr<AccessibilityBridge> bridge,
FlutterWindowsView* view)
: bridge_(bridge), view_(view) {
FML_DCHECK(!bridge_.expired())
<< "Expired AccessibilityBridge passed to node delegate";
FML_DCHECK(view_);
}
FlutterPlatformNodeDelegateWindows::~FlutterPlatformNodeDelegateWindows() {
if (ax_platform_node_) {
ax_platform_node_->Destroy();
}
}
// |ui::AXPlatformNodeDelegate|
void FlutterPlatformNodeDelegateWindows::Init(std::weak_ptr<OwnerBridge> bridge,
ui::AXNode* node) {
FlutterPlatformNodeDelegate::Init(bridge, node);
ax_platform_node_ = ui::AXPlatformNode::Create(this);
FML_DCHECK(ax_platform_node_) << "Failed to create AXPlatformNode";
}
// |ui::AXPlatformNodeDelegate|
gfx::NativeViewAccessible
FlutterPlatformNodeDelegateWindows::GetNativeViewAccessible() {
FML_DCHECK(ax_platform_node_) << "AXPlatformNode hasn't been created";
return ax_platform_node_->GetNativeViewAccessible();
}
// |ui::AXPlatformNodeDelegate|
gfx::NativeViewAccessible FlutterPlatformNodeDelegateWindows::HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const {
// If this node doesn't contain the point, return.
ui::AXOffscreenResult result;
gfx::Rect rect = GetBoundsRect(ui::AXCoordinateSystem::kScreenPhysicalPixels,
ui::AXClippingBehavior::kUnclipped, &result);
gfx::Point screen_point(screen_physical_pixel_x, screen_physical_pixel_y);
if (!rect.Contains(screen_point)) {
return nullptr;
}
// If any child in this node's subtree contains the point, return that child.
auto bridge = bridge_.lock();
FML_DCHECK(bridge);
for (const ui::AXNode* child : GetAXNode()->children()) {
std::shared_ptr<FlutterPlatformNodeDelegateWindows> win_delegate =
std::static_pointer_cast<FlutterPlatformNodeDelegateWindows>(
bridge->GetFlutterPlatformNodeDelegateFromID(child->id()).lock());
FML_DCHECK(win_delegate)
<< "No FlutterPlatformNodeDelegate found for node " << child->id();
auto hit_view = win_delegate->HitTestSync(screen_physical_pixel_x,
screen_physical_pixel_y);
if (hit_view) {
return hit_view;
}
}
// If no children contain the point, but this node does, return this node.
return ax_platform_node_->GetNativeViewAccessible();
}
// |FlutterPlatformNodeDelegate|
gfx::Rect FlutterPlatformNodeDelegateWindows::GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const {
gfx::Rect bounds = FlutterPlatformNodeDelegate::GetBoundsRect(
coordinate_system, clipping_behavior, offscreen_result);
POINT origin{bounds.x(), bounds.y()};
POINT extent{bounds.x() + bounds.width(), bounds.y() + bounds.height()};
ClientToScreen(view_->GetWindowHandle(), &origin);
ClientToScreen(view_->GetWindowHandle(), &extent);
return gfx::Rect(origin.x, origin.y, extent.x - origin.x,
extent.y - origin.y);
}
void FlutterPlatformNodeDelegateWindows::DispatchWinAccessibilityEvent(
ax::mojom::Event event_type) {
ax_platform_node_->NotifyAccessibilityEvent(event_type);
}
void FlutterPlatformNodeDelegateWindows::SetFocus() {
VARIANT varchild{};
varchild.vt = VT_I4;
varchild.lVal = CHILDID_SELF;
GetNativeViewAccessible()->accSelect(SELFLAG_TAKEFOCUS, varchild);
}
gfx::AcceleratedWidget
FlutterPlatformNodeDelegateWindows::GetTargetForNativeAccessibilityEvent() {
return view_->GetWindowHandle();
}
ui::AXPlatformNode* FlutterPlatformNodeDelegateWindows::GetPlatformNode()
const {
return ax_platform_node_;
}
} // namespace flutter
| engine/shell/platform/windows/flutter_platform_node_delegate_windows.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_platform_node_delegate_windows.cc",
"repo_id": "engine",
"token_count": 1611
} | 414 |
// 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/public/flutter_windows.h"
#include <dxgi.h>
#include <wrl/client.h>
#include <thread>
#include "flutter/fml/synchronization/count_down_latch.h"
#include "flutter/fml/synchronization/waitable_event.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/windows/egl/manager.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/windows_test.h"
#include "flutter/shell/platform/windows/testing/windows_test_config_builder.h"
#include "flutter/shell/platform/windows/testing/windows_test_context.h"
#include "flutter/shell/platform/windows/windows_lifecycle_manager.h"
#include "flutter/testing/stream_capture.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "third_party/tonic/converter/dart_converter.h"
namespace flutter {
namespace testing {
namespace {
// An EGL manager that initializes EGL but fails to create surfaces.
class HalfBrokenEGLManager : public egl::Manager {
public:
HalfBrokenEGLManager() : egl::Manager(/*enable_impeller = */ false) {}
std::unique_ptr<egl::WindowSurface>
CreateWindowSurface(HWND hwnd, size_t width, size_t height) override {
return nullptr;
}
};
class MockWindowsLifecycleManager : public WindowsLifecycleManager {
public:
MockWindowsLifecycleManager(FlutterWindowsEngine* engine)
: WindowsLifecycleManager(engine) {}
MOCK_METHOD(void, SetLifecycleState, (AppLifecycleState), (override));
};
} // namespace
// Verify that we can fetch a texture registrar.
// Prevent regression: https://github.com/flutter/flutter/issues/86617
TEST(WindowsNoFixtureTest, GetTextureRegistrar) {
FlutterDesktopEngineProperties properties = {};
properties.assets_path = L"";
properties.icu_data_path = L"icudtl.dat";
auto engine = FlutterDesktopEngineCreate(&properties);
ASSERT_NE(engine, nullptr);
auto texture_registrar = FlutterDesktopEngineGetTextureRegistrar(engine);
EXPECT_NE(texture_registrar, nullptr);
FlutterDesktopEngineDestroy(engine);
}
// Verify we can successfully launch main().
TEST_F(WindowsTest, LaunchMain) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
}
// Verify there is no unexpected output from launching main.
TEST_F(WindowsTest, LaunchMainHasNoOutput) {
// Replace stdout & stderr stream buffers with our own.
StreamCapture stdout_capture(&std::cout);
StreamCapture stderr_capture(&std::cerr);
auto& context = GetContext();
WindowsConfigBuilder builder(context);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
stdout_capture.Stop();
stderr_capture.Stop();
// Verify stdout & stderr have no output.
EXPECT_TRUE(stdout_capture.GetOutput().empty());
EXPECT_TRUE(stderr_capture.GetOutput().empty());
}
// Verify we can successfully launch a custom entry point.
TEST_F(WindowsTest, LaunchCustomEntrypoint) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("customEntrypoint");
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
}
// Verify that engine launches with the custom entrypoint specified in the
// FlutterDesktopEngineRun parameter when no entrypoint is specified in
// FlutterDesktopEngineProperties.dart_entrypoint.
//
// TODO(cbracken): https://github.com/flutter/flutter/issues/109285
TEST_F(WindowsTest, LaunchCustomEntrypointInEngineRunInvocation) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
EnginePtr engine{builder.InitializeEngine()};
ASSERT_NE(engine, nullptr);
ASSERT_TRUE(FlutterDesktopEngineRun(engine.get(), "customEntrypoint"));
}
// Verify that the engine can launch in headless mode.
TEST_F(WindowsTest, LaunchHeadlessEngine) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
EnginePtr engine{builder.RunHeadless()};
ASSERT_NE(engine, nullptr);
}
// Verify that accessibility features are initialized when a view is created.
TEST_F(WindowsTest, LaunchRefreshesAccessibility) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
EnginePtr engine{builder.InitializeEngine()};
EngineModifier modifier{
reinterpret_cast<FlutterWindowsEngine*>(engine.get())};
auto called = false;
modifier.embedder_api().UpdateAccessibilityFeatures = MOCK_ENGINE_PROC(
UpdateAccessibilityFeatures, ([&called](auto engine, auto flags) {
called = true;
return kSuccess;
}));
ViewControllerPtr controller{
FlutterDesktopViewControllerCreate(0, 0, engine.release())};
ASSERT_TRUE(called);
}
// Verify that engine fails to launch when a conflicting entrypoint in
// FlutterDesktopEngineProperties.dart_entrypoint and the
// FlutterDesktopEngineRun parameter.
//
// TODO(cbracken): https://github.com/flutter/flutter/issues/109285
TEST_F(WindowsTest, LaunchConflictingCustomEntrypoints) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("customEntrypoint");
EnginePtr engine{builder.InitializeEngine()};
ASSERT_NE(engine, nullptr);
ASSERT_FALSE(FlutterDesktopEngineRun(engine.get(), "conflictingEntrypoint"));
}
// Verify that native functions can be registered and resolved.
TEST_F(WindowsTest, VerifyNativeFunction) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("verifyNativeFunction");
fml::AutoResetWaitableEvent latch;
auto native_entry =
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) { latch.Signal(); });
context.AddNativeFunction("Signal", native_entry);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
// Wait until signal has been called.
latch.Wait();
}
// Verify that native functions that pass parameters can be registered and
// resolved.
TEST_F(WindowsTest, VerifyNativeFunctionWithParameters) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("verifyNativeFunctionWithParameters");
bool bool_value = false;
fml::AutoResetWaitableEvent latch;
auto native_entry = CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeBooleanArgument(args, 0, &bool_value);
ASSERT_FALSE(Dart_IsError(handle));
latch.Signal();
});
context.AddNativeFunction("SignalBoolValue", native_entry);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
// Wait until signalBoolValue has been called.
latch.Wait();
EXPECT_TRUE(bool_value);
}
// Verify that Platform.executable returns the executable name.
TEST_F(WindowsTest, PlatformExecutable) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("readPlatformExecutable");
std::string executable_name;
fml::AutoResetWaitableEvent latch;
auto native_entry = CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeArgument(args, 0);
ASSERT_FALSE(Dart_IsError(handle));
executable_name = tonic::DartConverter<std::string>::FromDart(handle);
latch.Signal();
});
context.AddNativeFunction("SignalStringValue", native_entry);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
// Wait until signalStringValue has been called.
latch.Wait();
EXPECT_EQ(executable_name, "flutter_windows_unittests.exe");
}
// Verify that native functions that return values can be registered and
// resolved.
TEST_F(WindowsTest, VerifyNativeFunctionWithReturn) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("verifyNativeFunctionWithReturn");
bool bool_value_to_return = true;
fml::CountDownLatch latch(2);
auto bool_return_entry = CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
Dart_SetBooleanReturnValue(args, bool_value_to_return);
latch.CountDown();
});
context.AddNativeFunction("SignalBoolReturn", bool_return_entry);
bool bool_value_passed = false;
auto bool_pass_entry = CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
auto handle = Dart_GetNativeBooleanArgument(args, 0, &bool_value_passed);
ASSERT_FALSE(Dart_IsError(handle));
latch.CountDown();
});
context.AddNativeFunction("SignalBoolValue", bool_pass_entry);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
// Wait until signalBoolReturn and signalBoolValue have been called.
latch.Wait();
EXPECT_TRUE(bool_value_passed);
}
// Verify the next frame callback is executed.
TEST_F(WindowsTest, NextFrameCallback) {
struct Captures {
fml::AutoResetWaitableEvent frame_scheduled_latch;
fml::AutoResetWaitableEvent frame_drawn_latch;
std::thread::id thread_id;
};
Captures captures;
CreateNewThread("test_platform_thread")->PostTask([&]() {
captures.thread_id = std::this_thread::get_id();
auto& context = GetContext();
WindowsConfigBuilder builder(context);
builder.SetDartEntrypoint("drawHelloWorld");
auto native_entry = CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
ASSERT_FALSE(captures.frame_drawn_latch.IsSignaledForTest());
captures.frame_scheduled_latch.Signal();
});
context.AddNativeFunction("NotifyFirstFrameScheduled", native_entry);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
auto engine = FlutterDesktopViewControllerGetEngine(controller.get());
FlutterDesktopEngineSetNextFrameCallback(
engine,
[](void* user_data) {
auto captures = static_cast<Captures*>(user_data);
ASSERT_TRUE(captures->frame_scheduled_latch.IsSignaledForTest());
// Callback should execute on platform thread.
ASSERT_EQ(std::this_thread::get_id(), captures->thread_id);
// Signal the test passed and end the Windows message loop.
captures->frame_drawn_latch.Signal();
::PostQuitMessage(0);
},
&captures);
// Pump messages for the Windows platform task runner.
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
});
captures.frame_drawn_latch.Wait();
}
// Implicit view has the implicit view ID.
TEST_F(WindowsTest, GetViewId) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
FlutterDesktopViewId view_id =
FlutterDesktopViewControllerGetViewId(controller.get());
ASSERT_EQ(view_id, static_cast<FlutterDesktopViewId>(kImplicitViewId));
}
TEST_F(WindowsTest, GetGraphicsAdapter) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
auto view = FlutterDesktopViewControllerGetView(controller.get());
Microsoft::WRL::ComPtr<IDXGIAdapter> dxgi_adapter;
dxgi_adapter = FlutterDesktopViewGetGraphicsAdapter(view);
ASSERT_NE(dxgi_adapter, nullptr);
DXGI_ADAPTER_DESC desc{};
ASSERT_TRUE(SUCCEEDED(dxgi_adapter->GetDesc(&desc)));
}
// Implicit view has the implicit view ID.
TEST_F(WindowsTest, PluginRegistrarGetImplicitView) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
FlutterDesktopEngineRef engine =
FlutterDesktopViewControllerGetEngine(controller.get());
FlutterDesktopPluginRegistrarRef registrar =
FlutterDesktopEngineGetPluginRegistrar(engine, "foo_bar");
FlutterDesktopViewRef implicit_view =
FlutterDesktopPluginRegistrarGetView(registrar);
ASSERT_NE(implicit_view, nullptr);
}
TEST_F(WindowsTest, PluginRegistrarGetView) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
ViewControllerPtr controller{builder.Run()};
ASSERT_NE(controller, nullptr);
FlutterDesktopEngineRef engine =
FlutterDesktopViewControllerGetEngine(controller.get());
FlutterDesktopPluginRegistrarRef registrar =
FlutterDesktopEngineGetPluginRegistrar(engine, "foo_bar");
FlutterDesktopViewId view_id =
FlutterDesktopViewControllerGetViewId(controller.get());
FlutterDesktopViewRef view =
FlutterDesktopPluginRegistrarGetViewById(registrar, view_id);
FlutterDesktopViewRef view_123 = FlutterDesktopPluginRegistrarGetViewById(
registrar, static_cast<FlutterDesktopViewId>(123));
ASSERT_NE(view, nullptr);
ASSERT_EQ(view_123, nullptr);
}
TEST_F(WindowsTest, PluginRegistrarGetViewHeadless) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
EnginePtr engine{builder.RunHeadless()};
ASSERT_NE(engine, nullptr);
FlutterDesktopPluginRegistrarRef registrar =
FlutterDesktopEngineGetPluginRegistrar(engine.get(), "foo_bar");
FlutterDesktopViewRef implicit_view =
FlutterDesktopPluginRegistrarGetView(registrar);
FlutterDesktopViewRef view_123 = FlutterDesktopPluginRegistrarGetViewById(
registrar, static_cast<FlutterDesktopViewId>(123));
ASSERT_EQ(implicit_view, nullptr);
ASSERT_EQ(view_123, nullptr);
}
// Verify the app does not crash if EGL initializes successfully but
// the rendering surface cannot be created.
TEST_F(WindowsTest, SurfaceOptional) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
EnginePtr engine{builder.InitializeEngine()};
EngineModifier modifier{
reinterpret_cast<FlutterWindowsEngine*>(engine.get())};
auto egl_manager = std::make_unique<HalfBrokenEGLManager>();
ASSERT_TRUE(egl_manager->IsValid());
modifier.SetEGLManager(std::move(egl_manager));
ViewControllerPtr controller{
FlutterDesktopViewControllerCreate(0, 0, engine.release())};
ASSERT_NE(controller, nullptr);
}
// Verify the app produces the expected lifecycle events.
TEST_F(WindowsTest, Lifecycle) {
auto& context = GetContext();
WindowsConfigBuilder builder(context);
EnginePtr engine{builder.InitializeEngine()};
auto windows_engine = reinterpret_cast<FlutterWindowsEngine*>(engine.get());
EngineModifier modifier{windows_engine};
auto lifecycle_manager =
std::make_unique<MockWindowsLifecycleManager>(windows_engine);
auto lifecycle_manager_ptr = lifecycle_manager.get();
modifier.SetLifecycleManager(std::move(lifecycle_manager));
EXPECT_CALL(*lifecycle_manager_ptr,
SetLifecycleState(AppLifecycleState::kResumed))
.WillOnce([lifecycle_manager_ptr](AppLifecycleState state) {
lifecycle_manager_ptr->WindowsLifecycleManager::SetLifecycleState(
state);
});
EXPECT_CALL(*lifecycle_manager_ptr,
SetLifecycleState(AppLifecycleState::kHidden))
.WillOnce([lifecycle_manager_ptr](AppLifecycleState state) {
lifecycle_manager_ptr->WindowsLifecycleManager::SetLifecycleState(
state);
});
// Create a controller. This launches the engine and sets the app lifecycle
// to the "resumed" state.
ViewControllerPtr controller{
FlutterDesktopViewControllerCreate(0, 0, engine.release())};
FlutterDesktopViewRef view =
FlutterDesktopViewControllerGetView(controller.get());
ASSERT_NE(view, nullptr);
HWND hwnd = FlutterDesktopViewGetHWND(view);
ASSERT_NE(hwnd, nullptr);
// Give the window a non-zero size to show it. This does not change the app
// lifecycle directly. However, destroying the view will now result in a
// "hidden" app lifecycle event.
::MoveWindow(hwnd, /* X */ 0, /* Y */ 0, /* nWidth*/ 100, /* nHeight*/ 100,
/* bRepaint*/ false);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/flutter_windows_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_unittests.cc",
"repo_id": "engine",
"token_count": 5220
} | 415 |
// 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_MANAGER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_MANAGER_H_
#include <windows.h>
#include <atomic>
#include <deque>
#include <functional>
#include <map>
#include "flutter/fml/macros.h"
namespace flutter {
// Handles keyboard and text messages on Win32.
//
// |KeyboardManager| consumes raw Win32 messages related to key and chars, and
// converts them to key calls (|WindowDelegate::OnKey|) and possibly text calls
// (|WindowDelegate::OnText|).
//
// |KeyboardManager| requires a |WindowDelegate| to define how to access Win32
// system calls (to allow mocking) and where to send the results of key calls
// and text calls to.
//
// Typically, |KeyboardManager| is owned by a |FlutterWindow|, which also
// implements the window delegate. The key calls and text calls are forwarded to
// the |FlutterWindow|, and consequently, to the |FlutterWindowsView|.
//
// ## Terminology
//
// The keyboard system uses the following terminology (which is different
// than Win32's terminology):
//
// * Message: An invocation of |WndProc|, which consists of an
// action, an lparam, and a wparam.
// * Action: The type of a message.
// * Session: One to three messages that should be processed together, such
// as a key down message followed by char messages.
// * Event: A FlutterKeyEvent/ui.KeyData sent to the framework.
// * Call: A call to |WindowDelegate::OnKey| or |WindowDelegate::OnText|,
// which contains semi-processed messages.
class KeyboardManager {
public:
// Define how the keyboard manager accesses Win32 system calls (to allow
// mocking) and sends key calls and text calls.
//
// Typically implemented by |Window|.
class WindowDelegate {
public:
using KeyEventCallback = std::function<void(bool)>;
virtual ~WindowDelegate() = default;
// Called when text input occurs.
virtual void OnText(const std::u16string& text) = 0;
// Called when raw keyboard input occurs.
//
// The `callback` must be called exactly once.
virtual void OnKey(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) = 0;
// Win32's PeekMessage.
//
// Used to process key messages.
virtual BOOL Win32PeekMessage(LPMSG lpMsg,
UINT wMsgFilterMin,
UINT wMsgFilterMax,
UINT wRemoveMsg) = 0;
// Win32's MapVirtualKey(*, MAPVK_VK_TO_CHAR).
//
// Used to process key messages.
virtual uint32_t Win32MapVkToChar(uint32_t virtual_key) = 0;
// Win32's |SendMessage|.
//
// Used to synthesize key messages.
virtual UINT Win32DispatchMessage(UINT Msg,
WPARAM wParam,
LPARAM lParam) = 0;
};
using KeyEventCallback = WindowDelegate::KeyEventCallback;
explicit KeyboardManager(WindowDelegate* delegate);
// Processes Win32 messages related to keyboard and text.
//
// All messages related to keyboard and text should be sent here without
// pre-processing, including WM_{SYS,}KEY{DOWN,UP} and WM_{SYS,}{DEAD,}CHAR.
// Other message types will trigger assertion error.
//
// |HandleMessage| returns true if Flutter keyboard system decides to handle
// this message synchronously. It doesn't mean that the Flutter framework
// handles it, which is reported asynchronously later. Not handling this
// message here usually means that this message is a redispatched message,
// but there are other rare cases too. |Window| should forward unhandled
// messages to |DefWindowProc|.
bool HandleMessage(UINT const message,
WPARAM const wparam,
LPARAM const lparam);
protected:
struct Win32Message {
UINT action;
WPARAM wparam;
LPARAM lparam;
bool IsHighSurrogate() const { return IS_HIGH_SURROGATE(wparam); }
bool IsLowSurrogate() const { return IS_LOW_SURROGATE(wparam); }
bool IsGeneralKeyDown() const {
return action == WM_KEYDOWN || action == WM_SYSKEYDOWN;
}
};
struct PendingEvent {
WPARAM key;
uint8_t scancode;
UINT action;
char32_t character;
bool extended;
bool was_down;
std::vector<Win32Message> session;
};
virtual void RedispatchEvent(std::unique_ptr<PendingEvent> event);
private:
using OnKeyCallback =
std::function<void(std::unique_ptr<PendingEvent>, bool)>;
struct PendingText {
bool ready;
std::u16string content;
bool placeholder = false;
};
// Resume processing the pending events.
//
// If there is at least one pending event and no event is being processed,
// the oldest pending event will be handed over to |PerformProcessEvent|.
// After the event is processed, the next pending event will be automatically
// started, until there are no pending events left.
//
// Otherwise, this call is a no-op.
void ProcessNextEvent();
// Process an event and call `callback` when it's completed.
//
// The `callback` is constructed by |ProcessNextEvent| to start the next
// event, and must be called exactly once.
void PerformProcessEvent(std::unique_ptr<PendingEvent> event,
std::function<void()> callback);
// Handle the result of |WindowDelegate::OnKey|, possibly dispatching the text
// result to |WindowDelegate::OnText| and then redispatching.
//
// The `pending_text` is either a valid iterator of `pending_texts`, or its
// end(). In the latter case, this OnKey message does not contain a text.
void HandleOnKeyResult(std::unique_ptr<PendingEvent> event,
bool framework_handled);
// Dispatch the text content of a |PendingEvent| to |WindowDelegate::OnText|.
//
// If the content is empty of invalid, |WindowDelegate::OnText| will not be
// called.
void DispatchText(const PendingEvent& event);
// Returns the type of the next WM message.
//
// The parameters limits the range of interested messages. See Win32's
// |PeekMessage| for information.
//
// If there's no message, returns 0.
UINT PeekNextMessageType(UINT wMsgFilterMin, UINT wMsgFilterMax);
// Find an event in the redispatch list that matches the given one.
//
// If an matching event is found, removes the matching event from the
// redispatch list, and returns true. Otherwise, returns false;
bool RemoveRedispatchedMessage(UINT action, WPARAM wparam, LPARAM lparam);
WindowDelegate* window_delegate_;
// Keeps track of all messages during the current session.
//
// At the end of a session, it is moved to the `PendingEvent`, which is
// passed to `WindowDelegate::OnKey`.
std::vector<Win32Message> current_session_;
// Whether the last event is a CtrlLeft key down.
//
// This is used to resolve a corner case described in |IsKeyDownAltRight|.
bool last_key_is_ctrl_left_down;
// The scancode of the last met CtrlLeft down.
//
// This is used to resolve a corner case described in |IsKeyDownAltRight|.
uint8_t ctrl_left_scancode;
// Whether a CtrlLeft up should be synthesized upon the next AltRight up.
//
// This is used to resolve a corner case described in |IsKeyDownAltRight|.
bool should_synthesize_ctrl_left_up;
// Store the messages coming from |HandleMessage|.
//
// Only one message is processed at a time. The next one will not start
// until the framework has responded to the previous message.
std::deque<std::unique_ptr<PendingEvent>> pending_events_;
// Whether a message is being processed.
std::atomic<bool> processing_event_;
// The queue of messages that have been redispatched to the system but have
// not yet been received for a second time.
std::deque<Win32Message> pending_redispatches_;
FML_DISALLOW_COPY_AND_ASSIGN(KeyboardManager);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_KEYBOARD_MANAGER_H_
| engine/shell/platform/windows/keyboard_manager.h/0 | {
"file_path": "engine/shell/platform/windows/keyboard_manager.h",
"repo_id": "engine",
"token_count": 2823
} | 416 |
// 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/settings_plugin.h"
#include "flutter/shell/platform/common/json_message_codec.h"
#include "flutter/shell/platform/windows/system_utils.h"
namespace flutter {
namespace {
constexpr char kChannelName[] = "flutter/settings";
constexpr char kAlwaysUse24HourFormat[] = "alwaysUse24HourFormat";
constexpr char kTextScaleFactor[] = "textScaleFactor";
constexpr char kPlatformBrightness[] = "platformBrightness";
constexpr char kPlatformBrightnessDark[] = "dark";
constexpr char kPlatformBrightnessLight[] = "light";
constexpr wchar_t kGetPreferredBrightnessRegKey[] =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
constexpr wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
constexpr wchar_t kGetTextScaleFactorRegKey[] =
L"Software\\Microsoft\\Accessibility";
constexpr wchar_t kGetTextScaleFactorRegValue[] = L"TextScaleFactor";
// Return an approximation of the apparent luminance of a given color.
int GetLuminance(DWORD color) {
int r = GetRValue(color);
int g = GetGValue(color);
int b = GetBValue(color);
return (r + r + r + b + (g << 2)) >> 3;
}
// Return kLight if light mode for apps is selected, otherwise return kDark.
SettingsPlugin::PlatformBrightness GetThemeBrightness() {
DWORD use_light_theme;
DWORD use_light_theme_size = sizeof(use_light_theme);
LONG result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
kGetPreferredBrightnessRegValue, RRF_RT_REG_DWORD,
nullptr, &use_light_theme, &use_light_theme_size);
if (result == 0) {
return use_light_theme ? SettingsPlugin::PlatformBrightness::kLight
: SettingsPlugin::PlatformBrightness::kDark;
} else {
// The current OS does not support dark mode. (Older Windows 10 or before
// Windows 10)
return SettingsPlugin::PlatformBrightness::kLight;
}
}
} // namespace
SettingsPlugin::SettingsPlugin(BinaryMessenger* messenger,
TaskRunner* task_runner)
: channel_(std::make_unique<BasicMessageChannel<rapidjson::Document>>(
messenger,
kChannelName,
&JsonMessageCodec::GetInstance())),
task_runner_(task_runner) {}
SettingsPlugin::~SettingsPlugin() {
StopWatching();
}
void SettingsPlugin::SendSettings() {
rapidjson::Document settings(rapidjson::kObjectType);
auto& allocator = settings.GetAllocator();
settings.AddMember(kAlwaysUse24HourFormat, GetAlwaysUse24HourFormat(),
allocator);
settings.AddMember(kTextScaleFactor, GetTextScaleFactor(), allocator);
if (GetPreferredBrightness() == PlatformBrightness::kDark) {
settings.AddMember(kPlatformBrightness, kPlatformBrightnessDark, allocator);
} else {
settings.AddMember(kPlatformBrightness, kPlatformBrightnessLight,
allocator);
}
channel_->Send(settings);
}
void SettingsPlugin::StartWatching() {
RegOpenKeyEx(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
RRF_RT_REG_DWORD, KEY_NOTIFY, &preferred_brightness_reg_hkey_);
RegOpenKeyEx(HKEY_CURRENT_USER, kGetTextScaleFactorRegKey, RRF_RT_REG_DWORD,
KEY_NOTIFY, &text_scale_factor_reg_hkey_);
// Start watching when the keys exist.
if (preferred_brightness_reg_hkey_ != nullptr) {
WatchPreferredBrightnessChanged();
}
if (text_scale_factor_reg_hkey_ != nullptr) {
WatchTextScaleFactorChanged();
}
}
void SettingsPlugin::StopWatching() {
preferred_brightness_changed_watcher_ = nullptr;
text_scale_factor_changed_watcher_ = nullptr;
if (preferred_brightness_reg_hkey_ != nullptr) {
RegCloseKey(preferred_brightness_reg_hkey_);
}
if (text_scale_factor_reg_hkey_ != nullptr) {
RegCloseKey(text_scale_factor_reg_hkey_);
}
}
bool SettingsPlugin::GetAlwaysUse24HourFormat() {
return Prefer24HourTime(GetUserTimeFormat());
}
float SettingsPlugin::GetTextScaleFactor() {
DWORD text_scale_factor;
DWORD text_scale_factor_size = sizeof(text_scale_factor);
LONG result = RegGetValue(
HKEY_CURRENT_USER, kGetTextScaleFactorRegKey, kGetTextScaleFactorRegValue,
RRF_RT_REG_DWORD, nullptr, &text_scale_factor, &text_scale_factor_size);
if (result == 0) {
return text_scale_factor / 100.0;
} else {
// The current OS does not have text scale factor.
return 1.0;
}
}
SettingsPlugin::PlatformBrightness SettingsPlugin::GetPreferredBrightness() {
if (is_high_contrast_) {
DWORD window_color = GetSysColor(COLOR_WINDOW);
int luminance = GetLuminance(window_color);
return luminance >= 127 ? SettingsPlugin::PlatformBrightness::kLight
: SettingsPlugin::PlatformBrightness::kDark;
} else {
return GetThemeBrightness();
}
}
void SettingsPlugin::WatchPreferredBrightnessChanged() {
preferred_brightness_changed_watcher_ =
std::make_unique<EventWatcher>([this]() {
task_runner_->PostTask([this]() {
SendSettings();
WatchPreferredBrightnessChanged();
});
});
RegNotifyChangeKeyValue(
preferred_brightness_reg_hkey_, FALSE, REG_NOTIFY_CHANGE_LAST_SET,
preferred_brightness_changed_watcher_->GetHandle(), TRUE);
}
void SettingsPlugin::WatchTextScaleFactorChanged() {
text_scale_factor_changed_watcher_ = std::make_unique<EventWatcher>([this]() {
task_runner_->PostTask([this]() {
SendSettings();
WatchTextScaleFactorChanged();
});
});
RegNotifyChangeKeyValue(
text_scale_factor_reg_hkey_, FALSE, REG_NOTIFY_CHANGE_LAST_SET,
text_scale_factor_changed_watcher_->GetHandle(), TRUE);
}
void SettingsPlugin::UpdateHighContrastMode(bool is_high_contrast) {
is_high_contrast_ = is_high_contrast;
SendSettings();
}
} // namespace flutter
| engine/shell/platform/windows/settings_plugin.cc/0 | {
"file_path": "engine/shell/platform/windows/settings_plugin.cc",
"repo_id": "engine",
"token_count": 2178
} | 417 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/testing/flutter_windows_engine_builder.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/windows_proc_table.h"
namespace flutter {
namespace testing {
class TestFlutterWindowsEngine : public FlutterWindowsEngine {
public:
TestFlutterWindowsEngine(
const FlutterProjectBundle& project,
KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state,
KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan,
std::shared_ptr<WindowsProcTable> windows_proc_table = nullptr)
: FlutterWindowsEngine(project, std::move(windows_proc_table)),
get_key_state_(std::move(get_key_state)),
map_vk_to_scan_(std::move(map_vk_to_scan)) {}
protected:
std::unique_ptr<KeyboardHandlerBase> CreateKeyboardKeyHandler(
BinaryMessenger* messenger,
KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state,
KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan) {
if (get_key_state_) {
get_key_state = get_key_state_;
}
if (map_vk_to_scan_) {
map_vk_to_scan = map_vk_to_scan_;
}
return FlutterWindowsEngine::CreateKeyboardKeyHandler(
messenger, get_key_state, map_vk_to_scan);
}
private:
KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state_;
KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan_;
FML_DISALLOW_COPY_AND_ASSIGN(TestFlutterWindowsEngine);
};
FlutterWindowsEngineBuilder::FlutterWindowsEngineBuilder(
WindowsTestContext& context)
: context_(context) {
properties_.assets_path = context.GetAssetsPath().c_str();
properties_.icu_data_path = context.GetIcuDataPath().c_str();
properties_.aot_library_path = context.GetAotLibraryPath().c_str();
}
FlutterWindowsEngineBuilder::~FlutterWindowsEngineBuilder() = default;
void FlutterWindowsEngineBuilder::SetDartEntrypoint(std::string entrypoint) {
dart_entrypoint_ = std::move(entrypoint);
properties_.dart_entrypoint = dart_entrypoint_.c_str();
}
void FlutterWindowsEngineBuilder::AddDartEntrypointArgument(std::string arg) {
dart_entrypoint_arguments_.emplace_back(std::move(arg));
}
void FlutterWindowsEngineBuilder::SetSwitches(
std::vector<std::string> switches) {
switches_ = std::move(switches);
}
void FlutterWindowsEngineBuilder::SetCreateKeyboardHandlerCallbacks(
KeyboardKeyEmbedderHandler::GetKeyStateHandler get_key_state,
KeyboardKeyEmbedderHandler::MapVirtualKeyToScanCode map_vk_to_scan) {
get_key_state_ = std::move(get_key_state);
map_vk_to_scan_ = std::move(map_vk_to_scan);
}
void FlutterWindowsEngineBuilder::SetWindowsProcTable(
std::shared_ptr<WindowsProcTable> windows_proc_table) {
windows_proc_table_ = std::move(windows_proc_table);
}
std::unique_ptr<FlutterWindowsEngine> FlutterWindowsEngineBuilder::Build() {
std::vector<const char*> dart_args;
dart_args.reserve(dart_entrypoint_arguments_.size());
for (const auto& arg : dart_entrypoint_arguments_) {
dart_args.push_back(arg.c_str());
}
if (!dart_args.empty()) {
properties_.dart_entrypoint_argv = dart_args.data();
properties_.dart_entrypoint_argc = dart_args.size();
} else {
properties_.dart_entrypoint_argv = nullptr;
properties_.dart_entrypoint_argc = 0;
}
FlutterProjectBundle project(properties_);
project.SetSwitches(switches_);
return std::make_unique<TestFlutterWindowsEngine>(
project, get_key_state_, map_vk_to_scan_, std::move(windows_proc_table_));
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/testing/flutter_windows_engine_builder.cc/0 | {
"file_path": "engine/shell/platform/windows/testing/flutter_windows_engine_builder.cc",
"repo_id": "engine",
"token_count": 1319
} | 418 |
// 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_VIEW_MODIFIER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_VIEW_MODIFIER_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/egl/window_surface.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
namespace flutter {
// A test utility class providing the ability to access and alter various
// private fields in a |FlutterWindowsView| instance.
class ViewModifier {
public:
explicit ViewModifier(FlutterWindowsView* view) : view_(view) {}
// Override the EGL surface used by the view.
//
// Modifications are to the view, and will last for the lifetime of the
// view unless overwritten again.
void SetSurface(std::unique_ptr<egl::WindowSurface> surface) {
view_->surface_ = std::move(surface);
}
private:
FlutterWindowsView* view_;
FML_DISALLOW_COPY_AND_ASSIGN(ViewModifier);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_VIEW_MODIFIER_H_
| engine/shell/platform/windows/testing/view_modifier.h/0 | {
"file_path": "engine/shell/platform/windows/testing/view_modifier.h",
"repo_id": "engine",
"token_count": 385
} | 419 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/window_proc_delegate_manager.h"
#include <algorithm>
#include "flutter/shell/platform/embedder/embedder.h"
namespace flutter {
WindowProcDelegateManager::WindowProcDelegateManager() = default;
WindowProcDelegateManager::~WindowProcDelegateManager() = default;
void WindowProcDelegateManager::RegisterTopLevelWindowProcDelegate(
FlutterDesktopWindowProcCallback callback,
void* user_data) {
UnregisterTopLevelWindowProcDelegate(callback);
delegates_.push_back(WindowProcDelegate{
.callback = callback,
.user_data = user_data,
});
}
void WindowProcDelegateManager::UnregisterTopLevelWindowProcDelegate(
FlutterDesktopWindowProcCallback callback) {
delegates_.erase(
std::remove_if(delegates_.begin(), delegates_.end(),
[&callback](const WindowProcDelegate& delegate) {
return delegate.callback == callback;
}),
delegates_.end());
}
std::optional<LRESULT> WindowProcDelegateManager::OnTopLevelWindowProc(
HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) const {
std::optional<LRESULT> result;
for (const auto& delegate : delegates_) {
LPARAM handler_result;
// Stop as soon as any delegate indicates that it has handled the message.
if (delegate.callback(hwnd, message, wparam, lparam, delegate.user_data,
&handler_result)) {
result = handler_result;
break;
}
}
return result;
}
} // namespace flutter
| engine/shell/platform/windows/window_proc_delegate_manager.cc/0 | {
"file_path": "engine/shell/platform/windows/window_proc_delegate_manager.cc",
"repo_id": "engine",
"token_count": 624
} | 420 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
_skia_root = "//flutter/third_party/skia"
import("$_skia_root/gn/skia.gni")
import("$_skia_root/modules/skparagraph/skparagraph.gni")
import("$_skia_root/modules/skshaper/skshaper.gni")
import("$_skia_root/modules/skunicode/skunicode.gni")
declare_args() {
skia_enable_skparagraph = true
paragraph_gms_enabled = true
paragraph_tests_enabled = true
paragraph_bench_enabled = false
}
config("public_config") {
defines = [ "SK_ENABLE_PARAGRAPH" ]
include_dirs = [
"$_skia_root/modules/skparagraph/include",
"$_skia_root/modules/skparagraph/utils",
]
}
skia_component("skparagraph") {
import("$_skia_root/modules/skparagraph/skparagraph.gni")
# Opted out of check_includes, due to (logically) being part of skia.
check_includes = false
public_configs = [ ":public_config" ]
public = skparagraph_public
sources = skparagraph_sources
public_deps = [
"../..:skia",
"../skunicode",
]
deps = [ "../skshaper" ]
}
| engine/skia/modules/skparagraph/BUILD.gn/0 | {
"file_path": "engine/skia/modules/skparagraph/BUILD.gn",
"repo_id": "engine",
"token_count": 413
} | 421 |
#!/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.
import argparse
import platform
import subprocess
import shutil
import sys
import os
from create_xcframework import create_xcframework # pylint: disable=import-error
ARCH_SUBPATH = 'mac-arm64' if platform.processor() == 'arm' else 'mac-x64'
DSYMUTIL = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'buildtools', ARCH_SUBPATH, 'clang', 'bin',
'dsymutil'
)
def main():
parser = argparse.ArgumentParser(description='Creates Flutter.framework and Flutter.xcframework')
parser.add_argument('--dst', type=str, required=True)
parser.add_argument('--arm64-out-dir', type=str, required=True)
parser.add_argument('--armv7-out-dir', type=str, required=False)
# TODO(gw280): Remove --simulator-out-dir alias when all recipes are updated
parser.add_argument('--simulator-x64-out-dir', '--simulator-out-dir', type=str, required=True)
parser.add_argument('--simulator-arm64-out-dir', type=str, required=False)
parser.add_argument('--strip', action='store_true', default=False)
parser.add_argument('--dsym', action='store_true', default=False)
args = parser.parse_args()
framework = os.path.join(args.dst, 'Flutter.framework')
simulator_framework = os.path.join(args.dst, 'sim', 'Flutter.framework')
arm64_framework = os.path.join(args.arm64_out_dir, 'Flutter.framework')
simulator_x64_framework = os.path.join(args.simulator_x64_out_dir, 'Flutter.framework')
if args.simulator_arm64_out_dir is not None:
simulator_arm64_framework = os.path.join(args.simulator_arm64_out_dir, 'Flutter.framework')
simulator_arm64_dylib = os.path.join(simulator_arm64_framework, 'Flutter')
arm64_dylib = os.path.join(arm64_framework, 'Flutter')
simulator_x64_dylib = os.path.join(simulator_x64_framework, 'Flutter')
if not os.path.isdir(arm64_framework):
print('Cannot find iOS arm64 Framework at %s' % arm64_framework)
return 1
if not os.path.isdir(simulator_x64_framework):
print('Cannot find iOS x64 simulator Framework at %s' % simulator_framework)
return 1
if not os.path.isfile(arm64_dylib):
print('Cannot find iOS arm64 dylib at %s' % arm64_dylib)
return 1
if not os.path.isfile(simulator_x64_dylib):
print('Cannot find iOS simulator dylib at %s' % simulator_x64_dylib)
return 1
if not os.path.isfile(DSYMUTIL):
print('Cannot find dsymutil at %s' % DSYMUTIL)
return 1
shutil.rmtree(framework, True)
shutil.copytree(arm64_framework, framework)
framework_binary = os.path.join(framework, 'Flutter')
process_framework(args, framework, framework_binary)
if args.simulator_arm64_out_dir is not None:
shutil.rmtree(simulator_framework, True)
shutil.copytree(simulator_arm64_framework, simulator_framework)
simulator_framework_binary = os.path.join(simulator_framework, 'Flutter')
# Create the arm64/x64 simulator fat framework.
subprocess.check_call([
'lipo', simulator_x64_dylib, simulator_arm64_dylib, '-create', '-output',
simulator_framework_binary
])
process_framework(args, simulator_framework, simulator_framework_binary)
else:
simulator_framework = simulator_x64_framework
# Create XCFramework from the arm-only fat framework and the arm64/x64
# simulator frameworks, or just the x64 simulator framework if only that one
# exists.
xcframeworks = [simulator_framework, framework]
create_xcframework(location=args.dst, name='Flutter', frameworks=xcframeworks)
# Add the x64 simulator into the fat framework
subprocess.check_call([
'lipo', arm64_dylib, simulator_x64_dylib, '-create', '-output', framework_binary
])
process_framework(args, framework, framework_binary)
return 0
def process_framework(args, framework, framework_binary):
if args.dsym:
dsym_out = os.path.splitext(framework)[0] + '.dSYM'
subprocess.check_call([DSYMUTIL, '-o', dsym_out, framework_binary])
if args.strip:
# copy unstripped
unstripped_out = os.path.join(args.dst, 'Flutter.unstripped')
shutil.copyfile(framework_binary, unstripped_out)
subprocess.check_call(['strip', '-x', '-S', framework_binary])
if __name__ == '__main__':
sys.exit(main())
| engine/sky/tools/create_ios_framework.py/0 | {
"file_path": "engine/sky/tools/create_ios_framework.py",
"repo_id": "engine",
"token_count": 1531
} | 422 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.android_background_image;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BinaryMessenger;
import java.nio.ByteBuffer;
public class MainActivity extends FlutterActivity {
@NonNull
private final BinaryMessenger.BinaryMessageHandler finishHandler =
new BinaryMessenger.BinaryMessageHandler() {
@Override
public void onMessage(ByteBuffer message, final BinaryMessenger.BinaryReply callback) {
if (message != null) {
// Make CI see that there is an error in the logs from Flutter.
Log.e("flutter", "Images did not match.");
}
final Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
MainActivity.this.startActivity(intent);
MainActivity.this.finish();
}
};
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
flutterEngine.getDartExecutor().getBinaryMessenger().setMessageHandler("finish", finishHandler);
final boolean moved = moveTaskToBack(true);
if (!moved) {
Log.e("flutter", "Failed to move to back.");
finish();
}
}
}
| engine/testing/android_background_image/android/app/src/main/java/dev/flutter/android_background_image/MainActivity.java/0 | {
"file_path": "engine/testing/android_background_image/android/app/src/main/java/dev/flutter/android_background_image/MainActivity.java",
"repo_id": "engine",
"token_count": 543
} | 423 |
{
"context": {
"date": "2019-12-17 15:14:14",
"num_cpus": 56,
"mhz_per_cpu": 2594,
"cpu_scaling_enabled": true,
"library_build_type": "release"
},
"benchmarks": [
{
"name": "BM_PaintRecordInit",
"iterations": 6749079,
"real_time": 101,
"cpu_time": 101,
"time_unit": "ns"
},
{
"name": "BM_ParagraphShortLayout",
"iterations": 151761,
"real_time": 4460,
"cpu_time": 4460,
"time_unit": "ns"
},
{
"name": "BM_ParagraphStylesBigO_BigO",
"cpu_coefficient": 6548,
"real_coefficient": 6548,
"big_o": "N",
"time_unit": "ns"
}
]
}
| engine/testing/benchmark/example/txt_benchmarks.json/0 | {
"file_path": "engine/testing/benchmark/example/txt_benchmarks.json",
"repo_id": "engine",
"token_count": 352
} | 424 |
// 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:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as path;
import 'impeller_enabled.dart';
const int _kWidth = 10;
const int _kRadius = 2;
const Color _kBlack = Color.fromRGBO(0, 0, 0, 1.0);
const Color _kGreen = Color.fromRGBO(0, 255, 0, 1.0);
void main() {
test('decodeImageFromPixels float32', () async {
if (impellerEnabled) {
print('Disabled on Impeller - https://github.com/flutter/flutter/issues/135702');
return;
}
const int width = 2;
const int height = 2;
final Float32List pixels = Float32List(width * height * 4);
final List<List<double>> pixels2d = <List<double>>[
<double>[1, 0, 0, 1],
<double>[0, 1, 0, 1],
<double>[0, 0, 1, 1],
<double>[1, 1, 1, 0],
];
int offset = 0;
for (final List<double> color in pixels2d) {
pixels[offset + 0] = color[0];
pixels[offset + 1] = color[1];
pixels[offset + 2] = color[2];
pixels[offset + 3] = color[3];
offset += 4;
}
final Completer<Image> completer = Completer<Image>();
decodeImageFromPixels(
Uint8List.view(pixels.buffer), width, height, PixelFormat.rgbaFloat32,
(Image result) {
completer.complete(result);
});
final Image image = await completer.future;
final ByteData data =
(await image.toByteData(format: ImageByteFormat.rawStraightRgba))!;
final Uint32List readPixels = Uint32List.view(data.buffer);
expect(width * height, readPixels.length);
expect(readPixels[0], 0xff0000ff);
expect(readPixels[1], 0xff00ff00);
expect(readPixels[2], 0xffff0000);
expect(readPixels[3], 0x00ffffff);
});
test('Image.toByteData RGBA format works with simple image', () async {
final Image image = await Square4x4Image.image;
final ByteData data = (await image.toByteData())!;
expect(Uint8List.view(data.buffer), Square4x4Image.bytes);
});
test('Image.toByteData RGBA format converts grayscale images', () async {
final Image image = await GrayscaleImage.load();
final ByteData data = (await image.toByteData())!;
final Uint8List bytes = data.buffer.asUint8List();
expect(bytes, hasLength(16));
expect(bytes, GrayscaleImage.bytesAsRgba);
});
test('Image.toByteData RGBA format works with transparent image', () async {
final Image image = await TransparentImage.load();
final ByteData data = (await image.toByteData())!;
final Uint8List bytes = data.buffer.asUint8List();
expect(bytes, hasLength(64));
expect(bytes, TransparentImage.bytesAsPremultipliedRgba);
});
test('Image.toByteData Straight RGBA format works with transparent image', () async {
final Image image = await TransparentImage.load();
final ByteData data = (await image.toByteData(format: ImageByteFormat.rawStraightRgba))!;
final Uint8List bytes = data.buffer.asUint8List();
expect(bytes, hasLength(64));
expect(bytes, TransparentImage.bytesAsStraightRgba);
});
test('Image.toByteData Unmodified format works with simple image', () async {
final Image image = await Square4x4Image.image;
final ByteData data = (await image.toByteData(format: ImageByteFormat.rawUnmodified))!;
expect(Uint8List.view(data.buffer), Square4x4Image.bytes);
});
test('Image.toByteData Unmodified format works with grayscale images', () async {
if (impellerEnabled) {
print('Disabled on Impeller - https://github.com/flutter/flutter/issues/135706');
return;
}
final Image image = await GrayscaleImage.load();
final ByteData data = (await image.toByteData(format: ImageByteFormat.rawUnmodified))!;
final Uint8List bytes = data.buffer.asUint8List();
expect(bytes, hasLength(4));
expect(bytes, GrayscaleImage.bytesUnmodified);
});
test('Image.toByteData PNG format works with simple image', () async {
if (impellerEnabled) {
print('Disabled on Impeller - https://github.com/flutter/flutter/issues/135706');
return;
}
final Image image = await Square4x4Image.image;
final ByteData data = (await image.toByteData(format: ImageByteFormat.png))!;
final List<int> expected = await readFile('square.png');
expect(Uint8List.view(data.buffer), expected);
});
test('Image.toByteData ExtendedRGBA128', () async {
final Image image = await Square4x4Image.image;
final ByteData data = (await image.toByteData(format: ImageByteFormat.rawExtendedRgba128))!;
expect(image.width, _kWidth);
expect(image.height, _kWidth);
expect(data.lengthInBytes, _kWidth * _kWidth * 4 * 4);
// Top-left pixel should be black.
final Float32List floats = Float32List.view(data.buffer);
expect(floats[0], 0.0);
expect(floats[1], 0.0);
expect(floats[2], 0.0);
expect(floats[3], 1.0);
expect(image.colorSpace, ColorSpace.sRGB);
});
}
class Square4x4Image {
Square4x4Image._();
static Future<Image> get image async {
final double width = _kWidth.toDouble();
final double radius = _kRadius.toDouble();
final double innerWidth = (_kWidth - 2 * _kRadius).toDouble();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas =
Canvas(recorder, Rect.fromLTWH(0.0, 0.0, width, width));
final Paint black = Paint()
..strokeWidth = 1.0
..color = _kBlack;
final Paint green = Paint()
..strokeWidth = 1.0
..color = _kGreen;
canvas.drawRect(Rect.fromLTWH(0.0, 0.0, width, width), black);
canvas.drawRect(
Rect.fromLTWH(radius, radius, innerWidth, innerWidth), green);
return recorder.endRecording().toImage(_kWidth, _kWidth);
}
static List<int> get bytes {
const int bytesPerChannel = 4;
final List<int> result = List<int>.filled(
_kWidth * _kWidth * bytesPerChannel, 0);
void fillWithColor(Color color, int min, int max) {
for (int i = min; i < max; i++) {
for (int j = min; j < max; j++) {
final int offset = i * bytesPerChannel + j * _kWidth * bytesPerChannel;
result[offset] = color.red;
result[offset + 1] = color.green;
result[offset + 2] = color.blue;
result[offset + 3] = color.alpha;
}
}
}
fillWithColor(_kBlack, 0, _kWidth);
fillWithColor(_kGreen, _kRadius, _kWidth - _kRadius);
return result;
}
}
class GrayscaleImage {
GrayscaleImage._();
static Future<Image> load() async {
final Uint8List bytes = await readFile('2x2.png');
final Completer<Image> completer = Completer<Image>();
decodeImageFromList(bytes, (Image image) => completer.complete(image));
return completer.future;
}
static List<int> get bytesAsRgba {
return <int>[
255, 255, 255, 255,
127, 127, 127, 255,
127, 127, 127, 255,
0, 0, 0, 255,
];
}
static List<int> get bytesUnmodified => <int>[255, 127, 127, 0];
}
class TransparentImage {
TransparentImage._();
static Future<Image> load() async {
final Uint8List bytes = await readFile('transparent_image.png');
final Completer<Image> completer = Completer<Image>();
decodeImageFromList(bytes, (Image image) => completer.complete(image));
return completer.future;
}
static List<int> get bytesAsPremultipliedRgba {
return <int>[
//First raw, solid colors
255, 0, 0, 255, // red
0, 255, 0, 255, // green
0, 0, 255, 255, // blue
136, 136, 136, 255, // grey
//Second raw, 50% transparent
127, 0, 0, 127, // red
0, 127, 0, 127, // green
0, 0, 127, 127, // blue
67, 67, 67, 127, // grey
//Third raw, 25% transparent
63, 0, 0, 63, // red
0, 63, 0, 63, // green
0, 0, 63, 63, // blue
33, 33, 33, 63, // grey
//Fourth raw, transparent
0, 0, 0, 0, // red
0, 0, 0, 0, // green
0, 0, 0, 0, // blue
0, 0, 0, 0, // grey
];
}
static List<int> get bytesAsStraightRgba {
return <int>[
//First raw, solid colors
255, 0, 0, 255, // red
0, 255, 0, 255, // green
0, 0, 255, 255, // blue
136, 136, 136, 255, // grey
//Second raw, 50% transparent
255, 0, 0, 127, // red
0, 255, 0, 127, // green
0, 0, 255, 127, // blue
135, 135, 135, 127, // grey
//Third raw, 25% transparent
255, 0, 0, 63, // red
0, 255, 0, 63, // green
0, 0, 255, 63, // blue
134, 134, 134, 63, // grey
//Fourth raw, transparent
0, 0, 0, 0, // red
0, 0, 0, 0, // green
0, 0, 0, 0, // blue
0, 0, 0, 0, // grey
];
}
}
Future<Uint8List> readFile(String fileName) async {
final File file = File(path.join('flutter', 'testing', 'resources', fileName));
return file.readAsBytes();
}
| engine/testing/dart/encoding_test.dart/0 | {
"file_path": "engine/testing/dart/encoding_test.dart",
"repo_id": "engine",
"token_count": 3697
} | 425 |
// Copyright 2022 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Picture construction invokes onCreate once', () async {
int onCreateInvokedCount = 0;
Picture? createdPicture;
Picture.onCreate = (Picture picture) {
onCreateInvokedCount++;
createdPicture = picture;
};
final Picture picture1 = _createPicture();
expect(onCreateInvokedCount, 1);
expect(createdPicture, picture1);
final Picture picture2 = _createPicture();
expect(onCreateInvokedCount, 2);
expect(createdPicture, picture2);
Picture.onCreate = null;
});
test('approximateBytesUsed is available for onCreate', () async {
int pictureSize = -1;
Picture.onCreate = (Picture picture) =>
pictureSize = picture.approximateBytesUsed;
_createPicture();
expect(pictureSize >= 0, true);
Picture.onCreate = null;
});
test('dispose() invokes onDispose once', () async {
int onDisposeInvokedCount = 0;
Picture? disposedPicture;
Picture.onDispose = (Picture picture) {
onDisposeInvokedCount++;
disposedPicture = picture;
};
final Picture picture1 = _createPicture()..dispose();
expect(onDisposeInvokedCount, 1);
expect(disposedPicture, picture1);
final Picture picture2 = _createPicture()..dispose();
expect(onDisposeInvokedCount, 2);
expect(disposedPicture, picture2);
Picture.onDispose = null;
});
}
Picture _createPicture() {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 100.0);
canvas.clipRect(rect);
return recorder.endRecording();
}
| engine/testing/dart/picture_test.dart/0 | {
"file_path": "engine/testing/dart/picture_test.dart",
"repo_id": "engine",
"token_count": 611
} | 426 |
// 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/dart_fixture.h"
#include <utility>
#include "flutter/fml/paths.h"
namespace flutter::testing {
DartFixture::DartFixture()
: DartFixture("kernel_blob.bin",
kDefaultAOTAppELFFileName,
kDefaultAOTAppELFSplitFileName) {}
DartFixture::DartFixture(std::string kernel_filename,
std::string elf_filename,
std::string elf_split_filename)
: native_resolver_(std::make_shared<TestDartNativeResolver>()),
split_aot_symbols_(LoadELFSplitSymbolFromFixturesIfNeccessary(
std::move(elf_split_filename))),
kernel_filename_(std::move(kernel_filename)),
assets_dir_(fml::OpenDirectory(GetFixturesPath(),
false,
fml::FilePermission::kRead)),
aot_symbols_(
LoadELFSymbolFromFixturesIfNeccessary(std::move(elf_filename))) {}
Settings DartFixture::CreateSettingsForFixture() {
Settings settings;
settings.leak_vm = false;
settings.task_observer_add = [](intptr_t, const fml::closure&) {};
settings.task_observer_remove = [](intptr_t) {};
settings.isolate_create_callback = [this]() {
native_resolver_->SetNativeResolverForIsolate();
};
settings.enable_vm_service = false;
SetSnapshotsAndAssets(settings);
return settings;
}
void DartFixture::SetSnapshotsAndAssets(Settings& settings) {
if (!assets_dir_.is_valid()) {
return;
}
settings.assets_dir = assets_dir_.get();
// In JIT execution, all snapshots are present within the binary itself and
// don't need to be explicitly supplied by the embedder. In AOT, these
// snapshots will be present in the application AOT dylib.
if (DartVM::IsRunningPrecompiledCode()) {
FML_CHECK(PrepareSettingsForAOTWithSymbols(settings, aot_symbols_));
#if FML_OS_LINUX
settings.vmservice_snapshot_library_path.emplace_back(fml::paths::JoinPaths(
{GetTestingAssetsPath(), "libvmservice_snapshot.so"}));
#endif // FML_OS_LINUX
} else {
settings.application_kernels = [this]() -> Mappings {
std::vector<std::unique_ptr<const fml::Mapping>> kernel_mappings;
auto kernel_mapping =
fml::FileMapping::CreateReadOnly(assets_dir_, kernel_filename_);
if (!kernel_mapping || !kernel_mapping->IsValid()) {
FML_LOG(ERROR) << "Could not find kernel blob for test fixture not "
"running in precompiled mode.";
return kernel_mappings;
}
kernel_mappings.emplace_back(std::move(kernel_mapping));
return kernel_mappings;
};
}
}
void DartFixture::AddNativeCallback(const std::string& name,
Dart_NativeFunction callback) {
native_resolver_->AddNativeCallback(name, callback);
}
void DartFixture::AddFfiNativeCallback(const std::string& name,
void* callback_ptr) {
native_resolver_->AddFfiNativeCallback(name, callback_ptr);
}
} // namespace flutter::testing
| engine/testing/dart_fixture.cc/0 | {
"file_path": "engine/testing/dart_fixture.cc",
"repo_id": "engine",
"token_count": 1308
} | 427 |
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
| engine/testing/ios/IosUnitTests/App/Base.lproj/Main.storyboard/0 | {
"file_path": "engine/testing/ios/IosUnitTests/App/Base.lproj/Main.storyboard",
"repo_id": "engine",
"token_count": 695
} | 428 |
// 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:collection';
import 'dart:io' show stdout;
import 'dart:isolate';
import 'test.dart';
/// A suite of tests, added with the [test] method, which will be run in a
/// following event.
class TestSuite {
/// Creates a new [TestSuite] with logs written to [logger] and callbacks
/// given by [lifecycle].
TestSuite({
StringSink? logger,
Lifecycle? lifecycle,
}) :
_logger = logger ?? stdout,
_lifecycle = lifecycle ?? _DefaultLifecycle();
final Lifecycle _lifecycle;
final StringSink _logger;
bool _testQueuePrimed = false;
final Queue<Test> _testQueue = Queue<Test>();
final Map<String, Test> _runningTests = <String, Test>{};
/// Adds a test to the test suite.
void test(
String name,
dynamic Function() body, {
bool skip = false,
}) {
if (_runningTests.isNotEmpty) {
throw StateError(
'Test "$name" added after tests have started to run. '
'Calls to test() must be synchronous with main().',
);
}
if (skip) {
_logger.writeln('Test "$name": Skipped');
_primeQueue();
return;
}
_pushTest(name, body);
}
void _primeQueue() {
if (!_testQueuePrimed) {
// All tests() must be added synchronously with main, so we can enqueue an
// event to start all tests to run after main() is done.
Timer.run(_startAllTests);
_testQueuePrimed = true;
}
}
void _pushTest(
String name,
dynamic Function() body,
) {
final Test newTest = Test(name, body, logger: _logger);
_testQueue.add(newTest);
newTest.state = TestState.queued;
_primeQueue();
}
void _startAllTests() {
for (final Test t in _testQueue) {
_runningTests[t.name] = t;
t.run(onDone: () {
_runningTests.remove(t.name);
if (_runningTests.isEmpty) {
_lifecycle.onDone(_testQueue);
}
});
}
_lifecycle.onStart();
if (_testQueue.isEmpty) {
_logger.writeln('All tests skipped.');
_lifecycle.onDone(_testQueue);
}
}
}
/// Callbacks for the lifecycle of a [TestSuite].
abstract class Lifecycle {
/// Called after a test suite has started.
void onStart();
/// Called after the last test in a test suite has completed.
void onDone(Queue<Test> tests);
}
class _DefaultLifecycle implements Lifecycle {
final ReceivePort _suitePort = ReceivePort('Suite port');
late Queue<Test> _tests;
@override
void onStart() {
_suitePort.listen((dynamic msg) {
_suitePort.close();
_processResults();
});
}
@override
void onDone(Queue<Test> tests) {
_tests = tests;
_suitePort.sendPort.send(null);
}
void _processResults() {
bool testsSucceeded = true;
for (final Test t in _tests) {
testsSucceeded = testsSucceeded && (t.state == TestState.succeeded);
}
if (!testsSucceeded) {
throw 'A test failed';
}
}
}
| engine/testing/litetest/lib/src/test_suite.dart/0 | {
"file_path": "engine/testing/litetest/lib/src/test_suite.dart",
"repo_id": "engine",
"token_count": 1194
} | 429 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package dev.flutter.scenariosui;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.test.filters.LargeTest;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import dev.flutter.scenarios.PlatformViewsActivity;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class PlatformViewWithSurfaceViewHybridFallbackUiTest {
Intent intent;
@Rule @NonNull
public ActivityTestRule<PlatformViewsActivity> activityRule =
new ActivityTestRule<>(
PlatformViewsActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false);
private static String goldName(String suffix) {
return "PlatformViewWithSurfaceViewHybridFallbackUiTest_" + suffix;
}
@Before
public void setUp() {
intent = new Intent(Intent.ACTION_MAIN);
// Request TLHC with fallback to HC.
intent.putExtra("use_android_view", false);
intent.putExtra("expect_android_view_fallback", true);
// Use a SurfaceView to trigger fallback.
intent.putExtra("view_type", PlatformViewsActivity.SURFACE_VIEW_PV);
}
@Test
public void testPlatformView() throws Exception {
intent.putExtra("scenario_name", "platform_view");
ScreenshotUtil.capture(activityRule.launchActivity(intent), goldName("testPlatformView"));
}
}
| engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewHybridFallbackUiTest.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/PlatformViewWithSurfaceViewHybridFallbackUiTest.java",
"repo_id": "engine",
"token_count": 506
} | 430 |
// 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.scenarios;
import static io.flutter.Build.API_LEVELS;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Window;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import io.flutter.FlutterInjector;
import io.flutter.Log;
import io.flutter.embedding.engine.FlutterShellArgs;
import io.flutter.embedding.engine.loader.FlutterLoader;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryCodec;
import io.flutter.plugin.common.JSONMethodCodec;
import io.flutter.plugin.common.MethodChannel;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class TestActivity extends TestableFlutterActivity {
static final String TAG = "Scenarios";
private final Runnable resultsTask =
new Runnable() {
@Override
public void run() {
final Uri logFileUri = getIntent().getData();
writeTimelineData(logFileUri);
testFlutterLoaderCallbackWhenInitializedTwice();
}
};
private final Handler handler = new Handler();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hideSystemBars(getWindow());
final Intent launchIntent = getIntent();
if ("com.google.intent.action.TEST_LOOP".equals(launchIntent.getAction())) {
if (Build.VERSION.SDK_INT > API_LEVELS.API_22) {
requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
handler.postDelayed(resultsTask, 20000);
} else {
testFlutterLoaderCallbackWhenInitializedTwice();
}
}
@Override
protected void onDestroy() {
handler.removeCallbacks(resultsTask);
super.onDestroy();
}
@Override
@NonNull
public FlutterShellArgs getFlutterShellArgs() {
FlutterShellArgs args = FlutterShellArgs.fromIntent(getIntent());
args.add(FlutterShellArgs.ARG_TRACE_STARTUP);
args.add(FlutterShellArgs.ARG_ENABLE_DART_PROFILING);
args.add(FlutterShellArgs.ARG_VERBOSE_LOGGING);
return args;
}
@Override
public void onFlutterUiDisplayed() {
final Intent launchIntent = getIntent();
MethodChannel channel =
new MethodChannel(
Objects.requireNonNull(getFlutterEngine()).getDartExecutor(),
"driver",
JSONMethodCodec.INSTANCE);
Map<String, Object> test = new HashMap<>(2);
if (launchIntent.hasExtra("scenario_name")) {
test.put("name", launchIntent.getStringExtra("scenario_name"));
} else {
test.put("name", "animated_color_square");
}
test.put("use_android_view", launchIntent.getBooleanExtra("use_android_view", false));
test.put(
"expect_android_view_fallback",
launchIntent.getBooleanExtra("expect_android_view_fallback", false));
test.put("view_type", launchIntent.getStringExtra("view_type"));
getScenarioParams(test);
channel.invokeMethod("set_scenario", test);
}
/**
* Populates test-specific parameters that are sent to the Dart test scenario.
*
* @param args The map of test arguments
*/
protected void getScenarioParams(@NonNull Map<String, Object> args) {}
protected void writeTimelineData(@Nullable Uri logFile) {
if (logFile == null) {
throw new IllegalArgumentException();
}
if (getFlutterEngine() == null) {
Log.e(TAG, "Could not write timeline data - no engine.");
return;
}
final BasicMessageChannel<ByteBuffer> channel =
new BasicMessageChannel<>(
getFlutterEngine().getDartExecutor(), "write_timeline", BinaryCodec.INSTANCE);
channel.send(
null,
(ByteBuffer reply) -> {
AssetFileDescriptor afd = null;
try {
afd = getContentResolver().openAssetFileDescriptor(logFile, "w");
assert afd != null;
final FileDescriptor fd = afd.getFileDescriptor();
final FileOutputStream outputStream = new FileOutputStream(fd);
assert reply != null;
outputStream.write(reply.array());
outputStream.close();
} catch (IOException ex) {
Log.e(TAG, "Could not write timeline file", ex);
} finally {
try {
if (afd != null) {
afd.close();
}
} catch (IOException e) {
Log.w(TAG, "Could not close", e);
}
}
finish();
});
}
/**
* This method verifies that {@link
* io.flutter.embedding.engine.loader.FlutterLoader#ensureInitializationCompleteAsync(Context,
* String[], Handler, Runnable)} invokes its callback when called after initialization.
*/
protected void testFlutterLoaderCallbackWhenInitializedTwice() {
FlutterLoader flutterLoader = FlutterInjector.instance().flutterLoader();
// Flutter is probably already loaded in this app based on
// code that ran before this method. Nonetheless, invoke the
// blocking initialization here to ensure it's initialized.
flutterLoader.startInitialization(getApplicationContext());
flutterLoader.ensureInitializationComplete(getApplication(), new String[] {});
// Now that Flutter is loaded, invoke ensureInitializationCompleteAsync with
// a callback and verify that the callback is invoked.
Handler mainHandler = new Handler(Looper.getMainLooper());
final AtomicBoolean didInvokeCallback = new AtomicBoolean(false);
flutterLoader.ensureInitializationCompleteAsync(
getApplication(),
new String[] {},
mainHandler,
new Runnable() {
@Override
public void run() {
didInvokeCallback.set(true);
}
});
mainHandler.post(
new Runnable() {
@Override
public void run() {
if (!didInvokeCallback.get()) {
throw new RuntimeException(
"Failed test: FlutterLoader#ensureInitializationCompleteAsync() did not invoke its callback.");
}
}
});
}
private static void hideSystemBars(Window window) {
final WindowInsetsControllerCompat insetController =
WindowCompat.getInsetsController(window, window.getDecorView());
assert insetController != null;
insetController.setSystemBarsBehavior(
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
insetController.hide(WindowInsetsCompat.Type.systemBars());
}
}
| engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestActivity.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TestActivity.java",
"repo_id": "engine",
"token_count": 2700
} | 431 |
// 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 'package:meta/meta.dart';
/// An overridable collection of values provided by the environment.
@immutable
final class Environment {
/// Creates a new environment from the given values.
const Environment({
required this.isCi,
required this.showVerbose,
required this.logsDir,
});
/// Whether the current program is running on a CI environment.
///
/// Useful for determining if certain features should be enabled or disabled
/// based on the environment, or to add safety checks (for example, using
/// confusing or ambiguous flags).
final bool isCi;
/// Whether the user has requested verbose logging and program output.
final bool showVerbose;
/// What directory to store logs and screenshots in.
final String? logsDir;
@override
bool operator ==(Object o) {
return o is Environment &&
o.isCi == isCi &&
o.showVerbose == showVerbose &&
o.logsDir == logsDir;
}
@override
int get hashCode => Object.hash(isCi, showVerbose, logsDir);
@override
String toString() {
return 'Environment(isCi: $isCi, showVerbose: $showVerbose, logsDir: $logsDir)';
}
}
| engine/testing/scenario_app/bin/utils/environment.dart/0 | {
"file_path": "engine/testing/scenario_app/bin/utils/environment.dart",
"repo_id": "engine",
"token_count": 406
} | 432 |
// 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 "ScreenBeforeFlutter.h"
#import "FlutterEngine+ScenariosTest.h"
@implementation ScreenBeforeFlutter
@synthesize engine = _engine;
- (id)initWithEngineRunCompletion:(dispatch_block_t)engineRunCompletion {
self = [super init];
_engine = [[FlutterEngine alloc] initWithScenario:@"poppable_screen"
withCompletion:engineRunCompletion];
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.grayColor;
UIButton* showFlutterButton = [UIButton buttonWithType:UIButtonTypeSystem];
showFlutterButton.translatesAutoresizingMaskIntoConstraints = NO;
showFlutterButton.backgroundColor = UIColor.blueColor;
[showFlutterButton setTitle:@"Show Flutter" forState:UIControlStateNormal];
showFlutterButton.tintColor = UIColor.whiteColor;
showFlutterButton.clipsToBounds = YES;
[showFlutterButton addTarget:self
action:@selector(showFlutter:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:showFlutterButton];
[[showFlutterButton.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor] setActive:YES];
[[showFlutterButton.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor] setActive:YES];
[[showFlutterButton.heightAnchor constraintEqualToConstant:50] setActive:YES];
[[showFlutterButton.widthAnchor constraintEqualToConstant:150] setActive:YES];
[_engine runWithEntrypoint:nil];
}
- (FlutterViewController*)showFlutter:(dispatch_block_t)showCompletion {
FlutterViewController* flutterVC = [[FlutterViewController alloc] initWithEngine:_engine
nibName:nil
bundle:nil];
[self presentViewController:flutterVC animated:NO completion:showCompletion];
return flutterVC;
}
- (FlutterEngine*)engine {
return _engine;
}
@end
| engine/testing/scenario_app/ios/Scenarios/Scenarios/ScreenBeforeFlutter.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/ScreenBeforeFlutter.m",
"repo_id": "engine",
"token_count": 836
} | 433 |
// 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 "GoldenTestManager.h"
@interface DarwinSystemFontTests : XCTestCase
@end
@implementation DarwinSystemFontTests
- (void)testFontRendering {
self.continueAfterFailure = NO;
XCUIApplication* application = [[XCUIApplication alloc] init];
application.launchArguments = @[ @"--darwin-system-font" ];
[application launch];
XCUIElement* addTextField = application.textFields[@"ready"];
XCTAssertTrue([addTextField waitForExistenceWithTimeout:30]);
GoldenTestManager* manager =
[[GoldenTestManager alloc] initWithLaunchArg:@"--darwin-system-font"];
[manager checkGoldenForTest:self rmesThreshold:kDefaultRmseThreshold];
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/DarwinSystemFontTests.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/DarwinSystemFontTests.m",
"repo_id": "engine",
"token_count": 282
} | 434 |
// 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 <XCTest/XCTest.h>
static const CGFloat kCompareAccuracy = 0.001;
@interface UnobstructedPlatformViewTests : XCTestCase
@end
@implementation UnobstructedPlatformViewTests
- (void)setUp {
self.continueAfterFailure = NO;
}
// A is the layer, which z index is higher than the platform view.
// +--------+
// | PV | +---+
// +--------+ | A |
// +---+
- (void)testNoOverlay {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-no-overlay-intersection" ];
[app launch];
XCUIElement* platform_view = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view.frame.origin.x, 0);
XCTAssertEqual(platform_view.frame.origin.y, 0);
XCTAssertEqual(platform_view.frame.size.width, 250);
XCTAssertEqual(platform_view.frame.size.height, 250);
XCUIElement* overlay = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertFalse(overlay.exists);
}
// A is the layer above the platform view.
// +-----------------+
// | PV +---+ |
// | | A | |
// | +---+ |
// +-----------------+
- (void)testOneOverlay {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view" ];
[app launch];
XCUIElement* platform_view = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view.frame.origin.x, 0);
XCTAssertEqual(platform_view.frame.origin.y, 0);
XCTAssertEqual(platform_view.frame.size.width, 250);
XCTAssertEqual(platform_view.frame.size.height, 250);
XCUIElement* overlay = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertTrue(overlay.exists);
XCTAssertEqual(overlay.frame.origin.x, 150);
XCTAssertEqual(overlay.frame.origin.y, 150);
XCTAssertEqual(overlay.frame.size.width, 50);
XCTAssertEqual(overlay.frame.size.height, 50);
XCUIElement* overlayView = app.otherElements[@"platform_view[0].overlay_view[0]"];
XCTAssertTrue(overlayView.exists);
// Overlay should always be the same frame as the app.
XCTAssertEqualWithAccuracy(overlayView.frame.origin.x, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView.frame.origin.y, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView.frame.size.width, app.frame.size.width, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView.frame.size.height, app.frame.size.height,
kCompareAccuracy);
}
// A is the layer above the platform view.
// +-----------------+
// | PV +---+ |
// +-----------| A |-+
// +---+
- (void)testOneOverlayPartialIntersection {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-partial-intersection" ];
[app launch];
XCUIElement* platform_view = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view.frame.origin.x, 0);
XCTAssertEqual(platform_view.frame.origin.y, 0);
XCTAssertEqual(platform_view.frame.size.width, 250);
XCTAssertEqual(platform_view.frame.size.height, 250);
XCUIElement* overlay = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertTrue(overlay.exists);
XCTAssertEqual(overlay.frame.origin.x, 200);
XCTAssertEqual(overlay.frame.origin.y, 245);
XCTAssertEqual(overlay.frame.size.width, 50);
// Half the height of the overlay.
XCTAssertEqual(overlay.frame.size.height, 5);
XCUIElement* overlayView = app.otherElements[@"platform_view[0].overlay_view[0]"];
XCTAssertTrue(overlayView.exists);
// Overlay should always be the same frame as the app.
XCTAssertEqualWithAccuracy(overlayView.frame.origin.x, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView.frame.origin.y, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView.frame.size.width, app.frame.size.width, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView.frame.size.height, app.frame.size.height,
kCompareAccuracy);
}
// A and B are the layers above the platform view.
// +--------------------+
// | PV +------------+ |
// | | B +-----+ | |
// | +---| A |-+ |
// +----------| |---+
// +-----+
- (void)testTwoIntersectingOverlays {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-two-intersecting-overlays" ];
[app launch];
XCUIElement* platform_view = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view.frame.origin.x, 0);
XCTAssertEqual(platform_view.frame.origin.y, 0);
XCTAssertEqual(platform_view.frame.size.width, 250);
XCTAssertEqual(platform_view.frame.size.height, 250);
XCUIElement* overlay = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertTrue(overlay.exists);
XCTAssertEqual(overlay.frame.origin.x, 150);
XCTAssertEqual(overlay.frame.origin.y, 150);
XCTAssertEqual(overlay.frame.size.width, 75);
XCTAssertEqual(overlay.frame.size.height, 75);
XCTAssertFalse(app.otherElements[@"platform_view[0].overlay[1]"].exists);
}
// A, B, and C are the layers above the platform view.
// +-------------------------+
// | PV +-----------+ |
// | +---+ | B +-----+ | |
// | | C | +---| A |-+ |
// | +---+ +-----+ |
// +-------------------------+
- (void)testOneOverlayAndTwoIntersectingOverlays {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-one-overlay-two-intersecting-overlays" ];
[app launch];
XCUIElement* platform_view = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view.frame.origin.x, 0);
XCTAssertEqual(platform_view.frame.origin.y, 0);
XCTAssertEqual(platform_view.frame.size.width, 250);
XCTAssertEqual(platform_view.frame.size.height, 250);
XCUIElement* overlay1 = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertTrue(overlay1.exists);
XCTAssertEqual(overlay1.frame.origin.x, 75);
XCTAssertEqual(overlay1.frame.origin.y, 150);
XCTAssertEqual(overlay1.frame.size.width, 150);
XCTAssertEqual(overlay1.frame.size.height, 100);
// There are three non overlapping rects above platform view, which
// FlutterPlatformViewsController merges into one.
XCTAssertFalse(app.otherElements[@"platform_view[0].overlay[1]"].exists);
XCUIElement* overlayView0 = app.otherElements[@"platform_view[0].overlay_view[0]"];
XCTAssertTrue(overlayView0.exists);
// Overlay should always be the same frame as the app.
XCTAssertEqualWithAccuracy(overlayView0.frame.origin.x, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.origin.y, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.size.width, app.frame.size.width, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.size.height, app.frame.size.height,
kCompareAccuracy);
}
// A is the layer, which z index is higher than the platform view.
// +--------+
// | PV | +---+
// +--------+ | A |
// +--------+ +---+
// | PV |
// +--------+
- (void)testMultiplePlatformViewsWithoutOverlays {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-multiple-without-overlays" ];
[app launch];
XCUIElement* platform_view1 = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view1 waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view1.frame.origin.x, 0);
XCTAssertEqual(platform_view1.frame.origin.y, 300);
XCTAssertEqual(platform_view1.frame.size.width, 250);
XCTAssertEqual(platform_view1.frame.size.height, 250);
XCUIElement* platform_view2 = app.otherElements[@"platform_view[1]"];
XCTAssertTrue(platform_view2.exists);
XCTAssertEqual(platform_view2.frame.origin.x, 0);
XCTAssertEqual(platform_view2.frame.origin.y, 0);
XCTAssertEqual(platform_view2.frame.size.width, 250);
XCTAssertEqual(platform_view2.frame.size.height, 250);
XCTAssertFalse(app.otherElements[@"platform_view[0].overlay[0]"].exists);
XCTAssertFalse(app.otherElements[@"platform_view[1].overlay[0]"].exists);
XCTAssertFalse(app.otherElements[@"platform_view[0].overlay_view[0]"].exists);
XCTAssertFalse(app.otherElements[@"platform_view[1].overlay_view[0]"].exists);
}
// A is the layer above both platform view.
// +------------+
// | PV +----+ |
// +-----| A |-+
// +-----| |-+
// | PV +----+ |
// +------------+
- (void)testMultiplePlatformViewsWithOverlays {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-multiple-background-foreground" ];
[app launch];
XCUIElement* platform_view1 = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view1 waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view1.frame.origin.x, 25);
XCTAssertEqual(platform_view1.frame.origin.y, 300);
XCTAssertEqual(platform_view1.frame.size.width, 250);
XCTAssertEqual(platform_view1.frame.size.height, 250);
XCUIElement* platform_view2 = app.otherElements[@"platform_view[1]"];
XCTAssertTrue(platform_view2.exists);
XCTAssertEqual(platform_view2.frame.origin.x, 25);
XCTAssertEqual(platform_view2.frame.origin.y, 0);
XCTAssertEqual(platform_view2.frame.size.width, 250);
XCTAssertEqual(platform_view2.frame.size.height, 250);
XCUIElement* overlay1 = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertTrue(overlay1.exists);
XCTAssertEqual(overlay1.frame.origin.x, 25);
XCTAssertEqual(overlay1.frame.origin.y, 300);
XCTAssertEqual(overlay1.frame.size.width, 225);
XCTAssertEqual(overlay1.frame.size.height, 200);
XCUIElement* overlay2 = app.otherElements[@"platform_view[1].overlay[0]"];
XCTAssertTrue(overlay2.exists);
XCTAssertEqual(overlay2.frame.origin.x, 25);
XCTAssertEqual(overlay2.frame.origin.y, 0);
XCTAssertEqual(overlay2.frame.size.width, 225);
XCTAssertEqual(overlay2.frame.size.height, 250);
XCUIElement* overlayView0 = app.otherElements[@"platform_view[0].overlay_view[0]"];
XCTAssertTrue(overlayView0.exists);
// Overlay should always be the same frame as the app.
XCTAssertEqualWithAccuracy(overlayView0.frame.origin.x, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.origin.y, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.size.width, app.frame.size.width, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.size.height, app.frame.size.height,
kCompareAccuracy);
XCUIElement* overlayView1 = app.otherElements[@"platform_view[1].overlay_view[0]"];
XCTAssertTrue(overlayView1.exists);
// Overlay should always be the same frame as the app.
XCTAssertEqualWithAccuracy(overlayView1.frame.origin.x, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView1.frame.origin.y, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView1.frame.size.width, app.frame.size.width, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView1.frame.size.height, app.frame.size.height,
kCompareAccuracy);
}
// More then two overlays are merged into a single layer.
// +---------------------+
// | +---+ +---+ +---+ |
// | | A | | B | | C | |
// | +---+ +---+ +---+ |
// | +-------+ |
// +-| D |-----------+
// +-------+
- (void)testPlatformViewsMaxOverlays {
XCUIApplication* app = [[XCUIApplication alloc] init];
app.launchArguments = @[ @"--platform-view-max-overlays" ];
[app launch];
XCUIElement* platform_view = app.otherElements[@"platform_view[0]"];
XCTAssertTrue([platform_view waitForExistenceWithTimeout:1.0]);
XCTAssertEqual(platform_view.frame.origin.x, 0);
XCTAssertEqual(platform_view.frame.origin.y, 0);
XCTAssertEqual(platform_view.frame.size.width, 250);
XCTAssertEqual(platform_view.frame.size.height, 250);
XCUIElement* overlay = app.otherElements[@"platform_view[0].overlay[0]"];
XCTAssertTrue(overlay.exists);
XCTAssertFalse(app.otherElements[@"platform_view[0].overlay[1]"].exists);
XCTAssertTrue(CGRectContainsRect(platform_view.frame, overlay.frame));
XCUIElement* overlayView0 = app.otherElements[@"platform_view[0].overlay_view[0]"];
XCTAssertTrue(overlayView0.exists);
// Overlay should always be the same frame as the app.
XCTAssertEqualWithAccuracy(overlayView0.frame.origin.x, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.origin.y, app.frame.origin.x, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.size.width, app.frame.size.width, kCompareAccuracy);
XCTAssertEqualWithAccuracy(overlayView0.frame.size.height, app.frame.size.height,
kCompareAccuracy);
XCUIElement* overlayView1 = app.otherElements[@"platform_view[0].overlay_view[1]"];
XCTAssertFalse(overlayView1.exists);
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/UnobstructedPlatformViewTests.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/UnobstructedPlatformViewTests.m",
"repo_id": "engine",
"token_count": 5194
} | 435 |
// 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 'channel_util.dart';
import 'scenario.dart';
/// Tries to draw some text in a bogus font. Should end up drawing in the
/// system default font.
class BogusFontText extends Scenario {
/// Creates the BogusFontText scenario.
BogusFontText(super.view);
// Semi-arbitrary.
final double _screenWidth = 700;
@override
void onBeginFrame(Duration duration) {
final SceneBuilder builder = SceneBuilder();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
final ParagraphBuilder paragraphBuilder =
ParagraphBuilder(ParagraphStyle(fontFamily: "some font that doesn't exist"))
..pushStyle(TextStyle(fontSize: 80))
..addText('One more thing...')
..pop();
final Paragraph paragraph = paragraphBuilder.build();
paragraph.layout(ParagraphConstraints(width: _screenWidth));
canvas.drawParagraph(paragraph, const Offset(50, 80));
final Picture picture = recorder.endRecording();
builder.addPicture(
Offset.zero,
picture,
willChangeHint: true,
);
final Scene scene = builder.build();
view.render(scene);
scene.dispose();
sendJsonMessage(
dispatcher: view.platformDispatcher,
channel: 'display_data',
json: <String, dynamic>{
'data': 'ready',
},
);
}
}
| engine/testing/scenario_app/lib/src/bogus_font_text.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/bogus_font_text.dart",
"repo_id": "engine",
"token_count": 524
} | 436 |
import 'package:litetest/litetest.dart';
import '../bin/utils/adb_logcat_filtering.dart';
import 'src/fake_adb_logcat.dart';
void main() {
/// Simulates the filtering of logcat output [lines].
Iterable<String> filter(Iterable<String> lines, {int? filterProcessId}) {
if (lines.isEmpty) {
throw StateError('No log lines to filter. This is unexpected.');
}
return lines.where((String line) {
final AdbLogLine? logLine = AdbLogLine.tryParse(line);
if (logLine == null) {
throw StateError('Invalid log line: $line');
}
final bool isVerbose = logLine.isVerbose(filterProcessId: filterProcessId?.toString());
return !isVerbose;
});
}
test('should always retain fatal logs', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
process.fatal('Something', 'A bad thing happened');
final Iterable<String> filtered = filter(logcat.drain());
expect(filtered, hasLength(1));
expect(filtered.first, contains('Something: A bad thing happened'));
});
test('should never retain debug logs', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
final String tag = AdbLogLine.knownNoiseTags.first;
process.debug(tag, 'A debug message');
final Iterable<String> filtered = filter(logcat.drain());
expect(filtered, isEmpty);
});
test('should never retain logs from known "noise" tags', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
final String tag = AdbLogLine.knownNoiseTags.first;
process.info(tag, 'Flutter flutter flutter');
final Iterable<String> filtered = filter(logcat.drain());
expect(filtered, isEmpty);
});
test('should always retain logs from known "useful" tags', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
final String tag = AdbLogLine.knownUsefulTags.first;
process.info(tag, 'A useful message');
final Iterable<String> filtered = filter(logcat.drain());
expect(filtered, hasLength(1));
expect(filtered.first, contains('$tag: A useful message'));
});
test('if a process ID is passed, retain the log', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
process.info('SomeTag', 'A message');
final Iterable<String> filtered = filter(logcat.drain(), filterProcessId: process.processId);
expect(filtered, hasLength(1));
expect(filtered.first, contains('SomeTag: A message'));
});
test('even if a process ID passed, retain logs containing "flutter"', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
process.info('SomeTag', 'A message with flutter');
final Iterable<String> filtered = filter(logcat.drain(), filterProcessId: process.processId);
expect(filtered, hasLength(1));
expect(filtered.first, contains('SomeTag: A message with flutter'));
});
test('should retain E-level flags from known "useful" error tags', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
final String tag = AdbLogLine.knownUsefulErrorTags.first;
process.error(tag, 'An error message');
process.info(tag, 'An info message');
final Iterable<String> filtered = filter(logcat.drain());
expect(filtered, hasLength(1));
expect(filtered.first, contains('$tag: An error message'));
});
test('should filter out error logs from unimportant processes', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess process = logcat.process();
// I hate this one.
const String tag = 'gs.intelligence';
process.error(tag, 'No package ID ff found for resource ID 0xffffffff.');
final Iterable<String> filtered = filter(logcat.drain());
expect(filtered, isEmpty);
});
test('should filter the flutter-launched process, not just any process', () {
final FakeAdbLogcat logcat = FakeAdbLogcat();
final FakeAdbProcess device = logcat.process();
final FakeAdbProcess unrelated = logcat.process();
final FakeAdbProcess flutter = logcat.process();
device.info(AdbLogLine.activityManagerTag, 'Start proc ${unrelated.processId}:com.example.unrelated');
List<String> rawLines = logcat.drain();
expect(rawLines, hasLength(1));
AdbLogLine parsedLogLine = AdbLogLine.tryParse(rawLines.single)!;
expect(parsedLogLine.tryParseProcess(), isNull);
device.info(AdbLogLine.activityManagerTag, 'Start proc ${flutter.processId}:${AdbLogLine.flutterProcessName}');
rawLines = logcat.drain();
expect(rawLines, hasLength(1));
parsedLogLine = AdbLogLine.tryParse(rawLines.single)!;
expect(parsedLogLine.tryParseProcess(), '${flutter.processId}');
});
}
| engine/testing/scenario_app/test/adb_log_filter_test.dart/0 | {
"file_path": "engine/testing/scenario_app/test/adb_log_filter_test.dart",
"repo_id": "engine",
"token_count": 1681
} | 437 |
// 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_METAL_SURFACE_H_
#define FLUTTER_TESTING_TEST_METAL_SURFACE_H_
#include "flutter/fml/macros.h"
#include "flutter/testing/test_metal_context.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief Creates a MTLTexture backed SkSurface and context that can be
/// used to render to in unit-tests.
///
class TestMetalSurface {
public:
static bool PlatformSupportsMetal();
static std::unique_ptr<TestMetalSurface> Create(
const TestMetalContext& test_metal_context,
SkISize surface_size = SkISize::MakeEmpty());
static std::unique_ptr<TestMetalSurface> Create(
const TestMetalContext& test_metal_context,
int64_t texture_id,
SkISize surface_size = SkISize::MakeEmpty());
virtual ~TestMetalSurface();
virtual bool IsValid() const;
virtual sk_sp<GrDirectContext> GetGrContext() const;
virtual sk_sp<SkSurface> GetSurface() const;
virtual sk_sp<SkImage> GetRasterSurfaceSnapshot();
virtual TestMetalContext::TextureInfo GetTextureInfo();
protected:
TestMetalSurface();
private:
std::unique_ptr<TestMetalSurface> impl_;
explicit TestMetalSurface(std::unique_ptr<TestMetalSurface> impl);
FML_DISALLOW_COPY_AND_ASSIGN(TestMetalSurface);
};
} // namespace flutter
#endif // FLUTTER_TESTING_TEST_METAL_SURFACE_H_
| engine/testing/test_metal_surface.h/0 | {
"file_path": "engine/testing/test_metal_surface.h",
"repo_id": "engine",
"token_count": 576
} | 438 |
// 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_THREAD_TEST_H_
#define FLUTTER_TESTING_THREAD_TEST_H_
#include <memory>
#include <string>
#include "flutter/fml/macros.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/task_runner.h"
#include "flutter/fml/thread.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
//------------------------------------------------------------------------------
/// @brief A fixture that creates threads with running message loops that
/// are terminated when the test is done (the threads are joined
/// then as well). While this fixture may be used on it's own, it is
/// often sub-classed by other fixtures whose functioning requires
/// threads to be created as necessary.
///
class ThreadTest : public ::testing::Test {
public:
ThreadTest();
//----------------------------------------------------------------------------
/// @brief Get the task runner for the thread that the current unit-test
/// is running on. This creates a message loop as necessary.
///
/// @attention Unlike all other threads and task runners, this task runner is
/// shared by all tests running in the process. Tests must ensure
/// that all tasks posted to this task runner are executed before
/// the test ends to prevent the task from one test being executed
/// while another test is running. When in doubt, just create a
/// bespoke thread and task running. These cannot be seen by other
/// tests in the process.
///
/// @see `GetThreadTaskRunner`, `CreateNewThread`.
///
/// @return The task runner for the thread the test is running on.
///
fml::RefPtr<fml::TaskRunner> GetCurrentTaskRunner();
//----------------------------------------------------------------------------
/// @brief Creates a new thread, initializes a message loop on it, and,
/// returns its task runner to the unit-test. The message loop is
/// terminated (and its thread joined) when the test ends. This
/// allows tests to create multiple named threads as necessary.
///
/// @param[in] name The name of the OS thread created.
///
/// @return The task runner for the newly created thread.
///
fml::RefPtr<fml::TaskRunner> CreateNewThread(const std::string& name = "");
private:
fml::RefPtr<fml::TaskRunner> current_task_runner_;
std::vector<std::unique_ptr<fml::Thread>> extra_threads_;
FML_DISALLOW_COPY_AND_ASSIGN(ThreadTest);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_THREAD_TEST_H_
| engine/testing/thread_test.h/0 | {
"file_path": "engine/testing/thread_test.h",
"repo_id": "engine",
"token_count": 920
} | 439 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_ACTION_HANDLER_BASE_H_
#define UI_ACCESSIBILITY_AX_ACTION_HANDLER_BASE_H_
#include "ax_export.h"
#include "ax_tree_id.h"
namespace ui {
struct AXActionData;
// Classes that host an accessibility tree in the browser process that also wish
// to become visible to accessibility clients (e.g. for relaying targets to
// source accessibility trees), can subclass this class. However, unless you
// need to have more control over how |tree_id_| is set, most classes will want
// to inherit from AXActionHandler instead, which manages it automatically.
//
// Subclasses can use |tree_id| when annotating their |AXNodeData| for clients
// to respond with the appropriate target node id.
class AX_EXPORT AXActionHandlerBase {
public:
virtual ~AXActionHandlerBase();
// Handle an action from an accessibility client.
virtual void PerformAction(const AXActionData& data) = 0;
// Returns whether this handler expects points in pixels (true) or dips
// (false) for data passed to |PerformAction|.
virtual bool RequiresPerformActionPointInPixels() const;
// A tree id appropriate for annotating events sent to an accessibility
// client.
const AXTreeID& ax_tree_id() const { return tree_id_; }
protected:
// Initializes the AXActionHandlerBase subclass with ui::AXTreeIDUnknown().
AXActionHandlerBase();
// Initializes the AXActionHandlerBase subclass with |ax_tree_id|. It is Ok to
// pass ui::AXTreeIDUnknown() and then call SetAXTreeID() at a later point.
explicit AXActionHandlerBase(const AXTreeID& ax_tree_id);
// Change the AXTreeID.
void SetAXTreeID(AXTreeID new_ax_tree_id);
private:
// Register or unregister this class with |AXTreeIDRegistry|.
void UpdateActiveState(bool active);
// Manually set in this base class, but automatically set by instances of the
// subclass AXActionHandler, which most classes inherit from.
AXTreeID tree_id_;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_ACTION_HANDLER_BASE_H_
| engine/third_party/accessibility/ax/ax_action_handler_base.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_action_handler_base.h",
"repo_id": "engine",
"token_count": 633
} | 440 |
// 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.
#ifndef UI_ACCESSIBILITY_AX_EXPORT_H_
#define UI_ACCESSIBILITY_AX_EXPORT_H_
// Defines AX_EXPORT so that functionality implemented by the
// ui/accessibility module can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(AX_IMPLEMENTATION)
#define AX_EXPORT __declspec(dllexport)
#else
#define AX_EXPORT __declspec(dllimport)
#endif // defined(ACCESSIBILITY_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(AX_IMPLEMENTATION)
#define AX_EXPORT __attribute__((visibility("default")))
#else
#define AX_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define AX_EXPORT
#endif
#endif // UI_ACCESSIBILITY_AX_EXPORT_H_
| engine/third_party/accessibility/ax/ax_export.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_export.h",
"repo_id": "engine",
"token_count": 293
} | 441 |
// 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_RANGE_H_
#define UI_ACCESSIBILITY_AX_RANGE_H_
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <vector>
#include "ax_clipping_behavior.h"
#include "ax_enums.h"
#include "ax_offscreen_result.h"
#include "ax_role_properties.h"
#include "ax_tree_manager_map.h"
#include "base/string_utils.h"
namespace ui {
// Specifies how AXRange::GetText treats line breaks introduced by layout.
// For example, consider the following HTML snippet: "A<div>B</div>C".
enum class AXTextConcatenationBehavior {
// Preserve any introduced line breaks, e.g. GetText = "A\nB\nC".
kAsInnerText,
// Ignore any introduced line breaks, e.g. GetText = "ABC".
kAsTextContent
};
class AXRangeRectDelegate {
public:
virtual gfx::Rect GetInnerTextRangeBoundsRect(
AXTreeID tree_id,
AXNode::AXID node_id,
int start_offset,
int end_offset,
ui::AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) = 0;
virtual gfx::Rect GetBoundsRect(AXTreeID tree_id,
AXNode::AXID node_id,
AXOffscreenResult* offscreen_result) = 0;
};
// A range delimited by two positions in the AXTree.
//
// In order to avoid any confusion regarding whether a deep or a shallow copy is
// being performed, this class can be moved, but not copied.
template <class AXPositionType>
class AXRange {
public:
using AXPositionInstance = std::unique_ptr<AXPositionType>;
AXRange()
: anchor_(AXPositionType::CreateNullPosition()),
focus_(AXPositionType::CreateNullPosition()) {}
AXRange(AXPositionInstance anchor, AXPositionInstance focus) {
anchor_ = anchor ? std::move(anchor) : AXPositionType::CreateNullPosition();
focus_ = focus ? std::move(focus) : AXPositionType::CreateNullPosition();
}
AXRange(const AXRange& other) = delete;
AXRange(AXRange&& other) : AXRange() {
anchor_.swap(other.anchor_);
focus_.swap(other.focus_);
}
virtual ~AXRange() = default;
AXPositionType* anchor() const {
BASE_DCHECK(anchor_);
return anchor_.get();
}
AXPositionType* focus() const {
BASE_DCHECK(focus_);
return focus_.get();
}
AXRange& operator=(const AXRange& other) = delete;
AXRange& operator=(AXRange&& other) {
if (this != &other) {
anchor_ = AXPositionType::CreateNullPosition();
focus_ = AXPositionType::CreateNullPosition();
anchor_.swap(other.anchor_);
focus_.swap(other.focus_);
}
return *this;
}
bool operator==(const AXRange& other) const {
if (IsNull())
return other.IsNull();
return !other.IsNull() && *anchor_ == *other.anchor() &&
*focus_ == *other.focus();
}
bool operator!=(const AXRange& other) const { return !(*this == other); }
// Given a pair of AXPosition, determines how the first compares with the
// second, relative to the order they would be iterated over by using
// AXRange::Iterator to traverse all leaf text ranges in a tree.
//
// Notice that this method is different from using AXPosition::CompareTo since
// the following logic takes into account BOTH tree pre-order traversal and
// text offsets when both positions are located within the same anchor.
//
// Returns:
// 0 - If both positions are equivalent.
// <0 - If the first position would come BEFORE the second.
// >0 - If the first position would come AFTER the second.
// nullopt - If positions are not comparable (see AXPosition::CompareTo).
static std::optional<int> CompareEndpoints(const AXPositionType* first,
const AXPositionType* second) {
std::optional<int> tree_position_comparison =
first->AsTreePosition()->CompareTo(*second->AsTreePosition());
// When the tree comparison is nullopt, using value_or(1) forces a default
// value of 1, making the following statement return nullopt as well.
return (tree_position_comparison.value_or(1) != 0)
? tree_position_comparison
: first->CompareTo(*second);
}
AXRange AsForwardRange() const {
return (CompareEndpoints(anchor(), focus()).value_or(0) > 0)
? AXRange(focus_->Clone(), anchor_->Clone())
: AXRange(anchor_->Clone(), focus_->Clone());
}
AXRange AsBackwardRange() const {
return (CompareEndpoints(anchor(), focus()).value_or(0) < 0)
? AXRange(focus_->Clone(), anchor_->Clone())
: AXRange(anchor_->Clone(), focus_->Clone());
}
bool IsCollapsed() const { return !IsNull() && *anchor_ == *focus_; }
// We define a "leaf text range" as an AXRange whose endpoints are leaf text
// positions located within the same anchor of the AXTree.
bool IsLeafTextRange() const {
return !IsNull() && anchor_->GetAnchor() == focus_->GetAnchor() &&
anchor_->IsLeafTextPosition() && focus_->IsLeafTextPosition();
}
bool IsNull() const {
BASE_DCHECK(anchor_ && focus_);
return anchor_->IsNullPosition() || focus_->IsNullPosition();
}
std::string ToString() const {
return "Range\nAnchor:" + anchor_->ToString() +
"\nFocus:" + focus_->ToString();
}
// We can decompose any given AXRange into multiple "leaf text ranges".
// As an example, consider the following HTML code:
//
// <p>line with text<br><input type="checkbox">line with checkbox</p>
//
// It will produce the following AXTree; notice that the leaf text nodes
// (enclosed in parenthesis) compose its text representation:
//
// paragraph
// staticText name='line with text'
// (inlineTextBox name='line with text')
// lineBreak name='<newline>'
// (inlineTextBox name='<newline>')
// (checkBox)
// staticText name='line with checkbox'
// (inlineTextBox name='line with checkbox')
//
// Suppose we have an AXRange containing all elements from the example above.
// The text representation of such range, with AXRange's endpoints marked by
// opening and closing brackets, will look like the following:
//
// "[line with text\n{checkBox}line with checkbox]"
//
// Note that in the text representation {checkBox} is not visible, but it is
// effectively a "leaf text range", so we include it in the example above only
// to visualize how the iterator should work.
//
// Decomposing the AXRange above into its "leaf text ranges" would result in:
//
// "[line with text][\n][{checkBox}][line with checkbox]"
//
// This class allows AXRange to be iterated through all "leaf text ranges"
// contained between its endpoints, composing the entire range.
class Iterator : public std::iterator<std::input_iterator_tag, AXRange> {
public:
Iterator()
: current_start_(AXPositionType::CreateNullPosition()),
iterator_end_(AXPositionType::CreateNullPosition()) {}
Iterator(AXPositionInstance start, AXPositionInstance end) {
if (end && !end->IsNullPosition()) {
current_start_ = !start ? AXPositionType::CreateNullPosition()
: start->AsLeafTextPosition();
iterator_end_ = end->AsLeafTextPosition();
} else {
current_start_ = AXPositionType::CreateNullPosition();
iterator_end_ = AXPositionType::CreateNullPosition();
}
}
Iterator(const Iterator& other) = delete;
Iterator(Iterator&& other)
: current_start_(std::move(other.current_start_)),
iterator_end_(std::move(other.iterator_end_)) {}
~Iterator() = default;
bool operator==(const Iterator& other) const {
return current_start_->GetAnchor() == other.current_start_->GetAnchor() &&
iterator_end_->GetAnchor() == other.iterator_end_->GetAnchor() &&
*current_start_ == *other.current_start_ &&
*iterator_end_ == *other.iterator_end_;
}
bool operator!=(const Iterator& other) const { return !(*this == other); }
// Only forward iteration is supported, so operator-- is not implemented.
Iterator& operator++() {
BASE_DCHECK(!current_start_->IsNullPosition());
if (current_start_->GetAnchor() == iterator_end_->GetAnchor()) {
current_start_ = AXPositionType::CreateNullPosition();
} else {
current_start_ = current_start_->CreateNextLeafTreePosition();
BASE_DCHECK(*current_start_ <= *iterator_end_);
}
return *this;
}
AXRange operator*() const {
BASE_DCHECK(!current_start_->IsNullPosition());
AXPositionInstance current_end =
(current_start_->GetAnchor() != iterator_end_->GetAnchor())
? current_start_->CreatePositionAtEndOfAnchor()
: iterator_end_->Clone();
BASE_DCHECK(*current_end <= *iterator_end_);
AXRange current_leaf_text_range(current_start_->AsTextPosition(),
current_end->AsTextPosition());
BASE_DCHECK(current_leaf_text_range.IsLeafTextRange());
return std::move(current_leaf_text_range);
}
private:
AXPositionInstance current_start_;
AXPositionInstance iterator_end_;
};
Iterator begin() const {
if (IsNull())
return Iterator(nullptr, nullptr);
AXRange forward_range = AsForwardRange();
return Iterator(std::move(forward_range.anchor_),
std::move(forward_range.focus_));
}
Iterator end() const {
if (IsNull())
return Iterator(nullptr, nullptr);
AXRange forward_range = AsForwardRange();
return Iterator(nullptr, std::move(forward_range.focus_));
}
// Returns the concatenation of the accessible names of all text nodes
// contained between this AXRange's endpoints.
// Pass a |max_count| of -1 to retrieve all text in the AXRange.
// Note that if this AXRange has its anchor or focus located at an ignored
// position, we shrink the range to the closest unignored positions.
std::u16string GetText(AXTextConcatenationBehavior concatenation_behavior =
AXTextConcatenationBehavior::kAsTextContent,
int max_count = -1,
bool include_ignored = false,
size_t* appended_newlines_count = nullptr) const {
if (max_count == 0 || IsNull())
return std::u16string();
std::optional<int> endpoint_comparison =
CompareEndpoints(anchor(), focus());
if (!endpoint_comparison)
return std::u16string();
AXPositionInstance start = (endpoint_comparison.value() < 0)
? anchor_->AsLeafTextPosition()
: focus_->AsLeafTextPosition();
AXPositionInstance end = (endpoint_comparison.value() < 0)
? focus_->AsLeafTextPosition()
: anchor_->AsLeafTextPosition();
std::u16string range_text;
size_t computed_newlines_count = 0;
bool is_first_non_whitespace_leaf = true;
bool crossed_paragraph_boundary = false;
bool is_first_unignored_leaf = true;
bool found_trailing_newline = false;
while (!start->IsNullPosition()) {
BASE_DCHECK(start->IsLeafTextPosition());
BASE_DCHECK(start->text_offset() >= 0);
if (include_ignored || !start->IsIgnored()) {
if (concatenation_behavior ==
AXTextConcatenationBehavior::kAsInnerText &&
!start->IsInWhiteSpace()) {
if (is_first_non_whitespace_leaf) {
// The first non-whitespace leaf in the range could be preceded by
// whitespace spanning even before the start of this range, we need
// to check such positions in order to correctly determine if this
// is a paragraph's start (see |AXPosition::AtStartOfParagraph|).
crossed_paragraph_boundary =
!is_first_unignored_leaf && start->AtStartOfParagraph();
}
// When preserving layout line breaks, don't append `\n` next if the
// previous leaf position was a <br> (already ending with a newline).
if (crossed_paragraph_boundary && !found_trailing_newline) {
range_text += base::ASCIIToUTF16("\n");
computed_newlines_count++;
}
is_first_non_whitespace_leaf = false;
crossed_paragraph_boundary = false;
}
int current_end_offset = (start->GetAnchor() != end->GetAnchor())
? start->MaxTextOffset()
: end->text_offset();
if (current_end_offset > start->text_offset()) {
int characters_to_append =
(max_count > 0)
? std::min(max_count - static_cast<int>(range_text.length()),
current_end_offset - start->text_offset())
: current_end_offset - start->text_offset();
range_text += start->GetText().substr(start->text_offset(),
characters_to_append);
// Collapse all whitespace following any line break.
found_trailing_newline =
start->IsInLineBreak() ||
(found_trailing_newline && start->IsInWhiteSpace());
}
BASE_DCHECK(max_count < 0 ||
static_cast<int>(range_text.length()) <= max_count);
is_first_unignored_leaf = false;
}
if (start->GetAnchor() == end->GetAnchor() ||
static_cast<int>(range_text.length()) == max_count) {
break;
} else if (concatenation_behavior ==
AXTextConcatenationBehavior::kAsInnerText &&
!crossed_paragraph_boundary && !is_first_non_whitespace_leaf) {
start = start->CreateNextLeafTextPosition(&crossed_paragraph_boundary);
} else {
start = start->CreateNextLeafTextPosition();
}
}
if (appended_newlines_count)
*appended_newlines_count = computed_newlines_count;
return range_text;
}
// Appends rects of all anchor nodes that span between anchor_ and focus_.
// Rects outside of the viewport are skipped.
// Coordinate system is determined by the passed-in delegate.
std::vector<gfx::Rect> GetRects(AXRangeRectDelegate* delegate) const {
std::vector<gfx::Rect> rects;
for (const AXRange& leaf_text_range : *this) {
BASE_DCHECK(leaf_text_range.IsLeafTextRange());
AXPositionType* current_line_start = leaf_text_range.anchor();
AXPositionType* current_line_end = leaf_text_range.focus();
// For text anchors, we retrieve the bounding rectangles of its text
// content. For non-text anchors (such as checkboxes, images, etc.), we
// want to directly retrieve their bounding rectangles.
AXOffscreenResult offscreen_result;
gfx::Rect current_rect =
(current_line_start->IsInLineBreak() ||
current_line_start->IsInTextObject())
? delegate->GetInnerTextRangeBoundsRect(
current_line_start->tree_id(),
current_line_start->anchor_id(),
current_line_start->text_offset(),
current_line_end->text_offset(),
ui::AXClippingBehavior::kUnclipped, &offscreen_result)
: delegate->GetBoundsRect(current_line_start->tree_id(),
current_line_start->anchor_id(),
&offscreen_result);
// If the bounding box of the current range is clipped because it lies
// outside an ancestor’s bounds, then the bounding box is pushed to the
// nearest edge of such ancestor's bounds, with its width and height
// forced to be 1, and the node will be marked as "offscreen".
//
// Only add rectangles that are not empty and not marked as "offscreen".
//
// See the documentation for how bounding boxes are calculated in AXTree:
// https://chromium.googlesource.com/chromium/src/+/HEAD/docs/accessibility/offscreen.md
if (!current_rect.IsEmpty() &&
offscreen_result == AXOffscreenResult::kOnscreen)
rects.push_back(current_rect);
}
return rects;
}
private:
AXPositionInstance anchor_;
AXPositionInstance focus_;
};
template <class AXPositionType>
std::ostream& operator<<(std::ostream& stream,
const AXRange<AXPositionType>& range) {
return stream << range.ToString();
}
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_RANGE_H_
| engine/third_party/accessibility/ax/ax_range.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_range.h",
"repo_id": "engine",
"token_count": 6613
} | 442 |
// 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.
#include "ax_tree_id_registry.h"
#include "ax_action_handler_base.h"
#include "base/logging.h"
namespace ui {
// static
AXTreeIDRegistry& AXTreeIDRegistry::GetInstance() {
static AXTreeIDRegistry INSTANCE;
return INSTANCE;
}
void AXTreeIDRegistry::SetFrameIDForAXTreeID(const FrameID& frame_id,
const AXTreeID& ax_tree_id) {
auto it = frame_to_ax_tree_id_map_.find(frame_id);
if (it != frame_to_ax_tree_id_map_.end()) {
BASE_UNREACHABLE();
return;
}
frame_to_ax_tree_id_map_[frame_id] = ax_tree_id;
ax_tree_to_frame_id_map_[ax_tree_id] = frame_id;
}
AXTreeIDRegistry::FrameID AXTreeIDRegistry::GetFrameID(
const AXTreeID& ax_tree_id) {
auto it = ax_tree_to_frame_id_map_.find(ax_tree_id);
if (it != ax_tree_to_frame_id_map_.end())
return it->second;
return FrameID(-1, -1);
}
AXTreeID AXTreeIDRegistry::GetAXTreeID(AXTreeIDRegistry::FrameID frame_id) {
auto it = frame_to_ax_tree_id_map_.find(frame_id);
if (it != frame_to_ax_tree_id_map_.end())
return it->second;
return ui::AXTreeIDUnknown();
}
AXTreeID AXTreeIDRegistry::GetOrCreateAXTreeID(AXActionHandlerBase* handler) {
for (auto it : id_to_action_handler_) {
if (it.second == handler)
return it.first;
}
AXTreeID new_id = AXTreeID::CreateNewAXTreeID();
SetAXTreeID(new_id, handler);
return new_id;
}
AXActionHandlerBase* AXTreeIDRegistry::GetActionHandler(AXTreeID ax_tree_id) {
auto it = id_to_action_handler_.find(ax_tree_id);
if (it == id_to_action_handler_.end())
return nullptr;
return it->second;
}
void AXTreeIDRegistry::SetAXTreeID(const ui::AXTreeID& id,
AXActionHandlerBase* action_handler) {
BASE_DCHECK(id_to_action_handler_.find(id) == id_to_action_handler_.end());
id_to_action_handler_[id] = action_handler;
}
void AXTreeIDRegistry::RemoveAXTreeID(AXTreeID ax_tree_id) {
auto frame_it = ax_tree_to_frame_id_map_.find(ax_tree_id);
if (frame_it != ax_tree_to_frame_id_map_.end()) {
frame_to_ax_tree_id_map_.erase(frame_it->second);
ax_tree_to_frame_id_map_.erase(frame_it);
}
auto action_it = id_to_action_handler_.find(ax_tree_id);
if (action_it != id_to_action_handler_.end())
id_to_action_handler_.erase(action_it);
}
AXTreeIDRegistry::AXTreeIDRegistry() {}
AXTreeIDRegistry::~AXTreeIDRegistry() {}
} // namespace ui
| engine/third_party/accessibility/ax/ax_tree_id_registry.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_id_registry.cc",
"repo_id": "engine",
"token_count": 1096
} | 443 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_BASE_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_BASE_H_
#include <map>
#include <string>
#include <vector>
#include "ax/ax_enums.h"
#include "ax/ax_node.h"
#include "ax_build/build_config.h"
#include "ax_platform_node.h"
#include "ax_platform_node_delegate.h"
#include "base/macros.h"
#include "gfx/geometry/point.h"
#include "gfx/native_widget_types.h"
namespace ui {
struct AXNodeData;
struct AX_EXPORT AXHypertext {
AXHypertext();
~AXHypertext();
AXHypertext(const AXHypertext& other);
AXHypertext& operator=(const AXHypertext& other);
// A flag that should be set if the hypertext information in this struct is
// out-of-date and needs to be updated. This flag should always be set upon
// construction because constructing this struct doesn't compute the
// hypertext.
bool needs_update = true;
// Maps an embedded character offset in |hypertext| to an index in
// |hyperlinks|.
std::map<int32_t, int32_t> hyperlink_offset_to_index;
// The unique id of a AXPlatformNodes for each hyperlink.
// TODO(nektar): Replace object IDs with child indices if we decide that
// we are not implementing IA2 hyperlinks for anything other than IA2
// Hypertext.
std::vector<int32_t> hyperlinks;
std::u16string hypertext;
};
class AX_EXPORT AXPlatformNodeBase : public AXPlatformNode {
public:
AXPlatformNodeBase();
~AXPlatformNodeBase() override;
virtual void Init(AXPlatformNodeDelegate* delegate);
// These are simple wrappers to our delegate.
const AXNodeData& GetData() const;
gfx::NativeViewAccessible GetFocus();
gfx::NativeViewAccessible GetParent() const;
int GetChildCount() const;
gfx::NativeViewAccessible ChildAtIndex(int index) const;
std::string GetName() const;
std::u16string GetNameAsString16() const;
// This returns nullopt if there's no parent, it's unable to find the child in
// the list of its parent's children, or its parent doesn't have children.
virtual std::optional<int> GetIndexInParent();
// Returns a stack of ancestors of this node. The node at the top of the stack
// is the top most ancestor.
std::stack<gfx::NativeViewAccessible> GetAncestors();
// Returns an optional integer indicating the logical order of this node
// compared to another node or returns an empty optional if the nodes
// are not comparable.
// 0: if this position is logically equivalent to the other node
// <0: if this position is logically less than (before) the other node
// >0: if this position is logically greater than (after) the other node
std::optional<int> CompareTo(AXPlatformNodeBase& other);
// AXPlatformNode.
void Destroy() override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
void NotifyAccessibilityEvent(ax::mojom::Event event_type) override;
#if defined(OS_APPLE)
void AnnounceText(const std::u16string& text) override;
#endif
AXPlatformNodeDelegate* GetDelegate() const override;
bool IsDescendantOf(AXPlatformNode* ancestor) const override;
// Helpers.
AXPlatformNodeBase* GetPreviousSibling() const;
AXPlatformNodeBase* GetNextSibling() const;
AXPlatformNodeBase* GetFirstChild() const;
AXPlatformNodeBase* GetLastChild() const;
bool IsDescendant(AXPlatformNodeBase* descendant);
using AXPlatformNodeChildIterator =
ui::AXNode::ChildIteratorBase<AXPlatformNodeBase,
&AXPlatformNodeBase::GetNextSibling,
&AXPlatformNodeBase::GetPreviousSibling,
&AXPlatformNodeBase::GetFirstChild,
&AXPlatformNodeBase::GetLastChild>;
AXPlatformNodeChildIterator AXPlatformNodeChildrenBegin() const;
AXPlatformNodeChildIterator AXPlatformNodeChildrenEnd() const;
bool HasBoolAttribute(ax::mojom::BoolAttribute attr) const;
bool GetBoolAttribute(ax::mojom::BoolAttribute attr) const;
bool GetBoolAttribute(ax::mojom::BoolAttribute attr, bool* value) const;
bool HasFloatAttribute(ax::mojom::FloatAttribute attr) const;
float GetFloatAttribute(ax::mojom::FloatAttribute attr) const;
bool GetFloatAttribute(ax::mojom::FloatAttribute attr, float* value) const;
bool HasIntAttribute(ax::mojom::IntAttribute attribute) const;
int GetIntAttribute(ax::mojom::IntAttribute attribute) const;
bool GetIntAttribute(ax::mojom::IntAttribute attribute, int* value) const;
bool HasStringAttribute(ax::mojom::StringAttribute attribute) const;
const std::string& GetStringAttribute(
ax::mojom::StringAttribute attribute) const;
bool GetStringAttribute(ax::mojom::StringAttribute attribute,
std::string* value) const;
bool GetString16Attribute(ax::mojom::StringAttribute attribute,
std::u16string* value) const;
std::u16string GetString16Attribute(
ax::mojom::StringAttribute attribute) const;
bool HasInheritedStringAttribute(ax::mojom::StringAttribute attribute) const;
const std::string& GetInheritedStringAttribute(
ax::mojom::StringAttribute attribute) const;
std::u16string GetInheritedString16Attribute(
ax::mojom::StringAttribute attribute) const;
bool GetInheritedStringAttribute(ax::mojom::StringAttribute attribute,
std::string* value) const;
bool GetInheritedString16Attribute(ax::mojom::StringAttribute attribute,
std::u16string* value) const;
bool HasIntListAttribute(ax::mojom::IntListAttribute attribute) const;
const std::vector<int32_t>& GetIntListAttribute(
ax::mojom::IntListAttribute attribute) const;
bool GetIntListAttribute(ax::mojom::IntListAttribute attribute,
std::vector<int32_t>* value) const;
// Returns the selection container if inside one.
AXPlatformNodeBase* GetSelectionContainer() const;
// Returns the table or ARIA grid if inside one.
AXPlatformNodeBase* GetTable() const;
// If inside an HTML or ARIA table, returns the object containing the caption.
// Returns nullptr if not inside a table, or if there is no
// caption.
AXPlatformNodeBase* GetTableCaption() const;
// If inside a table or ARIA grid, returns the cell found at the given index.
// Indices are in row major order and each cell is counted once regardless of
// its span. Returns nullptr if the cell is not found or if not inside a
// table.
AXPlatformNodeBase* GetTableCell(int index) const;
// If inside a table or ARIA grid, returns the cell at the given row and
// column (0-based). Works correctly with cells that span multiple rows or
// columns. Returns nullptr if the cell is not found or if not inside a
// table.
AXPlatformNodeBase* GetTableCell(int row, int column) const;
// If inside a table or ARIA grid, returns the zero-based index of the cell.
// Indices are in row major order and each cell is counted once regardless of
// its span. Returns std::nullopt if not a cell or if not inside a table.
std::optional<int> GetTableCellIndex() const;
// If inside a table or ARIA grid, returns the physical column number for the
// current cell. In contrast to logical columns, physical columns always start
// from 0 and have no gaps in their numbering. Logical columns can be set
// using aria-colindex. Returns std::nullopt if not a cell or if not inside a
// table.
std::optional<int> GetTableColumn() const;
// If inside a table or ARIA grid, returns the number of physical columns.
// Returns std::nullopt if not inside a table.
std::optional<int> GetTableColumnCount() const;
// If inside a table or ARIA grid, returns the number of ARIA columns.
// Returns std::nullopt if not inside a table.
std::optional<int> GetTableAriaColumnCount() const;
// If inside a table or ARIA grid, returns the number of physical columns that
// this cell spans. Returns std::nullopt if not a cell or if not inside a
// table.
std::optional<int> GetTableColumnSpan() const;
// If inside a table or ARIA grid, returns the physical row number for the
// current cell. In contrast to logical rows, physical rows always start from
// 0 and have no gaps in their numbering. Logical rows can be set using
// aria-rowindex. Returns std::nullopt if not a cell or if not inside a
// table.
std::optional<int> GetTableRow() const;
// If inside a table or ARIA grid, returns the number of physical rows.
// Returns std::nullopt if not inside a table.
std::optional<int> GetTableRowCount() const;
// If inside a table or ARIA grid, returns the number of ARIA rows.
// Returns std::nullopt if not inside a table.
std::optional<int> GetTableAriaRowCount() const;
// If inside a table or ARIA grid, returns the number of physical rows that
// this cell spans. Returns std::nullopt if not a cell or if not inside a
// table.
std::optional<int> GetTableRowSpan() const;
// Returns the font size converted to points, if available.
std::optional<float> GetFontSizeInPoints() const;
// Returns true if either a descendant has selection (sel_focus_object_id) or
// if this node is a simple text element and has text selection attributes.
// Optionally accepts an unignored selection to avoid redundant computation.
bool HasCaret(const AXTree::Selection* unignored_selection = nullptr);
// See AXPlatformNodeDelegate::IsChildOfLeaf().
bool IsChildOfLeaf() const;
// See AXPlatformNodeDelegate::IsLeaf().
bool IsLeaf() const;
// See AXPlatformNodeDelegate::IsInvisibleOrIgnored().
bool IsInvisibleOrIgnored() const;
// Returns true if this node can be scrolled either in the horizontal or the
// vertical direction.
bool IsScrollable() const;
// Returns true if this node can be scrolled in the horizontal direction.
bool IsHorizontallyScrollable() const;
// Returns true if this node can be scrolled in the vertical direction.
bool IsVerticallyScrollable() const;
// See AXNodeData::IsTextField().
bool IsTextField() const;
// See AXNodeData::IsPlainTextField().
bool IsPlainTextField() const;
// See AXNodeData::IsRichTextField().
bool IsRichTextField() const;
// See AXNode::IsText().
bool IsText() const;
// Determines whether an element should be exposed with checkable state, and
// possibly the checked state. Examples are check box and radio button.
// Objects that are exposed as toggle buttons use the platform pressed state
// in some platform APIs, and should not be exposed as checkable. They don't
// expose the platform equivalent of the internal checked state.
virtual bool IsPlatformCheckable() const;
bool HasFocus();
// If this node is a leaf, returns the visible accessible name of this node.
// Otherwise represents every non-leaf child node with a special "embedded
// object character", and every leaf child node with its visible accessible
// name. This is how displayed text and embedded objects are represented in
// ATK and IA2 APIs.
std::u16string GetHypertext() const;
// Returns the text of this node and all descendant nodes; including text
// found in embedded objects.
//
// Only text displayed on screen is included. Text from ARIA and HTML
// attributes that is either not displayed on screen, or outside this node,
// e.g. aria-label and HTML title, is not returned.
std::u16string GetInnerText() const;
virtual std::u16string GetValue() const;
// Represents a non-static text node in IAccessibleHypertext (and ATK in the
// future). This character is embedded in the response to
// IAccessibleText::get_text, indicating the position where a non-static text
// child object appears.
static const char16_t kEmbeddedCharacter;
// Get a node given its unique id or null in the case that the id is unknown.
static AXPlatformNode* GetFromUniqueId(int32_t unique_id);
// Return the number of instances of AXPlatformNodeBase, for leak testing.
static size_t GetInstanceCountForTesting();
static void SetOnNotifyEventCallbackForTesting(
ax::mojom::Event event_type,
std::function<void()> callback);
enum ScrollType {
TopLeft,
BottomRight,
TopEdge,
BottomEdge,
LeftEdge,
RightEdge,
Anywhere,
};
bool ScrollToNode(ScrollType scroll_type);
// This will return the nearest leaf node to the point, the leaf node will not
// necessarily be directly under the point. This utilizes
// AXPlatformNodeDelegate::HitTestSync, which in the case of
// BrowserAccessibility, may not be accurate after a single call. See
// BrowserAccessibilityManager::CachingAsyncHitTest
AXPlatformNodeBase* NearestLeafToPoint(gfx::Point point) const;
// Return the nearest text index to a point in screen coordinates for an
// accessibility node. If the node is not a text only node, the implicit
// nearest index is zero. Note this will only find the index of text on the
// input node. Due to perf concerns, this should only be called on leaf nodes.
int NearestTextIndexToPoint(gfx::Point point);
ui::TextAttributeList ComputeTextAttributes() const;
// Get the number of items selected. It checks kMultiselectable and
// kFocusable. and uses GetSelectedItems to get the selected number.
int GetSelectionCount() const;
// If this object is a container that supports selectable children, returns
// the selected item at the provided index.
AXPlatformNodeBase* GetSelectedItem(int selected_index) const;
// If this object is a container that supports selectable children,
// returns the number of selected items in this container.
// |out_selected_items| could be set to nullptr if the caller just
// needs to know the number of items selected.
// |max_items| represents the number that the caller expects as a
// maximum. For a single selection list box, it will be 1.
int GetSelectedItems(
int max_items,
std::vector<AXPlatformNodeBase*>* out_selected_items = nullptr) const;
//
// Delegate. This is a weak reference which owns |this|.
//
AXPlatformNodeDelegate* delegate_ = nullptr;
protected:
bool IsDocument() const;
bool IsSelectionItemSupported() const;
// Get the range value text, which might come from aria-valuetext or
// a floating-point value. This is different from the value string
// attribute used in input controls such as text boxes and combo boxes.
std::u16string GetRangeValueText() const;
// Get the role description from the node data or from the image annotation
// status.
std::u16string GetRoleDescription() const;
std::u16string GetRoleDescriptionFromImageAnnotationStatusOrFromAttribute()
const;
// Cast a gfx::NativeViewAccessible to an AXPlatformNodeBase if it is one,
// or return NULL if it's not an instance of this class.
static AXPlatformNodeBase* FromNativeViewAccessible(
gfx::NativeViewAccessible accessible);
virtual void Dispose();
// Sets the hypertext selection in this object if possible.
bool SetHypertextSelection(int start_offset, int end_offset);
using PlatformAttributeList = std::vector<std::u16string>;
// Compute the attributes exposed via platform accessibility objects and put
// them into an attribute list, |attributes|. Currently only used by
// IAccessible2 on Windows and ATK on Aura Linux.
void ComputeAttributes(PlatformAttributeList* attributes);
// If the string attribute |attribute| is present, add its value as an
// IAccessible2 attribute with the name |name|.
void AddAttributeToList(const ax::mojom::StringAttribute attribute,
const char* name,
PlatformAttributeList* attributes);
// If the bool attribute |attribute| is present, add its value as an
// IAccessible2 attribute with the name |name|.
void AddAttributeToList(const ax::mojom::BoolAttribute attribute,
const char* name,
PlatformAttributeList* attributes);
// If the int attribute |attribute| is present, add its value as an
// IAccessible2 attribute with the name |name|.
void AddAttributeToList(const ax::mojom::IntAttribute attribute,
const char* name,
PlatformAttributeList* attributes);
// A helper to add the given string value to |attributes|.
virtual void AddAttributeToList(const char* name,
const std::string& value,
PlatformAttributeList* attributes);
// A virtual method that subclasses use to actually add the attribute to
// |attributes|.
virtual void AddAttributeToList(const char* name,
const char* value,
PlatformAttributeList* attributes);
// Escapes characters in string attributes as required by the IA2 Spec
// and AT-SPI2. It's okay for input to be the same as output.
static void SanitizeStringAttribute(const std::string& input,
std::string* output);
// Escapes characters in text attribute values as required by the platform.
// It's okay for input to be the same as output. The default implementation
// does nothing to the input value.
virtual void SanitizeTextAttributeValue(const std::string& input,
std::string* output) const;
// Compute the hypertext for this node to be exposed via IA2 and ATK This
// method is responsible for properly embedding children using the special
// embedded element character.
void UpdateComputedHypertext() const;
// Selection helper functions.
// The following functions retrieve the endpoints of the current selection.
// First they check for a local selection found on the current control, e.g.
// when querying the selection on a textarea.
// If not found they retrieve the global selection found on the current frame.
int GetSelectionAnchor(const AXTree::Selection* selection);
int GetSelectionFocus(const AXTree::Selection* selection);
// Retrieves the selection offsets in the way required by the IA2 APIs.
// selection_start and selection_end are -1 when there is no selection active
// on this object.
// The greatest of the two offsets is one past the last character of the
// selection.)
void GetSelectionOffsets(int* selection_start, int* selection_end);
void GetSelectionOffsets(const AXTree::Selection* selection,
int* selection_start,
int* selection_end);
void GetSelectionOffsetsFromTree(const AXTree::Selection* selection,
int* selection_start,
int* selection_end);
// Returns the hyperlink at the given text position, or nullptr if no
// hyperlink can be found.
AXPlatformNodeBase* GetHyperlinkFromHypertextOffset(int offset);
// Functions for retrieving offsets for hyperlinks and hypertext.
// Return -1 in case of failure.
int32_t GetHyperlinkIndexFromChild(AXPlatformNodeBase* child);
int32_t GetHypertextOffsetFromHyperlinkIndex(int32_t hyperlink_index);
int32_t GetHypertextOffsetFromChild(AXPlatformNodeBase* child);
int32_t GetHypertextOffsetFromDescendant(AXPlatformNodeBase* descendant);
// If the selection endpoint is either equal to or an ancestor of this object,
// returns endpoint_offset.
// If the selection endpoint is a descendant of this object, returns its
// offset. Otherwise, returns either 0 or the length of the hypertext
// depending on the direction of the selection.
// Returns -1 in case of unexpected failure, e.g. the selection endpoint
// cannot be found in the accessibility tree.
int GetHypertextOffsetFromEndpoint(AXPlatformNodeBase* endpoint_object,
int endpoint_offset);
bool IsSameHypertextCharacter(const AXHypertext& old_hypertext,
size_t old_char_index,
size_t new_char_index);
std::optional<int> GetPosInSet() const;
std::optional<int> GetSetSize() const;
std::string GetInvalidValue() const;
// Based on the characteristics of this object, such as its role and the
// presence of a multiselectable attribute, returns the maximum number of
// selectable children that this object could potentially contain.
int GetMaxSelectableItems() const;
mutable AXHypertext hypertext_;
private:
// Returns true if the index represents a text character.
bool IsText(const std::u16string& text,
size_t index,
bool is_indexed_from_end = false);
// Compute value for object attribute details-roles on aria-details nodes.
std::string ComputeDetailsRoles() const;
BASE_DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeBase);
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_BASE_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node_base.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_base.h",
"repo_id": "engine",
"token_count": 6531
} | 444 |
// 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/platform/ax_platform_node_win_unittest.h"
#include <UIAutomationClient.h>
#include <UIAutomationCoreApi.h>
#include <filesystem>
#include <memory>
#include <utility>
#include "ax/ax_tree.h"
#include "ax/platform/ax_fragment_root_win.h"
#include "ax/platform/ax_platform_node_textrangeprovider_win.h"
#include "base/win/atl.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_safearray.h"
#include "base/win/scoped_variant.h"
#include "flutter/fml/icu_util.h"
#include "third_party/icu/source/common/unicode/putil.h"
using Microsoft::WRL::ComPtr;
namespace ui {
// Helper macros for UIAutomation HRESULT expectations
#define EXPECT_UIA_ELEMENTNOTAVAILABLE(expr) \
EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), (expr))
#define EXPECT_UIA_INVALIDOPERATION(expr) \
EXPECT_EQ(static_cast<HRESULT>(UIA_E_INVALIDOPERATION), (expr))
#define EXPECT_UIA_ELEMENTNOTENABLED(expr) \
EXPECT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTENABLED), (expr))
#define EXPECT_UIA_NOTSUPPORTED(expr) \
EXPECT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), (expr))
#define ASSERT_UIA_ELEMENTNOTAVAILABLE(expr) \
ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE), (expr))
#define ASSERT_UIA_INVALIDOPERATION(expr) \
ASSERT_EQ(static_cast<HRESULT>(UIA_E_INVALIDOPERATION), (expr))
#define ASSERT_UIA_ELEMENTNOTENABLED(expr) \
ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTENABLED), (expr))
#define ASSERT_UIA_NOTSUPPORTED(expr) \
ASSERT_EQ(static_cast<HRESULT>(UIA_E_NOTSUPPORTED), (expr))
#define EXPECT_UIA_GETPROPERTYVALUE_EQ(node, property_id, expected) \
{ \
base::win::ScopedVariant expectedVariant(expected); \
ASSERT_EQ(VT_BSTR, expectedVariant.type()); \
ASSERT_NE(nullptr, expectedVariant.ptr()->bstrVal); \
base::win::ScopedVariant actual; \
ASSERT_HRESULT_SUCCEEDED( \
node->GetPropertyValue(property_id, actual.Receive())); \
ASSERT_EQ(VT_BSTR, actual.type()); \
ASSERT_NE(nullptr, actual.ptr()->bstrVal); \
EXPECT_STREQ(expectedVariant.ptr()->bstrVal, actual.ptr()->bstrVal); \
}
#define EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(array, element_test_property_id, \
expected_property_values) \
{ \
ASSERT_EQ(1u, SafeArrayGetDim(array)); \
LONG array_lower_bound; \
ASSERT_HRESULT_SUCCEEDED( \
SafeArrayGetLBound(array, 1, &array_lower_bound)); \
LONG array_upper_bound; \
ASSERT_HRESULT_SUCCEEDED( \
SafeArrayGetUBound(array, 1, &array_upper_bound)); \
IUnknown** array_data; \
ASSERT_HRESULT_SUCCEEDED( \
::SafeArrayAccessData(array, reinterpret_cast<void**>(&array_data))); \
size_t count = array_upper_bound - array_lower_bound + 1; \
ASSERT_EQ(expected_property_values.size(), count); \
for (size_t i = 0; i < count; ++i) { \
ComPtr<IRawElementProviderSimple> element; \
ASSERT_HRESULT_SUCCEEDED( \
array_data[i]->QueryInterface(IID_PPV_ARGS(&element))); \
EXPECT_UIA_GETPROPERTYVALUE_EQ(element, element_test_property_id, \
expected_property_values[i].c_str()); \
} \
ASSERT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(array)); \
}
#define EXPECT_UIA_SAFEARRAY_EQ(safearray, expected_property_values) \
{ \
using T = typename decltype(expected_property_values)::value_type; \
EXPECT_EQ(sizeof(T), ::SafeArrayGetElemsize(safearray)); \
EXPECT_EQ(1u, SafeArrayGetDim(safearray)); \
LONG array_lower_bound; \
EXPECT_HRESULT_SUCCEEDED( \
SafeArrayGetLBound(safearray, 1, &array_lower_bound)); \
LONG array_upper_bound; \
EXPECT_HRESULT_SUCCEEDED( \
SafeArrayGetUBound(safearray, 1, &array_upper_bound)); \
const size_t count = array_upper_bound - array_lower_bound + 1; \
EXPECT_EQ(expected_property_values.size(), count); \
if (sizeof(T) == ::SafeArrayGetElemsize(safearray) && \
count == expected_property_values.size()) { \
T* array_data; \
EXPECT_HRESULT_SUCCEEDED(::SafeArrayAccessData( \
safearray, reinterpret_cast<void**>(&array_data))); \
for (size_t i = 0; i < count; ++i) { \
EXPECT_EQ(array_data[i], expected_property_values[i]); \
} \
EXPECT_HRESULT_SUCCEEDED(::SafeArrayUnaccessData(safearray)); \
} \
}
#define EXPECT_UIA_TEXTATTRIBUTE_EQ(provider, attribute, variant) \
{ \
base::win::ScopedVariant scoped_variant; \
EXPECT_HRESULT_SUCCEEDED( \
provider->GetAttributeValue(attribute, scoped_variant.Receive())); \
EXPECT_EQ(0, scoped_variant.Compare(variant)); \
}
#define EXPECT_UIA_TEXTATTRIBUTE_MIXED(provider, attribute) \
{ \
ComPtr<IUnknown> expected_mixed; \
EXPECT_HRESULT_SUCCEEDED( \
::UiaGetReservedMixedAttributeValue(&expected_mixed)); \
base::win::ScopedVariant scoped_variant; \
EXPECT_HRESULT_SUCCEEDED( \
provider->GetAttributeValue(attribute, scoped_variant.Receive())); \
EXPECT_EQ(VT_UNKNOWN, scoped_variant.type()); \
EXPECT_EQ(expected_mixed.Get(), V_UNKNOWN(scoped_variant.ptr())); \
}
#define EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(provider, attribute) \
{ \
ComPtr<IUnknown> expected_notsupported; \
EXPECT_HRESULT_SUCCEEDED( \
::UiaGetReservedNotSupportedValue(&expected_notsupported)); \
base::win::ScopedVariant scoped_variant; \
EXPECT_HRESULT_SUCCEEDED( \
provider->GetAttributeValue(attribute, scoped_variant.Receive())); \
EXPECT_EQ(VT_UNKNOWN, scoped_variant.type()); \
EXPECT_EQ(expected_notsupported.Get(), V_UNKNOWN(scoped_variant.ptr())); \
}
#define EXPECT_UIA_TEXTRANGE_EQ(provider, expected_content) \
{ \
base::win::ScopedBstr provider_content; \
EXPECT_HRESULT_SUCCEEDED( \
provider->GetText(-1, provider_content.Receive())); \
EXPECT_STREQ(expected_content, provider_content.Get()); \
}
#define EXPECT_UIA_FIND_TEXT(text_range_provider, search_term, ignore_case, \
owner) \
{ \
base::win::ScopedBstr find_string(search_term); \
ComPtr<ITextRangeProvider> text_range_provider_found; \
EXPECT_HRESULT_SUCCEEDED(text_range_provider->FindText( \
find_string.Get(), false, ignore_case, &text_range_provider_found)); \
if (text_range_provider_found == nullptr) { \
EXPECT_TRUE(false); \
} else { \
SetOwner(owner, text_range_provider_found.Get()); \
base::win::ScopedBstr found_content; \
EXPECT_HRESULT_SUCCEEDED( \
text_range_provider_found->GetText(-1, found_content.Receive())); \
if (ignore_case) \
EXPECT_TRUE(StringCompareICU(found_content.Get(), find_string.Get())); \
else \
EXPECT_EQ(0, wcscmp(found_content.Get(), find_string.Get())); \
} \
}
#define EXPECT_UIA_FIND_TEXT_NO_MATCH(text_range_provider, search_term, \
ignore_case, owner) \
{ \
base::win::ScopedBstr find_string(search_term); \
ComPtr<ITextRangeProvider> text_range_provider_found; \
EXPECT_HRESULT_SUCCEEDED(text_range_provider->FindText( \
find_string.Get(), false, ignore_case, &text_range_provider_found)); \
EXPECT_EQ(nullptr, text_range_provider_found); \
}
#define EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider, endpoint, unit, \
count, expected_text, expected_count) \
{ \
int result_count; \
EXPECT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit( \
endpoint, unit, count, &result_count)); \
EXPECT_EQ(expected_count, result_count); \
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, expected_text); \
}
#define EXPECT_UIA_MOVE(text_range_provider, unit, count, expected_text, \
expected_count) \
{ \
int result_count; \
EXPECT_HRESULT_SUCCEEDED( \
text_range_provider->Move(unit, count, &result_count)); \
EXPECT_EQ(expected_count, result_count); \
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, expected_text); \
}
#define EXPECT_ENCLOSING_ELEMENT(ax_node_given, ax_node_expected) \
{ \
ComPtr<ITextRangeProvider> text_range_provider; \
GetTextRangeProviderFromTextNode(text_range_provider, ax_node_given); \
ComPtr<IRawElementProviderSimple> enclosing_element; \
ASSERT_HRESULT_SUCCEEDED( \
text_range_provider->GetEnclosingElement(&enclosing_element)); \
ComPtr<IRawElementProviderSimple> expected_text_provider = \
QueryInterfaceFromNode<IRawElementProviderSimple>(ax_node_expected); \
EXPECT_EQ(expected_text_provider.Get(), enclosing_element.Get()); \
}
#define DCHECK_EQ(a, b) BASE_DCHECK((a) == (b))
static bool StringCompareICU(BSTR left, BSTR right) {
size_t start, length;
if (!StringSearch(reinterpret_cast<char16_t*>(left),
reinterpret_cast<char16_t*>(right), &start, &length, true,
false)) {
return false;
}
return start == 0 && length == wcslen(left);
}
static AXNodePosition::AXPositionInstance CreateTextPosition(
const AXNode& anchor,
int text_offset,
ax::mojom::TextAffinity affinity) {
return AXNodePosition::CreateTextPosition(anchor.tree()->GetAXTreeID(),
anchor.id(), text_offset, affinity);
}
class AXPlatformNodeTextRangeProviderTest : public ui::AXPlatformNodeWinTest {
public:
const AXNodePosition::AXPositionInstance& GetStart(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->start();
}
const AXNodePosition::AXPositionInstance& GetEnd(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->end();
}
ui::AXPlatformNodeWin* GetOwner(
const AXPlatformNodeTextRangeProviderWin* text_range) {
return text_range->GetOwner();
}
void CopyOwnerToClone(ITextRangeProvider* source_range,
ITextRangeProvider* destination_range) {
ComPtr<ITextRangeProvider> source_provider = source_range;
ComPtr<ITextRangeProvider> destination_provider = destination_range;
ComPtr<AXPlatformNodeTextRangeProviderWin> source_provider_internal;
ComPtr<AXPlatformNodeTextRangeProviderWin> destination_provider_internal;
source_provider->QueryInterface(IID_PPV_ARGS(&source_provider_internal));
destination_provider->QueryInterface(
IID_PPV_ARGS(&destination_provider_internal));
destination_provider_internal->SetOwnerForTesting(
source_provider_internal->GetOwner());
}
void SetOwner(AXPlatformNodeWin* owner,
ITextRangeProvider* destination_range) {
ComPtr<AXPlatformNodeTextRangeProviderWin> destination_provider_internal;
auto as =
static_cast<AXPlatformNodeTextRangeProviderWin*>(destination_range);
destination_range->QueryInterface(
IID_PPV_ARGS(&destination_provider_internal));
destination_provider_internal->SetOwnerForTesting(owner);
}
void NormalizeTextRange(AXPlatformNodeTextRangeProviderWin* text_range,
AXNodePosition::AXPositionInstance& start,
AXNodePosition::AXPositionInstance& end) {
DCHECK_EQ(*GetStart(text_range), *start);
DCHECK_EQ(*GetEnd(text_range), *end);
text_range->NormalizeTextRange(start, end);
}
void GetTextRangeProviderFromTextNode(
ComPtr<ITextRangeProvider>& text_range_provider,
ui::AXNode* text_node) {
ComPtr<IRawElementProviderSimple> provider_simple =
QueryInterfaceFromNode<IRawElementProviderSimple>(text_node);
ASSERT_NE(nullptr, provider_simple.Get());
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
provider_simple->GetPatternProvider(UIA_TextPatternId, &text_provider));
ASSERT_NE(nullptr, text_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
ASSERT_NE(nullptr, text_range_provider.Get());
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range_provider_interal;
EXPECT_HRESULT_SUCCEEDED(text_range_provider->QueryInterface(
IID_PPV_ARGS(&text_range_provider_interal)));
AXPlatformNode* ax_platform_node = AXPlatformNodeFromNode(text_node);
ASSERT_NE(ax_platform_node, nullptr);
text_range_provider_interal->SetOwnerForTesting(
static_cast<AXPlatformNodeWin*>(ax_platform_node));
}
void CreateTextRangeProviderWin(
ComPtr<AXPlatformNodeTextRangeProviderWin>& text_range_provider_win,
AXPlatformNodeWin* owner,
const AXNode* start_anchor,
int start_offset,
ax::mojom::TextAffinity start_affinity,
const AXNode* end_anchor,
int end_offset,
ax::mojom::TextAffinity end_affinity) {
AXNodePosition::AXPositionInstance range_start =
CreateTextPosition(*start_anchor, start_offset, start_affinity);
AXNodePosition::AXPositionInstance range_end =
CreateTextPosition(*end_anchor, end_offset, end_affinity);
ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProviderForTesting(
owner, std::move(range_start), std::move(range_end));
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range_provider_win));
}
void ComputeWordBoundariesOffsets(const std::string& text,
std::vector<int>& word_start_offsets,
std::vector<int>& word_end_offsets) {
char previous_char = ' ';
word_start_offsets = std::vector<int>();
for (size_t i = 0; i < text.size(); ++i) {
if (previous_char == ' ' && text[i] != ' ')
word_start_offsets.push_back(i);
previous_char = text[i];
}
previous_char = ' ';
word_end_offsets = std::vector<int>();
for (size_t i = text.size(); i > 0; --i) {
if (previous_char == ' ' && text[i - 1] != ' ')
word_end_offsets.push_back(i);
previous_char = text[i - 1];
}
std::reverse(word_end_offsets.begin(), word_end_offsets.end());
}
AXTreeUpdate BuildTextDocument(
const std::vector<std::string>& text_nodes_content,
bool build_word_boundaries_offsets = false,
bool place_text_on_one_line = false) {
int current_id = 0;
AXNodeData root_data;
root_data.id = ++current_id;
root_data.role = ax::mojom::Role::kRootWebArea;
AXTreeUpdate update;
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
for (const std::string& text_content : text_nodes_content) {
AXNodeData static_text_data;
static_text_data.id = ++current_id;
static_text_data.role = ax::mojom::Role::kStaticText;
static_text_data.SetName(text_content);
root_data.child_ids.push_back(static_text_data.id);
AXNodeData inline_box_data;
inline_box_data.id = ++current_id;
inline_box_data.role = ax::mojom::Role::kInlineTextBox;
inline_box_data.SetName(text_content);
static_text_data.child_ids = {inline_box_data.id};
if (build_word_boundaries_offsets) {
std::vector<int> word_end_offsets;
std::vector<int> word_start_offsets;
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
inline_box_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, word_start_offsets);
inline_box_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordEnds, word_end_offsets);
}
if (place_text_on_one_line && !update.nodes.empty()) {
AXNodeData* previous_inline_box_data = &update.nodes.back();
static_text_data.AddIntAttribute(
ax::mojom::IntAttribute::kPreviousOnLineId,
previous_inline_box_data->id);
inline_box_data.AddIntAttribute(
ax::mojom::IntAttribute::kPreviousOnLineId,
previous_inline_box_data->id);
previous_inline_box_data->AddIntAttribute(
ax::mojom::IntAttribute::kNextOnLineId, inline_box_data.id);
}
update.nodes.push_back(static_text_data);
update.nodes.push_back(inline_box_data);
}
update.nodes.insert(update.nodes.begin(), root_data);
update.root_id = root_data.id;
return update;
}
ui::AXTreeUpdate BuildAXTreeForBoundingRectangles() {
// AXTree content:
// <button>Button</button><input type="checkbox">Line 1<br>Line 2
ui::AXNodeData root;
ui::AXNodeData button;
ui::AXNodeData check_box;
ui::AXNodeData text_field;
ui::AXNodeData static_text1;
ui::AXNodeData line_break;
ui::AXNodeData static_text2;
ui::AXNodeData inline_box1;
ui::AXNodeData inline_box2;
ui::AXNodeData inline_box_line_break;
const int ROOT_ID = 1;
const int BUTTON_ID = 2;
const int CHECK_BOX_ID = 3;
const int TEXT_FIELD_ID = 4;
const int STATIC_TEXT1_ID = 5;
const int INLINE_BOX1_ID = 6;
const int LINE_BREAK_ID = 7;
const int INLINE_BOX_LINE_BREAK_ID = 8;
const int STATIC_TEXT2_ID = 9;
const int INLINE_BOX2_ID = 10;
root.id = ROOT_ID;
button.id = BUTTON_ID;
check_box.id = CHECK_BOX_ID;
text_field.id = TEXT_FIELD_ID;
static_text1.id = STATIC_TEXT1_ID;
inline_box1.id = INLINE_BOX1_ID;
line_break.id = LINE_BREAK_ID;
inline_box_line_break.id = INLINE_BOX_LINE_BREAK_ID;
static_text2.id = STATIC_TEXT2_ID;
inline_box2.id = INLINE_BOX2_ID;
std::string LINE_1_TEXT = "Line 1";
std::string LINE_2_TEXT = "Line 2";
std::string LINE_BREAK_TEXT = "\n";
std::string ALL_TEXT = LINE_1_TEXT + LINE_BREAK_TEXT + LINE_2_TEXT;
std::string BUTTON_TEXT = "Button";
std::string CHECKBOX_TEXT = "Check box";
root.role = ax::mojom::Role::kRootWebArea;
button.role = ax::mojom::Role::kButton;
button.SetHasPopup(ax::mojom::HasPopup::kMenu);
button.SetName(BUTTON_TEXT);
button.SetValue(BUTTON_TEXT);
button.relative_bounds.bounds = gfx::RectF(20, 20, 200, 30);
button.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
check_box.id);
root.child_ids.push_back(button.id);
check_box.role = ax::mojom::Role::kCheckBox;
check_box.SetCheckedState(ax::mojom::CheckedState::kTrue);
check_box.SetName(CHECKBOX_TEXT);
check_box.relative_bounds.bounds = gfx::RectF(20, 50, 200, 30);
check_box.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
button.id);
root.child_ids.push_back(check_box.id);
text_field.role = ax::mojom::Role::kTextField;
text_field.AddState(ax::mojom::State::kEditable);
text_field.AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag,
"input");
text_field.AddStringAttribute(ax::mojom::StringAttribute::kInputType,
"text");
text_field.SetValue(ALL_TEXT);
text_field.AddIntListAttribute(
ax::mojom::IntListAttribute::kCachedLineStarts,
std::vector<int32_t>{0, 7});
text_field.child_ids.push_back(static_text1.id);
text_field.child_ids.push_back(line_break.id);
text_field.child_ids.push_back(static_text2.id);
root.child_ids.push_back(text_field.id);
static_text1.role = ax::mojom::Role::kStaticText;
static_text1.AddState(ax::mojom::State::kEditable);
static_text1.SetName(LINE_1_TEXT);
static_text1.child_ids.push_back(inline_box1.id);
inline_box1.role = ax::mojom::Role::kInlineTextBox;
inline_box1.AddState(ax::mojom::State::kEditable);
inline_box1.SetName(LINE_1_TEXT);
inline_box1.relative_bounds.bounds = gfx::RectF(220, 20, 100, 30);
std::vector<int32_t> character_offsets1;
// The width of each character is 5px.
character_offsets1.push_back(225); // "L" {220, 20, 5x30}
character_offsets1.push_back(230); // "i" {225, 20, 5x30}
character_offsets1.push_back(235); // "n" {230, 20, 5x30}
character_offsets1.push_back(240); // "e" {235, 20, 5x30}
character_offsets1.push_back(245); // " " {240, 20, 5x30}
character_offsets1.push_back(250); // "1" {245, 20, 5x30}
inline_box1.AddIntListAttribute(
ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets1);
inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 5});
inline_box1.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{4, 6});
inline_box1.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
line_break.id);
line_break.role = ax::mojom::Role::kLineBreak;
line_break.AddState(ax::mojom::State::kEditable);
line_break.SetName(LINE_BREAK_TEXT);
line_break.relative_bounds.bounds = gfx::RectF(250, 20, 0, 30);
line_break.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
inline_box1.id);
line_break.child_ids.push_back(inline_box_line_break.id);
inline_box_line_break.role = ax::mojom::Role::kInlineTextBox;
inline_box_line_break.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
inline_box_line_break.SetName(LINE_BREAK_TEXT);
inline_box_line_break.relative_bounds.bounds = gfx::RectF(250, 20, 0, 30);
inline_box_line_break.AddIntListAttribute(
ax::mojom::IntListAttribute::kCharacterOffsets, {0});
inline_box_line_break.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, std::vector<int32_t>{0});
inline_box_line_break.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordEnds, std::vector<int32_t>{0});
static_text2.role = ax::mojom::Role::kStaticText;
static_text2.AddState(ax::mojom::State::kEditable);
static_text2.SetName(LINE_2_TEXT);
static_text2.child_ids.push_back(inline_box2.id);
inline_box2.role = ax::mojom::Role::kInlineTextBox;
inline_box2.AddState(ax::mojom::State::kEditable);
inline_box2.SetName(LINE_2_TEXT);
inline_box2.relative_bounds.bounds = gfx::RectF(220, 50, 100, 30);
std::vector<int32_t> character_offsets2;
// The width of each character is 7 px.
character_offsets2.push_back(227); // "L" {220, 50, 7x30}
character_offsets2.push_back(234); // "i" {227, 50, 7x30}
character_offsets2.push_back(241); // "n" {234, 50, 7x30}
character_offsets2.push_back(248); // "e" {241, 50, 7x30}
character_offsets2.push_back(255); // " " {248, 50, 7x30}
character_offsets2.push_back(262); // "2" {255, 50, 7x30}
inline_box2.AddIntListAttribute(
ax::mojom::IntListAttribute::kCharacterOffsets, character_offsets2);
inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
std::vector<int32_t>{0, 5});
inline_box2.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
std::vector<int32_t>{4, 6});
AXTreeUpdate update;
update.has_tree_data = true;
update.root_id = ROOT_ID;
update.nodes = {
root, button, check_box, text_field,
static_text1, inline_box1, line_break, inline_box_line_break,
static_text2, inline_box2};
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
return update;
}
const std::wstring tree_for_move_full_text =
L"First line of text\nStandalone line\n"
L"bold text\nParagraph 1\nParagraph 2";
ui::AXTreeUpdate BuildAXTreeForMove() {
ui::AXNodeData group1_data;
group1_data.id = 2;
group1_data.role = ax::mojom::Role::kGenericContainer;
group1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
ui::AXNodeData text_data;
text_data.id = 3;
text_data.role = ax::mojom::Role::kStaticText;
std::string text_content = "First line of text";
text_data.SetName(text_content);
std::vector<int> word_end_offsets;
std::vector<int> word_start_offsets;
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
word_start_offsets);
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
word_end_offsets);
group1_data.child_ids = {text_data.id};
ui::AXNodeData group2_data;
group2_data.id = 4;
group2_data.role = ax::mojom::Role::kGenericContainer;
ui::AXNodeData line_break1_data;
line_break1_data.id = 5;
line_break1_data.role = ax::mojom::Role::kLineBreak;
line_break1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
line_break1_data.SetName("\n");
ui::AXNodeData standalone_text_data;
standalone_text_data.id = 6;
standalone_text_data.role = ax::mojom::Role::kStaticText;
text_content = "Standalone line";
standalone_text_data.SetName(text_content);
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
standalone_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, word_start_offsets);
standalone_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordEnds, word_end_offsets);
ui::AXNodeData line_break2_data;
line_break2_data.id = 7;
line_break2_data.role = ax::mojom::Role::kLineBreak;
line_break2_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
line_break2_data.SetName("\n");
group2_data.child_ids = {line_break1_data.id, standalone_text_data.id,
line_break2_data.id};
standalone_text_data.AddIntAttribute(ax::mojom::IntAttribute::kNextOnLineId,
line_break2_data.id);
line_break2_data.AddIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId,
standalone_text_data.id);
ui::AXNodeData bold_text_data;
bold_text_data.id = 8;
bold_text_data.role = ax::mojom::Role::kStaticText;
bold_text_data.AddIntAttribute(
ax::mojom::IntAttribute::kTextStyle,
static_cast<int32_t>(ax::mojom::TextStyle::kBold));
text_content = "bold text";
bold_text_data.SetName(text_content);
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
bold_text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
word_start_offsets);
bold_text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
word_end_offsets);
ui::AXNodeData paragraph1_data;
paragraph1_data.id = 9;
paragraph1_data.role = ax::mojom::Role::kParagraph;
paragraph1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
ui::AXNodeData paragraph1_text_data;
paragraph1_text_data.id = 10;
paragraph1_text_data.role = ax::mojom::Role::kStaticText;
text_content = "Paragraph 1";
paragraph1_text_data.SetName(text_content);
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
paragraph1_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, word_start_offsets);
paragraph1_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordEnds, word_end_offsets);
paragraph1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
ui::AXNodeData ignored_text_data;
ignored_text_data.id = 11;
ignored_text_data.role = ax::mojom::Role::kStaticText;
ignored_text_data.AddState(ax::mojom::State::kIgnored);
text_content = "ignored text";
ignored_text_data.SetName(text_content);
paragraph1_data.child_ids = {paragraph1_text_data.id, ignored_text_data.id};
ui::AXNodeData paragraph2_data;
paragraph2_data.id = 12;
paragraph2_data.role = ax::mojom::Role::kParagraph;
paragraph2_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
ui::AXNodeData paragraph2_text_data;
paragraph2_text_data.id = 13;
paragraph2_text_data.role = ax::mojom::Role::kStaticText;
text_content = "Paragraph 2";
paragraph2_text_data.SetName(text_content);
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
paragraph2_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordStarts, word_start_offsets);
paragraph2_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kWordEnds, word_end_offsets);
paragraph1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
paragraph2_data.child_ids = {paragraph2_text_data.id};
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {group1_data.id, group2_data.id, bold_text_data.id,
paragraph1_data.id, paragraph2_data.id};
ui::AXTreeUpdate update;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, group1_data,
text_data, group2_data,
line_break1_data, standalone_text_data,
line_break2_data, bold_text_data,
paragraph1_data, paragraph1_text_data,
ignored_text_data, paragraph2_data,
paragraph2_text_data};
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
return update;
}
AXTreeUpdate BuildAXTreeForMoveByFormat() {
// 1
// |
// -------------------------------------
// | | | | | | |
// 2 4 8 10 12 14 16
// | | | | | | |
// | --------- | | | | |
// | | | | | | | | |
// 3 5 6 7 9 11 13 15 17
AXNodeData group1_data;
group1_data.id = 2;
group1_data.role = ax::mojom::Role::kGenericContainer;
group1_data.AddStringAttribute(ax::mojom::StringAttribute::kFontFamily,
"test font");
group1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData text_data;
text_data.id = 3;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("Text with formatting");
group1_data.child_ids = {text_data.id};
AXNodeData group2_data;
group2_data.id = 4;
group2_data.role = ax::mojom::Role::kGenericContainer;
group2_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData line_break1_data;
line_break1_data.id = 5;
line_break1_data.role = ax::mojom::Role::kLineBreak;
line_break1_data.SetName("\n");
AXNodeData standalone_text_data;
standalone_text_data.id = 6;
standalone_text_data.role = ax::mojom::Role::kStaticText;
standalone_text_data.SetName("Standalone line with no formatting");
AXNodeData line_break2_data;
line_break2_data.id = 7;
line_break2_data.role = ax::mojom::Role::kLineBreak;
line_break2_data.SetName("\n");
group2_data.child_ids = {line_break1_data.id, standalone_text_data.id,
line_break2_data.id};
AXNodeData group3_data;
group3_data.id = 8;
group3_data.role = ax::mojom::Role::kGenericContainer;
group3_data.AddIntAttribute(
ax::mojom::IntAttribute::kTextStyle,
static_cast<int32_t>(ax::mojom::TextStyle::kBold));
group3_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData bold_text_data;
bold_text_data.id = 9;
bold_text_data.role = ax::mojom::Role::kStaticText;
bold_text_data.SetName("bold text");
group3_data.child_ids = {bold_text_data.id};
AXNodeData paragraph1_data;
paragraph1_data.id = 10;
paragraph1_data.role = ax::mojom::Role::kParagraph;
paragraph1_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 100);
paragraph1_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData paragraph1_text_data;
paragraph1_text_data.id = 11;
paragraph1_text_data.role = ax::mojom::Role::kStaticText;
paragraph1_text_data.SetName("Paragraph 1");
paragraph1_data.child_ids = {paragraph1_text_data.id};
AXNodeData paragraph2_data;
paragraph2_data.id = 12;
paragraph2_data.role = ax::mojom::Role::kParagraph;
paragraph2_data.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize,
1.0f);
paragraph2_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData paragraph2_text_data;
paragraph2_text_data.id = 13;
paragraph2_text_data.role = ax::mojom::Role::kStaticText;
paragraph2_text_data.SetName("Paragraph 2");
paragraph2_data.child_ids = {paragraph2_text_data.id};
AXNodeData paragraph3_data;
paragraph3_data.id = 14;
paragraph3_data.role = ax::mojom::Role::kParagraph;
paragraph3_data.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize,
1.0f);
paragraph3_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData paragraph3_text_data;
paragraph3_text_data.id = 15;
paragraph3_text_data.role = ax::mojom::Role::kStaticText;
paragraph3_text_data.SetName("Paragraph 3");
paragraph3_data.child_ids = {paragraph3_text_data.id};
AXNodeData paragraph4_data;
paragraph4_data.id = 16;
paragraph4_data.role = ax::mojom::Role::kParagraph;
paragraph4_data.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize,
2.0f);
paragraph4_data.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
AXNodeData paragraph4_text_data;
paragraph4_text_data.id = 17;
paragraph4_text_data.role = ax::mojom::Role::kStaticText;
paragraph4_text_data.SetName("Paragraph 4");
paragraph4_data.child_ids = {paragraph4_text_data.id};
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {group1_data.id, group2_data.id,
group3_data.id, paragraph1_data.id,
paragraph2_data.id, paragraph3_data.id,
paragraph4_data.id};
AXTreeUpdate update;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data,
group1_data,
text_data,
group2_data,
line_break1_data,
standalone_text_data,
line_break2_data,
group3_data,
bold_text_data,
paragraph1_data,
paragraph1_text_data,
paragraph2_data,
paragraph2_text_data,
paragraph3_data,
paragraph3_text_data,
paragraph4_data,
paragraph4_text_data};
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
return update;
}
void ExpectPositionsEqual(const AXNodePosition::AXPositionInstance& a,
const AXNodePosition::AXPositionInstance& b) {
EXPECT_EQ(*a, *b);
EXPECT_EQ(a->anchor_id(), b->anchor_id());
EXPECT_EQ(a->text_offset(), b->text_offset());
}
};
class MockAXPlatformNodeTextRangeProviderWin
: public CComObjectRootEx<CComMultiThreadModel>,
public ITextRangeProvider {
public:
BEGIN_COM_MAP(MockAXPlatformNodeTextRangeProviderWin)
COM_INTERFACE_ENTRY(ITextRangeProvider)
END_COM_MAP()
MockAXPlatformNodeTextRangeProviderWin() {}
~MockAXPlatformNodeTextRangeProviderWin() {}
static HRESULT CreateMockTextRangeProvider(ITextRangeProvider** provider) {
CComObject<MockAXPlatformNodeTextRangeProviderWin>* text_range_provider =
nullptr;
HRESULT hr =
CComObject<MockAXPlatformNodeTextRangeProviderWin>::CreateInstance(
&text_range_provider);
if (SUCCEEDED(hr)) {
*provider = text_range_provider;
}
return hr;
}
//
// ITextRangeProvider methods.
//
IFACEMETHODIMP Clone(ITextRangeProvider** clone) override {
return E_NOTIMPL;
}
IFACEMETHODIMP Compare(ITextRangeProvider* other, BOOL* result) override {
return E_NOTIMPL;
}
IFACEMETHODIMP CompareEndpoints(TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint,
int* result) override {
return E_NOTIMPL;
}
IFACEMETHODIMP ExpandToEnclosingUnit(TextUnit unit) override {
return E_NOTIMPL;
}
IFACEMETHODIMP FindAttribute(TEXTATTRIBUTEID attribute_id,
VARIANT val,
BOOL backward,
ITextRangeProvider** result) override {
return E_NOTIMPL;
}
IFACEMETHODIMP FindText(BSTR string,
BOOL backwards,
BOOL ignore_case,
ITextRangeProvider** result) override {
return E_NOTIMPL;
}
IFACEMETHODIMP GetAttributeValue(TEXTATTRIBUTEID attribute_id,
VARIANT* value) override {
return E_NOTIMPL;
}
IFACEMETHODIMP GetBoundingRectangles(SAFEARRAY** rectangles) override {
return E_NOTIMPL;
}
IFACEMETHODIMP GetEnclosingElement(
IRawElementProviderSimple** element) override {
return E_NOTIMPL;
}
IFACEMETHODIMP GetText(int max_count, BSTR* text) override {
return E_NOTIMPL;
}
IFACEMETHODIMP Move(TextUnit unit, int count, int* units_moved) override {
return E_NOTIMPL;
}
IFACEMETHODIMP MoveEndpointByUnit(TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved) override {
return E_NOTIMPL;
}
IFACEMETHODIMP MoveEndpointByRange(
TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint) override {
return E_NOTIMPL;
}
IFACEMETHODIMP Select() override { return E_NOTIMPL; }
IFACEMETHODIMP AddToSelection() override { return E_NOTIMPL; }
IFACEMETHODIMP RemoveFromSelection() override { return E_NOTIMPL; }
IFACEMETHODIMP ScrollIntoView(BOOL align_to_top) override {
return E_NOTIMPL;
}
IFACEMETHODIMP GetChildren(SAFEARRAY** children) override {
return E_NOTIMPL;
}
};
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderClone) {
Init(BuildTextDocument({"some text"}));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetRootAsAXNode()->children()[0]);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text");
ComPtr<ITextRangeProvider> text_range_provider_clone;
text_range_provider->Clone(&text_range_provider_clone);
CopyOwnerToClone(text_range_provider.Get(), text_range_provider_clone.Get());
ComPtr<AXPlatformNodeTextRangeProviderWin> original_range;
ComPtr<AXPlatformNodeTextRangeProviderWin> clone_range;
text_range_provider->QueryInterface(IID_PPV_ARGS(&original_range));
text_range_provider_clone->QueryInterface(IID_PPV_ARGS(&clone_range));
EXPECT_EQ(*GetStart(original_range.Get()), *GetStart(clone_range.Get()));
EXPECT_EQ(*GetEnd(original_range.Get()), *GetEnd(clone_range.Get()));
EXPECT_EQ(GetOwner(original_range.Get()), GetOwner(clone_range.Get()));
// Clear original text range provider.
text_range_provider.Reset();
EXPECT_EQ(nullptr, text_range_provider.Get());
// Ensure the clone still works correctly.
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider_clone, L"some text");
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderCompareEndpoints) {
Init(BuildTextDocument({"some text", "more text"},
false /* build_word_boundaries_offsets */,
true /* place_text_on_one_line */));
AXNode* root_node = GetRootAsAXNode();
// Get the textRangeProvider for the document,
// which contains text "some textmore text".
ComPtr<ITextRangeProvider> document_text_range_provider;
GetTextRangeProviderFromTextNode(document_text_range_provider, root_node);
// Get the textRangeProvider for "some text".
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
root_node->children()[0]);
// Get the textRangeProvider for "more text".
ComPtr<ITextRangeProvider> more_text_range_provider;
GetTextRangeProviderFromTextNode(more_text_range_provider,
root_node->children()[1]);
// Compare the endpoints of the document which contains "some textmore text".
int result;
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, document_text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &result));
EXPECT_EQ(0, result);
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_End, document_text_range_provider.Get(),
TextPatternRangeEndpoint_End, &result));
EXPECT_EQ(0, result);
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, document_text_range_provider.Get(),
TextPatternRangeEndpoint_End, &result));
EXPECT_EQ(-1, result);
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_End, document_text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &result));
EXPECT_EQ(1, result);
// Compare the endpoints of "some text" and "more text". The position at the
// end of "some text" is logically equivalent to the position at the start of
// "more text".
EXPECT_HRESULT_SUCCEEDED(text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, more_text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &result));
EXPECT_EQ(-1, result);
EXPECT_HRESULT_SUCCEEDED(text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_End, more_text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &result));
EXPECT_EQ(0, result);
// Compare the endpoints of "some text" with those of the entire document. The
// position at the start of "some text" is logically equivalent to the
// position at the start of the document.
EXPECT_HRESULT_SUCCEEDED(text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, document_text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &result));
EXPECT_EQ(0, result);
EXPECT_HRESULT_SUCCEEDED(text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_End, document_text_range_provider.Get(),
TextPatternRangeEndpoint_End, &result));
EXPECT_EQ(-1, result);
// Compare the endpoints of "more text" with those of the entire document.
EXPECT_HRESULT_SUCCEEDED(more_text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, document_text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &result));
EXPECT_EQ(1, result);
EXPECT_HRESULT_SUCCEEDED(more_text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_End, document_text_range_provider.Get(),
TextPatternRangeEndpoint_End, &result));
EXPECT_EQ(0, result);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderExpandToEnclosingCharacter) {
ui::AXTreeUpdate update = BuildTextDocument({"some text", "more text"});
Init(update);
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"s");
int count;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 2, &count));
ASSERT_EQ(2, count);
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"om");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"o");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 9, &count));
ASSERT_EQ(9, count);
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 8, &count));
ASSERT_EQ(8, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"mo");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"m");
// Move the start and end to the end of the document.
// Expand to enclosing unit should never return a null position.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 9, &count));
ASSERT_EQ(8, count);
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 9, &count));
ASSERT_EQ(9, count);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"t");
// Move both endpoints to the position before the start of the "more text"
// anchor. Then, force the start to be on the position after the end of
// "some text" by moving one character backward and one forward.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -9, &count));
ASSERT_EQ(-9, count);
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ -1,
&count));
ASSERT_EQ(-1, count);
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 1, &count));
ASSERT_EQ(1, count);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"m");
// Check that the enclosing element of the range matches ATs expectations.
ComPtr<IRawElementProviderSimple> more_text_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(
root_node->children()[1]->children()[0]);
ComPtr<IRawElementProviderSimple> enclosing_element;
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(more_text_provider.Get(), enclosing_element.Get());
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderExpandToEnclosingWord) {
Init(BuildTextDocument({"some text", "definitely not text"},
/*build_word_boundaries_offsets*/ true));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetRootAsAXNode()->children()[1]);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"definitely not text");
// Start endpoint is already on a word's start boundary.
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Word));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"definitely ");
// Start endpoint is between a word's start and end boundaries.
int count;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ -2,
&count));
ASSERT_EQ(-2, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"xtdefinitely ");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 4, &count));
ASSERT_EQ(4, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"xtdefinitely not ");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Word));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"text");
// Start endpoint is on a word's end boundary.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 18,
&count));
ASSERT_EQ(18, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L" ");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Word));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"not ");
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderExpandToEnclosingLine) {
Init(BuildTextDocument({"line #1", "maybe line #1?", "not line #1"}));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetRootAsAXNode()->children()[0]);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"line #1");
// Start endpoint is already on a line's start boundary.
int count;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -11, &count));
ASSERT_EQ(-7, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Line));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"line #1");
// Start endpoint is between a line's start and end boundaries.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 13,
&count));
ASSERT_EQ(13, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 4, &count));
ASSERT_EQ(4, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"line");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Line));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"maybe line #1?");
// Start endpoint is on a line's end boundary.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 29,
&count));
ASSERT_EQ(25, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Line));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"not line #1");
}
// TOOD(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderExpandToEnclosingParagraph) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider,
/*expected_text*/ tree_for_move_full_text.data());
// Start endpoint is already on a paragraph's start boundary.
//
// Note that there are 5 paragraphs, not 6, because the line break element
// between the first and second paragraph is merged in the text of the first
// paragraph. This is standard UIA behavior which merges any trailing
// whitespace with the previous paragraph.
int count;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Paragraph, /*count*/ -5, &count));
EXPECT_EQ(-5, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Paragraph));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"First line of text\n");
// Moving the start by two lines will create a degenerate range positioned
// at the next paragraph (skipping the newline).
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Line, /*count*/ 2, &count));
EXPECT_EQ(2, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Paragraph));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"Standalone line\n");
// Move to the next paragraph via MoveEndpointByUnit (line), then move to
// the middle of the paragraph via Move (word), then expand by paragraph.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Line, /*count*/ 1, &count));
EXPECT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 1,
/*expected_text*/
L"",
/*expected_count*/ 1);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Paragraph));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"bold text\n");
// Create a degenerate range at the end of the document, then expand by
// paragraph.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Document, /*count*/ 1, &count));
EXPECT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Paragraph));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"Paragraph 2");
}
// TOOD(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderExpandToEnclosingFormat) {
Init(BuildAXTreeForMoveByFormat());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range_provider_internal;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->QueryInterface(
IID_PPV_ARGS(&text_range_provider_internal)));
EXPECT_UIA_TEXTRANGE_EQ(
text_range_provider,
L"Text with formatting\nStandalone line with no formatting\nbold "
L"text\nParagraph 1\nParagraph 2\nParagraph 3\nParagraph 4");
// https://docs.microsoft.com/en-us/windows/win32/api/uiautomationclient/nf-uiautomationclient-iuiautomationtextrange-expandtoenclosingunit
// Consider two consecutive text units A and B.
// The documentation illustrates 9 cases, but cases 1 and 9 are equivalent.
// In each case, the expected output is a range from start of A to end of A.
// Create a range encompassing nodes 11-15 which will serve as text units A
// and B for this test.
ComPtr<ITextRangeProvider> units_a_b_provider;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->Clone(&units_a_b_provider));
CopyOwnerToClone(text_range_provider.Get(), units_a_b_provider.Get());
int count;
ASSERT_HRESULT_SUCCEEDED(units_a_b_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Line, /*count*/ 5, &count));
ASSERT_EQ(5, count);
ASSERT_HRESULT_SUCCEEDED(units_a_b_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(units_a_b_provider,
L"Paragraph 1\nParagraph 2\nParagraph 3");
// Create a range encompassing node 11 which will serve as our expected
// value of a range from start of A to end of A.
ComPtr<ITextRangeProvider> unit_a_provider;
ASSERT_HRESULT_SUCCEEDED(units_a_b_provider->Clone(&unit_a_provider));
CopyOwnerToClone(units_a_b_provider.Get(), unit_a_provider.Get());
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -2, &count));
ASSERT_EQ(-2, count);
EXPECT_UIA_TEXTRANGE_EQ(unit_a_provider, L"Paragraph 1");
// Case 1: Degenerate range at start of A.
{
SCOPED_TRACE("Case 1: Degenerate range at start of A.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_End, test_case_provider.Get(),
TextPatternRangeEndpoint_Start));
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 2: Range from start of A to middle of A.
{
SCOPED_TRACE("Case 2: Range from start of A to middle of A.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -7,
&count));
ASSERT_EQ(-7, count);
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"Para");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 3: Range from start of A to end of A.
{
SCOPED_TRACE("Case 3: Range from start of A to end of A.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"Paragraph 1");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 4: Range from start of A to middle of B.
{
SCOPED_TRACE("Case 4: Range from start of A to middle of B.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 5, &count));
ASSERT_EQ(5, count);
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"Paragraph 1\nPara");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 5: Degenerate range in middle of A.
{
SCOPED_TRACE("Case 5: Degenerate range in middle of A.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 4,
&count));
ASSERT_EQ(4, count);
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_End, test_case_provider.Get(),
TextPatternRangeEndpoint_Start));
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 6: Range from middle of A to middle of A.
{
SCOPED_TRACE("Case 6: Range from middle of A to middle of A.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 4,
&count));
ASSERT_EQ(4, count);
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -2,
&count));
ASSERT_EQ(-2, count);
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"graph");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 7: Range from middle of A to end of A.
{
SCOPED_TRACE("Case 7: Range from middle of A to end of A.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 4,
&count));
ASSERT_EQ(4, count);
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"graph 1");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
// Case 8: Range from middle of A to middle of B.
{
SCOPED_TRACE("Case 8: Range from middle of A to middle of B.");
ComPtr<ITextRangeProvider> test_case_provider;
ASSERT_HRESULT_SUCCEEDED(unit_a_provider->Clone(&test_case_provider));
CopyOwnerToClone(unit_a_provider.Get(), test_case_provider.Get());
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 5,
&count));
ASSERT_EQ(5, count);
ASSERT_HRESULT_SUCCEEDED(test_case_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 5, &count));
ASSERT_EQ(5, count);
EXPECT_UIA_TEXTRANGE_EQ(test_case_provider, L"raph 1\nPara");
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->ExpandToEnclosingUnit(TextUnit_Format));
BOOL are_same;
ASSERT_HRESULT_SUCCEEDED(
test_case_provider->Compare(unit_a_provider.Get(), &are_same));
EXPECT_TRUE(are_same);
}
}
// TOOD(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderExpandToEnclosingFormatWithEmptyObjects) {
// This test updates the tree structure to test a specific edge case.
//
// When using heading navigation, the empty objects (see
// AXPosition::IsEmptyObjectReplacedByCharacter for information about empty
// objects) sometimes cause a problem with
// AXPlatformNodeTextRangeProviderWin::ExpandToEnclosingUnit.
// With some specific AXTree (like the one used below), the empty object
// causes ExpandToEnclosingUnit to move the range back on the heading that it
// previously was instead of moving it forward/backward to the next heading.
// To avoid this, empty objects are always marked as format boundaries.
//
// The issue normally occurs when a heading is directly followed by an ignored
// empty object, itself followed by an unignored empty object.
//
// ++1 kRootWebArea
// ++++2 kHeading
// ++++++3 kStaticText
// ++++++++4 kInlineTextBox
// ++++5 kGenericContainer ignored
// ++++6 kButton
ui::AXNodeData root_1;
ui::AXNodeData heading_2;
ui::AXNodeData static_text_3;
ui::AXNodeData inline_box_4;
ui::AXNodeData generic_container_5;
ui::AXNodeData button_6;
root_1.id = 1;
heading_2.id = 2;
static_text_3.id = 3;
inline_box_4.id = 4;
generic_container_5.id = 5;
button_6.id = 6;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {heading_2.id, generic_container_5.id, button_6.id};
heading_2.role = ax::mojom::Role::kHeading;
heading_2.child_ids = {static_text_3.id};
static_text_3.role = ax::mojom::Role::kStaticText;
static_text_3.child_ids = {inline_box_4.id};
static_text_3.SetName("3.14");
inline_box_4.role = ax::mojom::Role::kInlineTextBox;
inline_box_4.SetName("3.14");
generic_container_5.role = ax::mojom::Role::kGenericContainer;
generic_container_5.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
generic_container_5.AddState(ax::mojom::State::kIgnored);
button_6.role = ax::mojom::Role::kButton;
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes.push_back(root_1);
update.nodes.push_back(heading_2);
update.nodes.push_back(static_text_3);
update.nodes.push_back(inline_box_4);
update.nodes.push_back(generic_container_5);
update.nodes.push_back(button_6);
Init(update);
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"3.14\xFFFC");
// Create a degenerate range positioned at the boundary between nodes 4 and 6,
// e.g., "3.14<>" and "<\xFFFC>" (because node 5 is ignored).
int count;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Character, /*count*/ 5, &count));
ASSERT_EQ(5, count);
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
// ExpandToEnclosingUnit should move the range to the next non-ignored empty
// object (i.e, node 6), and not at the beginning of node 4.
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Format));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"\xFFFC");
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderExpandToEnclosingDocument) {
Init(BuildTextDocument({"some text", "more text", "even more text"}));
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
AXNode* more_text_node = root_node->children()[1];
AXNode* even_more_text_node = root_node->children()[2];
// Run the test twice, one for TextUnit_Document and once for TextUnit_Page,
// since they should have identical behavior.
const TextUnit textunit_types[] = {TextUnit_Document, TextUnit_Page};
ComPtr<ITextRangeProvider> text_range_provider;
for (auto& textunit : textunit_types) {
GetTextRangeProviderFromTextNode(text_range_provider, text_node);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(textunit));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider,
L"some textmore texteven more text");
GetTextRangeProviderFromTextNode(text_range_provider, more_text_node);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(textunit));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider,
L"some textmore texteven more text");
GetTextRangeProviderFromTextNode(text_range_provider, even_more_text_node);
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(textunit));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider,
L"some textmore texteven more text");
}
}
// TOOD(schectman) Why should this be ignored?
// https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderIgnoredForTextNavigation) {
// ++1 kRootWebArea
// ++++2 kStaticText
// ++++++3 kInlineTextBox foo
// ++++4 kSplitter
// ++++5 kStaticText
// ++++++6 kInlineTextBox bar
// ++++7 genericContainer
// ++++8 kStaticText
// ++++++9 kInlineTextBox baz
ui::AXNodeData root_1;
ui::AXNodeData static_text_2;
ui::AXNodeData inline_box_3;
ui::AXNodeData splitter_4;
ui::AXNodeData static_text_5;
ui::AXNodeData inline_box_6;
ui::AXNodeData generic_container_7;
ui::AXNodeData static_text_8;
ui::AXNodeData inline_box_9;
root_1.id = 1;
static_text_2.id = 2;
inline_box_3.id = 3;
splitter_4.id = 4;
static_text_5.id = 5;
inline_box_6.id = 6;
generic_container_7.id = 7;
static_text_8.id = 8;
inline_box_9.id = 9;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {static_text_2.id, splitter_4.id, static_text_5.id,
generic_container_7.id, static_text_8.id};
static_text_2.role = ax::mojom::Role::kStaticText;
static_text_2.child_ids = {inline_box_3.id};
static_text_2.SetName("foo");
inline_box_3.role = ax::mojom::Role::kInlineTextBox;
inline_box_3.SetName("foo");
splitter_4.role = ax::mojom::Role::kSplitter;
splitter_4.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
static_text_5.role = ax::mojom::Role::kStaticText;
static_text_5.child_ids = {inline_box_6.id};
static_text_5.SetName("bar");
inline_box_6.role = ax::mojom::Role::kInlineTextBox;
inline_box_6.SetName("bar");
generic_container_7.role = ax::mojom::Role::kGenericContainer;
generic_container_7.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
static_text_8.role = ax::mojom::Role::kStaticText;
static_text_8.child_ids = {inline_box_9.id};
static_text_8.SetName("bar");
inline_box_9.role = ax::mojom::Role::kInlineTextBox;
inline_box_9.SetName("baz");
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes = {
root_1, static_text_2, inline_box_3, splitter_4,
static_text_5, inline_box_6, generic_container_7, static_text_8,
inline_box_9};
Init(update);
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider,
L"foo\n\xFFFC\nbar\n\xFFFC\nbaz");
int count;
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Paragraph, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"bar\n\xFFFC\nbaz");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_Start, TextUnit_Paragraph, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"baz");
}
// TODO(schectman) Segfault after test completes.
// Why? https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderInvalidCalls) {
// Test for when a text range provider is invalid. Because no ax tree is
// available, the anchor is invalid, so the text range provider fails the
// validate call.
{
Init(BuildTextDocument({}));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, GetRootAsAXNode());
DestroyTree();
ComPtr<ITextRangeProvider> text_range_provider_clone;
EXPECT_UIA_ELEMENTNOTAVAILABLE(
text_range_provider->Clone(&text_range_provider_clone));
BOOL compare_result;
EXPECT_UIA_ELEMENTNOTAVAILABLE(text_range_provider->Compare(
text_range_provider.Get(), &compare_result));
int compare_endpoints_result;
EXPECT_UIA_ELEMENTNOTAVAILABLE(text_range_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, text_range_provider.Get(),
TextPatternRangeEndpoint_Start, &compare_endpoints_result));
VARIANT attr_val;
V_VT(&attr_val) = VT_BOOL;
V_BOOL(&attr_val) = VARIANT_TRUE;
ComPtr<ITextRangeProvider> matched_range_provider;
EXPECT_UIA_ELEMENTNOTAVAILABLE(text_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, attr_val, true, &matched_range_provider));
EXPECT_UIA_ELEMENTNOTAVAILABLE(text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_Start, text_range_provider.Get(),
TextPatternRangeEndpoint_Start));
EXPECT_UIA_ELEMENTNOTAVAILABLE(text_range_provider->Select());
}
// Test for when this provider is valid, but the other provider is not an
// instance of AXPlatformNodeTextRangeProviderWin, so no operation can be
// performed on the other provider.
{
Init(BuildTextDocument({}));
ComPtr<ITextRangeProvider> this_provider;
GetTextRangeProviderFromTextNode(this_provider, GetRootAsAXNode());
ComPtr<ITextRangeProvider> other_provider_different_type;
MockAXPlatformNodeTextRangeProviderWin::CreateMockTextRangeProvider(
&other_provider_different_type);
BOOL compare_result;
EXPECT_UIA_INVALIDOPERATION(this_provider->Compare(
other_provider_different_type.Get(), &compare_result));
int compare_endpoints_result;
EXPECT_UIA_INVALIDOPERATION(this_provider->CompareEndpoints(
TextPatternRangeEndpoint_Start, other_provider_different_type.Get(),
TextPatternRangeEndpoint_Start, &compare_endpoints_result));
EXPECT_UIA_INVALIDOPERATION(this_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_Start, other_provider_different_type.Get(),
TextPatternRangeEndpoint_Start));
}
}
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderGetText) {
Init(BuildTextDocument({"some text", "more text"}));
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, text_node);
base::win::ScopedBstr text_content;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(-1, text_content.Receive()));
EXPECT_STREQ(text_content.Get(), L"some text");
text_content.Reset();
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(4, text_content.Receive()));
EXPECT_STREQ(text_content.Get(), L"some");
text_content.Reset();
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(0, text_content.Receive()));
EXPECT_STREQ(text_content.Get(), L"");
text_content.Reset();
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(9, text_content.Receive()));
EXPECT_STREQ(text_content.Get(), L"some text");
text_content.Reset();
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetText(10, text_content.Receive()));
EXPECT_STREQ(text_content.Get(), L"some text");
text_content.Reset();
EXPECT_HRESULT_FAILED(text_range_provider->GetText(-1, nullptr));
EXPECT_HRESULT_FAILED(
text_range_provider->GetText(-2, text_content.Receive()));
text_content.Reset();
ComPtr<ITextRangeProvider> document_textrange;
GetTextRangeProviderFromTextNode(document_textrange, root_node);
EXPECT_HRESULT_SUCCEEDED(
document_textrange->GetText(-1, text_content.Receive()));
EXPECT_STREQ(text_content.Get(), L"some textmore text");
text_content.Reset();
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderMoveCharacter) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// Moving by 0 should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character, /*count*/ 0,
/*expected_text*/
L"First line of text\nStandalone line\n"
L"bold textParagraph 1Paragraph 2",
/*expected_count*/ 0);
// Move forward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"i",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 18,
/*expected_text*/ L"S",
/*expected_count*/ 18);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 16,
/*expected_text*/ L"b",
/*expected_count*/ 16);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 60,
/*expected_text*/ L"2",
/*expected_count*/ 30);
// Trying to move past the last character should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"2",
/*expected_count*/ 0);
// Move backward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ -2,
/*expected_text*/ L"h",
/*expected_count*/ -2);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ -9,
/*expected_text*/ L"1",
/*expected_count*/ -9);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ -60,
/*expected_text*/ L"F",
/*expected_count*/ -54);
// Moving backward by any number of characters at the start of document
// should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ -1,
/*expected_text*/
L"F",
/*expected_count*/ 0);
// Degenerate range moves.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 4,
/*expected_text*/ L"",
/*expected_count*/ 4);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 62);
// Trying to move past the last character should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Character,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -2);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveFormat) {
Init(BuildAXTreeForMoveByFormat());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// Moving by 0 should have no effect.
EXPECT_UIA_MOVE(
text_range_provider, TextUnit_Format,
/*count*/ 0,
/*expected_text*/
L"Text with formatting\nStandalone line with no formatting\nbold "
L"text\nParagraph 1\nParagraph 2\nParagraph 3\nParagraph 4",
/*expected_count*/ 0);
// Move forward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"\nStandalone line with no formatting\n",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 2,
/*expected_text*/ L"Paragraph 1",
/*expected_count*/ 2);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"Paragraph 2\nParagraph 3",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"Paragraph 4",
/*expected_count*/ 1);
// Trying to move past the last format should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"Paragraph 4",
/*expected_count*/ 0);
// Move backward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ -3,
/*expected_text*/ L"bold text",
/*expected_count*/ -3);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"\nStandalone line with no formatting\n",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"Text with formatting",
/*expected_count*/ -1);
// Moving backward by any number of formats at the start of document
// should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ -1,
/*expected_text*/
L"Text with formatting",
/*expected_count*/ 0);
// Test degenerate range creation at the beginning of the document.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"Text with formatting",
/*expected_count*/ 1);
// Test degenerate range creation at the end of the document.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 5,
/*expected_text*/ L"Paragraph 4",
/*expected_count*/ 5);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"Paragraph 4",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Format,
/*count*/ 1,
/*expected_text*/ L"",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"Paragraph 4",
/*expected_count*/ -1);
// Degenerate range moves.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ -5,
/*expected_text*/ L"Text with formatting",
/*expected_count*/ -5);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 3,
/*expected_text*/ L"",
/*expected_count*/ 3);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 3);
// Trying to move past the last format should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Format,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -2);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveWord) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// Moving by 0 should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word, /*count*/ 0,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
// Move forward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 1,
/*expected_text*/ L"line ",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 2,
/*expected_text*/ L"text",
/*expected_count*/ 2);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 2,
/*expected_text*/ L"line",
/*expected_count*/ 2);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 3,
/*expected_text*/ L"Paragraph ",
/*expected_count*/ 3);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 6,
/*expected_text*/ L"2",
/*expected_count*/ 3);
// Trying to move past the last word should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 1,
/*expected_text*/ L"2",
/*expected_count*/ 0);
// Move backward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ -3,
/*expected_text*/ L"Paragraph ",
/*expected_count*/ -3);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ -3,
/*expected_text*/ L"line",
/*expected_count*/ -3);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ -2,
/*expected_text*/ L"text",
/*expected_count*/ -2);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ -6,
/*expected_text*/ L"First ",
/*expected_count*/ -3);
// Moving backward by any number of words at the start of document
// should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ -20,
/*expected_text*/ L"First ",
/*expected_count*/ 0);
// Degenerate range moves.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 4,
/*expected_text*/ L"",
/*expected_count*/ 4);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 8);
// Trying to move past the last word should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Word,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -2);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveLine) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// Moving by 0 should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line, /*count*/ 0,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
// Move forward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 2,
/*expected_text*/ L"Standalone line",
/*expected_count*/ 2);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 1,
/*expected_text*/ L"bold text",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 10,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ 2);
// Trying to move past the last line should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 1,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ 0);
// Move backward.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ -1,
/*expected_text*/ L"Paragraph 1",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ -5,
/*expected_text*/ L"First line of text",
/*expected_count*/ -4);
// Moving backward by any number of lines at the start of document
// should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ -20,
/*expected_text*/ L"First line of text",
/*expected_count*/ 0);
// Degenerate range moves.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 4,
/*expected_text*/ L"",
/*expected_count*/ 4);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 2);
// Trying to move past the last line should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Line,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -2);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveParagraph) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// Moving by 0 should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph, /*count*/ 0,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Paragraph,
/*count*/ -4,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ -4);
// The first line break does not create an empty paragraph because even though
// it is in a block element (i.e. a kGenericContainer) of its own which is a
// line breaking object, it merges with the previous paragraph. This is
// standard UIA behavior which merges any trailing whitespace with the
// previous paragraph.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ 1);
//
// Move forward.
//
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"Standalone line\n",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"bold text\n",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"Paragraph 1\n",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ 1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 2,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ 0);
// Trying to move past the last paragraph should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ 0);
//
// Move backward.
//
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"Paragraph 1\n",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"bold text\n",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"Standalone line\n",
/*expected_count*/ -1);
// The first line break creates an empty paragraph because it is in a block
// element (i.e. a kGenericContainer) of its own which is a line breaking
// object. It's like having a <br> element wrapped inside a <div>.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ 0);
// Moving backward by any number of paragraphs at the start of document
// should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ 0);
// Test degenerate range creation at the beginning of the document.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ 1);
// Test degenerate range creation at the end of the document.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 5,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ 4);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"Paragraph 2",
/*expected_count*/ -1);
//
// Degenerate range moves.
//
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -6,
/*expected_text*/ L"First line of text\n",
/*expected_count*/ -4);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Paragraph,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 3,
/*expected_text*/ L"",
/*expected_count*/ 3);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 2);
// Trying to move past the last paragraph should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ 70,
/*expected_text*/ L"",
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Paragraph,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -2);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveDocument) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// Moving by 0 should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Document, /*count*/ 0,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Document, /*count*/ -1,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Document, /*count*/ 2,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Page, /*count*/ 1,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Page, /*count*/ -1,
/*expected_text*/ tree_for_move_full_text.data(),
/*expected_count*/ 0);
// Degenerate range moves.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Document,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Page,
/*count*/ 4,
/*expected_text*/ L"",
/*expected_count*/ 1);
// Trying to move past the last character should have no effect.
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Document,
/*count*/ 1,
/*expected_text*/ L"",
/*expected_count*/ 0);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Page,
/*count*/ -2,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE(text_range_provider, TextUnit_Document,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ 0);
}
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderMove) {
Init(BuildAXTreeForMove());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
// TODO(https://crbug.com/928948): test intermixed unit types
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderMoveEndpointByDocument) {
Init(BuildTextDocument({"some text", "more text", "even more text"}));
AXNode* text_node = GetRootAsAXNode()->children()[1];
// Run the test twice, one for TextUnit_Document and once for TextUnit_Page,
// since they should have identical behavior.
const TextUnit textunit_types[] = {TextUnit_Document, TextUnit_Page};
ComPtr<ITextRangeProvider> text_range_provider;
for (auto& textunit : textunit_types) {
GetTextRangeProviderFromTextNode(text_range_provider, text_node);
// Verify MoveEndpointByUnit with zero count has no effect
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, textunit,
/*count*/ 0,
/*expected_text*/ L"more text",
/*expected_count*/ 0);
// Move the endpoint to the end of the document. Verify all text content.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, textunit,
/*count*/ 1,
/*expected_text*/ L"more texteven more text",
/*expected_count*/ 1);
// Verify no moves occur since the end is already at the end of the document
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, textunit,
/*count*/ 5,
/*expected_text*/ L"more texteven more text",
/*expected_count*/ 0);
// Move the end before the start
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, textunit,
/*count*/ -4,
/*expected_text*/ L"",
/*expected_count*/ -1);
// Move the end back to the end of the document. The text content
// should now include the entire document since end was previously
// moved before start.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, textunit,
/*count*/ 1,
/*expected_text*/ L"some textmore texteven more text",
/*expected_count*/ 1);
// Move the start point to the end
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_Start, textunit,
/*count*/ 3,
/*expected_text*/ L"",
/*expected_count*/ 1);
// Move the start point back to the beginning
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, textunit,
/*count*/ -3,
/*expected_text*/ L"some textmore texteven more text",
/*expected_count*/ -1);
}
}
// TODO(schectman) We are probably not accounting for multibyte characters
// properly yet. https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveEndpointByCharacterMultilingual) {
// The English string has three characters, each 8 bits in length.
const std::string english = "hey";
// The Hindi string has two characters, the first one 32 bits and the second
// 64 bits in length. It is formatted in UTF16.
const std::string hindi =
base::UTF16ToUTF8(u"\x0939\x093F\x0928\x094D\x0926\x0940");
// The Thai string has three characters, the first one 48, the second 32 and
// the last one 16 bits in length. It is formatted in UTF16.
const std::string thai =
base::UTF16ToUTF8(u"\x0E23\x0E39\x0E49\x0E2A\x0E36\x0E01");
Init(BuildTextDocument({english, hindi, thai}));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetRootAsAXNode()->children()[0]);
// Verify MoveEndpointByUnit with zero count has no effect
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"hey");
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 0,
/*expected_text*/ L"hey",
/*expected_count*/ 0);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"ey",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ -1,
/*expected_text*/ L"e",
/*expected_count*/ -1);
// Move end into the adjacent node.
//
// The first character of the second node is 32 bits in length.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 2,
/*expected_text*/ L"ey\x0939\x093F",
/*expected_count*/ 2);
// The second character of the second node is 64 bits in length.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"ey\x939\x93F\x928\x94D\x926\x940",
/*expected_count*/ 1);
// Move start into the adjacent node as well.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 2,
/*expected_text*/ L"\x939\x93F\x928\x94D\x926\x940",
/*expected_count*/ 2);
// Move end into the last node.
//
// The first character of the last node is 48 bits in length.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"\x939\x93F\x928\x94D\x926\x940\xE23\xE39\xE49",
/*expected_count*/ 1);
// Move end back into the second node and then into the last node again.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ -2,
/*expected_text*/ L"\x939\x93F",
/*expected_count*/ -2);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 3,
/*expected_text*/
L"\x939\x93F\x928\x94D\x926\x940\xE23\xE39\xE49\xE2A\xE36",
/*expected_count*/ 3);
// The last character of the last node is only 16 bits in length.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 1,
/*expected_text*/
L"\x939\x93F\x928\x94D\x926\x940\xE23\xE39\xE49\xE2A\xE36\xE01",
/*expected_count*/ 1);
// Move start into the last node.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 3,
/*expected_text*/ L"\x0E2A\x0E36\x0E01",
/*expected_count*/ 3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ -1,
/*expected_text*/ L"\x0E23\x0E39\x0E49\x0E2A\x0E36\x0E01",
/*expected_count*/ -1);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveEndpointByWord) {
Init(BuildTextDocument({"some text", "more text", "even more text"},
/*build_word_boundaries_offsets*/ true));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetRootAsAXNode()->children()[1]);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"more text");
// Moving with zero count does not alter the range.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ 0,
/*expected_text*/ L"more text",
/*expected_count*/ 0);
// Moving the start forward and backward.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ 1,
/*expected_text*/ L"text",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ -1,
/*expected_text*/ L"more text",
/*expected_count*/ -1);
// Moving the end backward and forward.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ -1,
/*expected_text*/ L"more ",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ 1,
/*expected_text*/ L"more text",
/*expected_count*/ 1);
// Moving the start past the end, then reverting.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ 3,
/*expected_text*/ L"",
/*expected_count*/ 3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ -3,
/*expected_text*/ L"more texteven ",
/*expected_count*/ -3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ -1,
/*expected_text*/ L"more text",
/*expected_count*/ -1);
// Moving the end past the start, then reverting.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ -3,
/*expected_text*/ L"",
/*expected_count*/ -3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ 3,
/*expected_text*/ L"textmore text",
/*expected_count*/ 3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ 1,
/*expected_text*/ L"more text",
/*expected_count*/ 1);
// Moving the endpoints further than both ends of the document.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ 5,
/*expected_text*/ L"more texteven more text",
/*expected_count*/ 3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ 6,
/*expected_text*/ L"",
/*expected_count*/ 5);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Word,
/*count*/ -8,
/*expected_text*/ L"some textmore texteven more text",
/*expected_count*/ -7);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Word,
/*count*/ -8,
/*expected_text*/ L"",
/*expected_count*/ -7);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveEndpointByLine) {
Init(BuildTextDocument({"0", "1", "2", "3", "4", "5", "6"}));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetRootAsAXNode()->children()[3]);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"3");
// Moving with zero count does not alter the range.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ 0,
/*expected_text*/ L"3",
/*expected_count*/ 0);
// Moving the start backward and forward.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ -2,
/*expected_text*/ L"123",
/*expected_count*/ -2);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ 1,
/*expected_text*/ L"23",
/*expected_count*/ 1);
// Moving the end forward and backward.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ 3,
/*expected_text*/ L"23456",
/*expected_count*/ 3);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ -2,
/*expected_text*/ L"234",
/*expected_count*/ -2);
// Moving the end past the start and vice versa.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ -4,
/*expected_text*/ L"",
/*expected_count*/ -4);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ -1,
/*expected_text*/ L"0",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ 6,
/*expected_text*/ L"",
/*expected_count*/ 6);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ -6,
/*expected_text*/ L"012345",
/*expected_count*/ -6);
// Moving the endpoints further than both ends of the document.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ -13,
/*expected_text*/ L"",
/*expected_count*/ -6);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(text_range_provider,
TextPatternRangeEndpoint_End, TextUnit_Line,
/*count*/ 11,
/*expected_text*/ L"0123456",
/*expected_count*/ 7);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ 9,
/*expected_text*/ L"",
/*expected_count*/ 7);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Line,
/*count*/ -7,
/*expected_text*/ L"0123456",
/*expected_count*/ -7);
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
// Verify that the endpoint can move past an empty text field.
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveEndpointByUnitTextField) {
// An empty text field should also be a character, word, and line boundary.
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
ui::AXNodeData group1_data;
group1_data.id = 2;
group1_data.role = ax::mojom::Role::kGenericContainer;
ui::AXNodeData text_data;
text_data.id = 3;
text_data.role = ax::mojom::Role::kStaticText;
std::string text_content = "some text";
text_data.SetName(text_content);
std::vector<int> word_start_offsets, word_end_offsets;
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
word_start_offsets);
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
word_end_offsets);
ui::AXNodeData text_input_data;
text_input_data.id = 4;
text_input_data.role = ax::mojom::Role::kTextField;
text_input_data.AddState(ax::mojom::State::kEditable);
text_input_data.AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag,
"input");
text_input_data.AddStringAttribute(ax::mojom::StringAttribute::kInputType,
"text");
ui::AXNodeData group2_data;
group2_data.id = 5;
group2_data.role = ax::mojom::Role::kGenericContainer;
ui::AXNodeData more_text_data;
more_text_data.id = 6;
more_text_data.role = ax::mojom::Role::kStaticText;
text_content = "more text";
more_text_data.SetName(text_content);
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
more_text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
word_start_offsets);
more_text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
word_end_offsets);
ui::AXNodeData empty_text_data;
empty_text_data.id = 7;
empty_text_data.role = ax::mojom::Role::kStaticText;
empty_text_data.AddState(ax::mojom::State::kEditable);
text_content = "";
empty_text_data.SetNameExplicitlyEmpty();
ComputeWordBoundariesOffsets(text_content, word_start_offsets,
word_end_offsets);
empty_text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
word_start_offsets);
empty_text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
word_end_offsets);
root_data.child_ids = {group1_data.id, text_input_data.id, group2_data.id};
group1_data.child_ids = {text_data.id};
text_input_data.child_ids = {empty_text_data.id};
group2_data.child_ids = {more_text_data.id};
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, group1_data, text_data, text_input_data,
group2_data, more_text_data, empty_text_data};
Init(update);
// Set up variables from the tree for testing.
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0]->children()[0];
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, text_node);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text");
int count;
// Tests for TextUnit_Character.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 2, &count));
ASSERT_EQ(2, count);
// Note that by design, empty objects such as empty text fields, are placed in
// their own paragraph for easier screen reader navigation.
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFc");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ 2, &count));
ASSERT_EQ(2, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFc\nm");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC\n");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -2, &count));
ASSERT_EQ(-2, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n");
// Tests for TextUnit_Word.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Word, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC\n");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Word, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC\nmore ");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Word, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC\n");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Word, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n");
// Tests for TextUnit_Line.
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ 1, &count));
ASSERT_EQ(1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC\nmore text");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text\n\xFFFC");
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -1, &count));
ASSERT_EQ(-1, count);
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"some text");
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderMoveEndpointByFormat) {
Init(BuildAXTreeForMoveByFormat());
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
EXPECT_UIA_TEXTRANGE_EQ(
text_range_provider,
L"Text with formatting\nStandalone line with no formatting\nbold "
L"text\nParagraph 1\nParagraph 2\nParagraph 3\nParagraph 4");
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -2,
/*expected_text*/
L"Text with formatting\nStandalone line with no formatting\nbold "
L"text\nParagraph 1",
/*expected_count*/ -2);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -1,
/*expected_text*/
L"Text with formatting\nStandalone line with no formatting\nbold text",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -1,
/*expected_text*/
L"Text with formatting\nStandalone line with no formatting\n",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"Text with formatting",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -1,
/*expected_text*/ L"",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ 7,
/*expected_text*/
L"Text with formatting\nStandalone line with no formatting\nbold "
L"text\nParagraph 1\nParagraph 2\nParagraph 3\nParagraph 4",
/*expected_count*/ 6);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Format,
/*count*/ -8,
/*expected_text*/ L"",
/*expected_count*/ -6);
}
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderCompare) {
Init(BuildTextDocument({"some text", "some text"}));
AXNode* root_node = GetRootAsAXNode();
// Get the textRangeProvider for the document,
// which contains text "some textsome text".
ComPtr<ITextRangeProvider> document_text_range_provider;
GetTextRangeProviderFromTextNode(document_text_range_provider, root_node);
// Get the textRangeProvider for the first text node.
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
root_node->children()[0]);
// Get the textRangeProvider for the second text node.
ComPtr<ITextRangeProvider> more_text_range_provider;
GetTextRangeProviderFromTextNode(more_text_range_provider,
root_node->children()[1]);
// Compare text range of the entire document with itself, which should return
// that they are equal.
BOOL result;
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->Compare(
document_text_range_provider.Get(), &result));
EXPECT_TRUE(result);
// Compare the text range of the entire document with one of its child, which
// should return that they are not equal.
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->Compare(
text_range_provider.Get(), &result));
EXPECT_FALSE(result);
// Compare the text range of text_node which contains "some text" with
// text range of more_text_node which also contains "some text". Those two
// text ranges should not equal, because their endpoints are different, even
// though their contents are the same.
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->Compare(more_text_range_provider.Get(), &result));
EXPECT_FALSE(result);
}
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderSelection) {
Init(BuildTextDocument({"some text"}));
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, GetRootAsAXNode());
ASSERT_UIA_INVALIDOPERATION(text_range_provider->AddToSelection());
ASSERT_UIA_INVALIDOPERATION(text_range_provider->RemoveFromSelection());
}
// TODO(schectman) Rectangles not implemented as in Chromium.
// https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderGetBoundingRectangles) {
ui::AXTreeUpdate update = BuildAXTreeForBoundingRectangles();
Init(update);
ComPtr<ITextRangeProvider> text_range_provider;
base::win::ScopedSafearray rectangles;
int units_moved;
// Expected bounding rects:
// <button>Button</button><input type="checkbox">Line 1<br>Line 2
// |---------------------||---------------------||----| |------|
GetTextRangeProviderFromTextNode(text_range_provider, GetRootAsAXNode());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetBoundingRectangles(rectangles.Receive()));
std::vector<double> expected_values = {20, 20, 200, 30, /* button */
20, 50, 200, 30, /* check box */
220, 20, 30, 30, /* line 1 */
220, 50, 42, 30 /* line 2 */};
EXPECT_UIA_SAFEARRAY_EQ(rectangles.Get(), expected_values);
rectangles.Reset();
// Move the text range end back by one character.
// Expected bounding rects:
// <button>Button</button><input type="checkbox">Line 1<br>Line 2
// |---------------------||---------------------||----| |----|
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Character, /*count*/ -1,
&units_moved));
ASSERT_EQ(-1, units_moved);
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetBoundingRectangles(rectangles.Receive()));
expected_values = {20, 20, 200, 30, /* button */
20, 50, 200, 30, /* check box */
220, 20, 30, 30, /* line 1 */
220, 50, 35, 30 /* line 2 */};
EXPECT_UIA_SAFEARRAY_EQ(rectangles.Get(), expected_values);
rectangles.Reset();
// Move the text range end back by one line.
// Expected bounding rects:
// <button>Button</button><input type="checkbox">Line 1<br>Line 2
// |---------------------||---------------------||--------|
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Line, /*count*/ -1, &units_moved));
ASSERT_EQ(-1, units_moved);
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetBoundingRectangles(rectangles.Receive()));
expected_values = {20, 20, 200, 30, /* button */
20, 50, 200, 30, /* check box */
220, 20, 30, 30 /* line 1 */};
EXPECT_UIA_SAFEARRAY_EQ(rectangles.Get(), expected_values);
rectangles.Reset();
// Move the text range end back by one line.
// Expected bounding rects:
// <button>Button</button><input type="checkbox">Line 1<br>Line 2
// |---------------------||---------------------|
ASSERT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByUnit(
TextPatternRangeEndpoint_End, TextUnit_Word, /*count*/ -3, &units_moved));
ASSERT_EQ(-3, units_moved);
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetBoundingRectangles(rectangles.Receive()));
expected_values = {20, 20, 200, 30, /* button */
20, 50, 200, 30 /* check box */};
EXPECT_UIA_SAFEARRAY_EQ(rectangles.Get(), expected_values);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderGetEnclosingElement) {
// Set up ax tree with the following structure:
//
// root
// |
// paragraph______________________________________________
// | | | | |
// static_text link link search input pdf_highlight
// | | | | |
// text_node static_text ul text_node static_text
// | | |
// text_node li text_node
// |
// static_text
// |
// text_node
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
ui::AXNodeData paragraph_data;
paragraph_data.id = 2;
paragraph_data.role = ax::mojom::Role::kParagraph;
root_data.child_ids.push_back(paragraph_data.id);
ui::AXNodeData static_text_data1;
static_text_data1.id = 3;
static_text_data1.role = ax::mojom::Role::kStaticText;
paragraph_data.child_ids.push_back(static_text_data1.id);
ui::AXNodeData inline_text_data1;
inline_text_data1.id = 4;
inline_text_data1.role = ax::mojom::Role::kInlineTextBox;
static_text_data1.child_ids.push_back(inline_text_data1.id);
ui::AXNodeData link_data;
link_data.id = 5;
link_data.role = ax::mojom::Role::kLink;
paragraph_data.child_ids.push_back(link_data.id);
ui::AXNodeData static_text_data2;
static_text_data2.id = 6;
static_text_data2.role = ax::mojom::Role::kStaticText;
link_data.child_ids.push_back(static_text_data2.id);
ui::AXNodeData inline_text_data2;
inline_text_data2.id = 7;
inline_text_data2.role = ax::mojom::Role::kInlineTextBox;
static_text_data2.child_ids.push_back(inline_text_data2.id);
ui::AXNodeData link_data2;
link_data2.id = 8;
link_data2.role = ax::mojom::Role::kLink;
paragraph_data.child_ids.push_back(link_data2.id);
ui::AXNodeData list_data;
list_data.id = 9;
list_data.role = ax::mojom::Role::kList;
link_data2.child_ids.push_back(list_data.id);
ui::AXNodeData list_item_data;
list_item_data.id = 10;
list_item_data.role = ax::mojom::Role::kListItem;
list_data.child_ids.push_back(list_item_data.id);
ui::AXNodeData static_text_data3;
static_text_data3.id = 11;
static_text_data3.role = ax::mojom::Role::kStaticText;
list_item_data.child_ids.push_back(static_text_data3.id);
ui::AXNodeData inline_text_data3;
inline_text_data3.id = 12;
inline_text_data3.role = ax::mojom::Role::kInlineTextBox;
static_text_data3.child_ids.push_back(inline_text_data3.id);
ui::AXNodeData search_box;
search_box.id = 13;
search_box.role = ax::mojom::Role::kSearchBox;
search_box.AddState(ax::mojom::State::kEditable);
search_box.AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag, "input");
search_box.AddStringAttribute(ax::mojom::StringAttribute::kInputType,
"search");
paragraph_data.child_ids.push_back(search_box.id);
ui::AXNodeData search_text;
search_text.id = 14;
search_text.role = ax::mojom::Role::kStaticText;
search_text.AddState(ax::mojom::State::kEditable);
search_text.SetName("placeholder");
search_box.child_ids.push_back(search_text.id);
ui::AXNodeData pdf_highlight_data;
pdf_highlight_data.id = 15;
pdf_highlight_data.role = ax::mojom::Role::kPdfActionableHighlight;
paragraph_data.child_ids.push_back(pdf_highlight_data.id);
ui::AXNodeData static_text_data4;
static_text_data4.id = 16;
static_text_data4.role = ax::mojom::Role::kStaticText;
pdf_highlight_data.child_ids.push_back(static_text_data4.id);
ui::AXNodeData inline_text_data4;
inline_text_data4.id = 17;
inline_text_data4.role = ax::mojom::Role::kInlineTextBox;
static_text_data4.child_ids.push_back(inline_text_data4.id);
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, paragraph_data, static_text_data1,
inline_text_data1, link_data, static_text_data2,
inline_text_data2, link_data2, list_data,
list_item_data, static_text_data3, inline_text_data3,
search_box, search_text, pdf_highlight_data,
static_text_data4, inline_text_data4};
Init(update);
// Set up variables from the tree for testing.
AXNode* paragraph_node = GetRootAsAXNode()->children()[0];
AXNode* static_text_node1 = paragraph_node->children()[0];
AXNode* link_node = paragraph_node->children()[1];
AXNode* inline_text_node1 = static_text_node1->children()[0];
AXNode* static_text_node2 = link_node->children()[0];
AXNode* inline_text_node2 = static_text_node2->children()[0];
AXNode* link_node2 = paragraph_node->children()[2];
AXNode* list_node = link_node2->children()[0];
AXNode* list_item_node = list_node->children()[0];
AXNode* static_text_node3 = list_item_node->children()[0];
AXNode* inline_text_node3 = static_text_node3->children()[0];
AXNode* search_box_node = paragraph_node->children()[3];
AXNode* search_text_node = search_box_node->children()[0];
AXNode* pdf_highlight_node = paragraph_node->children()[4];
AXNode* static_text_node4 = pdf_highlight_node->children()[0];
AXNode* inline_text_node4 = static_text_node4->children()[0];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(paragraph_node));
ASSERT_NE(owner, nullptr);
ComPtr<IRawElementProviderSimple> link_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(link_node);
ComPtr<IRawElementProviderSimple> static_text_node_raw1 =
QueryInterfaceFromNode<IRawElementProviderSimple>(static_text_node1);
ComPtr<IRawElementProviderSimple> static_text_node_raw2 =
QueryInterfaceFromNode<IRawElementProviderSimple>(static_text_node2);
ComPtr<IRawElementProviderSimple> static_text_node_raw3 =
QueryInterfaceFromNode<IRawElementProviderSimple>(static_text_node3);
ComPtr<IRawElementProviderSimple> inline_text_node_raw1 =
QueryInterfaceFromNode<IRawElementProviderSimple>(inline_text_node1);
ComPtr<IRawElementProviderSimple> inline_text_node_raw2 =
QueryInterfaceFromNode<IRawElementProviderSimple>(inline_text_node2);
ComPtr<IRawElementProviderSimple> inline_text_node_raw3 =
QueryInterfaceFromNode<IRawElementProviderSimple>(inline_text_node3);
ComPtr<IRawElementProviderSimple> search_box_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(search_box_node);
ComPtr<IRawElementProviderSimple> search_text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(search_text_node);
ComPtr<IRawElementProviderSimple> pdf_highlight_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(pdf_highlight_node);
ComPtr<IRawElementProviderSimple> inline_text_node_raw4 =
QueryInterfaceFromNode<IRawElementProviderSimple>(inline_text_node4);
// Test GetEnclosingElement for the two leaves text nodes. The enclosing
// element of the first one should be its static text parent (because inline
// text boxes shouldn't be exposed) and the enclosing element for the text
// node that is grandchild of the link node should return the link node.
// The text node in the link node with a complex subtree should behave
// normally and return the static text parent.
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(inline_text_node_raw1->GetPatternProvider(
UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
ComPtr<IRawElementProviderSimple> enclosing_element;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(inline_text_node_raw1.Get(), enclosing_element.Get());
EXPECT_HRESULT_SUCCEEDED(inline_text_node_raw2->GetPatternProvider(
UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(link_node_raw.Get(), enclosing_element.Get());
EXPECT_HRESULT_SUCCEEDED(inline_text_node_raw3->GetPatternProvider(
UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(inline_text_node_raw3.Get(), enclosing_element.Get());
// The enclosing element of a text range in the search text should give the
// search box
EXPECT_HRESULT_SUCCEEDED(search_text_node_raw->GetPatternProvider(
UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(search_box_node_raw.Get(), enclosing_element.Get());
// The enclosing element for the text node that is grandchild of the
// pdf_highlight node should return the pdf_highlight node.
EXPECT_HRESULT_SUCCEEDED(inline_text_node_raw4->GetPatternProvider(
UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(pdf_highlight_node_raw.Get(), enclosing_element.Get());
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderGetEnclosingElementRichButton) {
// Set up ax tree with the following structure:
//
// root
// ++button_1
// ++++static_text_1
// ++++++inline_text_1
// ++button_2
// ++++heading
// ++++++statix_text_2
// ++++++++inline_text_2
ui::AXNodeData root;
ui::AXNodeData button_1;
ui::AXNodeData static_text_1;
ui::AXNodeData inline_text_1;
ui::AXNodeData button_2;
ui::AXNodeData heading;
ui::AXNodeData static_text_2;
ui::AXNodeData inline_text_2;
root.id = 1;
button_1.id = 2;
static_text_1.id = 3;
inline_text_1.id = 4;
button_2.id = 5;
heading.id = 6;
static_text_2.id = 7;
inline_text_2.id = 8;
root.role = ax::mojom::Role::kRootWebArea;
root.child_ids = {button_1.id, button_2.id};
button_1.role = ax::mojom::Role::kButton;
button_1.child_ids.push_back(static_text_1.id);
static_text_1.role = ax::mojom::Role::kStaticText;
static_text_1.child_ids.push_back(inline_text_1.id);
inline_text_1.role = ax::mojom::Role::kInlineTextBox;
button_2.role = ax::mojom::Role::kButton;
button_2.child_ids.push_back(heading.id);
heading.role = ax::mojom::Role::kHeading;
heading.child_ids.push_back(static_text_2.id);
static_text_2.role = ax::mojom::Role::kStaticText;
static_text_2.child_ids.push_back(inline_text_2.id);
inline_text_2.role = ax::mojom::Role::kInlineTextBox;
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root.id;
update.nodes = {root, button_1, static_text_1, inline_text_1,
button_2, heading, static_text_2, inline_text_2};
Init(update);
// Set up variables from the tree for testing.
AXNode* button_1_node = GetRootAsAXNode()->children()[0];
AXNode* static_text_1_node = button_1_node->children()[0];
AXNode* inline_text_1_node = static_text_1_node->children()[0];
AXNode* button_2_node = GetRootAsAXNode()->children()[1];
AXNode* heading_node = button_2_node->children()[0];
AXNode* static_text_2_node = heading_node->children()[0];
AXNode* inline_text_2_node = static_text_2_node->children()[0];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(button_1_node));
ASSERT_NE(owner, nullptr);
ComPtr<IRawElementProviderSimple> button_1_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(button_1_node);
ComPtr<IRawElementProviderSimple> inline_text_1_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(inline_text_1_node);
ComPtr<IRawElementProviderSimple> button_2_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(button_2_node);
ComPtr<IRawElementProviderSimple> static_text_2_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(static_text_2_node);
ComPtr<IRawElementProviderSimple> inline_text_2_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(inline_text_2_node);
// 1. The first button should hide its children since it contains a single
// text node. Thus, calling GetEnclosingElement on a descendant inline text
// box should return the button itself.
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(inline_text_1_node_raw->GetPatternProvider(
UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
ComPtr<IRawElementProviderSimple> enclosing_element;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(button_1_node_raw.Get(), enclosing_element.Get());
// 2. The second button shouldn't hide its children since it doesn't contain a
// single text node (it contains a heading node). Thus, calling
// GetEnclosingElement on a descendant inline text box should return the
// parent node.
EXPECT_HRESULT_SUCCEEDED(inline_text_2_node_raw->GetPatternProvider(
UIA_TextPatternId, &text_provider));
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->GetEnclosingElement(&enclosing_element));
EXPECT_EQ(button_2_node_raw.Get(), enclosing_element.Get());
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderMoveEndpointByRange) {
Init(BuildTextDocument({"some text", "more text"}));
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
AXNode* more_text_node = root_node->children()[1];
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
ASSERT_NE(owner, nullptr);
// Text range for the document, which contains text "some textmore text".
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<ITextProvider> document_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &document_provider));
ComPtr<ITextRangeProvider> document_text_range_provider;
ComPtr<AXPlatformNodeTextRangeProviderWin> document_text_range;
// Text range related to "some text".
ComPtr<IRawElementProviderSimple> text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(text_node);
ComPtr<ITextProvider> text_provider;
EXPECT_HRESULT_SUCCEEDED(
text_node_raw->GetPatternProvider(UIA_TextPatternId, &text_provider));
ComPtr<ITextRangeProvider> text_range_provider;
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range;
// Text range related to "more text".
ComPtr<IRawElementProviderSimple> more_text_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(more_text_node);
ComPtr<ITextProvider> more_text_provider;
EXPECT_HRESULT_SUCCEEDED(more_text_node_raw->GetPatternProvider(
UIA_TextPatternId, &more_text_provider));
ComPtr<ITextRangeProvider> more_text_range_provider;
ComPtr<AXPlatformNodeTextRangeProviderWin> more_text_range;
// Move the start of document text range "some textmore text" to the end of
// itself.
// The start of document text range "some textmore text" is at the end of
// itself.
//
// Before:
// |s e|
// "some textmore text"
// After:
// |s
// e|
// "some textmore text"
// Get the textRangeProvider for the document, which contains text
// "some textmore text".
EXPECT_HRESULT_SUCCEEDED(
document_provider->get_DocumentRange(&document_text_range_provider));
SetOwner(owner, document_text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_Start, document_text_range_provider.Get(),
TextPatternRangeEndpoint_End));
document_text_range_provider->QueryInterface(
IID_PPV_ARGS(&document_text_range));
EXPECT_EQ(*GetStart(document_text_range.Get()),
*GetEnd(document_text_range.Get()));
// Move the end of document text range "some textmore text" to the start of
// itself.
// The end of document text range "some textmore text" is at the start of
// itself.
//
// Before:
// |s e|
// "some textmore text"
// After:
// |s
// e|
// "some textmore text"
// Get the textRangeProvider for the document, which contains text
// "some textmore text".
EXPECT_HRESULT_SUCCEEDED(
document_provider->get_DocumentRange(&document_text_range_provider));
SetOwner(owner, document_text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_Start, document_text_range_provider.Get(),
TextPatternRangeEndpoint_End));
document_text_range_provider->QueryInterface(
IID_PPV_ARGS(&document_text_range));
EXPECT_EQ(*GetStart(document_text_range.Get()),
*GetEnd(document_text_range.Get()));
// Move the start of document text range "some textmore text" to the start
// of text range "more text". The start of document text range "some
// textmore text" is at the start of text range "more text". The end of
// document range does not change.
//
// Before:
// |s e|
// "some textmore text"
// After:
// |s e|
// "some textmore text"
// Get the textRangeProvider for the document, which contains text
// "some textmore text".
EXPECT_HRESULT_SUCCEEDED(
document_provider->get_DocumentRange(&document_text_range_provider));
SetOwner(owner, document_text_range_provider.Get());
// Get the textRangeProvider for more_text_node which contains "more text".
EXPECT_HRESULT_SUCCEEDED(
more_text_provider->get_DocumentRange(&more_text_range_provider));
SetOwner(owner, more_text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_Start, more_text_range_provider.Get(),
TextPatternRangeEndpoint_Start));
document_text_range_provider->QueryInterface(
IID_PPV_ARGS(&document_text_range));
more_text_range_provider->QueryInterface(IID_PPV_ARGS(&more_text_range));
EXPECT_EQ(*GetStart(document_text_range.Get()),
*GetStart(more_text_range.Get()));
// Move the end of document text range "some textmore text" to the end of
// text range "some text".
// The end of document text range "some textmore text" is at the end of text
// range "some text". The start of document range does not change.
//
// Before:
// |s e|
// "some textmore text"
// After:
// |s e|
// "some textmore text"
// Get the textRangeProvider for the document, which contains text
// "some textmore text".
EXPECT_HRESULT_SUCCEEDED(
document_provider->get_DocumentRange(&document_text_range_provider));
SetOwner(owner, document_text_range_provider.Get());
// Get the textRangeProvider for text_node which contains "some text".
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(document_text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_End, text_range_provider.Get(),
TextPatternRangeEndpoint_End));
document_text_range_provider->QueryInterface(
IID_PPV_ARGS(&document_text_range));
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range));
EXPECT_EQ(*GetEnd(document_text_range.Get()), *GetEnd(text_range.Get()));
// Move the end of text range "more text" to the start of
// text range "some text". Since the order of the endpoints being moved
// (those of "more text") have to be ensured, both endpoints of "more text"
// is at the start of "some text".
//
// Before:
// |s e|
// "some textmore text"
// After:
// e|
// |s
// "some textmore text"
// Get the textRangeProvider for text_node which contains "some text".
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, document_text_range_provider.Get());
// Get the textRangeProvider for more_text_node which contains "more text".
EXPECT_HRESULT_SUCCEEDED(
more_text_provider->get_DocumentRange(&more_text_range_provider));
SetOwner(owner, more_text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(more_text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_End, text_range_provider.Get(),
TextPatternRangeEndpoint_Start));
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range));
more_text_range_provider->QueryInterface(IID_PPV_ARGS(&more_text_range));
EXPECT_EQ(*GetEnd(more_text_range.Get()), *GetStart(text_range.Get()));
EXPECT_EQ(*GetStart(more_text_range.Get()), *GetStart(text_range.Get()));
// Move the start of text range "some text" to the end of text range
// "more text". Since the order of the endpoints being moved (those
// of "some text") have to be ensured, both endpoints of "some text" is at
// the end of "more text".
//
// Before:
// |s e|
// "some textmore text"
// After:
// |s
// e|
// "some textmore text"
// Get the textRangeProvider for text_node which contains "some text".
EXPECT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
SetOwner(owner, text_range_provider.Get());
// Get the textRangeProvider for more_text_node which contains "more text".
EXPECT_HRESULT_SUCCEEDED(
more_text_provider->get_DocumentRange(&more_text_range_provider));
SetOwner(owner, more_text_range_provider.Get());
EXPECT_HRESULT_SUCCEEDED(text_range_provider->MoveEndpointByRange(
TextPatternRangeEndpoint_Start, more_text_range_provider.Get(),
TextPatternRangeEndpoint_End));
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range));
more_text_range_provider->QueryInterface(IID_PPV_ARGS(&more_text_range));
EXPECT_EQ(*GetStart(text_range.Get()), *GetEnd(more_text_range.Get()));
EXPECT_EQ(*GetEnd(text_range.Get()), *GetEnd(more_text_range.Get()));
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderGetAttributeValue) {
ui::AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.AddStringAttribute(ax::mojom::StringAttribute::kFontFamily, "sans");
text_data.AddFloatAttribute(ax::mojom::FloatAttribute::kFontSize, 16);
text_data.AddFloatAttribute(ax::mojom::FloatAttribute::kFontWeight, 300);
text_data.AddIntAttribute(ax::mojom::IntAttribute::kTextOverlineStyle, 1);
text_data.AddIntAttribute(ax::mojom::IntAttribute::kTextStrikethroughStyle,
2);
text_data.AddIntAttribute(ax::mojom::IntAttribute::kTextUnderlineStyle, 3);
text_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
text_data.AddStringAttribute(ax::mojom::StringAttribute::kLanguage, "fr-CA");
text_data.SetTextDirection(ax::mojom::WritingDirection::kRtl);
text_data.AddTextStyle(ax::mojom::TextStyle::kItalic);
text_data.SetTextPosition(ax::mojom::TextPosition::kSubscript);
text_data.SetRestriction(ax::mojom::Restriction::kReadOnly);
text_data.SetTextAlign(ax::mojom::TextAlign::kCenter);
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kMarkerTypes,
{(int)ax::mojom::MarkerType::kGrammar,
(int)ax::mojom::MarkerType::kSpelling});
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kMarkerStarts,
{0, 5, 0, 14, 19});
text_data.AddIntListAttribute(ax::mojom::IntListAttribute::kMarkerEnds,
{9, 9, 4, 18, 24});
text_data.SetName("some text and some other text");
ui::AXNodeData heading_data;
heading_data.id = 3;
heading_data.role = ax::mojom::Role::kHeading;
heading_data.AddIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel, 6);
heading_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
heading_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
heading_data.SetTextDirection(ax::mojom::WritingDirection::kRtl);
heading_data.SetTextPosition(ax::mojom::TextPosition::kSuperscript);
heading_data.AddState(ax::mojom::State::kEditable);
heading_data.child_ids = {4};
ui::AXNodeData heading_text_data;
heading_text_data.id = 4;
heading_text_data.role = ax::mojom::Role::kStaticText;
heading_text_data.AddState(ax::mojom::State::kInvisible);
heading_text_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
heading_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor,
0xFFADC0DEU);
heading_text_data.SetTextDirection(ax::mojom::WritingDirection::kRtl);
heading_text_data.SetTextPosition(ax::mojom::TextPosition::kSuperscript);
heading_text_data.AddState(ax::mojom::State::kEditable);
heading_text_data.SetTextAlign(ax::mojom::TextAlign::kJustify);
heading_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerTypes,
{(int)ax::mojom::MarkerType::kSpelling});
heading_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerStarts, {5});
heading_text_data.AddIntListAttribute(
ax::mojom::IntListAttribute::kMarkerEnds, {9});
heading_text_data.SetName("more text");
ui::AXNodeData mark_data;
mark_data.id = 5;
mark_data.role = ax::mojom::Role::kMark;
mark_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
mark_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
mark_data.SetTextDirection(ax::mojom::WritingDirection::kRtl);
mark_data.child_ids = {6};
ui::AXNodeData mark_text_data;
mark_text_data.id = 6;
mark_text_data.role = ax::mojom::Role::kStaticText;
mark_text_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
mark_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
mark_text_data.SetTextDirection(ax::mojom::WritingDirection::kRtl);
mark_text_data.SetTextAlign(ax::mojom::TextAlign::kNone);
mark_text_data.SetName("marked text");
ui::AXNodeData list_data;
list_data.id = 7;
list_data.role = ax::mojom::Role::kList;
list_data.child_ids = {8, 10};
list_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
list_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
ui::AXNodeData list_item_data;
list_item_data.id = 8;
list_item_data.role = ax::mojom::Role::kListItem;
list_item_data.child_ids = {9};
list_item_data.AddIntAttribute(
ax::mojom::IntAttribute::kListStyle,
static_cast<int>(ax::mojom::ListStyle::kOther));
list_item_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
list_item_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
ui::AXNodeData list_item_text_data;
list_item_text_data.id = 9;
list_item_text_data.role = ax::mojom::Role::kStaticText;
list_item_text_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
list_item_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor,
0xFFADC0DEU);
list_item_text_data.SetName("list item");
ui::AXNodeData list_item2_data;
list_item2_data.id = 10;
list_item2_data.role = ax::mojom::Role::kListItem;
list_item2_data.child_ids = {11};
list_item2_data.AddIntAttribute(
ax::mojom::IntAttribute::kListStyle,
static_cast<int>(ax::mojom::ListStyle::kDisc));
list_item2_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
list_item2_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
ui::AXNodeData list_item2_text_data;
list_item2_text_data.id = 11;
list_item2_text_data.role = ax::mojom::Role::kStaticText;
list_item2_text_data.AddIntAttribute(
ax::mojom::IntAttribute::kBackgroundColor, 0xFFADBEEFU);
list_item2_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor,
0xFFADC0DEU);
list_item2_text_data.SetName("list item 2");
ui::AXNodeData input_text_data;
input_text_data.id = 12;
input_text_data.role = ax::mojom::Role::kTextField;
input_text_data.AddState(ax::mojom::State::kEditable);
input_text_data.AddIntAttribute(
ax::mojom::IntAttribute::kNameFrom,
static_cast<int>(ax::mojom::NameFrom::kPlaceholder));
input_text_data.AddStringAttribute(ax::mojom::StringAttribute::kPlaceholder,
"placeholder2");
input_text_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
input_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
input_text_data.AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag,
"input");
input_text_data.AddStringAttribute(ax::mojom::StringAttribute::kInputType,
"text");
input_text_data.SetName("placeholder");
input_text_data.child_ids = {13};
ui::AXNodeData placeholder_text_data;
placeholder_text_data.id = 13;
placeholder_text_data.role = ax::mojom::Role::kStaticText;
placeholder_text_data.AddIntAttribute(
ax::mojom::IntAttribute::kBackgroundColor, 0xFFADBEEFU);
placeholder_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor,
0xFFADC0DEU);
placeholder_text_data.SetName("placeholder");
ui::AXNodeData input_text_data2;
input_text_data2.id = 14;
input_text_data2.role = ax::mojom::Role::kTextField;
input_text_data2.AddState(ax::mojom::State::kEditable);
input_text_data2.SetRestriction(ax::mojom::Restriction::kDisabled);
input_text_data2.AddStringAttribute(ax::mojom::StringAttribute::kPlaceholder,
"placeholder2");
input_text_data2.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
input_text_data2.AddIntAttribute(ax::mojom::IntAttribute::kColor,
0xFFADC0DEU);
input_text_data2.AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag,
"input");
input_text_data2.AddStringAttribute(ax::mojom::StringAttribute::kInputType,
"text");
input_text_data2.SetName("foo");
input_text_data2.child_ids = {15};
ui::AXNodeData placeholder_text_data2;
placeholder_text_data2.id = 15;
placeholder_text_data2.role = ax::mojom::Role::kStaticText;
placeholder_text_data2.AddIntAttribute(
ax::mojom::IntAttribute::kBackgroundColor, 0xFFADBEEFU);
placeholder_text_data2.AddIntAttribute(ax::mojom::IntAttribute::kColor,
0xFFADC0DEU);
placeholder_text_data2.SetName("placeholder2");
ui::AXNodeData link_data;
link_data.id = 16;
link_data.role = ax::mojom::Role::kLink;
link_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
link_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
ui::AXNodeData link_text_data;
link_text_data.id = 17;
link_text_data.role = ax::mojom::Role::kStaticText;
link_text_data.AddIntAttribute(ax::mojom::IntAttribute::kBackgroundColor,
0xFFADBEEFU);
link_text_data.AddIntAttribute(ax::mojom::IntAttribute::kColor, 0xFFADC0DEU);
link_data.child_ids = {17};
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {2, 3, 5, 7, 12, 14, 16};
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data);
update.nodes.push_back(heading_data);
update.nodes.push_back(heading_text_data);
update.nodes.push_back(mark_data);
update.nodes.push_back(mark_text_data);
update.nodes.push_back(list_data);
update.nodes.push_back(list_item_data);
update.nodes.push_back(list_item_text_data);
update.nodes.push_back(list_item2_data);
update.nodes.push_back(list_item2_text_data);
update.nodes.push_back(input_text_data);
update.nodes.push_back(placeholder_text_data);
update.nodes.push_back(input_text_data2);
update.nodes.push_back(placeholder_text_data2);
update.nodes.push_back(link_data);
update.nodes.push_back(link_text_data);
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* text_node = root_node->children()[0];
AXNode* heading_node = root_node->children()[1];
AXNode* heading_text_node = heading_node->children()[0];
AXNode* mark_node = root_node->children()[2];
AXNode* mark_text_node = mark_node->children()[0];
AXNode* list_node = root_node->children()[3];
AXNode* list_item_node = list_node->children()[0];
AXNode* list_item_text_node = list_item_node->children()[0];
AXNode* list_item2_node = list_node->children()[1];
AXNode* list_item2_text_node = list_item2_node->children()[0];
AXNode* input_text_node = root_node->children()[4];
AXNode* placeholder_text_node = input_text_node->children()[0];
AXNode* input_text_node2 = root_node->children()[5];
AXNode* placeholder_text_node2 = input_text_node2->children()[0];
AXNode* link_node = root_node->children()[6];
AXNode* link_text_node = link_node->children()[0];
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider, root_node);
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, text_node);
ComPtr<ITextRangeProvider> heading_text_range_provider;
GetTextRangeProviderFromTextNode(heading_text_range_provider,
heading_text_node);
ComPtr<ITextRangeProvider> mark_text_range_provider;
GetTextRangeProviderFromTextNode(mark_text_range_provider, mark_text_node);
ComPtr<ITextRangeProvider> list_item_text_range_provider;
GetTextRangeProviderFromTextNode(list_item_text_range_provider,
list_item_text_node);
ComPtr<ITextRangeProvider> list_item2_text_range_provider;
GetTextRangeProviderFromTextNode(list_item2_text_range_provider,
list_item2_text_node);
ComPtr<ITextRangeProvider> placeholder_text_range_provider;
GetTextRangeProviderFromTextNode(placeholder_text_range_provider,
placeholder_text_node);
ComPtr<ITextRangeProvider> placeholder_text_range_provider2;
GetTextRangeProviderFromTextNode(placeholder_text_range_provider2,
placeholder_text_node2);
ComPtr<ITextRangeProvider> link_text_range_provider;
GetTextRangeProviderFromTextNode(link_text_range_provider, link_text_node);
base::win::ScopedVariant expected_variant;
// SkColor is ARGB, COLORREF is 0BGR
expected_variant.Set(static_cast<int32_t>(0x00EFBEADU));
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider,
UIA_BackgroundColorAttributeId, expected_variant);
// Important: all nodes need to have the kColor and kBackgroundColor attribute
// set for this test, otherwise the following assert will fail.
EXPECT_UIA_TEXTATTRIBUTE_EQ(document_range_provider,
UIA_BackgroundColorAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(static_cast<int32_t>(BulletStyle::BulletStyle_None));
EXPECT_UIA_TEXTATTRIBUTE_EQ(list_item_text_range_provider,
UIA_BulletStyleAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(
static_cast<int32_t>(BulletStyle::BulletStyle_FilledRoundBullet));
EXPECT_UIA_TEXTATTRIBUTE_EQ(list_item2_text_range_provider,
UIA_BulletStyleAttributeId, expected_variant);
expected_variant.Reset();
{
base::win::ScopedVariant lang_variant;
EXPECT_HRESULT_SUCCEEDED(text_range_provider->GetAttributeValue(
UIA_CultureAttributeId, lang_variant.Receive()));
EXPECT_EQ(lang_variant.type(), VT_I4);
const LCID lcid = V_I4(lang_variant.ptr());
EXPECT_EQ(LANG_FRENCH, PRIMARYLANGID(lcid));
EXPECT_EQ(SUBLANG_FRENCH_CANADIAN, SUBLANGID(lcid));
EXPECT_EQ(SORT_DEFAULT, SORTIDFROMLCID(lcid));
}
std::wstring font_name = L"sans";
expected_variant.Set(SysAllocString(font_name.c_str()));
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_FontNameAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(12.0);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_FontSizeAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(300);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_FontWeightAttributeId,
expected_variant);
expected_variant.Reset();
// SkColor is ARGB, COLORREF is 0BGR
expected_variant.Set(static_cast<int32_t>(0x00DEC0ADU));
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider,
UIA_ForegroundColorAttributeId, expected_variant);
EXPECT_UIA_TEXTATTRIBUTE_EQ(document_range_provider,
UIA_ForegroundColorAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_IsHiddenAttributeId,
expected_variant);
expected_variant.Reset();
EXPECT_UIA_TEXTATTRIBUTE_MIXED(document_range_provider,
UIA_IsHiddenAttributeId);
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_IsItalicAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(heading_text_range_provider,
UIA_IsItalicAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_IsReadOnlyAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(heading_text_range_provider,
UIA_IsReadOnlyAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(placeholder_text_range_provider,
UIA_IsReadOnlyAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(placeholder_text_range_provider2,
UIA_IsReadOnlyAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(link_text_range_provider,
UIA_IsReadOnlyAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(HorizontalTextAlignment_Centered);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider,
UIA_HorizontalTextAlignmentAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(HorizontalTextAlignment_Justified);
EXPECT_UIA_TEXTATTRIBUTE_EQ(heading_text_range_provider,
UIA_HorizontalTextAlignmentAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_IsSubscriptAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(heading_text_range_provider,
UIA_IsSubscriptAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_IsSuperscriptAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(heading_text_range_provider,
UIA_IsSuperscriptAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(TextDecorationLineStyle::TextDecorationLineStyle_Dot);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_OverlineStyleAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(TextDecorationLineStyle::TextDecorationLineStyle_Dash);
EXPECT_UIA_TEXTATTRIBUTE_EQ(
text_range_provider, UIA_StrikethroughStyleAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(TextDecorationLineStyle::TextDecorationLineStyle_Single);
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider,
UIA_UnderlineStyleAttributeId, expected_variant);
expected_variant.Reset();
std::wstring style_name;
expected_variant.Set(SysAllocString(style_name.c_str()));
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider, UIA_StyleNameAttributeId,
expected_variant);
expected_variant.Reset();
expected_variant.Set(static_cast<int32_t>(StyleId_Heading6));
EXPECT_UIA_TEXTATTRIBUTE_EQ(heading_text_range_provider,
UIA_StyleIdAttributeId, expected_variant);
expected_variant.Reset();
style_name = L"mark";
expected_variant.Set(SysAllocString(style_name.c_str()));
EXPECT_UIA_TEXTATTRIBUTE_EQ(mark_text_range_provider,
UIA_StyleNameAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(static_cast<int32_t>(StyleId_NumberedList));
EXPECT_UIA_TEXTATTRIBUTE_EQ(list_item_text_range_provider,
UIA_StyleIdAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(static_cast<int32_t>(StyleId_BulletedList));
EXPECT_UIA_TEXTATTRIBUTE_EQ(list_item2_text_range_provider,
UIA_StyleIdAttributeId, expected_variant);
expected_variant.Reset();
expected_variant.Set(
static_cast<int32_t>(FlowDirections::FlowDirections_RightToLeft));
EXPECT_UIA_TEXTATTRIBUTE_EQ(
text_range_provider, UIA_TextFlowDirectionsAttributeId, expected_variant);
EXPECT_UIA_TEXTATTRIBUTE_MIXED(document_range_provider,
UIA_TextFlowDirectionsAttributeId);
expected_variant.Reset();
// Move the start endpoint back and forth one character to force such endpoint
// to be located at the end of the previous anchor, this shouldn't cause
// GetAttributeValue to include the previous anchor's attributes.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(mark_text_range_provider,
TextPatternRangeEndpoint_Start,
TextUnit_Character,
/*count*/ -1,
/*expected_text*/ L"tmarked text",
/*expected_count*/ -1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(mark_text_range_provider,
TextPatternRangeEndpoint_Start,
TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"marked text",
/*expected_count*/ 1);
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(mark_text_range_provider,
UIA_IsSuperscriptAttributeId, expected_variant);
expected_variant.Reset();
// Same idea as above, but moving forth and back the end endpoint to force it
// to be located at the start of the next anchor.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(mark_text_range_provider,
TextPatternRangeEndpoint_End,
TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"marked textl",
/*expected_count*/ 1);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(mark_text_range_provider,
TextPatternRangeEndpoint_End,
TextUnit_Character,
/*count*/ -1,
/*expected_text*/ L"marked text",
/*expected_count*/ -1);
expected_variant.Set(
static_cast<int32_t>(FlowDirections::FlowDirections_RightToLeft));
EXPECT_UIA_TEXTATTRIBUTE_EQ(mark_text_range_provider,
UIA_TextFlowDirectionsAttributeId,
expected_variant);
expected_variant.Reset();
{
// |text_node| has a grammar error on "some text", a highlight for the
// first word, a spelling error for the second word, a "spelling-error"
// highlight for the fourth word, and a "grammar-error" highlight for the
// fifth word. So the range has mixed annotations.
EXPECT_UIA_TEXTATTRIBUTE_MIXED(text_range_provider,
UIA_AnnotationTypesAttributeId);
// Testing annotations in range [5,9)
// start: TextPosition, anchor_id=2, text_offset=5,
// annotated_text=some <t>ext and some other text
// end : TextPosition, anchor_id=2, text_offset=9,
// annotated_text=some text<> and some other text
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(text_node));
ComPtr<AXPlatformNodeTextRangeProviderWin> range_with_annotations;
CreateTextRangeProviderWin(
range_with_annotations, owner,
/*start_anchor=*/text_node, /*start_offset=*/5,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/text_node, /*end_offset=*/9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
base::win::ScopedVariant annotation_types_variant;
EXPECT_HRESULT_SUCCEEDED(range_with_annotations->GetAttributeValue(
UIA_AnnotationTypesAttributeId, annotation_types_variant.Receive()));
EXPECT_EQ(annotation_types_variant.type(), VT_ARRAY | VT_I4);
std::vector<int> expected_annotations = {AnnotationType_SpellingError,
AnnotationType_GrammarError};
EXPECT_UIA_SAFEARRAY_EQ(V_ARRAY(annotation_types_variant.ptr()),
expected_annotations);
}
{
// Testing annotations in range [0,4)
// start: TextPosition, anchor_id=2, text_offset=0,
// annotated_text=<s>ome text and some other text
// end : TextPosition, anchor_id=2, text_offset=4,
// annotated_text=some<> text and some other text
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(text_node));
ComPtr<AXPlatformNodeTextRangeProviderWin> range_with_annotations;
CreateTextRangeProviderWin(
range_with_annotations, owner,
/*start_anchor=*/text_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/text_node, /*end_offset=*/4,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
base::win::ScopedVariant annotation_types_variant;
EXPECT_HRESULT_SUCCEEDED(range_with_annotations->GetAttributeValue(
UIA_AnnotationTypesAttributeId, annotation_types_variant.Receive()));
EXPECT_EQ(annotation_types_variant.type(), VT_ARRAY | VT_I4);
std::vector<int> expected_annotations = {AnnotationType_GrammarError,
AnnotationType_Highlighted};
EXPECT_UIA_SAFEARRAY_EQ(V_ARRAY(annotation_types_variant.ptr()),
expected_annotations);
}
{
// Testing annotations in range [14,18)
// start: TextPosition, anchor_id=2, text_offset=14,
// annotated_text=some text and <s>ome other text
// end : TextPosition, anchor_id=2, text_offset=18,
// annotated_text=some text and some<> other text
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(text_node));
ComPtr<AXPlatformNodeTextRangeProviderWin> range_with_annotations;
CreateTextRangeProviderWin(
range_with_annotations, owner,
/*start_anchor=*/text_node, /*start_offset=*/14,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/text_node, /*end_offset=*/18,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
base::win::ScopedVariant annotation_types_variant;
EXPECT_HRESULT_SUCCEEDED(range_with_annotations->GetAttributeValue(
UIA_AnnotationTypesAttributeId, annotation_types_variant.Receive()));
EXPECT_EQ(annotation_types_variant.type(), VT_ARRAY | VT_I4);
std::vector<int> expected_annotations = {AnnotationType_SpellingError};
EXPECT_UIA_SAFEARRAY_EQ(V_ARRAY(annotation_types_variant.ptr()),
expected_annotations);
}
{
// Testing annotations in range [19,24)
// start: TextPosition, anchor_id=2, text_offset=19,
// annotated_text=some text and some <o>ther text
// end : TextPosition, anchor_id=2, text_offset=24,
// annotated_text=some text and some other<> text
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(text_node));
ComPtr<AXPlatformNodeTextRangeProviderWin> range_with_annotations;
CreateTextRangeProviderWin(
range_with_annotations, owner,
/*start_anchor=*/text_node, /*start_offset=*/19,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/text_node, /*end_offset=*/24,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
base::win::ScopedVariant annotation_types_variant;
EXPECT_HRESULT_SUCCEEDED(range_with_annotations->GetAttributeValue(
UIA_AnnotationTypesAttributeId, annotation_types_variant.Receive()));
EXPECT_EQ(annotation_types_variant.type(), VT_ARRAY | VT_I4);
std::vector<int> expected_annotations = {AnnotationType_GrammarError};
EXPECT_UIA_SAFEARRAY_EQ(V_ARRAY(annotation_types_variant.ptr()),
expected_annotations);
}
{
// |heading_text_node| has a spelling error for one word, and no
// annotations for the remaining text, so the range has mixed annotations.
EXPECT_UIA_TEXTATTRIBUTE_MIXED(heading_text_range_provider,
UIA_AnnotationTypesAttributeId);
// start: TextPosition, anchor_id=4, text_offset=5,
// annotated_text=more <t>ext
// end : TextPosition, anchor_id=4, text_offset=9,
// annotated_text=more text<>
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(heading_text_node));
ComPtr<AXPlatformNodeTextRangeProviderWin> range_with_annotations;
CreateTextRangeProviderWin(
range_with_annotations, owner,
/*start_anchor=*/heading_text_node, /*start_offset=*/5,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/heading_text_node, /*end_offset=*/9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
base::win::ScopedVariant annotation_types_variant;
EXPECT_HRESULT_SUCCEEDED(range_with_annotations->GetAttributeValue(
UIA_AnnotationTypesAttributeId, annotation_types_variant.Receive()));
std::vector<int> expected_annotations = {AnnotationType_SpellingError};
EXPECT_UIA_SAFEARRAY_EQ(V_ARRAY(annotation_types_variant.ptr()),
expected_annotations);
}
{
base::win::ScopedVariant empty_variant;
EXPECT_UIA_TEXTATTRIBUTE_EQ(mark_text_range_provider,
UIA_AnnotationTypesAttributeId, empty_variant);
}
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderGetAttributeValueAnnotationObjects) {
// rootWebArea id=1
// ++mark id=2 detailsIds=comment1 comment2 highlighted
// ++++staticText id=3 name="some text"
// ++comment id=4 name="comment 1"
// ++++staticText id=5 name="comment 1"
// ++comment id=6 name="comment 2"
// ++++staticText id=7 name="comment 2"
// ++mark id=8 name="highlighted"
// ++++staticText id=9 name="highlighted"
AXNodeData root;
AXNodeData annotation_target;
AXNodeData some_text;
AXNodeData comment1;
AXNodeData comment1_text;
AXNodeData comment2;
AXNodeData comment2_text;
AXNodeData highlighted;
AXNodeData highlighted_text;
root.id = 1;
annotation_target.id = 2;
some_text.id = 3;
comment1.id = 4;
comment1_text.id = 5;
comment2.id = 6;
comment2_text.id = 7;
highlighted.id = 8;
highlighted_text.id = 9;
root.role = ax::mojom::Role::kRootWebArea;
root.SetName("root");
root.child_ids = {annotation_target.id, comment1.id, comment2.id,
highlighted.id};
annotation_target.role = ax::mojom::Role::kMark;
annotation_target.child_ids = {some_text.id};
annotation_target.AddIntListAttribute(
ax::mojom::IntListAttribute::kDetailsIds,
{comment1.id, comment2.id, highlighted.id});
some_text.role = ax::mojom::Role::kStaticText;
some_text.SetName("some text");
comment1.role = ax::mojom::Role::kComment;
comment1.SetName("comment 1");
comment1.child_ids = {comment1_text.id};
comment1_text.role = ax::mojom::Role::kStaticText;
comment1_text.SetName("comment 1");
comment2.role = ax::mojom::Role::kComment;
comment2.SetName("comment 2");
comment2.child_ids = {comment2_text.id};
comment2_text.role = ax::mojom::Role::kStaticText;
comment2_text.SetName("comment 2");
highlighted.role = ax::mojom::Role::kMark;
highlighted.SetName("highlighted");
highlighted.child_ids = {highlighted_text.id};
highlighted_text.role = ax::mojom::Role::kStaticText;
highlighted_text.SetName("highlighted");
ui::AXTreeUpdate update;
update.has_tree_data = true;
update.root_id = root.id;
update.nodes = {root, annotation_target, some_text,
comment1, comment1_text, comment2,
comment2_text, highlighted, highlighted_text};
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* annotation_target_node = root_node->children()[0];
AXNode* comment1_node = root_node->children()[1];
AXNode* comment2_node = root_node->children()[2];
AXNode* highlighted_node = root_node->children()[3];
ComPtr<AXPlatformNodeTextRangeProviderWin> some_text_range_provider;
// Create a text range encapsulates |annotation_target_node| with content
// "some text".
// start: TextPosition, anchor_id=2, text_offset=0, annotated_text=<s>ome text
// end : TextPosition, anchor_id=2, text_offset=9, annotated_text=some text<>
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(annotation_target_node));
CreateTextRangeProviderWin(
some_text_range_provider, owner,
/*start_anchor=*/annotation_target_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/annotation_target_node, /*end_offset=*/9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, some_text_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(some_text_range_provider, L"some text");
ComPtr<IRawElementProviderSimple> comment1_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(comment1_node);
ASSERT_NE(nullptr, comment1_provider.Get());
ComPtr<IRawElementProviderSimple> comment2_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(comment2_node);
ASSERT_NE(nullptr, comment2_provider.Get());
ComPtr<IRawElementProviderSimple> highlighted_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(highlighted_node);
ASSERT_NE(nullptr, highlighted_provider.Get());
ComPtr<IAnnotationProvider> annotation_provider;
int annotation_type;
// Validate |comment1_node| with Role::kComment supports IAnnotationProvider.
EXPECT_HRESULT_SUCCEEDED(comment1_provider->GetPatternProvider(
UIA_AnnotationPatternId, &annotation_provider));
ASSERT_NE(nullptr, annotation_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
annotation_provider->get_AnnotationTypeId(&annotation_type));
EXPECT_EQ(AnnotationType_Comment, annotation_type);
annotation_provider.Reset();
// Validate |comment2_node| with Role::kComment supports IAnnotationProvider.
EXPECT_HRESULT_SUCCEEDED(comment2_provider->GetPatternProvider(
UIA_AnnotationPatternId, &annotation_provider));
ASSERT_NE(nullptr, annotation_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
annotation_provider->get_AnnotationTypeId(&annotation_type));
EXPECT_EQ(AnnotationType_Comment, annotation_type);
annotation_provider.Reset();
// Validate |highlighted_node| with Role::kMark supports
// IAnnotationProvider.
EXPECT_HRESULT_SUCCEEDED(highlighted_provider->GetPatternProvider(
UIA_AnnotationPatternId, &annotation_provider));
ASSERT_NE(nullptr, annotation_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
annotation_provider->get_AnnotationTypeId(&annotation_type));
EXPECT_EQ(AnnotationType_Highlighted, annotation_type);
annotation_provider.Reset();
base::win::ScopedVariant annotation_objects_variant;
EXPECT_HRESULT_SUCCEEDED(some_text_range_provider->GetAttributeValue(
UIA_AnnotationObjectsAttributeId, annotation_objects_variant.Receive()));
EXPECT_EQ(VT_UNKNOWN | VT_ARRAY, annotation_objects_variant.type());
std::vector<std::wstring> expected_names = {L"comment 1", L"comment 2",
L"highlighted"};
EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(V_ARRAY(annotation_objects_variant.ptr()),
UIA_NamePropertyId, expected_names);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderGetAttributeValueAnnotationObjectsMixed) {
// rootWebArea id=1
// ++mark id=2 detailsIds=comment
// ++++staticText id=3 name="some text"
// ++staticText id=4 name="read only" restriction=readOnly
// ++comment id=5 name="comment 1"
// ++++staticText id=6 name="comment 1"
AXNodeData root;
AXNodeData highlighted;
AXNodeData some_text;
AXNodeData readonly_text;
AXNodeData comment1;
AXNodeData comment1_text;
root.id = 1;
highlighted.id = 2;
some_text.id = 3;
readonly_text.id = 4;
comment1.id = 5;
comment1_text.id = 6;
root.role = ax::mojom::Role::kRootWebArea;
root.SetName("root");
root.child_ids = {highlighted.id, readonly_text.id, comment1.id};
highlighted.role = ax::mojom::Role::kMark;
highlighted.child_ids = {some_text.id};
highlighted.AddIntListAttribute(ax::mojom::IntListAttribute::kDetailsIds,
{comment1.id});
some_text.role = ax::mojom::Role::kStaticText;
some_text.SetName("some text");
readonly_text.role = ax::mojom::Role::kStaticText;
readonly_text.SetRestriction(ax::mojom::Restriction::kReadOnly);
readonly_text.SetName("read only");
comment1.role = ax::mojom::Role::kComment;
comment1.SetName("comment 1");
comment1.child_ids = {comment1_text.id};
comment1_text.role = ax::mojom::Role::kStaticText;
comment1_text.SetName("comment 1");
ui::AXTreeUpdate update;
update.has_tree_data = true;
update.root_id = root.id;
update.nodes = {root, highlighted, some_text,
readonly_text, comment1, comment1_text};
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
Init(update);
AXNode* root_node = GetRootAsAXNode();
AXNode* highlighted_node = root_node->children()[0];
AXNode* some_text_node = highlighted_node->children()[0];
AXNode* readonly_text_node = root_node->children()[1];
AXNode* comment1_node = root_node->children()[2];
// Create a text range encapsulates |highlighted_node| with content
// "some text".
// start: TextPosition, anchor_id=2, text_offset=0, annotated_text=<s>ome text
// end : TextPosition, anchor_id=2, text_offset=9, annotated_text=some text<>
ComPtr<AXPlatformNodeTextRangeProviderWin> some_text_range_provider;
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(highlighted_node));
CreateTextRangeProviderWin(
some_text_range_provider, owner,
/*start_anchor=*/highlighted_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/highlighted_node, /*end_offset=*/9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
ASSERT_NE(nullptr, some_text_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(some_text_range_provider, L"some text");
ComPtr<ITextRangeProvider> readonly_text_range_provider;
GetTextRangeProviderFromTextNode(readonly_text_range_provider,
readonly_text_node);
ASSERT_NE(nullptr, readonly_text_range_provider.Get());
ComPtr<IRawElementProviderSimple> comment1_provider =
QueryInterfaceFromNode<IRawElementProviderSimple>(comment1_node);
ASSERT_NE(nullptr, comment1_provider.Get());
ComPtr<IAnnotationProvider> annotation_provider;
int annotation_type;
base::win::ScopedVariant expected_variant;
// Validate |comment1_node| with Role::kComment supports IAnnotationProvider.
EXPECT_HRESULT_SUCCEEDED(comment1_provider->GetPatternProvider(
UIA_AnnotationPatternId, &annotation_provider));
ASSERT_NE(nullptr, annotation_provider.Get());
EXPECT_HRESULT_SUCCEEDED(
annotation_provider->get_AnnotationTypeId(&annotation_type));
EXPECT_EQ(AnnotationType_Comment, annotation_type);
annotation_provider.Reset();
// Validate text range "some text" supports AnnotationObjectsAttribute.
EXPECT_HRESULT_SUCCEEDED(some_text_range_provider->GetAttributeValue(
UIA_AnnotationObjectsAttributeId, expected_variant.Receive()));
EXPECT_EQ(VT_UNKNOWN | VT_ARRAY, expected_variant.type());
std::vector<std::wstring> expected_names = {L"comment 1"};
EXPECT_UIA_ELEMENT_ARRAY_BSTR_EQ(V_ARRAY(expected_variant.ptr()),
UIA_NamePropertyId, expected_names);
expected_variant.Reset();
// Validate text range "read only" supports IsReadOnlyAttribute.
// Use IsReadOnly on text range "read only" as a second property in order to
// test the "mixed" property in the following section.
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(readonly_text_range_provider,
UIA_IsReadOnlyAttributeId, expected_variant);
// Validate text range "some textread only" returns mixed attribute.
// start: TextPosition, anchor_id=2, text_offset=0, annotated_text=<s>ome text
// end : TextPosition, anchor_id=3, text_offset=9, annotated_text=read only<>
ComPtr<AXPlatformNodeTextRangeProviderWin> mixed_text_range_provider;
CreateTextRangeProviderWin(
mixed_text_range_provider, owner,
/*start_anchor=*/some_text_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/readonly_text_node, /*end_offset=*/9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(mixed_text_range_provider, L"some textread only");
EXPECT_UIA_TEXTATTRIBUTE_MIXED(mixed_text_range_provider,
UIA_AnnotationObjectsAttributeId);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderGetAttributeValueNotSupported) {
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
ui::AXNodeData text_data_first;
text_data_first.id = 2;
text_data_first.role = ax::mojom::Role::kStaticText;
text_data_first.SetName("first");
root_data.child_ids.push_back(text_data_first.id);
ui::AXNodeData text_data_second;
text_data_second.id = 3;
text_data_second.role = ax::mojom::Role::kStaticText;
text_data_second.SetName("second");
root_data.child_ids.push_back(text_data_second.id);
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes.push_back(root_data);
update.nodes.push_back(text_data_first);
update.nodes.push_back(text_data_second);
Init(update);
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider, GetRootAsAXNode());
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_AfterParagraphSpacingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_AnimationStyleAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_BeforeParagraphSpacingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_CapStyleAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_CaretBidiModeAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_CaretPositionAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_IndentationFirstLineAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_IndentationLeadingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_IndentationTrailingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_IsActiveAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_LineSpacingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_LinkAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_MarginBottomAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_MarginLeadingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_MarginTopAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_MarginTrailingAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_OutlineStylesAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_OverlineColorAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_SelectionActiveEndAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_StrikethroughColorAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_TabsAttributeId);
EXPECT_UIA_TEXTATTRIBUTE_NOTSUPPORTED(document_range_provider,
UIA_UnderlineColorAttributeId);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderGetAttributeValueWithAncestorTextPosition) {
ui::AXTreeUpdate initial_state;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
initial_state.tree_data.tree_id = tree_id;
initial_state.has_tree_data = true;
initial_state.root_id = 1;
initial_state.nodes.resize(5);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[1].id = 2;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[1].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[2].id = 3;
initial_state.nodes[2].child_ids = {4, 5};
initial_state.nodes[2].role = ax::mojom::Role::kGenericContainer;
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kStaticText;
initial_state.nodes[3].SetName("some text");
initial_state.nodes[3].AddIntAttribute(
ax::mojom::IntAttribute::kBackgroundColor, 0xFFADBEEFU);
initial_state.nodes[4].id = 5;
initial_state.nodes[4].role = ax::mojom::Role::kStaticText;
initial_state.nodes[4].SetName("more text");
initial_state.nodes[4].AddIntAttribute(
ax::mojom::IntAttribute::kBackgroundColor, 0xFFADBEEFU);
Init(initial_state);
const AXTree* tree = GetTree();
const AXNode* some_text_node = tree->GetFromId(4);
const AXNode* more_text_node = tree->GetFromId(5);
// Making |owner| AXID:2 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire subtree, and not only AXID:3 for example.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 2)));
// start: TextPosition, anchor_id=4, text_offset=0, annotated_text=<s>ome text
// end : TextPosition, anchor_id=5, text_offset=8,
// annotated_text=more tex<t>
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range_provider_win;
CreateTextRangeProviderWin(
text_range_provider_win, owner,
/*start_anchor=*/some_text_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/more_text_node, /*end_offset=*/8,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
ASSERT_TRUE(GetStart(text_range_provider_win.Get())->IsTextPosition());
ASSERT_EQ(4, GetStart(text_range_provider_win.Get())->anchor_id());
ASSERT_EQ(0, GetStart(text_range_provider_win.Get())->text_offset());
ASSERT_TRUE(GetEnd(text_range_provider_win.Get())->IsTextPosition());
ASSERT_EQ(5, GetEnd(text_range_provider_win.Get())->anchor_id());
ASSERT_EQ(8, GetEnd(text_range_provider_win.Get())->text_offset());
base::win::ScopedVariant expected_variant;
// SkColor is ARGB, COLORREF is 0BGR
expected_variant.Set(static_cast<int32_t>(0x00EFBEADU));
EXPECT_UIA_TEXTATTRIBUTE_EQ(text_range_provider_win,
UIA_BackgroundColorAttributeId, expected_variant);
}
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderSelect) {
Init(BuildTextDocument({"some text", "more text2"}));
AXNode* root_node = GetRootAsAXNode();
// Text range for the document, which contains text "some textmore text2".
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<ITextProvider> document_provider;
ComPtr<ITextRangeProvider> document_text_range_provider;
ComPtr<AXPlatformNodeTextRangeProviderWin> document_text_range;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &document_provider));
EXPECT_HRESULT_SUCCEEDED(
document_provider->get_DocumentRange(&document_text_range_provider));
document_text_range_provider->QueryInterface(
IID_PPV_ARGS(&document_text_range));
AXPlatformNodeWin* owner_platform =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
ASSERT_NE(owner_platform, nullptr);
SetOwner(owner_platform, document_text_range_provider.Get());
// Text range related to "some text".
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
root_node->children()[0]);
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range)));
// Text range related to "more text2".
ComPtr<ITextRangeProvider> more_text_range_provider;
GetTextRangeProviderFromTextNode(more_text_range_provider,
root_node->children()[1]);
SetOwner(owner_platform, more_text_range_provider.Get());
ComPtr<AXPlatformNodeTextRangeProviderWin> more_text_range;
more_text_range_provider->QueryInterface(IID_PPV_ARGS(&more_text_range));
AXPlatformNodeDelegate* delegate =
GetOwner(document_text_range.Get())->GetDelegate();
ComPtr<ITextRangeProvider> selected_text_range_provider;
base::win::ScopedSafearray selection;
LONG index = 0;
LONG ubound;
LONG lbound;
// Text range "some text" performs select.
{
text_range_provider->Select();
// Verify selection.
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
EXPECT_EQ(3, unignored_selection.anchor_object_id);
EXPECT_EQ(3, unignored_selection.focus_object_id);
EXPECT_EQ(0, unignored_selection.anchor_offset);
EXPECT_EQ(9, unignored_selection.focus_offset);
// Verify the content of the selection.
document_provider->GetSelection(selection.Receive());
ASSERT_NE(nullptr, selection.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selection.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selection.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selection.Get(), &index,
static_cast<void**>(&selected_text_range_provider)));
SetOwner(owner_platform, selected_text_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(selected_text_range_provider, L"some text");
selected_text_range_provider.Reset();
selection.Reset();
}
// Text range "more text2" performs select.
{
more_text_range_provider->Select();
// Verify selection
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
EXPECT_EQ(5, unignored_selection.anchor_object_id);
EXPECT_EQ(5, unignored_selection.focus_object_id);
EXPECT_EQ(0, unignored_selection.anchor_offset);
EXPECT_EQ(10, unignored_selection.focus_offset);
// Verify the content of the selection.
document_provider->GetSelection(selection.Receive());
ASSERT_NE(nullptr, selection.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selection.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selection.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selection.Get(), &index,
static_cast<void**>(&selected_text_range_provider)));
SetOwner(owner_platform, selected_text_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(selected_text_range_provider, L"more text2");
selected_text_range_provider.Reset();
selection.Reset();
}
// Document text range "some textmore text2" performs select.
{
document_text_range_provider->Select();
// Verify selection.
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
EXPECT_EQ(3, unignored_selection.anchor_object_id);
EXPECT_EQ(5, unignored_selection.focus_object_id);
EXPECT_EQ(0, unignored_selection.anchor_offset);
EXPECT_EQ(10, unignored_selection.focus_offset);
// Verify the content of the selection.
document_provider->GetSelection(selection.Receive());
ASSERT_NE(nullptr, selection.Get());
document_provider->GetSelection(selection.Receive());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selection.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selection.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selection.Get(), &index,
static_cast<void**>(&selected_text_range_provider)));
SetOwner(owner_platform, selected_text_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(selected_text_range_provider,
L"some textmore text2");
}
// A degenerate text range performs select.
{
// Move the endpoint of text range so it becomes degenerate, then select.
text_range_provider->MoveEndpointByRange(TextPatternRangeEndpoint_Start,
text_range_provider.Get(),
TextPatternRangeEndpoint_End);
text_range_provider->Select();
// Verify selection.
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
EXPECT_EQ(3, unignored_selection.anchor_object_id);
EXPECT_EQ(3, unignored_selection.focus_object_id);
EXPECT_EQ(9, unignored_selection.anchor_offset);
EXPECT_EQ(9, unignored_selection.focus_offset);
// Verify selection on degenerate range.
document_provider->GetSelection(selection.Receive());
ASSERT_NE(nullptr, selection.Get());
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetUBound(selection.Get(), 1, &ubound));
EXPECT_EQ(0, ubound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetLBound(selection.Get(), 1, &lbound));
EXPECT_EQ(0, lbound);
EXPECT_HRESULT_SUCCEEDED(SafeArrayGetElement(
selection.Get(), &index,
static_cast<void**>(&selected_text_range_provider)));
SetOwner(owner_platform, selected_text_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(selected_text_range_provider, L"");
selected_text_range_provider.Reset();
selection.Reset();
}
}
// TODO(crbug.com/1124051): Remove this test once this crbug is fixed.
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderSelectListMarker) {
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
ui::AXNodeData list_data;
list_data.id = 2;
list_data.role = ax::mojom::Role::kList;
root_data.child_ids.push_back(list_data.id);
ui::AXNodeData list_item_data;
list_item_data.id = 3;
list_item_data.role = ax::mojom::Role::kListItem;
list_data.child_ids.push_back(list_item_data.id);
ui::AXNodeData list_marker;
list_marker.id = 4;
list_marker.role = ax::mojom::Role::kListMarker;
list_item_data.child_ids.push_back(list_marker.id);
ui::AXNodeData static_text_data;
static_text_data.id = 5;
static_text_data.role = ax::mojom::Role::kStaticText;
static_text_data.SetName("1. ");
list_marker.child_ids.push_back(static_text_data.id);
ui::AXNodeData list_item_text_data;
list_item_text_data.id = 6;
list_item_text_data.role = ax::mojom::Role::kStaticText;
list_item_text_data.SetName("First Item");
list_item_data.child_ids.push_back(list_item_text_data.id);
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, list_data, list_item_data,
list_marker, static_text_data, list_item_text_data};
Init(update);
AXNode* root_node = GetRootAsAXNode();
// Text range related to "1. ".
AXNode* list_node = root_node->children()[0];
AXNode* list_item_node = list_node->children()[0];
AXNode* list_marker_node = list_item_node->children()[0];
ComPtr<ITextRangeProvider> list_marker_text_range_provider;
GetTextRangeProviderFromTextNode(list_marker_text_range_provider,
list_marker_node->children()[0]);
// A list marker text range performs select.
EXPECT_HRESULT_SUCCEEDED(list_marker_text_range_provider->Select());
// Verify selection was not performed on list marker range.
base::win::ScopedSafearray selection;
ComPtr<IRawElementProviderSimple> root_node_raw =
QueryInterfaceFromNode<IRawElementProviderSimple>(root_node);
ComPtr<ITextProvider> document_provider;
EXPECT_HRESULT_SUCCEEDED(
root_node_raw->GetPatternProvider(UIA_TextPatternId, &document_provider));
EXPECT_HRESULT_SUCCEEDED(
document_provider->GetSelection(selection.Receive()));
ASSERT_EQ(nullptr, selection.Get());
selection.Reset();
}
TEST_F(AXPlatformNodeTextRangeProviderTest, TestITextRangeProviderFindText) {
// Initialize the ICU data from the icudtl.dat file, if it exists.
wchar_t buffer[MAX_PATH];
GetModuleFileName(nullptr, buffer, MAX_PATH);
std::filesystem::path exec_path(buffer);
exec_path.remove_filename();
exec_path.append("icudtl.dat");
const std::string icudtl_path = exec_path.string();
if (std::filesystem::exists(icudtl_path)) {
fml::icu::InitializeICU(icudtl_path);
}
// \xC3\xA9 are the UTF8 bytes for codepoint 0xE9 - accented lowercase e.
Init(BuildTextDocument({"some text", "more text", "resum\xC3\xA9"},
false /* build_word_boundaries_offsets */,
true /* place_text_on_one_line */));
AXNode* root_node = GetRootAsAXNode();
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
ASSERT_NE(owner, nullptr);
ComPtr<ITextRangeProvider> range;
// Test Leaf kStaticText search.
GetTextRangeProviderFromTextNode(range, root_node->children()[0]);
EXPECT_UIA_FIND_TEXT(range, L"some text", false, owner);
EXPECT_UIA_FIND_TEXT(range, L"SoMe TeXt", true, owner);
GetTextRangeProviderFromTextNode(range, root_node->children()[1]);
EXPECT_UIA_FIND_TEXT(range, L"more", false, owner);
EXPECT_UIA_FIND_TEXT(range, L"MoRe", true, owner);
// Test searching for leaf content from ancestor.
GetTextRangeProviderFromTextNode(range, root_node);
EXPECT_UIA_FIND_TEXT(range, L"some text", false, owner);
EXPECT_UIA_FIND_TEXT(range, L"SoMe TeXt", true, owner);
EXPECT_UIA_FIND_TEXT(range, L"more text", false, owner);
EXPECT_UIA_FIND_TEXT(range, L"MoRe TeXt", true, owner);
EXPECT_UIA_FIND_TEXT(range, L"more", false, owner);
// Accented lowercase e.
EXPECT_UIA_FIND_TEXT(range, L"resum\xE9", false, owner);
// Accented uppercase +e.
EXPECT_UIA_FIND_TEXT(range, L"resum\xC9", true, owner);
EXPECT_UIA_FIND_TEXT(range, L"resume", true, owner);
EXPECT_UIA_FIND_TEXT(range, L"resumE", true, owner);
// Test finding text that crosses a node boundary.
EXPECT_UIA_FIND_TEXT(range, L"textmore", false, owner);
// Test no match.
EXPECT_UIA_FIND_TEXT_NO_MATCH(range, L"no match", false, owner);
EXPECT_UIA_FIND_TEXT_NO_MATCH(range, L"resume", false, owner);
// Test if range returned is in expected anchor node.
GetTextRangeProviderFromTextNode(range, root_node->children()[1]);
base::win::ScopedBstr find_string(L"more text");
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider_found;
EXPECT_HRESULT_SUCCEEDED(range->FindText(find_string.Get(), false, false,
&text_range_provider_found));
Microsoft::WRL::ComPtr<AXPlatformNodeTextRangeProviderWin>
text_range_provider_win;
text_range_provider_found->QueryInterface(
IID_PPV_ARGS(&text_range_provider_win));
ASSERT_TRUE(GetStart(text_range_provider_win.Get())->IsTextPosition());
EXPECT_EQ(5, GetStart(text_range_provider_win.Get())->anchor_id());
EXPECT_EQ(0, GetStart(text_range_provider_win.Get())->text_offset());
ASSERT_TRUE(GetEnd(text_range_provider_win.Get())->IsTextPosition());
EXPECT_EQ(5, GetEnd(text_range_provider_win.Get())->anchor_id());
EXPECT_EQ(9, GetEnd(text_range_provider_win.Get())->text_offset());
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
FindTextWithEmbeddedObjectCharacter) {
// ++1 kRootWebArea
// ++++2 kList
// ++++++3 kListItem
// ++++++++4 kStaticText
// ++++++++++5 kInlineTextBox
// ++++++6 kListItem
// ++++++++7 kStaticText
// ++++++++++8 kInlineTextBox
ui::AXNodeData root_1;
ui::AXNodeData list_2;
ui::AXNodeData list_item_3;
ui::AXNodeData static_text_4;
ui::AXNodeData inline_box_5;
ui::AXNodeData list_item_6;
ui::AXNodeData static_text_7;
ui::AXNodeData inline_box_8;
root_1.id = 1;
list_2.id = 2;
list_item_3.id = 3;
static_text_4.id = 4;
inline_box_5.id = 5;
list_item_6.id = 6;
static_text_7.id = 7;
inline_box_8.id = 8;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {list_2.id};
list_2.role = ax::mojom::Role::kList;
list_2.child_ids = {list_item_3.id, list_item_6.id};
list_item_3.role = ax::mojom::Role::kListItem;
list_item_3.child_ids = {static_text_4.id};
static_text_4.role = ax::mojom::Role::kStaticText;
static_text_4.SetName("foo");
static_text_4.child_ids = {inline_box_5.id};
inline_box_5.role = ax::mojom::Role::kInlineTextBox;
inline_box_5.SetName("foo");
list_item_6.role = ax::mojom::Role::kListItem;
list_item_6.child_ids = {static_text_7.id};
static_text_7.role = ax::mojom::Role::kStaticText;
static_text_7.child_ids = {inline_box_8.id};
static_text_7.SetName("bar");
inline_box_8.role = ax::mojom::Role::kInlineTextBox;
inline_box_8.SetName("bar");
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes = {root_1, list_2, list_item_3, static_text_4,
inline_box_5, list_item_6, static_text_7, inline_box_8};
Init(update);
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider, root_node);
base::win::ScopedBstr find_string(L"oobar");
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider_found;
EXPECT_HRESULT_SUCCEEDED(text_range_provider->FindText(
find_string.Get(), false, false, &text_range_provider_found));
ASSERT_TRUE(text_range_provider_found.Get());
Microsoft::WRL::ComPtr<AXPlatformNodeTextRangeProviderWin>
text_range_provider_win;
text_range_provider_found->QueryInterface(
IID_PPV_ARGS(&text_range_provider_win));
ASSERT_TRUE(GetStart(text_range_provider_win.Get())->IsTextPosition());
EXPECT_EQ(5, GetStart(text_range_provider_win.Get())->anchor_id());
EXPECT_EQ(1, GetStart(text_range_provider_win.Get())->text_offset());
ASSERT_TRUE(GetEnd(text_range_provider_win.Get())->IsTextPosition());
EXPECT_EQ(8, GetEnd(text_range_provider_win.Get())->anchor_id());
EXPECT_EQ(3, GetEnd(text_range_provider_win.Get())->text_offset());
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderFindTextBackwards) {
Init(BuildTextDocument({"text", "some", "text"},
false /* build_word_boundaries_offsets */,
true /* place_text_on_one_line */));
AXNode* root_node = GetRootAsAXNode();
ComPtr<ITextRangeProvider> root_range_provider;
GetTextRangeProviderFromTextNode(root_range_provider, root_node);
ComPtr<ITextRangeProvider> text_node1_range;
GetTextRangeProviderFromTextNode(text_node1_range, root_node->children()[0]);
ComPtr<ITextRangeProvider> text_node3_range;
GetTextRangeProviderFromTextNode(text_node3_range, root_node->children()[2]);
ComPtr<ITextRangeProvider> text_range_provider_found;
base::win::ScopedBstr find_string(L"text");
BOOL range_equal;
// Forward search finds the text_node1.
EXPECT_HRESULT_SUCCEEDED(root_range_provider->FindText(
find_string.Get(), false, false, &text_range_provider_found));
CopyOwnerToClone(root_range_provider.Get(), text_range_provider_found.Get());
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider_found, find_string.Get());
range_equal = false;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider_found->Compare(text_node1_range.Get(), &range_equal));
EXPECT_TRUE(range_equal);
// Backwards search finds the text_node3.
EXPECT_HRESULT_SUCCEEDED(root_range_provider->FindText(
find_string.Get(), true, false, &text_range_provider_found));
CopyOwnerToClone(root_range_provider.Get(), text_range_provider_found.Get());
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider_found, find_string.Get());
range_equal = false;
EXPECT_HRESULT_SUCCEEDED(
text_range_provider_found->Compare(text_node3_range.Get(), &range_equal));
EXPECT_TRUE(range_equal);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestITextRangeProviderFindAttribute) {
// document - visible
// [empty]
//
// Search forward, look for IsHidden=true.
// Expected: nullptr
// Search forward, look for IsHidden=false.
// Expected: ""
// Note: returns "" rather than nullptr here because document root web area by
// default set to visible. So the text range represents document matches
// our searching criteria. And we return a degenerate range.
//
// Search backward, look for IsHidden=true.
// Expected: nullptr
// Search backward, look for IsHidden=false.
// Expected: ""
// Note: returns "" rather than nullptr here because document root web area by
// default set to visible. So the text range represents document matches
// our searching criteria. And we return a degenerate range.
{
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
ui::AXTreeUpdate update;
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data};
Init(update);
bool is_search_backward;
VARIANT is_hidden_attr_val;
V_VT(&is_hidden_attr_val) = VT_BOOL;
ComPtr<ITextRangeProvider> matched_range_provider;
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider,
GetRootAsAXNode());
// Search forward, look for IsHidden=true.
// Expected: nullptr
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_EQ(nullptr, matched_range_provider.Get());
// Search forward, look for IsHidden=false.
// Expected: ""
// Note: returns "" rather than nullptr here because document root web area
// by default set to visible. So the text range represents document
// matches our searching criteria. And we return a degenerate range.
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"");
matched_range_provider.Reset();
// Search backward, look for IsHidden=true.
// Expected: nullptr
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_EQ(nullptr, matched_range_provider.Get());
// Search backward, look for IsHidden=false.
// Expected: ""
// Note: returns "" rather than nullptr here because document root web area
// by default set to visible. So the text range represents document
// matches our searching criteria. And we return a degenerate range.
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"");
}
// document - visible
// text1 - invisible
//
// Search forward, look for IsHidden=true.
// Expected: "text1"
// Search forward, look for IsHidden=false.
// Expected: nullptr
// Search backward, look for IsHidden=true.
// Expected: "text1"
// Search backward, look for IsHidden=false.
// Expected: nullptr
{
ui::AXNodeData text_data1;
text_data1.id = 2;
text_data1.role = ax::mojom::Role::kStaticText;
text_data1.AddState(ax::mojom::State::kInvisible);
text_data1.SetName("text1");
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {2};
ui::AXTreeUpdate update;
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, text_data1};
Init(update);
bool is_search_backward;
VARIANT is_hidden_attr_val;
V_VT(&is_hidden_attr_val) = VT_BOOL;
ComPtr<ITextRangeProvider> matched_range_provider;
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider,
GetRootAsAXNode());
// Search forward, look for IsHidden=true.
// Expected: "text1"
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text1");
matched_range_provider.Reset();
// Search forward, look for IsHidden=false.
// Expected: nullptr
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_EQ(nullptr, matched_range_provider.Get());
// Search backward, look for IsHidden=true.
// Expected: "text1"
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text1");
matched_range_provider.Reset();
// Search backward, look for IsHidden=false.
// Expected: nullptr
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_EQ(nullptr, matched_range_provider.Get());
}
// document - visible
// text1 - visible
// text2 - visible
//
// Search forward, look for IsHidden=true.
// Expected: nullptr
// Search forward, look for IsHidden=false.
// Expected: "text1text2"
// Search backward, look for IsHidden=true.
// Expected: nullptr
// Search backward, look for IsHidden=false.
// Expected: "text1text2"
{
ui::AXNodeData text_data1;
text_data1.id = 2;
text_data1.role = ax::mojom::Role::kStaticText;
text_data1.SetName("text1");
ui::AXNodeData text_data2;
text_data2.id = 3;
text_data2.role = ax::mojom::Role::kStaticText;
text_data2.SetName("text2");
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {2, 3};
ui::AXTreeUpdate update;
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, text_data1, text_data2};
Init(update);
bool is_search_backward;
VARIANT is_hidden_attr_val;
V_VT(&is_hidden_attr_val) = VT_BOOL;
ComPtr<ITextRangeProvider> matched_range_provider;
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider,
GetRootAsAXNode());
// Search forward, look for IsHidden=true.
// Expected: nullptr
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_EQ(nullptr, matched_range_provider.Get());
// Search forward, look for IsHidden=false.
// Expected: "text1text2"
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text1text2");
matched_range_provider.Reset();
// Search backward, look for IsHidden=true.
// Expected: nullptr
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_EQ(nullptr, matched_range_provider.Get());
// Search backward, look for IsHidden=false.
// Expected: "text1text2"
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text1text2");
}
// document - visible
// text1 - visible
// text2 - invisible
// text3 - invisible
// text4 - visible
// text5 - invisible
//
// Search forward, look for IsHidden=true.
// Expected: "text2text3"
// Search forward, look for IsHidden=false.
// Expected: "text1"
// Search backward, look for IsHidden=true.
// Expected: "text5"
// Search backward, look for IsHidden=false.
// Expected: "text4"
{
ui::AXNodeData text_data1;
text_data1.id = 2;
text_data1.role = ax::mojom::Role::kStaticText;
text_data1.SetName("text1");
ui::AXNodeData text_data2;
text_data2.id = 3;
text_data2.role = ax::mojom::Role::kStaticText;
text_data2.AddState(ax::mojom::State::kInvisible);
text_data2.SetName("text2");
ui::AXNodeData text_data3;
text_data3.id = 4;
text_data3.role = ax::mojom::Role::kStaticText;
text_data3.AddState(ax::mojom::State::kInvisible);
text_data3.SetName("text3");
ui::AXNodeData text_data4;
text_data4.id = 5;
text_data4.role = ax::mojom::Role::kStaticText;
text_data4.SetName("text4");
ui::AXNodeData text_data5;
text_data5.id = 6;
text_data5.role = ax::mojom::Role::kStaticText;
text_data5.AddState(ax::mojom::State::kInvisible);
text_data5.SetName("text5");
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {2, 3, 4, 5, 6};
ui::AXTreeUpdate update;
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, text_data1, text_data2,
text_data3, text_data4, text_data5};
Init(update);
bool is_search_backward;
VARIANT is_hidden_attr_val;
V_VT(&is_hidden_attr_val) = VT_BOOL;
ComPtr<ITextRangeProvider> matched_range_provider;
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider,
GetRootAsAXNode());
// Search forward, look for IsHidden=true.
// Expected: "text2text3"
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text2text3");
matched_range_provider.Reset();
// Search forward, look for IsHidden=false.
// Expected: "text1"
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text1");
matched_range_provider.Reset();
// Search backward, look for IsHidden=true.
// Expected: "text5"
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text5");
matched_range_provider.Reset();
// Search backward, look for IsHidden=false.
// Expected: "text4"
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text4");
}
// document - visible
// text1 - visible
// text2 - invisible
// text3 - invisible
// text4 - invisible
// text5 - visible
//
// Search forward, look for IsHidden=true.
// Expected: "text2text3text4"
// Search forward, look for IsHidden=false.
// Expected: "text1"
// Search backward, look for IsHidden=true.
// Expected: "text2text3text4"
// Search backward, look for IsHidden=false.
// Expected: "text5"
{
ui::AXNodeData text_data1;
text_data1.id = 2;
text_data1.role = ax::mojom::Role::kStaticText;
text_data1.SetName("text1");
ui::AXNodeData text_data2;
text_data2.id = 3;
text_data2.role = ax::mojom::Role::kStaticText;
text_data2.AddState(ax::mojom::State::kInvisible);
text_data2.SetName("text2");
ui::AXNodeData text_data3;
text_data3.id = 4;
text_data3.role = ax::mojom::Role::kStaticText;
text_data3.AddState(ax::mojom::State::kInvisible);
text_data3.SetName("text3");
ui::AXNodeData text_data4;
text_data4.id = 5;
text_data4.role = ax::mojom::Role::kStaticText;
text_data4.AddState(ax::mojom::State::kInvisible);
text_data4.SetName("text4");
ui::AXNodeData text_data5;
text_data5.id = 6;
text_data5.role = ax::mojom::Role::kStaticText;
text_data5.SetName("text5");
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
root_data.child_ids = {2, 3, 4, 5, 6};
ui::AXTreeUpdate update;
update.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.has_tree_data = true;
update.root_id = root_data.id;
update.nodes = {root_data, text_data1, text_data2,
text_data3, text_data4, text_data5};
Init(update);
bool is_search_backward;
VARIANT is_hidden_attr_val;
V_VT(&is_hidden_attr_val) = VT_BOOL;
ComPtr<ITextRangeProvider> matched_range_provider;
ComPtr<ITextRangeProvider> document_range_provider;
GetTextRangeProviderFromTextNode(document_range_provider,
GetRootAsAXNode());
// Search forward, look for IsHidden=true.
// Expected: "text2text3text4"
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text2text3text4");
matched_range_provider.Reset();
// Search forward, look for IsHidden=false.
// Expected: "text1"
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = false;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text1");
matched_range_provider.Reset();
// Search backward, look for IsHidden=true.
// Expected: "text2text3text4"
V_BOOL(&is_hidden_attr_val) = VARIANT_TRUE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text2text3text4");
matched_range_provider.Reset();
// Search backward, look for IsHidden=false.
// Expected: "text5"
V_BOOL(&is_hidden_attr_val) = VARIANT_FALSE;
is_search_backward = true;
document_range_provider->FindAttribute(
UIA_IsHiddenAttributeId, is_hidden_attr_val, is_search_backward,
&matched_range_provider);
ASSERT_NE(nullptr, matched_range_provider.Get());
CopyOwnerToClone(document_range_provider.Get(),
matched_range_provider.Get());
EXPECT_UIA_TEXTRANGE_EQ(matched_range_provider, L"text5");
}
}
TEST_F(AXPlatformNodeTextRangeProviderTest, ElementNotAvailable) {
AXNodeData root_ax_node_data;
root_ax_node_data.id = 1;
root_ax_node_data.role = ax::mojom::Role::kRootWebArea;
Init(root_ax_node_data);
ComPtr<IRawElementProviderSimple> raw_element_provider_simple =
QueryInterfaceFromNode<IRawElementProviderSimple>(GetRootAsAXNode());
ASSERT_NE(nullptr, raw_element_provider_simple.Get());
ComPtr<ITextProvider> text_provider;
ASSERT_HRESULT_SUCCEEDED(raw_element_provider_simple->GetPatternProvider(
UIA_TextPatternId, &text_provider));
ASSERT_NE(nullptr, text_provider.Get());
ComPtr<ITextRangeProvider> text_range_provider;
ASSERT_HRESULT_SUCCEEDED(
text_provider->get_DocumentRange(&text_range_provider));
ASSERT_NE(nullptr, text_range_provider.Get());
// An empty tree.
SetTree(std::make_unique<AXTree>());
BOOL bool_arg = FALSE;
ASSERT_EQ(static_cast<HRESULT>(UIA_E_ELEMENTNOTAVAILABLE),
text_range_provider->ScrollIntoView(bool_arg));
}
// TODO(schectman) Non-empty ignored nodes are not used by Flutter.
// https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestITextRangeProviderIgnoredNodes) {
// Parent Tree
// 1
// |
// 2(i)
// |________________________________
// | | | | | |
// 3 4 5 6 7(i) 8(i)
// | |________
// | | |
// 9(i) 10(i) 11
// | |____
// | | |
// 12 13 14
ui::AXTreeUpdate tree_update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
tree_update.tree_data.tree_id = tree_id;
tree_update.has_tree_data = true;
tree_update.root_id = 1;
tree_update.nodes.resize(14);
tree_update.nodes[0].id = 1;
tree_update.nodes[0].child_ids = {2};
tree_update.nodes[0].role = ax::mojom::Role::kRootWebArea;
tree_update.nodes[1].id = 2;
tree_update.nodes[1].child_ids = {3, 4, 5, 6, 7, 8};
// According to the existing Blink code, editable roots are never ignored.
// However, we can still create this tree structure only for test purposes.
tree_update.nodes[1].AddState(ax::mojom::State::kIgnored);
tree_update.nodes[1].AddState(ax::mojom::State::kEditable);
tree_update.nodes[1].AddState(ax::mojom::State::kRichlyEditable);
// tree_update.nodes[1].AddBoolAttribute(
// ax::mojom::BoolAttribute::kNonAtomicTextFieldRoot, true);
tree_update.nodes[1].role = ax::mojom::Role::kGenericContainer;
tree_update.nodes[2].id = 3;
tree_update.nodes[2].role = ax::mojom::Role::kStaticText;
tree_update.nodes[2].SetName(".3.");
tree_update.nodes[3].id = 4;
tree_update.nodes[3].role = ax::mojom::Role::kStaticText;
tree_update.nodes[3].SetName(".4.");
tree_update.nodes[4].id = 5;
tree_update.nodes[4].role = ax::mojom::Role::kStaticText;
tree_update.nodes[4].SetName(".5.");
tree_update.nodes[5].id = 6;
tree_update.nodes[5].role = ax::mojom::Role::kButton;
tree_update.nodes[5].child_ids = {9};
tree_update.nodes[6].id = 7;
tree_update.nodes[6].child_ids = {10, 11};
tree_update.nodes[6].AddState(ax::mojom::State::kIgnored);
tree_update.nodes[6].role = ax::mojom::Role::kGenericContainer;
tree_update.nodes[7].id = 8;
tree_update.nodes[7].AddState(ax::mojom::State::kIgnored);
tree_update.nodes[7].role = ax::mojom::Role::kStaticText;
tree_update.nodes[7].SetName(".8.");
tree_update.nodes[8].id = 9;
tree_update.nodes[8].child_ids = {12};
tree_update.nodes[8].AddState(ax::mojom::State::kIgnored);
tree_update.nodes[8].role = ax::mojom::Role::kGenericContainer;
tree_update.nodes[9].id = 10;
tree_update.nodes[9].child_ids = {13, 14};
tree_update.nodes[9].AddState(ax::mojom::State::kIgnored);
tree_update.nodes[8].role = ax::mojom::Role::kGenericContainer;
tree_update.nodes[10].id = 11;
tree_update.nodes[10].role = ax::mojom::Role::kStaticText;
tree_update.nodes[10].SetName(".11.");
tree_update.nodes[11].id = 12;
tree_update.nodes[11].role = ax::mojom::Role::kStaticText;
tree_update.nodes[11].AddState(ax::mojom::State::kIgnored);
tree_update.nodes[11].SetName(".12.");
tree_update.nodes[12].id = 13;
tree_update.nodes[12].role = ax::mojom::Role::kStaticText;
tree_update.nodes[12].SetName(".13.");
tree_update.nodes[13].id = 14;
tree_update.nodes[13].role = ax::mojom::Role::kStaticText;
tree_update.nodes[13].SetName(".14.");
Init(tree_update);
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 1),
GetNodeFromTree(tree_id, 1));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 2),
GetNodeFromTree(tree_id, 1));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 3),
GetNodeFromTree(tree_id, 3));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 4),
GetNodeFromTree(tree_id, 4));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 5),
GetNodeFromTree(tree_id, 5));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 8),
GetNodeFromTree(tree_id, 1));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 11),
GetNodeFromTree(tree_id, 11));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 13),
GetNodeFromTree(tree_id, 13));
EXPECT_ENCLOSING_ELEMENT(GetNodeFromTree(tree_id, 14),
GetNodeFromTree(tree_id, 14));
// Test movement and GetText()
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetNodeFromTree(tree_id, 1));
ASSERT_HRESULT_SUCCEEDED(
text_range_provider->ExpandToEnclosingUnit(TextUnit_Character));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L".");
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 2,
/*expected_text*/ L".3.",
/*expected_count*/ 2);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 6,
/*expected_text*/ L".3..4..5.",
/*expected_count*/ 6);
// By design, empty objects, such as the unlabelled button in this case, are
// placed in their own paragraph for easier screen reader navigation.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 15,
/*expected_text*/ L".3..4..5.\n\xFFFC\n.13..14..11.",
/*expected_count*/ 15);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestNormalizeTextRangePastEndOfDocument) {
ui::AXTreeUpdate initial_state;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
initial_state.tree_data.tree_id = tree_id;
initial_state.has_tree_data = true;
initial_state.root_id = 1;
initial_state.nodes.resize(3);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[1].id = 2;
initial_state.nodes[1].child_ids = {3};
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].SetName("aaa");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kInlineTextBox;
initial_state.nodes[2].SetName("aaa");
Init(initial_state);
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetNodeFromTree(tree_id, 3));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"aaa");
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 2,
/*expected_text*/ L"a",
/*expected_count*/ 2);
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range_provider_win;
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range_provider_win));
const AXNodePosition::AXPositionInstance start_after_move =
GetStart(text_range_provider_win.Get())->Clone();
const AXNodePosition::AXPositionInstance end_after_move =
GetEnd(text_range_provider_win.Get())->Clone();
EXPECT_LT(*start_after_move, *end_after_move);
AXTreeUpdate update;
update.nodes.resize(2);
update.nodes[0] = initial_state.nodes[1];
update.nodes[0].SetName("aa");
update.nodes[1] = initial_state.nodes[2];
update.nodes[1].SetName("aa");
ASSERT_TRUE(GetTree()->Unserialize(update));
auto* text_range = text_range_provider_win.Get();
auto original_start = GetStart(text_range)->Clone();
auto original_end = GetEnd(text_range)->Clone();
auto normalized_start = GetStart(text_range)->Clone();
auto normalized_end = GetEnd(text_range)->Clone();
NormalizeTextRange(text_range, normalized_start, normalized_end);
// Verify that the original range was not changed by normalization.
ExpectPositionsEqual(original_start, GetStart(text_range));
ExpectPositionsEqual(original_end, GetEnd(text_range));
EXPECT_EQ(*start_after_move, *normalized_start);
EXPECT_EQ(*end_after_move, *normalized_end);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestNormalizeTextRangePastEndOfDocumentWithIgnoredNodes) {
ui::AXTreeUpdate initial_state;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
initial_state.tree_data.tree_id = tree_id;
initial_state.has_tree_data = true;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids = {2};
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[1].id = 2;
initial_state.nodes[1].child_ids = {3, 4};
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].SetName("aaa");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kInlineTextBox;
initial_state.nodes[2].SetName("aaa");
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kInlineTextBox;
initial_state.nodes[3].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[3].SetName("ignored");
Init(initial_state);
ComPtr<ITextRangeProvider> text_range_provider;
GetTextRangeProviderFromTextNode(text_range_provider,
GetNodeFromTree(tree_id, 3));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"aaa");
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 2,
/*expected_text*/ L"a",
/*expected_count*/ 2);
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range_provider_win;
text_range_provider->QueryInterface(IID_PPV_ARGS(&text_range_provider_win));
const AXNodePosition::AXPositionInstance start_after_move =
GetStart(text_range_provider_win.Get())->Clone();
const AXNodePosition::AXPositionInstance end_after_move =
GetEnd(text_range_provider_win.Get())->Clone();
EXPECT_LT(*start_after_move, *end_after_move);
AXTreeUpdate update;
update.nodes.resize(2);
update.nodes[0] = initial_state.nodes[1];
update.nodes[0].SetName("aa");
update.nodes[1] = initial_state.nodes[2];
update.nodes[1].SetName("aa");
ASSERT_TRUE(GetTree()->Unserialize(update));
auto* text_range = text_range_provider_win.Get();
auto original_start = GetStart(text_range)->Clone();
auto original_end = GetEnd(text_range)->Clone();
auto normalized_start = GetStart(text_range)->Clone();
auto normalized_end = GetEnd(text_range)->Clone();
NormalizeTextRange(text_range, normalized_start, normalized_end);
// Verify that the original range was not changed by normalization.
ExpectPositionsEqual(original_start, GetStart(text_range));
ExpectPositionsEqual(original_end, GetEnd(text_range));
EXPECT_EQ(*start_after_move, *normalized_start);
EXPECT_EQ(*end_after_move, *normalized_end);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestNormalizeTextRangeInsideIgnoredNodes) {
ui::AXTreeUpdate initial_state;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
initial_state.tree_data.tree_id = tree_id;
initial_state.has_tree_data = true;
initial_state.root_id = 1;
initial_state.nodes.resize(4);
initial_state.nodes[0].id = 1;
initial_state.nodes[0].child_ids = {2, 3, 4};
initial_state.nodes[0].role = ax::mojom::Role::kRootWebArea;
initial_state.nodes[1].id = 2;
initial_state.nodes[1].role = ax::mojom::Role::kStaticText;
initial_state.nodes[1].SetName("before");
initial_state.nodes[2].id = 3;
initial_state.nodes[2].role = ax::mojom::Role::kStaticText;
initial_state.nodes[2].AddState(ax::mojom::State::kIgnored);
initial_state.nodes[2].SetName("ignored");
initial_state.nodes[3].id = 4;
initial_state.nodes[3].role = ax::mojom::Role::kStaticText;
initial_state.nodes[3].SetName("after");
Init(initial_state);
const AXTree* tree = GetTree();
const AXNode* ignored_node = tree->GetFromId(3);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// start: TextPosition, anchor_id=3, text_offset=1, annotated_text=i<g>nored
// end : TextPosition, anchor_id=3, text_offset=6, annotated_text=ignore<d>
ComPtr<AXPlatformNodeTextRangeProviderWin> ignored_range_win;
CreateTextRangeProviderWin(
ignored_range_win, owner,
/*start_anchor=*/ignored_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/ignored_node, /*end_offset=*/0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_TRUE(GetStart(ignored_range_win.Get())->IsIgnored());
EXPECT_TRUE(GetEnd(ignored_range_win.Get())->IsIgnored());
auto original_start = GetStart(ignored_range_win.Get())->Clone();
auto original_end = GetEnd(ignored_range_win.Get())->Clone();
auto normalized_start = GetStart(ignored_range_win.Get())->Clone();
auto normalized_end = GetEnd(ignored_range_win.Get())->Clone();
NormalizeTextRange(ignored_range_win.Get(), normalized_start, normalized_end);
// Verify that the original range was not changed by normalization.
ExpectPositionsEqual(original_start, GetStart(ignored_range_win.Get()));
ExpectPositionsEqual(original_end, GetEnd(ignored_range_win.Get()));
EXPECT_FALSE(normalized_start->IsIgnored());
EXPECT_FALSE(normalized_end->IsIgnored());
EXPECT_LE(*GetStart(ignored_range_win.Get()), *normalized_start);
EXPECT_LE(*GetEnd(ignored_range_win.Get()), *normalized_end);
EXPECT_LE(*normalized_start, *normalized_end);
// Remove the last node, forcing |NormalizeTextRange| to normalize
// using the opposite AdjustmentBehavior.
AXTreeUpdate update;
update.nodes.resize(1);
update.nodes[0] = initial_state.nodes[0];
update.nodes[0].child_ids = {2, 3};
ASSERT_TRUE(GetTree()->Unserialize(update));
original_start = GetStart(ignored_range_win.Get())->Clone();
original_end = GetEnd(ignored_range_win.Get())->Clone();
normalized_start = GetStart(ignored_range_win.Get())->Clone();
normalized_end = GetEnd(ignored_range_win.Get())->Clone();
NormalizeTextRange(ignored_range_win.Get(), normalized_start, normalized_end);
// Verify that the original range was not changed by normalization.
ExpectPositionsEqual(original_start, GetStart(ignored_range_win.Get()));
ExpectPositionsEqual(original_end, GetEnd(ignored_range_win.Get()));
EXPECT_FALSE(normalized_start->IsIgnored());
EXPECT_FALSE(normalized_end->IsIgnored());
EXPECT_GE(*GetStart(ignored_range_win.Get()), *normalized_start);
EXPECT_GE(*GetEnd(ignored_range_win.Get()), *normalized_end);
EXPECT_LE(*normalized_start, *normalized_end);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestNormalizeTextRangeSpanIgnoredNodes) {
ui::AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
ui::AXNodeData before_text;
before_text.id = 2;
before_text.role = ax::mojom::Role::kStaticText;
before_text.SetName("before");
root_data.child_ids.push_back(before_text.id);
ui::AXNodeData ignored_text1;
ignored_text1.id = 3;
ignored_text1.role = ax::mojom::Role::kStaticText;
ignored_text1.AddState(ax::mojom::State::kIgnored);
ignored_text1.SetName("ignored1");
root_data.child_ids.push_back(ignored_text1.id);
ui::AXNodeData ignored_text2;
ignored_text2.id = 4;
ignored_text2.role = ax::mojom::Role::kStaticText;
ignored_text2.AddState(ax::mojom::State::kIgnored);
ignored_text2.SetName("ignored2");
root_data.child_ids.push_back(ignored_text2.id);
ui::AXNodeData after_text;
after_text.id = 5;
after_text.role = ax::mojom::Role::kStaticText;
after_text.SetName("after");
root_data.child_ids.push_back(after_text.id);
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_data.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_data, before_text, ignored_text1, ignored_text2,
after_text};
Init(update);
const AXTree* tree = GetTree();
const AXNode* before_text_node = tree->GetFromId(before_text.id);
const AXNode* after_text_node = tree->GetFromId(after_text.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// Original range before NormalizeTextRange()
// |before<>||ignored1||ignored2||<a>fter|
// |-----------------------|
// start: TextPosition, anchor_id=2, text_offset=6, annotated_text=before<>
// end : TextPosition, anchor_id=5, text_offset=0, annotated_text=<a>fter
ComPtr<AXPlatformNodeTextRangeProviderWin> range_span_ignored_nodes;
CreateTextRangeProviderWin(
range_span_ignored_nodes, owner,
/*start_anchor=*/before_text_node, /*start_offset=*/6,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/after_text_node, /*end_offset=*/0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
auto original_start = GetStart(range_span_ignored_nodes.Get())->Clone();
auto original_end = GetEnd(range_span_ignored_nodes.Get())->Clone();
// Normalized range after NormalizeTextRange()
// |before||ignored1||ignored2||<a>fter|
// |-|
AXNodePosition::AXPositionInstance normalized_start =
GetStart(range_span_ignored_nodes.Get())->Clone();
AXNodePosition::AXPositionInstance normalized_end =
GetEnd(range_span_ignored_nodes.Get())->Clone();
NormalizeTextRange(range_span_ignored_nodes.Get(), normalized_start,
normalized_end);
// Verify that the original range was not changed by normalization.
ExpectPositionsEqual(original_start,
GetStart(range_span_ignored_nodes.Get()));
ExpectPositionsEqual(original_end, GetEnd(range_span_ignored_nodes.Get()));
EXPECT_EQ(*normalized_start, *normalized_end);
EXPECT_TRUE(normalized_start->IsTextPosition());
EXPECT_TRUE(normalized_start->AtStartOfAnchor());
EXPECT_EQ(5, normalized_start->anchor_id());
EXPECT_EQ(0, normalized_start->text_offset());
EXPECT_TRUE(normalized_end->IsTextPosition());
EXPECT_TRUE(normalized_end->AtStartOfAnchor());
EXPECT_EQ(5, normalized_end->anchor_id());
EXPECT_EQ(0, normalized_end->text_offset());
}
// TODO(schectman) Non-zero text offset in position into an empty node.
// Why? https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestNormalizeTextRangeForceSameAnchorOnDegenerateRange) {
// ++1 kRootWebArea
// ++++2 kGenericContainer
// ++++++3 kImage
// ++++4 kTextField
// ++++++5 kGenericContainer
// ++++++++6 kStaticText
// ++++++++++7 kInlineTextBox
ui::AXNodeData root_1;
ui::AXNodeData generic_container_2;
ui::AXNodeData line_break_3;
ui::AXNodeData text_field_4;
ui::AXNodeData generic_container_5;
ui::AXNodeData static_text_6;
ui::AXNodeData inline_box_7;
root_1.id = 1;
generic_container_2.id = 2;
line_break_3.id = 3;
text_field_4.id = 4;
generic_container_5.id = 5;
static_text_6.id = 6;
inline_box_7.id = 7;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {generic_container_2.id, text_field_4.id};
generic_container_2.role = ax::mojom::Role::kGenericContainer;
generic_container_2.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
generic_container_2.child_ids = {line_break_3.id};
line_break_3.role = ax::mojom::Role::kLineBreak;
text_field_4.role = ax::mojom::Role::kTextField;
text_field_4.AddState(ax::mojom::State::kEditable);
text_field_4.child_ids = {generic_container_5.id};
text_field_4.SetValue("3.14");
generic_container_5.role = ax::mojom::Role::kGenericContainer;
generic_container_5.child_ids = {static_text_6.id};
static_text_6.role = ax::mojom::Role::kStaticText;
static_text_6.child_ids = {inline_box_7.id};
static_text_6.SetName("3.14");
inline_box_7.role = ax::mojom::Role::kInlineTextBox;
inline_box_7.SetName("3.14");
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes.push_back(root_1);
update.nodes.push_back(generic_container_2);
update.nodes.push_back(line_break_3);
update.nodes.push_back(text_field_4);
update.nodes.push_back(generic_container_5);
update.nodes.push_back(static_text_6);
update.nodes.push_back(inline_box_7);
Init(update);
const AXTree* tree = GetTree();
const AXNode* line_break_3_node = tree->GetFromId(line_break_3.id);
const AXNode* inline_box_7_node = tree->GetFromId(inline_box_7.id);
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_data.tree_id, 1)));
// start: TextPosition, anchor_id=3, text_offset=1, annotated_text=/xFFFC<>
// end : TextPosition, anchor_id=7, text_offset=0, annotated_text=<p>i
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor=*/line_break_3_node, /*start_offset=*/1,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/inline_box_7_node, /*end_offset=*/0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
auto original_start = GetStart(range.Get())->Clone();
auto original_end = GetEnd(range.Get())->Clone();
AXNodePosition::AXPositionInstance normalized_start =
GetStart(range.Get())->Clone();
AXNodePosition::AXPositionInstance normalized_end =
GetEnd(range.Get())->Clone();
NormalizeTextRange(range.Get(), normalized_start, normalized_end);
// Verify that the original range was not changed by normalization.
ExpectPositionsEqual(original_start, GetStart(range.Get()));
ExpectPositionsEqual(original_end, GetEnd(range.Get()));
EXPECT_EQ(*normalized_start, *normalized_start);
EXPECT_TRUE(normalized_start->AtStartOfAnchor());
EXPECT_TRUE(normalized_end->AtStartOfAnchor());
EXPECT_EQ(7, normalized_start->anchor_id());
EXPECT_EQ(7, normalized_end->anchor_id());
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest, DISABLED_TestValidateStartAndEnd) {
// This test updates the tree structure to test a specific edge case -
// CreatePositionAtFormatBoundary when text lies at the beginning and end
// of the AX tree.
AXNodeData root_data;
root_data.id = 1;
root_data.role = ax::mojom::Role::kRootWebArea;
AXNodeData text_data;
text_data.id = 2;
text_data.role = ax::mojom::Role::kStaticText;
text_data.SetName("some text");
AXNodeData more_text_data;
more_text_data.id = 3;
more_text_data.role = ax::mojom::Role::kStaticText;
more_text_data.SetName("more text");
root_data.child_ids = {text_data.id, more_text_data.id};
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_data.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_data, text_data, more_text_data};
Init(update);
const AXTree* tree = GetTree();
const AXNode* root_node = tree->GetFromId(root_data.id);
const AXNode* more_text_node = tree->GetFromId(more_text_data.id);
// Create a position at MaxTextOffset
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// start: TextPosition, anchor_id=1, text_offset=0, annotated_text=<s>ome text
// end : TextPosition, anchor_id=3, text_offset=9, annotated_text=more text<>
ComPtr<AXPlatformNodeTextRangeProviderWin> text_range_provider;
CreateTextRangeProviderWin(
text_range_provider, owner,
/*start_anchor=*/root_node, /*start_offset=*/0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor=*/more_text_node, /*end_offset=*/9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
// Since the end of the range is at MaxTextOffset, moving it by 1 character
// should have an expected_count of 0.
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"some textmore text",
/*expected_count*/ 0);
// Now make a change to shorten MaxTextOffset. Ensure that this position is
// invalid, then call SnapToMaxTextOffsetIfBeyond and ensure that it is now
// valid.
more_text_data.SetName("ore tex");
AXTreeUpdate test_update;
test_update.nodes = {more_text_data};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"some textore tex",
/*expected_count*/ 0);
// Now modify the tree so that start_ is pointing to a node that has been
// removed from the tree.
text_data.SetNameExplicitlyEmpty();
AXTreeUpdate test_update2;
test_update2.nodes = {text_data};
ASSERT_TRUE(GetTree()->Unserialize(test_update2));
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"re tex",
/*expected_count*/ 1);
// Now adjust a node that's not the final node in the tree to point past
// MaxTextOffset. First move the range endpoints so that they're pointing to
// MaxTextOffset on the first node.
text_data.SetName("some text");
AXTreeUpdate test_update3;
test_update3.nodes = {text_data};
ASSERT_TRUE(GetTree()->Unserialize(test_update3));
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ -10,
/*expected_text*/ L"some textore tex",
/*expected_count*/ -10);
// Ensure that we're at MaxTextOffset on the first node by first
// overshooting a negative move...
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ -8,
/*expected_text*/ L"some tex",
/*expected_count*/ -8);
// ...followed by a positive move
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_End, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"some text",
/*expected_count*/ 1);
// Now our range's start_ is pointing to offset 0 on the first node and end_
// is pointing to MaxTextOffset on the first node. Now modify the tree so
// that MaxTextOffset is invalid on the first node and ensure that we can
// still move
text_data.SetName("some tex");
AXTreeUpdate test_update4;
test_update4.nodes = {text_data};
ASSERT_TRUE(GetTree()->Unserialize(test_update4));
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(
text_range_provider, TextPatternRangeEndpoint_Start, TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"ome tex",
/*expected_count*/ 1);
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestReplaceStartAndEndEndpointNode) {
// This test updates the tree structure to ensure that the text range is still
// valid after a text node gets replaced by another one. This case occurs
// every time an AT's focus moves to a node whose style is affected by focus,
// thus generating a tree update.
//
// ++1 kRootWebArea
// ++++2 kGroup (ignored)
// ++++++3 kStaticText/++++4 kStaticText (replacement node)
// ++++5 kStaticText/++++6 kStaticText (replacement node)
AXNodeData root_1;
AXNodeData group_2;
AXNodeData text_3;
AXNodeData text_4;
AXNodeData text_5;
AXNodeData text_6;
root_1.id = 1;
group_2.id = 2;
text_3.id = 3;
text_4.id = 4;
text_5.id = 5;
text_6.id = 6;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_3.id, text_5.id};
group_2.role = ax::mojom::Role::kGroup;
group_2.AddState(ax::mojom::State::kIgnored);
group_2.child_ids = {text_3.id};
text_3.role = ax::mojom::Role::kStaticText;
text_3.SetName("some text");
// Replacement node of |text_3|.
text_4.role = ax::mojom::Role::kStaticText;
text_4.SetName("some text");
text_5.role = ax::mojom::Role::kStaticText;
text_5.SetName("more text");
// Replacement node of |text_5|.
text_6.role = ax::mojom::Role::kStaticText;
text_6.SetName("more text");
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, text_3, text_5};
Init(update);
const AXTree* tree = GetTree();
const AXNode* text_3_node = tree->GetFromId(text_3.id);
const AXNode* text_5_node = tree->GetFromId(text_5.id);
// Create a position at MaxTextOffset.
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// start: TextPosition, anchor_id=3, text_offset=0, annotated_text=<s>ome text
// end : TextPosition, anchor_id=5, text_offset=9, annotated_text=more text<>
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ text_3_node, /*start_offset*/ 0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_5_node, /*end_offset*/ 9,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"some textmore text");
// 1. Replace the node on which |start_| is.
{
// Replace node |text_3| with |text_4|.
root_1.child_ids = {text_4.id, text_5.id};
AXTreeUpdate test_update;
test_update.nodes = {root_1, text_4};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// Replacing that node shouldn't impact the range.
base::win::ScopedSafearray children;
range->GetChildren(children.Receive());
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"some textmore text");
// The |start_| endpoint should have moved to the root, skipping its ignored
// parent.
EXPECT_EQ(root_1.id, GetStart(range.Get())->anchor_id());
EXPECT_EQ(0, GetStart(range.Get())->text_offset());
// The |end_| endpoint should not have moved.
EXPECT_EQ(text_5.id, GetEnd(range.Get())->anchor_id());
EXPECT_EQ(9, GetEnd(range.Get())->text_offset());
}
// 2. Replace the node on which |end_| is.
{
// Replace node |text_4| with |text_5|.
root_1.child_ids = {text_4.id, text_6.id};
AXTreeUpdate test_update;
test_update.nodes = {root_1, text_6};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// Replacing that node shouldn't impact the range.
base::win::ScopedSafearray children;
range->GetChildren(children.Receive());
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"some textmore text");
// The |start_| endpoint should still be on its parent.
EXPECT_EQ(root_1.id, GetStart(range.Get())->anchor_id());
EXPECT_EQ(0, GetStart(range.Get())->text_offset());
// The |end_| endpoint should have moved to its parent.
EXPECT_EQ(root_1.id, GetEnd(range.Get())->anchor_id());
EXPECT_EQ(18, GetEnd(range.Get())->text_offset());
}
// 3. Replace the node on which |start_| and |end_| is.
{
// start: TextPosition, anchor_id=4, text_offset=0, annotated_text=<s>ome
// end : TextPosition, anchor_id=4, text_offset=4, annotated_text=some<>
const AXNode* text_4_node = tree->GetFromId(text_4.id);
ComPtr<AXPlatformNodeTextRangeProviderWin> range_2;
CreateTextRangeProviderWin(
range_2, owner,
/*start_anchor*/ text_4_node, /*start_offset*/ 0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_4_node, /*end_offset*/ 4,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range_2, /*expected_text*/ L"some");
// Replace node |text_4| with |text_3|.
root_1.child_ids = {text_3.id, text_6.id};
AXTreeUpdate test_update;
test_update.nodes = {root_1, text_3};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// Replacing that node shouldn't impact the range.
base::win::ScopedSafearray children;
range_2->GetChildren(children.Receive());
EXPECT_UIA_TEXTRANGE_EQ(range_2, /*expected_text*/ L"some");
// The |start_| endpoint should have moved to its parent.
EXPECT_EQ(root_1.id, GetStart(range_2.Get())->anchor_id());
EXPECT_EQ(0, GetStart(range_2.Get())->text_offset());
// The |end_| endpoint should have moved to its parent.
EXPECT_EQ(root_1.id, GetEnd(range_2.Get())->anchor_id());
EXPECT_EQ(4, GetEnd(range_2.Get())->text_offset());
}
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestDeleteSubtreeThatIncludesEndpoints) {
// This test updates the tree structure to ensure that the text range is still
// valid after a subtree that includes the text range is deleted, resulting in
// a change to the range.
//
// ++1 kRootWebArea
// ++++2 kStaticText "one"
// ++++3 kGenericContainer
// ++++++4 kGenericContainer
// ++++++++5 kStaticText " two"
// ++++++6 kGenericContainer
// ++++++++7 kStaticText " three"
AXNodeData root_1;
AXNodeData text_2;
AXNodeData gc_3;
AXNodeData gc_4;
AXNodeData text_5;
AXNodeData gc_6;
AXNodeData text_7;
root_1.id = 1;
text_2.id = 2;
gc_3.id = 3;
gc_4.id = 4;
text_5.id = 5;
gc_6.id = 6;
text_7.id = 7;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_2.id, gc_3.id};
text_2.role = ax::mojom::Role::kStaticText;
text_2.SetName("one");
gc_3.role = ax::mojom::Role::kGenericContainer;
gc_3.child_ids = {gc_4.id, gc_6.id};
gc_4.role = ax::mojom::Role::kGenericContainer;
gc_4.child_ids = {text_5.id};
text_5.role = ax::mojom::Role::kStaticText;
text_5.SetName(" two");
gc_6.role = ax::mojom::Role::kGenericContainer;
gc_6.child_ids = {text_7.id};
text_7.role = ax::mojom::Role::kStaticText;
text_7.SetName(" three");
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, text_2, gc_3, gc_4, text_5, gc_6, text_7};
Init(update);
const AXTree* tree = GetTree();
const AXNode* text_5_node = tree->GetFromId(text_5.id);
const AXNode* text_7_node = tree->GetFromId(text_7.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// Create a range that spans " two three" located on the leaf nodes.
// start: TextPosition, anchor_id=5, text_offset=0
// end : TextPosition, anchor_id=7, text_offset=6
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ text_5_node, /*start_offset*/ 0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_7_node, /*end_offset*/ 6,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L" two three");
// Delete |gc_3|, which will delete the entire subtree where both of our
// endpoints are.
AXTreeUpdate test_update;
root_1.child_ids = {text_2.id};
test_update.nodes = {root_1};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// The text range should now be a degenerate range positioned at the end of
// root, the parent of |gc_3|, since |gc_3| has been deleted.
EXPECT_EQ(root_1.id, GetStart(range.Get())->anchor_id());
EXPECT_EQ(3, GetStart(range.Get())->text_offset());
EXPECT_EQ(root_1.id, GetEnd(range.Get())->anchor_id());
EXPECT_EQ(3, GetEnd(range.Get())->text_offset());
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestDeleteSubtreeWithIgnoredAncestors) {
// This test updates the tree structure to ensure that the text range doesn't
// crash and points to null positions after a subtree that includes the text
// range is deleted and all ancestors are ignored.
//
// ++1 kRootWebArea ignored
// ++++2 kStaticText "one"
// ++++3 kGenericContainer ignored
// ++++++4 kGenericContainer
// ++++++++5 kGenericContainer
// ++++++++++6 kStaticText " two"
// ++++++++7 kGenericContainer ignored
// ++++++++++8 kStaticText " ignored" ignored
// ++++++++9 kGenericContainer
// ++++++++++10 kStaticText " three"
// ++++11 kGenericContainer
// ++++++12 kStaticText "four"
AXNodeData root_1;
AXNodeData text_2;
AXNodeData gc_3;
AXNodeData gc_4;
AXNodeData gc_5;
AXNodeData text_6;
AXNodeData gc_7;
AXNodeData text_8;
AXNodeData gc_9;
AXNodeData text_10;
AXNodeData gc_11;
AXNodeData text_12;
root_1.id = 1;
text_2.id = 2;
gc_3.id = 3;
gc_4.id = 4;
gc_5.id = 5;
text_6.id = 6;
gc_7.id = 7;
text_8.id = 8;
gc_9.id = 9;
text_10.id = 10;
gc_11.id = 11;
text_12.id = 12;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_2.id, gc_3.id, gc_11.id};
root_1.AddState(ax::mojom::State::kIgnored);
text_2.role = ax::mojom::Role::kStaticText;
text_2.SetName("one");
gc_3.role = ax::mojom::Role::kGenericContainer;
gc_3.AddState(ax::mojom::State::kIgnored);
gc_3.child_ids = {gc_4.id};
gc_4.role = ax::mojom::Role::kGenericContainer;
gc_4.child_ids = {gc_5.id, gc_7.id, gc_9.id};
gc_5.role = ax::mojom::Role::kGenericContainer;
gc_5.child_ids = {text_6.id};
text_6.role = ax::mojom::Role::kStaticText;
text_6.SetName(" two");
gc_7.role = ax::mojom::Role::kGenericContainer;
gc_7.AddState(ax::mojom::State::kIgnored);
gc_7.child_ids = {text_8.id};
text_8.role = ax::mojom::Role::kStaticText;
text_8.AddState(ax::mojom::State::kIgnored);
text_8.SetName(" ignored");
gc_9.role = ax::mojom::Role::kGenericContainer;
gc_9.child_ids = {text_10.id};
text_10.role = ax::mojom::Role::kStaticText;
text_10.SetName(" three");
gc_11.role = ax::mojom::Role::kGenericContainer;
gc_11.child_ids = {text_12.id};
text_12.role = ax::mojom::Role::kStaticText;
text_12.SetName("four");
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, text_2, gc_3, gc_4, gc_5, text_6,
gc_7, text_8, gc_9, text_10, gc_11, text_12};
Init(update);
const AXTree* tree = GetTree();
const AXNode* text_6_node = tree->GetFromId(text_6.id);
const AXNode* text_10_node = tree->GetFromId(text_10.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// Create a range that spans " two three" located on the leaf nodes.
// start: TextPosition, anchor_id=5, text_offset=0
// end : TextPosition, anchor_id=7, text_offset=6
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ text_6_node, /*start_offset*/ 2,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_10_node, /*end_offset*/ 6,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"wo three");
// Delete |gc_3|, which will delete the entire subtree where both of our
// endpoints are.
AXTreeUpdate test_update;
gc_3.child_ids = {};
test_update.nodes = {gc_3};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// There was no unignored position in which to place the start and end - they
// should now be null positions.
EXPECT_TRUE(GetStart(range.Get())->IsNullPosition());
EXPECT_TRUE(GetEnd(range.Get())->IsNullPosition());
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_TestDeleteSubtreeThatIncludesEndpointsNormalizeMoves) {
// This test updates the tree structure to ensure that the text range is still
// valid after a subtree that includes the text range is deleted, resulting in
// a change to the range that is adjusted forwards due to an ignored node.
//
// ++1 kRootWebArea
// ++++2 kStaticText "one"
// ++++3 kGenericContainer ignored
// ++++++4 kGenericContainer
// ++++++++5 kGenericContainer
// ++++++++++6 kStaticText " two"
// ++++++++7 kGenericContainer
// ++++++++++8 kStaticText " three"
// ++++++++9 kGenericContainer ignored
// ++++++++++10 kStaticText " ignored" ignored
// ++++11 kGenericContainer
// ++++++12 kStaticText "four"
AXNodeData root_1;
AXNodeData text_2;
AXNodeData gc_3;
AXNodeData gc_4;
AXNodeData gc_5;
AXNodeData text_6;
AXNodeData gc_7;
AXNodeData text_8;
AXNodeData gc_9;
AXNodeData text_10;
AXNodeData gc_11;
AXNodeData text_12;
root_1.id = 1;
text_2.id = 2;
gc_3.id = 3;
gc_4.id = 4;
gc_5.id = 5;
text_6.id = 6;
gc_7.id = 7;
text_8.id = 8;
gc_9.id = 9;
text_10.id = 10;
gc_11.id = 11;
text_12.id = 12;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_2.id, gc_3.id, gc_11.id};
text_2.role = ax::mojom::Role::kStaticText;
text_2.SetName("one");
gc_3.role = ax::mojom::Role::kGenericContainer;
gc_3.AddState(ax::mojom::State::kIgnored);
gc_3.child_ids = {gc_4.id};
gc_4.role = ax::mojom::Role::kGenericContainer;
gc_4.child_ids = {gc_5.id, gc_7.id, gc_9.id};
gc_5.role = ax::mojom::Role::kGenericContainer;
gc_5.child_ids = {text_6.id};
text_6.role = ax::mojom::Role::kStaticText;
text_6.SetName(" two");
gc_7.role = ax::mojom::Role::kGenericContainer;
gc_7.child_ids = {text_8.id};
text_8.role = ax::mojom::Role::kStaticText;
text_8.SetName(" three");
gc_9.role = ax::mojom::Role::kGenericContainer;
gc_9.AddState(ax::mojom::State::kIgnored);
gc_9.child_ids = {text_10.id};
text_10.role = ax::mojom::Role::kStaticText;
text_10.AddState(ax::mojom::State::kIgnored);
text_10.SetName(" ignored");
gc_11.role = ax::mojom::Role::kGenericContainer;
gc_11.child_ids = {text_12.id};
text_12.role = ax::mojom::Role::kStaticText;
text_12.SetName("four");
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, text_2, gc_3, gc_4, gc_5, text_6,
gc_7, text_8, gc_9, text_10, gc_11, text_12};
Init(update);
const AXTree* tree = GetTree();
const AXNode* text_6_node = tree->GetFromId(text_6.id);
const AXNode* text_8_node = tree->GetFromId(text_8.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
// Create a range that spans " two three" located on the leaf nodes.
// start: TextPosition, anchor_id=5, text_offset=0
// end : TextPosition, anchor_id=7, text_offset=6
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ text_6_node, /*start_offset*/ 2,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_8_node, /*end_offset*/ 6,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"wo three");
// Delete |gc_3|, which will delete the entire subtree where both of our
// endpoints are.
AXTreeUpdate test_update;
gc_3.child_ids = {};
test_update.nodes = {gc_3};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// The text range should now be a degenerate range positioned at the end of
// root, the parent of |gc_3|, since |gc_3| has been deleted.
EXPECT_EQ(text_12.id, GetStart(range.Get())->anchor_id());
EXPECT_EQ(0, GetStart(range.Get())->text_offset());
EXPECT_EQ(text_12.id, GetEnd(range.Get())->anchor_id());
EXPECT_EQ(0, GetEnd(range.Get())->text_offset());
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestDeleteTreePositionPreviousSibling) {
// This test creates a degenerate range with endpoints pointing after the last
// child of the 2 generic container. It then deletes a previous sibling and
// ensures that we don't crash with an out of bounds index that causes null
// child positions to be created.
//
// ++1 kRootWebArea
// ++++2 kGenericContainer
// ++++++3 kHeading
// ++++++++4 kStaticText
// ++++++++++5 kInlineTextBox
// ++++++6 kGenericContainer
// ++++++7 kButton
ui::AXNodeData root_1;
ui::AXNodeData generic_container_2;
ui::AXNodeData heading_3;
ui::AXNodeData static_text_4;
ui::AXNodeData inline_box_5;
ui::AXNodeData generic_container_6;
ui::AXNodeData button_7;
root_1.id = 1;
generic_container_2.id = 2;
heading_3.id = 3;
static_text_4.id = 4;
inline_box_5.id = 5;
generic_container_6.id = 6;
button_7.id = 7;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {generic_container_2.id};
generic_container_2.role = ax::mojom::Role::kGenericContainer;
generic_container_2.child_ids = {heading_3.id, generic_container_6.id,
button_7.id};
heading_3.role = ax::mojom::Role::kHeading;
heading_3.child_ids = {static_text_4.id};
static_text_4.role = ax::mojom::Role::kStaticText;
static_text_4.child_ids = {inline_box_5.id};
static_text_4.SetName("3.14");
inline_box_5.role = ax::mojom::Role::kInlineTextBox;
inline_box_5.SetName("3.14");
generic_container_6.role = ax::mojom::Role::kGenericContainer;
generic_container_6.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
button_7.role = ax::mojom::Role::kButton;
ui::AXTreeUpdate update;
ui::AXTreeData tree_data;
tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.tree_data = tree_data;
update.has_tree_data = true;
update.root_id = root_1.id;
update.nodes = {root_1, generic_container_2, heading_3, static_text_4,
inline_box_5, generic_container_6, button_7};
Init(update);
AXTree* tree = GetTree();
AXNode* root_node = GetRootAsAXNode();
AXNodePosition::AXPositionInstance range_start =
AXNodePosition::CreateTreePosition(tree->GetAXTreeID(),
generic_container_2.id,
/*child_index*/ 3);
AXNodePosition::AXPositionInstance range_end = range_start->Clone();
AXPlatformNodeWin* owner =
static_cast<AXPlatformNodeWin*>(AXPlatformNodeFromNode(root_node));
ComPtr<ITextRangeProvider> text_range_provider =
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProviderForTesting(
owner, std::move(range_start), std::move(range_end));
EXPECT_UIA_TEXTRANGE_EQ(text_range_provider, L"");
generic_container_2.child_ids = {heading_3.id, button_7.id};
AXTreeUpdate test_update;
test_update.nodes = {generic_container_2};
ASSERT_TRUE(tree->Unserialize(test_update));
root_1.child_ids = {};
test_update.nodes = {root_1};
ASSERT_TRUE(tree->Unserialize(test_update));
}
TEST_F(AXPlatformNodeTextRangeProviderTest,
TestReplaceStartAndEndEndpointRepeatRemoval) {
// This test updates the tree structure to ensure that the text range is still
// valid after text nodes get removed repeatedly.
//
// ++1 kRootWebArea
// ++++2 kStaticText
// ++++3 kGroup (ignored)
// ++++++4 kStaticText
// ++++5 kStaticText
AXNodeData root_1;
AXNodeData text_2;
AXNodeData group_3;
AXNodeData text_4;
AXNodeData text_5;
root_1.id = 1;
text_2.id = 2;
group_3.id = 3;
text_4.id = 4;
text_5.id = 5;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_2.id, group_3.id, text_5.id};
text_2.role = ax::mojom::Role::kStaticText;
text_2.SetName("text 2");
group_3.role = ax::mojom::Role::kGroup;
group_3.AddState(ax::mojom::State::kIgnored);
group_3.child_ids = {text_4.id};
text_4.role = ax::mojom::Role::kStaticText;
text_4.SetName("text 4");
text_5.role = ax::mojom::Role::kStaticText;
text_5.SetName("text 5");
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, text_2, group_3, text_4, text_5};
Init(update);
const AXTree* tree = GetTree();
const AXNode* text_2_node = tree->GetFromId(text_2.id);
const AXNode* text_4_node = tree->GetFromId(text_4.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ text_2_node, /*start_offset*/ 0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_4_node, /*end_offset*/ 0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"text 2");
// start: TextPosition, anchor_id=2, text_offset=0, annotated_text=<t>ext2
// end : TextPosition, anchor_id=4, text_offset=0, annotated_text=<>text4
// 1. Remove |text_4| which |end_| is anchored on.
{
// Remove node |text_4|.
group_3.child_ids = {};
AXTreeUpdate test_update;
test_update.nodes = {root_1, group_3};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// Replacing that node should not impact the range.
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"text 2");
}
// start: TextPosition, anchor_id=2, text_offset=0, annotated_text=<>text2
// end : TextPosition, anchor_id=2, text_offset=5, annotated_text=text2<>
// 2. Remove |text_2|, which both |start_| and |end_| are anchored to and
// replace with |text_5|.
{
root_1.child_ids = {group_3.id, text_5.id};
AXTreeUpdate test_update;
test_update.nodes = {root_1, group_3};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// Removing that node should adjust the range to the |text_5|, as it took
// |text_2|'s position.
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"text 5");
}
// start: TextPosition, anchor_id=5, text_offset=0, annotated_text=<>text5
// end : TextPosition, anchor_id=5, text_offset=5, annotated_text=text5<>
// 3. Remove |text_5|, which both |start_| and |end_| are pointing to.
{
root_1.child_ids = {group_3.id};
AXTreeUpdate test_update;
test_update.nodes = {root_1, group_3};
ASSERT_TRUE(GetTree()->Unserialize(test_update));
// Removing the last text node should leave a degenerate range.
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"");
}
}
TEST_F(AXPlatformNodeTextRangeProviderTest, CaretAtEndOfTextFieldReadOnly) {
// This test places a degenerate range at end of text field, and it should not
// normalize to other positions, so we should expect the
// 'UIA_IsReadOnlyAttributeId' attribute queried at this position to return
// false.
// ++1 kRootWebArea
// ++++2 kTextField editable value="hello"
// ++++++3 kGenericContainer editable isLineBreakingObject=true
// ++++++++4 kStaticText editable name="hello"
// ++++++++++5 kInlineTextBox editable name="hello"
// ++++6 kStaticText name="abc"
// ++++++7 kInlineTextBox name="abc"
AXNodeData root_1;
AXNodeData text_field_2;
AXNodeData generic_container_3;
AXNodeData static_text_4;
AXNodeData inline_text_5;
AXNodeData static_text_6;
AXNodeData inline_text_7;
root_1.id = 1;
text_field_2.id = 2;
generic_container_3.id = 3;
static_text_4.id = 4;
inline_text_5.id = 5;
static_text_6.id = 6;
inline_text_7.id = 7;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {text_field_2.id, static_text_6.id};
text_field_2.role = ax::mojom::Role::kTextField;
text_field_2.AddState(ax::mojom::State::kEditable);
text_field_2.SetValue("hello");
text_field_2.child_ids = {generic_container_3.id};
generic_container_3.role = ax::mojom::Role::kGenericContainer;
generic_container_3.AddState(ax::mojom::State::kEditable);
generic_container_3.AddBoolAttribute(
ax::mojom::BoolAttribute::kIsLineBreakingObject, true);
generic_container_3.child_ids = {static_text_4.id};
static_text_4.role = ax::mojom::Role::kStaticText;
static_text_4.SetName("hello");
static_text_4.AddState(ax::mojom::State::kEditable);
static_text_4.child_ids = {inline_text_5.id};
inline_text_5.role = ax::mojom::Role::kInlineTextBox;
inline_text_5.SetName("hello");
inline_text_5.AddState(ax::mojom::State::kEditable);
static_text_6.role = ax::mojom::Role::kStaticText;
static_text_6.SetName("abc");
static_text_6.child_ids = {inline_text_7.id};
inline_text_7.role = ax::mojom::Role::kInlineTextBox;
inline_text_7.SetName("abc");
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, text_field_2, generic_container_3,
static_text_4, inline_text_5, static_text_6,
inline_text_7};
Init(update);
const AXTree* tree = GetTree();
const AXNode* inline_text_5_node = tree->GetFromId(inline_text_5.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
base::win::ScopedVariant expected_variant;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ inline_text_5_node, /*start_offset*/ 3,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ inline_text_5_node, /*end_offset*/ 4,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"l");
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(range, UIA_IsReadOnlyAttributeId,
expected_variant);
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(range, TextPatternRangeEndpoint_Start,
TextUnit_Character,
/*count*/ 1,
/*expected_text*/ L"",
/*expected_count*/ 1);
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(range, UIA_IsReadOnlyAttributeId,
expected_variant);
EXPECT_UIA_MOVE(range, TextUnit_Character,
/*count*/ 1,
/*expected_text*/
L"",
/*expected_count*/ 1);
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(range, UIA_IsReadOnlyAttributeId,
expected_variant);
const AXNodePosition::AXPositionInstance& start = GetStart(range.Get());
const AXNodePosition::AXPositionInstance& end = GetEnd(range.Get());
EXPECT_TRUE(start->AtEndOfAnchor());
EXPECT_EQ(5, start->anchor_id());
EXPECT_EQ(5, start->text_offset());
EXPECT_TRUE(end->AtEndOfAnchor());
EXPECT_EQ(5, end->anchor_id());
EXPECT_EQ(5, end->text_offset());
}
// TODO(schectman) Not all attributes treated as in Chromium.
// https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_GeneratedNewlineReturnsCommonAnchorReadonly) {
// This test places a range that starts at the end of a paragraph and
// ends at the beginning of the next paragraph. The range only contains the
// generated newline character. The readonly attribute value returned should
// be the one of the common anchor of the start and end endpoint.
// ++1 kRootWebArea
// ++++2 kGenericContainer
// ++++++3 kImage
// ++++++4 kTextField editable
// ++++5 kGenericContainer editable
// ++++++6 kImage
// ++++++7 kTextField editable
// ++++8 kGenericContainer
// ++++++9 kTextField editable
// ++++++10 kTextField editable
AXNodeData root_1;
AXNodeData generic_container_2;
AXNodeData image_3;
AXNodeData text_field_4;
AXNodeData generic_container_5;
AXNodeData image_6;
AXNodeData text_field_7;
AXNodeData generic_container_8;
AXNodeData text_field_9;
AXNodeData text_field_10;
root_1.id = 1;
generic_container_2.id = 2;
image_3.id = 3;
text_field_4.id = 4;
generic_container_5.id = 5;
image_6.id = 6;
text_field_7.id = 7;
generic_container_8.id = 8;
text_field_9.id = 9;
text_field_10.id = 10;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {generic_container_2.id, generic_container_5.id,
generic_container_8.id};
generic_container_2.role = ax::mojom::Role::kGenericContainer;
generic_container_2.child_ids = {image_3.id, text_field_4.id};
image_3.role = ax::mojom::Role::kImage;
image_3.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
text_field_4.role = ax::mojom::Role::kTextField;
text_field_4.AddState(ax::mojom::State::kEditable);
generic_container_5.role = ax::mojom::Role::kGenericContainer;
generic_container_5.AddState(ax::mojom::State::kEditable);
generic_container_5.child_ids = {image_6.id, text_field_7.id};
image_6.role = ax::mojom::Role::kImage;
image_6.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
text_field_7.role = ax::mojom::Role::kTextField;
text_field_7.AddState(ax::mojom::State::kEditable);
generic_container_8.role = ax::mojom::Role::kGenericContainer;
generic_container_8.child_ids = {text_field_9.id, text_field_10.id};
text_field_9.role = ax::mojom::Role::kTextField;
text_field_9.AddState(ax::mojom::State::kEditable);
text_field_9.AddBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject,
true);
text_field_10.role = ax::mojom::Role::kTextField;
text_field_10.AddState(ax::mojom::State::kEditable);
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, generic_container_2, image_3,
text_field_4, generic_container_5, image_6,
text_field_7, generic_container_8, text_field_9,
text_field_10};
Init(update);
const AXTree* tree = GetTree();
const AXNode* image_3_node = tree->GetFromId(image_3.id);
const AXNode* image_6_node = tree->GetFromId(image_6.id);
const AXNode* text_field_4_node = tree->GetFromId(text_field_4.id);
const AXNode* text_field_7_node = tree->GetFromId(text_field_7.id);
const AXNode* text_field_9_node = tree->GetFromId(text_field_9.id);
const AXNode* text_field_10_node = tree->GetFromId(text_field_10.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
base::win::ScopedVariant expected_variant;
ComPtr<AXPlatformNodeTextRangeProviderWin> range_1;
CreateTextRangeProviderWin(
range_1, owner,
/*start_anchor*/ image_3_node, /*start_offset*/ 1,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_field_4_node, /*end_offset*/ 0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range_1, /*expected_text*/ L"");
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(range_1, UIA_IsReadOnlyAttributeId,
expected_variant);
expected_variant.Reset();
ComPtr<AXPlatformNodeTextRangeProviderWin> range_2;
CreateTextRangeProviderWin(
range_2, owner,
/*start_anchor*/ image_6_node, /*start_offset*/ 1,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_field_7_node, /*end_offset*/ 0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range_2, /*expected_text*/ L"");
expected_variant.Set(false);
EXPECT_UIA_TEXTATTRIBUTE_EQ(range_2, UIA_IsReadOnlyAttributeId,
expected_variant);
expected_variant.Reset();
// This is testing a corner case when the range spans two text fields
// separated by a paragraph boundary. This case used to not work because we
// were relying on NormalizeTextRange to handle generated newlines and
// normalization doesn't work when the range spans text fields.
ComPtr<AXPlatformNodeTextRangeProviderWin> range_3;
CreateTextRangeProviderWin(
range_3, owner,
/*start_anchor*/ text_field_9_node, /*start_offset*/ 1,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ text_field_10_node, /*end_offset*/ 0,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range_3, /*expected_text*/ L"");
expected_variant.Set(true);
EXPECT_UIA_TEXTATTRIBUTE_EQ(range_3, UIA_IsReadOnlyAttributeId,
expected_variant);
expected_variant.Reset();
}
// TODO(schectman) https://github.com/flutter/flutter/issues/117012
TEST_F(AXPlatformNodeTextRangeProviderTest,
DISABLED_MoveEndpointToLastIgnoredForTextNavigationNode) {
// This test moves the end endpoint of a range by one paragraph unit forward
// to the last node of the tree. That last node happens to be a node that is
// ignored for text navigation, but since it's the last node in the tree, it
// should successfully move the endpoint to that node and keep the units_moved
// value in sync.
// ++1 kRootWebArea
// ++++2 kStaticText name="abc"
// ++++++3 kInlineTextBox name="abc"
// ++++4 kGenericContainer
AXNodeData root_1;
AXNodeData static_text_2;
AXNodeData inline_text_3;
AXNodeData generic_container_4;
root_1.id = 1;
static_text_2.id = 2;
inline_text_3.id = 3;
generic_container_4.id = 4;
root_1.role = ax::mojom::Role::kRootWebArea;
root_1.child_ids = {static_text_2.id, generic_container_4.id};
static_text_2.role = ax::mojom::Role::kStaticText;
static_text_2.SetName("abc");
static_text_2.child_ids = {inline_text_3.id};
inline_text_3.role = ax::mojom::Role::kInlineTextBox;
inline_text_3.SetName("abc");
generic_container_4.role = ax::mojom::Role::kGenericContainer;
ui::AXTreeUpdate update;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
update.root_id = root_1.id;
update.tree_data.tree_id = tree_id;
update.has_tree_data = true;
update.nodes = {root_1, static_text_2, inline_text_3, generic_container_4};
Init(update);
const AXTree* tree = GetTree();
const AXNode* inline_text_3_node = tree->GetFromId(inline_text_3.id);
// Making |owner| AXID:1 so that |TestAXNodeWrapper::BuildAllWrappers|
// will build the entire tree.
AXPlatformNodeWin* owner = static_cast<AXPlatformNodeWin*>(
AXPlatformNodeFromNode(GetNodeFromTree(tree_id, 1)));
ComPtr<AXPlatformNodeTextRangeProviderWin> range;
base::win::ScopedVariant expected_variant;
CreateTextRangeProviderWin(
range, owner,
/*start_anchor*/ inline_text_3_node, /*start_offset*/ 0,
/*start_affinity*/ ax::mojom::TextAffinity::kDownstream,
/*end_anchor*/ inline_text_3_node, /*end_offset*/ 3,
/*end_affinity*/ ax::mojom::TextAffinity::kDownstream);
EXPECT_UIA_TEXTRANGE_EQ(range, /*expected_text*/ L"abc");
EXPECT_UIA_MOVE_ENDPOINT_BY_UNIT(range, TextPatternRangeEndpoint_End,
TextUnit_Paragraph,
/*count*/ 1,
/*expected_text*/ L"abc\xFFFC",
/*expected_count*/ 1);
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win_unittest.cc",
"repo_id": "engine",
"token_count": 133954
} | 445 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_TEST_AX_NODE_WRAPPER_H_
#define UI_ACCESSIBILITY_PLATFORM_TEST_AX_NODE_WRAPPER_H_
#include <set>
#include <string>
#include <vector>
#include "ax/ax_node.h"
#include "ax/ax_tree.h"
#include "ax_build/build_config.h"
#include "ax_platform_node.h"
#include "ax_platform_node_delegate_base.h"
#include "base/auto_reset.h"
#if defined(OS_WIN)
namespace gfx {
const AcceleratedWidget kMockAcceleratedWidget = reinterpret_cast<HWND>(-1);
}
#endif
namespace ui {
// For testing, a TestAXNodeWrapper wraps an AXNode, implements
// AXPlatformNodeDelegate, and owns an AXPlatformNode.
class TestAXNodeWrapper : public AXPlatformNodeDelegateBase {
public:
// Create TestAXNodeWrapper instances on-demand from an AXTree and AXNode.
static TestAXNodeWrapper* GetOrCreate(AXTree* tree, AXNode* node);
// Set a global coordinate offset for testing.
static void SetGlobalCoordinateOffset(const gfx::Vector2d& offset);
// Get the last node which ShowContextMenu was called from for testing.
static const AXNode* GetNodeFromLastShowContextMenu();
// Get the last node which AccessibilityPerformAction default action was
// called from for testing.
static const AXNode* GetNodeFromLastDefaultAction();
// Set the last node which AccessibilityPerformAction default action was
// called for testing.
static void SetNodeFromLastDefaultAction(AXNode* node);
// Set a global scale factor for testing.
static std::unique_ptr<base::AutoReset<float>> SetScaleFactor(float value);
// Set a global indicating that AXPlatformNodeDelegates are for web content.
static void SetGlobalIsWebContent(bool is_web_content);
// When a hit test is called on |src_node_id|, return |dst_node_id| as
// the result.
static void SetHitTestResult(AXNode::AXID src_node_id,
AXNode::AXID dst_node_id);
// Remove all hit test overrides added by SetHitTestResult.
static void ClearHitTestResults();
~TestAXNodeWrapper() override;
AXPlatformNode* ax_platform_node() const { return platform_node_; }
void set_minimized(bool minimized) { minimized_ = minimized; }
// Test helpers.
void BuildAllWrappers(AXTree* tree, AXNode* node);
void ResetNativeEventTarget();
// AXPlatformNodeDelegate.
const AXNodeData& GetData() const override;
const AXTreeData& GetTreeData() const override;
const AXTree::Selection GetUnignoredSelection() const override;
AXNodePosition::AXPositionInstance CreateTextPositionAt(
int offset) const override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
gfx::NativeViewAccessible GetParent() override;
int GetChildCount() const override;
gfx::NativeViewAccessible ChildAtIndex(int index) override;
gfx::Rect GetBoundsRect(const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const override;
gfx::Rect GetInnerTextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const override;
gfx::Rect GetHypertextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) const override;
gfx::NativeViewAccessible HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const override;
gfx::NativeViewAccessible GetFocus() override;
bool IsMinimized() const override;
bool IsWebContent() const override;
AXPlatformNode* GetFromNodeID(int32_t id) override;
AXPlatformNode* GetFromTreeIDAndNodeID(const ui::AXTreeID& ax_tree_id,
int32_t id) override;
int GetIndexInParent() override;
bool IsTable() const override;
std::optional<int> GetTableRowCount() const override;
std::optional<int> GetTableColCount() const override;
std::optional<int> GetTableAriaColCount() const override;
std::optional<int> GetTableAriaRowCount() const override;
std::optional<int> GetTableCellCount() const override;
std::optional<bool> GetTableHasColumnOrRowHeaderNode() const override;
std::vector<int32_t> GetColHeaderNodeIds() const override;
std::vector<int32_t> GetColHeaderNodeIds(int col_index) const override;
std::vector<int32_t> GetRowHeaderNodeIds() const override;
std::vector<int32_t> GetRowHeaderNodeIds(int row_index) const override;
bool IsTableRow() const override;
std::optional<int> GetTableRowRowIndex() const override;
bool IsTableCellOrHeader() const override;
std::optional<int> GetTableCellIndex() const override;
std::optional<int> GetTableCellColIndex() const override;
std::optional<int> GetTableCellRowIndex() const override;
std::optional<int> GetTableCellColSpan() const override;
std::optional<int> GetTableCellRowSpan() const override;
std::optional<int> GetTableCellAriaColIndex() const override;
std::optional<int> GetTableCellAriaRowIndex() const override;
std::optional<int32_t> GetCellId(int row_index, int col_index) const override;
std::optional<int32_t> CellIndexToId(int cell_index) const override;
bool IsCellOrHeaderOfARIATable() const override;
bool IsCellOrHeaderOfARIAGrid() const override;
gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override;
bool AccessibilityPerformAction(const AXActionData& data) override;
std::u16string GetLocalizedRoleDescriptionForUnlabeledImage() const override;
std::u16string GetLocalizedStringForLandmarkType() const override;
std::u16string GetLocalizedStringForRoleDescription() const override;
std::u16string GetLocalizedStringForImageAnnotationStatus(
ax::mojom::ImageAnnotationStatus status) const override;
std::u16string GetStyleNameAttributeAsLocalizedString() const override;
bool ShouldIgnoreHoveredStateForTesting() override;
const ui::AXUniqueId& GetUniqueId() const override;
bool HasVisibleCaretOrSelection() const override;
std::set<AXPlatformNode*> GetReverseRelations(
ax::mojom::IntAttribute attr) override;
std::set<AXPlatformNode*> GetReverseRelations(
ax::mojom::IntListAttribute attr) override;
bool IsOrderedSetItem() const override;
bool IsOrderedSet() const override;
std::optional<int> GetPosInSet() const override;
std::optional<int> GetSetSize() const override;
const std::vector<gfx::NativeViewAccessible> GetUIADescendants()
const override;
gfx::RectF GetLocation() const;
int InternalChildCount() const;
TestAXNodeWrapper* InternalGetChild(int index) const;
private:
TestAXNodeWrapper(AXTree* tree, AXNode* node);
void ReplaceIntAttribute(int32_t node_id,
ax::mojom::IntAttribute attribute,
int32_t value);
void ReplaceFloatAttribute(ax::mojom::FloatAttribute attribute, float value);
void ReplaceBoolAttribute(ax::mojom::BoolAttribute attribute, bool value);
void ReplaceStringAttribute(ax::mojom::StringAttribute attribute,
std::string value);
void ReplaceTreeDataTextSelection(int32_t anchor_node_id,
int32_t anchor_offset,
int32_t focus_node_id,
int32_t focus_offset);
TestAXNodeWrapper* HitTestSyncInternal(int x, int y);
void UIADescendants(
const AXNode* node,
std::vector<gfx::NativeViewAccessible>* descendants) const;
static bool ShouldHideChildrenForUIA(const AXNode* node);
// Return the bounds of inline text in this node's coordinate system (which is
// relative to its container node specified in AXRelativeBounds).
gfx::RectF GetInlineTextRect(const int start_offset,
const int end_offset) const;
// Determine the offscreen status of a particular element given its bounds..
AXOffscreenResult DetermineOffscreenResult(gfx::RectF bounds) const;
AXTree* tree_;
AXNode* node_;
ui::AXUniqueId unique_id_;
AXPlatformNode* platform_node_;
gfx::AcceleratedWidget native_event_target_;
bool minimized_ = false;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_TEST_AX_NODE_WRAPPER_H_
| engine/third_party/accessibility/ax/platform/test_ax_node_wrapper.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/test_ax_node_wrapper.h",
"repo_id": "engine",
"token_count": 2881
} | 446 |
// 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 ACCESSIBILITY_BASE_LOGGING_H_
#define ACCESSIBILITY_BASE_LOGGING_H_
#include <sstream>
#include "macros.h"
namespace base {
class LogMessageVoidify {
public:
void operator&(std::ostream&) {}
};
class LogMessage {
public:
LogMessage(const char* file,
int line,
const char* condition,
bool killProcess);
~LogMessage();
std::ostream& stream() { return stream_; }
private:
std::ostringstream stream_;
const char* file_;
const int line_;
const bool killProcess_;
BASE_DISALLOW_COPY_AND_ASSIGN(LogMessage);
};
[[noreturn]] void KillProcess();
} // namespace base
#define BASE_LOG_STREAM() \
::base::LogMessage(__FILE__, __LINE__, nullptr, false).stream()
#define BASE_LAZY_STREAM(stream, condition) \
!(condition) ? (void)0 : ::base::LogMessageVoidify() & (stream)
#define BASE_EAT_STREAM_PARAMETERS(ignored) \
true || (ignored) \
? (void)0 \
: ::base::LogMessageVoidify() & \
::base::LogMessage(0, 0, nullptr, !(ignored)).stream()
#define BASE_LOG() BASE_LAZY_STREAM(BASE_LOG_STREAM(), true)
#define BASE_CHECK(condition) \
BASE_LAZY_STREAM( \
::base::LogMessage(__FILE__, __LINE__, #condition, true).stream(), \
!(condition))
#ifndef NDEBUG
#define BASE_DLOG() BASE_LOG()
#define BASE_DCHECK(condition) BASE_CHECK(condition)
#else
#define BASE_DLOG() BASE_EAT_STREAM_PARAMETERS(true)
#define BASE_DCHECK(condition) BASE_EAT_STREAM_PARAMETERS(condition)
#endif
#define BASE_UNREACHABLE() \
{ \
BASE_LOG() << "Reached unreachable code."; \
::base::KillProcess(); \
}
#endif // ACCESSIBILITY_BASE_LOGGING_H_
| engine/third_party/accessibility/base/logging.h/0 | {
"file_path": "engine/third_party/accessibility/base/logging.h",
"repo_id": "engine",
"token_count": 949
} | 447 |
// 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_SAFE_MATH_ARM_IMPL_H_
#define BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_
#include <cassert>
#include <limits>
#include <type_traits>
#include "base/numerics/safe_conversions.h"
namespace base {
namespace internal {
template <typename T, typename U>
struct CheckedMulFastAsmOp {
static const bool is_supported =
FastIntegerArithmeticPromotion<T, U>::is_contained;
// The following is much more efficient than the Clang and GCC builtins for
// performing overflow-checked multiplication when a twice wider type is
// available. The below compiles down to 2-3 instructions, depending on the
// width of the types in use.
// As an example, an int32_t multiply compiles to:
// smull r0, r1, r0, r1
// cmp r1, r1, asr #31
// And an int16_t multiply compiles to:
// smulbb r1, r1, r0
// asr r2, r1, #16
// cmp r2, r1, asr #15
template <typename V>
__attribute__((always_inline)) static bool Do(T x, U y, V* result) {
using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type;
Promotion presult;
presult = static_cast<Promotion>(x) * static_cast<Promotion>(y);
*result = static_cast<V>(presult);
return IsValueInRangeForNumericType<V>(presult);
}
};
template <typename T, typename U>
struct ClampedAddFastAsmOp {
static const bool is_supported =
BigEnoughPromotion<T, U>::is_contained &&
IsTypeInRangeForNumericType<
int32_t,
typename BigEnoughPromotion<T, U>::type>::value;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
// This will get promoted to an int, so let the compiler do whatever is
// clever and rely on the saturated cast to bounds check.
if (IsIntegerArithmeticSafe<int, T, U>::value)
return saturated_cast<V>(x + y);
int32_t result;
int32_t x_i32 = checked_cast<int32_t>(x);
int32_t y_i32 = checked_cast<int32_t>(y);
asm("qadd %[result], %[first], %[second]"
: [result] "=r"(result)
: [first] "r"(x_i32), [second] "r"(y_i32));
return saturated_cast<V>(result);
}
};
template <typename T, typename U>
struct ClampedSubFastAsmOp {
static const bool is_supported =
BigEnoughPromotion<T, U>::is_contained &&
IsTypeInRangeForNumericType<
int32_t,
typename BigEnoughPromotion<T, U>::type>::value;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
// This will get promoted to an int, so let the compiler do whatever is
// clever and rely on the saturated cast to bounds check.
if (IsIntegerArithmeticSafe<int, T, U>::value)
return saturated_cast<V>(x - y);
int32_t result;
int32_t x_i32 = checked_cast<int32_t>(x);
int32_t y_i32 = checked_cast<int32_t>(y);
asm("qsub %[result], %[first], %[second]"
: [result] "=r"(result)
: [first] "r"(x_i32), [second] "r"(y_i32));
return saturated_cast<V>(result);
}
};
template <typename T, typename U>
struct ClampedMulFastAsmOp {
static const bool is_supported = CheckedMulFastAsmOp<T, U>::is_supported;
template <typename V>
__attribute__((always_inline)) static V Do(T x, U y) {
// Use the CheckedMulFastAsmOp for full-width 32-bit values, because
// it's fewer instructions than promoting and then saturating.
if (!IsIntegerArithmeticSafe<int32_t, T, U>::value &&
!IsIntegerArithmeticSafe<uint32_t, T, U>::value) {
V result;
if (CheckedMulFastAsmOp<T, U>::Do(x, y, &result))
return result;
return CommonMaxOrMin<V>(IsValueNegative(x) ^ IsValueNegative(y));
}
assert((FastIntegerArithmeticPromotion<T, U>::is_contained));
using Promotion = typename FastIntegerArithmeticPromotion<T, U>::type;
return saturated_cast<V>(static_cast<Promotion>(x) *
static_cast<Promotion>(y));
}
};
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_
| engine/third_party/accessibility/base/numerics/safe_math_arm_impl.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/safe_math_arm_impl.h",
"repo_id": "engine",
"token_count": 1645
} | 448 |
// 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 BASE_WIN_DISPLAY_H_
#define BASE_WIN_DISPLAY_H_
#include <windows.h>
#include <shellscalingapi.h>
#include "base/base_export.h"
namespace base {
namespace win {
float GetScaleFactorForHWND(HWND hwnd);
float ScaleFactorToFloat(DEVICE_SCALE_FACTOR scale_factor);
} // namespace win
} // namespace base
#endif // BASE_WIN_DISPLAY_H_
| engine/third_party/accessibility/base/win/display.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/display.h",
"repo_id": "engine",
"token_count": 182
} | 449 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/win/variant_vector.h"
#include <windows.foundation.h>
#include <wrl/client.h>
#include <cstddef>
#include "base/stl_util.h"
#include "base/test/gtest_util.h"
#include "base/win/dispatch_stub.h"
#include "base/win/scoped_safearray.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::win::test::DispatchStub;
namespace base {
namespace win {
TEST(VariantVectorTest, InitiallyEmpty) {
VariantVector vector;
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_TRUE(vector.Empty());
}
TEST(VariantVectorTest, MoveConstructor) {
VariantVector vector1;
Microsoft::WRL::ComPtr<IDispatch> dispatch =
Microsoft::WRL::Make<DispatchStub>();
vector1.Insert<VT_DISPATCH>(dispatch.Get());
EXPECT_EQ(vector1.Type(), VT_DISPATCH);
EXPECT_EQ(vector1.Size(), 1U);
VariantVector vector2(std::move(vector1));
EXPECT_EQ(vector1.Type(), VT_EMPTY);
EXPECT_EQ(vector1.Size(), 0U);
EXPECT_EQ(vector2.Type(), VT_DISPATCH);
EXPECT_EQ(vector2.Size(), 1U);
// |dispatch| should have been transferred to |vector2|.
EXPECT_EQ(dispatch.Reset(), 1U);
}
TEST(VariantVectorTest, MoveAssignOperator) {
VariantVector vector1, vector2;
Microsoft::WRL::ComPtr<IDispatch> dispatch1 =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IDispatch> dispatch2 =
Microsoft::WRL::Make<DispatchStub>();
vector1.Insert<VT_DISPATCH>(dispatch1.Get());
vector2.Insert<VT_UNKNOWN>(dispatch2.Get());
EXPECT_EQ(vector1.Type(), VT_DISPATCH);
EXPECT_EQ(vector1.Size(), 1U);
EXPECT_EQ(vector2.Type(), VT_UNKNOWN);
EXPECT_EQ(vector2.Size(), 1U);
vector1 = std::move(vector2);
EXPECT_EQ(vector1.Type(), VT_UNKNOWN);
EXPECT_EQ(vector1.Size(), 1U);
EXPECT_EQ(vector2.Type(), VT_EMPTY);
EXPECT_EQ(vector2.Size(), 0U);
// |dispatch1| should have been released during the move.
EXPECT_EQ(dispatch1.Reset(), 0U);
// |dispatch2| should have been transferred to |vector1|.
EXPECT_EQ(dispatch2.Reset(), 1U);
// Indirectly move |vector1| into itself.
VariantVector& reference_to_vector1 = vector1;
EXPECT_DCHECK_DEATH(vector1 = std::move(reference_to_vector1));
}
TEST(VariantVectorTest, Insert) {
VariantVector vector;
vector.Insert<VT_I4>(123);
EXPECT_EQ(vector.Type(), VT_I4);
// The first insert sets the type to VT_I4, and attempting to insert
// unrelated types will silently fail in release builds but DCHECKs
// in debug builds.
EXPECT_DCHECK_DEATH(vector.Insert<VT_UI4>(1U));
EXPECT_DCHECK_DEATH(vector.Insert<VT_R8>(100.0));
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 1U);
EXPECT_FALSE(vector.Empty());
}
TEST(VariantVectorTest, InsertCanUpcastDispatchToUnknown) {
Microsoft::WRL::ComPtr<IDispatch> dispatch =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IDispatch> unknown;
dispatch.CopyTo(&unknown);
VariantVector vector;
vector.Insert<VT_UNKNOWN>(unknown.Get());
vector.Insert<VT_UNKNOWN>(dispatch.Get());
vector.Insert<VT_DISPATCH>(dispatch.Get());
EXPECT_EQ(vector.Type(), VT_UNKNOWN);
EXPECT_EQ(vector.Size(), 3U);
}
TEST(VariantVectorTest, InsertCannotDowncastUnknownToDispatch) {
Microsoft::WRL::ComPtr<IDispatch> dispatch =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IDispatch> unknown;
dispatch.CopyTo(&unknown);
VariantVector vector;
vector.Insert<VT_DISPATCH>(dispatch.Get());
// The first insert sets the type to VT_DISPATCH, and attempting to
// explicitly insert VT_UNKNOWN will silently fail in release builds
// but DCHECKs in debug builds.
EXPECT_DCHECK_DEATH(vector.Insert<VT_UNKNOWN>(unknown.Get()));
EXPECT_DCHECK_DEATH(vector.Insert<VT_UNKNOWN>(dispatch.Get()));
EXPECT_EQ(vector.Type(), VT_DISPATCH);
EXPECT_EQ(vector.Size(), 1U);
}
TEST(VariantVectorTest, Reset) {
VariantVector vector;
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
vector.Insert<VT_I4>(123);
vector.Insert<VT_I4>(456);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 2U);
vector.Reset();
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
}
TEST(VariantVectorTest, ResetWithManagedContents) {
VariantVector vector;
// Test that managed contents are released when cleared.
Microsoft::WRL::ComPtr<IUnknown> unknown1 =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IUnknown> unknown2;
unknown1.CopyTo(&unknown2);
vector.Insert<VT_UNKNOWN>(unknown1.Get());
EXPECT_EQ(vector.Type(), VT_UNKNOWN);
EXPECT_EQ(vector.Size(), 1U);
// There are now 3 references to the value owned by |unknown1|.
// Remove ownership from |unknown2| should reduce the count to 2.
EXPECT_EQ(unknown2.Reset(), 2U);
// Resetting the VariantVector will reduce the count to 1.
vector.Reset();
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
// Then resetting |unknown1| should reduce to 0.
EXPECT_EQ(unknown1.Reset(), 0U);
}
TEST(VariantVectorTest, ScopeWithManagedContents) {
Microsoft::WRL::ComPtr<IUnknown> unknown1 =
Microsoft::WRL::Make<DispatchStub>();
{
VariantVector vector;
vector.Insert<VT_UNKNOWN>(unknown1.Get());
EXPECT_EQ(vector.Type(), VT_UNKNOWN);
EXPECT_EQ(vector.Size(), 1U);
Microsoft::WRL::ComPtr<IUnknown> unknown2;
unknown1.CopyTo(&unknown2);
// There are now 3 references to the value owned by |unknown1|.
// Remove ownership from |unknown2| should reduce the count to 2.
EXPECT_EQ(unknown2.Reset(), 2U);
}
// The VariantVector going out of scope will reduce the count to 1.
// Then resetting |unknown1| should reduce to 0.
EXPECT_EQ(unknown1.Reset(), 0U);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantEmpty) {
VariantVector vector;
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(variant.type(), VT_EMPTY);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleBool) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set(true);
vector.Insert<VT_BOOL>(true);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleI1) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((int8_t)34);
vector.Insert<VT_I1>(34);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleUI1) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((uint8_t)35U);
vector.Insert<VT_UI1>(35U);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleI2) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((int16_t)8738);
vector.Insert<VT_I2>(8738);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleUI2) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((uint16_t)8739U);
vector.Insert<VT_UI2>(8739U);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleI4) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((int32_t)572662306);
vector.Insert<VT_I4>(572662306);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleUI4) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((uint32_t)572662307U);
vector.Insert<VT_UI4>(572662307U);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleI8) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((int64_t)2459565876494606882);
vector.Insert<VT_I8>(2459565876494606882);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleUI8) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set((uint64_t)2459565876494606883U);
vector.Insert<VT_UI8>(2459565876494606883U);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleR4) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set(3.14159f);
vector.Insert<VT_R4>(3.14159f);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleR8) {
VariantVector vector;
ScopedVariant expected_variant;
expected_variant.Set(6.28318);
vector.Insert<VT_R8>(6.28318);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleDate) {
VariantVector vector;
ScopedVariant expected_variant;
SYSTEMTIME sys_time;
::GetSystemTime(&sys_time);
DATE date;
::SystemTimeToVariantTime(&sys_time, &date);
expected_variant.SetDate(date);
vector.Insert<VT_DATE>(date);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleBstr) {
VariantVector vector;
ScopedVariant expected_variant;
wchar_t test_string[] = L"Test string for BSTRs.";
expected_variant.Set(test_string);
vector.Insert<VT_BSTR>(test_string);
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleUnknown) {
VariantVector vector;
ScopedVariant expected_variant;
Microsoft::WRL::ComPtr<IUnknown> unknown =
Microsoft::WRL::Make<DispatchStub>();
expected_variant.Set(unknown.Get());
vector.Insert<VT_UNKNOWN>(unknown.Get());
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantSingleDispatch) {
VariantVector vector;
ScopedVariant expected_variant;
Microsoft::WRL::ComPtr<IDispatch> dispatch =
Microsoft::WRL::Make<DispatchStub>();
expected_variant.Set(dispatch.Get());
vector.Insert<VT_DISPATCH>(dispatch.Get());
EXPECT_EQ(vector.Type(), expected_variant.type());
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsScalarVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.Compare(expected_variant), 0);
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleBool) {
constexpr VARTYPE kVariantType = VT_BOOL;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(true);
vector.Insert<kVariantType>(false);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleI1) {
constexpr VARTYPE kVariantType = VT_I1;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(34);
vector.Insert<kVariantType>(52);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleUI1) {
constexpr VARTYPE kVariantType = VT_UI1;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(34U);
vector.Insert<kVariantType>(52U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleI2) {
constexpr VARTYPE kVariantType = VT_I2;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(8738);
vector.Insert<kVariantType>(8758);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleUI2) {
constexpr VARTYPE kVariantType = VT_UI2;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(8739U);
vector.Insert<kVariantType>(8759U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleI4) {
constexpr VARTYPE kVariantType = VT_I4;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(572662306);
vector.Insert<kVariantType>(572662307);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleUI4) {
constexpr VARTYPE kVariantType = VT_UI4;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(578662306U);
vector.Insert<kVariantType>(578662307U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleI8) {
constexpr VARTYPE kVariantType = VT_I8;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(2459565876494606882);
vector.Insert<kVariantType>(2459565876494606883);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleUI8) {
constexpr VARTYPE kVariantType = VT_UI8;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(2459565876494606883U);
vector.Insert<kVariantType>(2459565876494606884U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleR4) {
constexpr VARTYPE kVariantType = VT_R4;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(3.14159f);
vector.Insert<kVariantType>(6.28318f);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleR8) {
constexpr VARTYPE kVariantType = VT_R8;
VariantVector vector;
ScopedVariant variant;
vector.Insert<kVariantType>(6.28318);
vector.Insert<kVariantType>(3.14159);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleDate) {
constexpr VARTYPE kVariantType = VT_DATE;
VariantVector vector;
ScopedVariant variant;
SYSTEMTIME sys_time;
::GetSystemTime(&sys_time);
DATE date;
::SystemTimeToVariantTime(&sys_time, &date);
vector.Insert<kVariantType>(date);
vector.Insert<kVariantType>(date);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleBstr) {
constexpr VARTYPE kVariantType = VT_BSTR;
VariantVector vector;
ScopedVariant variant;
wchar_t some_text[] = L"some text";
wchar_t more_text[] = L"more text";
vector.Insert<kVariantType>(some_text);
vector.Insert<kVariantType>(more_text);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleUnknown) {
constexpr VARTYPE kVariantType = VT_UNKNOWN;
VariantVector vector;
ScopedVariant variant;
Microsoft::WRL::ComPtr<IUnknown> unknown1 =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IUnknown> unknown2 =
Microsoft::WRL::Make<DispatchStub>();
vector.Insert<kVariantType>(unknown1.Get());
vector.Insert<kVariantType>(unknown2.Get());
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsScalarVariantMultipleDispatch) {
constexpr VARTYPE kVariantType = VT_DISPATCH;
VariantVector vector;
ScopedVariant variant;
Microsoft::WRL::ComPtr<IDispatch> dispatch1 =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IDispatch> dispatch2 =
Microsoft::WRL::Make<DispatchStub>();
vector.Insert<kVariantType>(dispatch1.Get());
vector.Insert<kVariantType>(dispatch2.Get());
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
EXPECT_DCHECK_DEATH(vector.ReleaseAsScalarVariant());
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantEmpty) {
VariantVector vector;
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(variant.type(), VT_EMPTY);
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleBool) {
constexpr VARTYPE kVariantType = VT_BOOL;
VariantVector vector;
vector.Insert<kVariantType>(true);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), VARIANT_TRUE);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleI1) {
constexpr VARTYPE kVariantType = VT_I1;
VariantVector vector;
vector.Insert<kVariantType>(34);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 34);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleUI1) {
constexpr VARTYPE kVariantType = VT_UI1;
VariantVector vector;
vector.Insert<kVariantType>(34U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 34U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleI2) {
constexpr VARTYPE kVariantType = VT_I2;
VariantVector vector;
vector.Insert<kVariantType>(8738);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 8738);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleUI2) {
constexpr VARTYPE kVariantType = VT_UI2;
VariantVector vector;
vector.Insert<kVariantType>(8739U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 8739U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleI4) {
constexpr VARTYPE kVariantType = VT_I4;
VariantVector vector;
vector.Insert<kVariantType>(572662306);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 572662306);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleUI4) {
constexpr VARTYPE kVariantType = VT_UI4;
VariantVector vector;
vector.Insert<kVariantType>(578662306U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 578662306U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleI8) {
constexpr VARTYPE kVariantType = VT_I8;
VariantVector vector;
vector.Insert<kVariantType>(2459565876494606882);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 2459565876494606882);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleUI8) {
constexpr VARTYPE kVariantType = VT_UI8;
VariantVector vector;
vector.Insert<kVariantType>(2459565876494606883U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 2459565876494606883U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleR4) {
constexpr VARTYPE kVariantType = VT_R4;
VariantVector vector;
vector.Insert<kVariantType>(3.14159f);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 3.14159f);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleR8) {
constexpr VARTYPE kVariantType = VT_R8;
VariantVector vector;
vector.Insert<kVariantType>(6.28318);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), 6.28318);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleDate) {
constexpr VARTYPE kVariantType = VT_DATE;
VariantVector vector;
SYSTEMTIME sys_time;
::GetSystemTime(&sys_time);
DATE date;
::SystemTimeToVariantTime(&sys_time, &date);
vector.Insert<kVariantType>(date);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), date);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleBstr) {
constexpr VARTYPE kVariantType = VT_BSTR;
VariantVector vector;
wchar_t some_text[] = L"some text";
vector.Insert<kVariantType>(some_text);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_STREQ(lock_scope->at(0), some_text);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleUnknown) {
constexpr VARTYPE kVariantType = VT_UNKNOWN;
VariantVector vector;
Microsoft::WRL::ComPtr<IUnknown> unknown =
Microsoft::WRL::Make<DispatchStub>();
vector.Insert<kVariantType>(unknown.Get());
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), unknown.Get());
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantSingleDispatch) {
constexpr VARTYPE kVariantType = VT_DISPATCH;
VariantVector vector;
Microsoft::WRL::ComPtr<IDispatch> dispatch =
Microsoft::WRL::Make<DispatchStub>();
vector.Insert<kVariantType>(dispatch.Get());
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 1U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 1U);
EXPECT_EQ(lock_scope->at(0), dispatch.Get());
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleBool) {
constexpr VARTYPE kVariantType = VT_BOOL;
VariantVector vector;
vector.Insert<kVariantType>(true);
vector.Insert<kVariantType>(false);
vector.Insert<kVariantType>(true);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), VARIANT_TRUE);
EXPECT_EQ(lock_scope->at(1), VARIANT_FALSE);
EXPECT_EQ(lock_scope->at(2), VARIANT_TRUE);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleI1) {
constexpr VARTYPE kVariantType = VT_I1;
VariantVector vector;
vector.Insert<kVariantType>(34);
vector.Insert<kVariantType>(52);
vector.Insert<kVariantType>(12);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 34);
EXPECT_EQ(lock_scope->at(1), 52);
EXPECT_EQ(lock_scope->at(2), 12);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleUI1) {
constexpr VARTYPE kVariantType = VT_UI1;
VariantVector vector;
vector.Insert<kVariantType>(34U);
vector.Insert<kVariantType>(52U);
vector.Insert<kVariantType>(12U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 34U);
EXPECT_EQ(lock_scope->at(1), 52U);
EXPECT_EQ(lock_scope->at(2), 12U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleI2) {
constexpr VARTYPE kVariantType = VT_I2;
VariantVector vector;
vector.Insert<kVariantType>(8738);
vector.Insert<kVariantType>(8758);
vector.Insert<kVariantType>(42);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 8738);
EXPECT_EQ(lock_scope->at(1), 8758);
EXPECT_EQ(lock_scope->at(2), 42);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleUI2) {
constexpr VARTYPE kVariantType = VT_UI2;
VariantVector vector;
vector.Insert<kVariantType>(8739U);
vector.Insert<kVariantType>(8759U);
vector.Insert<kVariantType>(42U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 8739U);
EXPECT_EQ(lock_scope->at(1), 8759U);
EXPECT_EQ(lock_scope->at(2), 42U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleI4) {
constexpr VARTYPE kVariantType = VT_I4;
VariantVector vector;
vector.Insert<kVariantType>(572662306);
vector.Insert<kVariantType>(572662307);
vector.Insert<kVariantType>(572662308);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 572662306);
EXPECT_EQ(lock_scope->at(1), 572662307);
EXPECT_EQ(lock_scope->at(2), 572662308);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleUI4) {
constexpr VARTYPE kVariantType = VT_UI4;
VariantVector vector;
vector.Insert<kVariantType>(578662306U);
vector.Insert<kVariantType>(578662307U);
vector.Insert<kVariantType>(578662308U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 578662306U);
EXPECT_EQ(lock_scope->at(1), 578662307U);
EXPECT_EQ(lock_scope->at(2), 578662308U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleI8) {
constexpr VARTYPE kVariantType = VT_I8;
VariantVector vector;
vector.Insert<kVariantType>(2459565876494606882);
vector.Insert<kVariantType>(2459565876494606883);
vector.Insert<kVariantType>(2459565876494606884);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 2459565876494606882);
EXPECT_EQ(lock_scope->at(1), 2459565876494606883);
EXPECT_EQ(lock_scope->at(2), 2459565876494606884);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleUI8) {
constexpr VARTYPE kVariantType = VT_UI8;
VariantVector vector;
vector.Insert<kVariantType>(2459565876494606883U);
vector.Insert<kVariantType>(2459565876494606884U);
vector.Insert<kVariantType>(2459565876494606885U);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 3U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 3U);
EXPECT_EQ(lock_scope->at(0), 2459565876494606883U);
EXPECT_EQ(lock_scope->at(1), 2459565876494606884U);
EXPECT_EQ(lock_scope->at(2), 2459565876494606885U);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleR4) {
constexpr VARTYPE kVariantType = VT_R4;
VariantVector vector;
vector.Insert<kVariantType>(3.14159f);
vector.Insert<kVariantType>(6.28318f);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 2U);
EXPECT_EQ(lock_scope->at(0), 3.14159f);
EXPECT_EQ(lock_scope->at(1), 6.28318f);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleR8) {
constexpr VARTYPE kVariantType = VT_R8;
VariantVector vector;
vector.Insert<kVariantType>(6.28318);
vector.Insert<kVariantType>(3.14159);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 2U);
EXPECT_EQ(lock_scope->at(0), 6.28318);
EXPECT_EQ(lock_scope->at(1), 3.14159);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleDate) {
constexpr VARTYPE kVariantType = VT_DATE;
VariantVector vector;
SYSTEMTIME sys_time;
::GetSystemTime(&sys_time);
DATE date;
::SystemTimeToVariantTime(&sys_time, &date);
vector.Insert<kVariantType>(date);
vector.Insert<kVariantType>(date);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 2U);
EXPECT_EQ(lock_scope->at(0), date);
EXPECT_EQ(lock_scope->at(1), date);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleBstr) {
constexpr VARTYPE kVariantType = VT_BSTR;
VariantVector vector;
wchar_t some_text[] = L"some text";
wchar_t more_text[] = L"more text";
vector.Insert<kVariantType>(some_text);
vector.Insert<kVariantType>(more_text);
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 2U);
EXPECT_STREQ(lock_scope->at(0), some_text);
EXPECT_STREQ(lock_scope->at(1), more_text);
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleUnknown) {
constexpr VARTYPE kVariantType = VT_UNKNOWN;
VariantVector vector;
Microsoft::WRL::ComPtr<IUnknown> unknown1 =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IUnknown> unknown2 =
Microsoft::WRL::Make<DispatchStub>();
vector.Insert<kVariantType>(unknown1.Get());
vector.Insert<kVariantType>(unknown2.Get());
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 2U);
EXPECT_EQ(lock_scope->at(0), unknown1.Get());
EXPECT_EQ(lock_scope->at(1), unknown2.Get());
safearray.Release();
}
TEST(VariantVectorTest, ReleaseAsSafearrayVariantMultipleDispatch) {
constexpr VARTYPE kVariantType = VT_DISPATCH;
VariantVector vector;
Microsoft::WRL::ComPtr<IDispatch> dispatch1 =
Microsoft::WRL::Make<DispatchStub>();
Microsoft::WRL::ComPtr<IDispatch> dispatch2 =
Microsoft::WRL::Make<DispatchStub>();
vector.Insert<kVariantType>(dispatch1.Get());
vector.Insert<kVariantType>(dispatch2.Get());
EXPECT_EQ(vector.Type(), kVariantType);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
EXPECT_EQ(variant.type(), VT_ARRAY | kVariantType);
ScopedSafearray safearray(V_ARRAY(variant.ptr()));
base::Optional<ScopedSafearray::LockScope<kVariantType>> lock_scope =
safearray.CreateLockScope<kVariantType>();
ASSERT_TRUE(lock_scope.has_value());
ASSERT_EQ(lock_scope->size(), 2U);
EXPECT_EQ(lock_scope->at(0), dispatch1.Get());
EXPECT_EQ(lock_scope->at(1), dispatch2.Get());
safearray.Release();
}
TEST(VariantVectorTest, CompareVariant) {
VariantVector vector;
ScopedVariant variant;
EXPECT_EQ(vector.Compare(variant), 0);
vector.Insert<VT_I4>(123);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 1U);
variant.Set(123);
EXPECT_EQ(vector.Compare(variant), 0);
variant.Set(4);
EXPECT_EQ(vector.Compare(variant), 1);
variant.Set(567);
EXPECT_EQ(vector.Compare(variant), -1);
// Because the types do not match and VT_I4 is less-than VT_R8,
// |vector| compares as less-than |variant|, even though the value
// in |vector| is greater.
variant.Set(1.0);
EXPECT_EQ(variant.type(), VT_R8);
EXPECT_LT(vector.Type(), variant.type());
EXPECT_EQ(vector.Compare(variant), -1);
vector.Insert<VT_I4>(456);
EXPECT_EQ(vector.Size(), 2U);
// The first element of |vector| is equal to |variant|, but |vector|
// has more than one element so it is greater-than |variant|.
variant.Set(123);
EXPECT_EQ(vector.Compare(variant), 1);
// The first element of |vector| is greater-than |variant|.
variant.Set(5);
EXPECT_EQ(vector.Compare(variant), 1);
// The first element of |vector| is less-than |variant|.
variant.Set(1000);
EXPECT_EQ(vector.Compare(variant), -1);
}
TEST(VariantVectorTest, CompareSafearray) {
VariantVector vector;
vector.Insert<VT_I4>(123);
vector.Insert<VT_I4>(456);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 2U);
ScopedVariant variant(vector.ReleaseAsSafearrayVariant());
EXPECT_EQ(variant.type(), VT_ARRAY | VT_I4);
EXPECT_EQ(vector.Type(), VT_EMPTY);
EXPECT_EQ(vector.Size(), 0U);
// Because |vector| is now empty, it will compare as less-than the array.
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), -1);
EXPECT_EQ(vector.Compare(variant), -1);
vector.Insert<VT_I4>(123);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 1U);
// |vector| has fewer elements than |variant|.
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), -1);
EXPECT_EQ(vector.Compare(variant), -1);
vector.Insert<VT_I4>(456);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 2U);
// |vector| is now equal to |variant|.
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), 0);
EXPECT_EQ(vector.Compare(variant), 0);
vector.Insert<VT_I4>(789);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 3U);
// |vector| contains |variant| but has more elements so
// |vector| is now greater-than |variant|.
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), 1);
EXPECT_EQ(vector.Compare(variant), 1);
vector.Reset();
vector.Insert<VT_I4>(456);
EXPECT_EQ(vector.Type(), VT_I4);
EXPECT_EQ(vector.Size(), 1U);
// |vector| has fewer elements than |variant|, but the first element in
// |vector| compares as greater-than the first element in |variant|.
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), 1);
EXPECT_EQ(vector.Compare(variant), 1);
vector.Reset();
vector.Insert<VT_R8>(0.0);
vector.Insert<VT_R8>(0.0);
EXPECT_EQ(vector.Type(), VT_R8);
// Because the types do not match and VT_R8 is greater-than VT_I4,
// |vector| compares as greater-than |variant|, even though the values
// in |vector| are less-than the values in |variant|.
EXPECT_GT(VT_R8, VT_I4);
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), 1);
EXPECT_EQ(vector.Compare(variant), 1);
vector.Reset();
vector.Insert<VT_I2>(1000);
vector.Insert<VT_I2>(1000);
EXPECT_EQ(vector.Type(), VT_I2);
// Because the types do not match and VT_I2 is less-than VT_I4,
// |vector| compares as less-than |variant|, even though the values
// in |vector| are greater-than the values in |variant|.
EXPECT_LT(VT_I2, VT_I4);
EXPECT_EQ(vector.Compare(V_ARRAY(variant.ptr())), -1);
EXPECT_EQ(vector.Compare(variant), -1);
}
TEST(VariantVectorTest, CompareVariantVector) {
VariantVector vector1, vector2;
EXPECT_EQ(vector1.Compare(vector2), 0);
EXPECT_EQ(vector1, vector2);
vector1.Insert<VT_I4>(1);
EXPECT_EQ(vector1.Compare(vector2), 1);
EXPECT_EQ(vector2.Compare(vector1), -1);
EXPECT_NE(vector1, vector2);
vector2.Insert<VT_I4>(1);
EXPECT_EQ(vector1.Compare(vector2), 0);
EXPECT_EQ(vector2.Compare(vector1), 0);
EXPECT_EQ(vector1, vector2);
vector1.Insert<VT_I4>(1);
EXPECT_EQ(vector1.Compare(vector2), 1);
EXPECT_EQ(vector2.Compare(vector1), -1);
EXPECT_NE(vector1, vector2);
vector2.Insert<VT_I4>(2);
EXPECT_EQ(vector1.Compare(vector2), -1);
EXPECT_EQ(vector2.Compare(vector1), 1);
EXPECT_NE(vector1, vector2);
vector1.Reset();
vector1.Insert<VT_I4>(10);
vector2.Reset();
vector2.Insert<VT_R8>(5.0);
// Because the types do not match and VT_I4 is less-than VT_R8,
// |vector1| compares as less-than |vector2|, even though the value
// in |vector1| is greater.
EXPECT_LT(vector1.Type(), vector2.Type());
EXPECT_EQ(vector1.Compare(vector2), -1);
EXPECT_EQ(vector2.Compare(vector1), 1);
EXPECT_NE(vector1, vector2);
}
} // namespace win
} // namespace base
| engine/third_party/accessibility/base/win/variant_vector_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/base/win/variant_vector_unittest.cc",
"repo_id": "engine",
"token_count": 19669
} | 450 |
// 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.
// Defines a simple integer rectangle class. The containment semantics
// are array-like; that is, the coordinate (x, y) is considered to be
// contained by the rectangle, but the coordinate (x + width, y) is not.
// The class will happily let you create malformed rectangles (that is,
// rectangles with negative width and/or height), but there will be assertions
// in the operations (such as Contains()) to complain in this case.
#ifndef UI_GFX_GEOMETRY_RECT_H_
#define UI_GFX_GEOMETRY_RECT_H_
#include <cmath>
#include <iosfwd>
#include <string>
#include "ax_build/build_config.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "point.h"
#include "size.h"
#include "vector2d.h"
#if defined(OS_WIN)
typedef struct tagRECT RECT;
#elif defined(OS_APPLE)
typedef struct CGRect CGRect;
#endif
namespace gfx {
class Insets;
class GFX_EXPORT Rect {
public:
constexpr Rect() = default;
constexpr Rect(int width, int height) : size_(width, height) {}
constexpr Rect(int x, int y, int width, int height)
: origin_(x, y), size_(GetClampedValue(x, width), GetClampedValue(y, height)) {}
constexpr explicit Rect(const Size& size) : size_(size) {}
constexpr Rect(const Point& origin, const Size& size)
: origin_(origin),
size_(GetClampedValue(origin.x(), size.width()),
GetClampedValue(origin.y(), size.height())) {}
#if defined(OS_WIN)
explicit Rect(const RECT& r);
#elif defined(OS_APPLE)
explicit Rect(const CGRect& r);
#endif
#if defined(OS_WIN)
// Construct an equivalent Win32 RECT object.
RECT ToRECT() const;
#elif defined(OS_APPLE)
// Construct an equivalent CoreGraphics object.
CGRect ToCGRect() const;
#endif
constexpr int x() const { return origin_.x(); }
// Sets the X position while preserving the width.
void set_x(int x) {
origin_.set_x(x);
size_.set_width(GetClampedValue(x, width()));
}
constexpr int y() const { return origin_.y(); }
// Sets the Y position while preserving the height.
void set_y(int y) {
origin_.set_y(y);
size_.set_height(GetClampedValue(y, height()));
}
constexpr int width() const { return size_.width(); }
void set_width(int width) { size_.set_width(GetClampedValue(x(), width)); }
constexpr int height() const { return size_.height(); }
void set_height(int height) { size_.set_height(GetClampedValue(y(), height)); }
constexpr const Point& origin() const { return origin_; }
void set_origin(const Point& origin) {
origin_ = origin;
// Ensure that width and height remain valid.
set_width(width());
set_height(height());
}
constexpr const Size& size() const { return size_; }
void set_size(const Size& size) {
set_width(size.width());
set_height(size.height());
}
constexpr int right() const { return x() + width(); }
constexpr int bottom() const { return y() + height(); }
constexpr Point top_right() const { return Point(right(), y()); }
constexpr Point bottom_left() const { return Point(x(), bottom()); }
constexpr Point bottom_right() const { return Point(right(), bottom()); }
constexpr Point left_center() const { return Point(x(), y() + height() / 2); }
constexpr Point top_center() const { return Point(x() + width() / 2, y()); }
constexpr Point right_center() const { return Point(right(), y() + height() / 2); }
constexpr Point bottom_center() const { return Point(x() + width() / 2, bottom()); }
Vector2d OffsetFromOrigin() const { return Vector2d(x(), y()); }
void SetRect(int x, int y, int width, int height) {
origin_.SetPoint(x, y);
// Ensure that width and height remain valid.
set_width(width);
set_height(height);
}
// Use in place of SetRect() when you know the edges of the rectangle instead
// of the dimensions, rather than trying to determine the width/height
// yourself. This safely handles cases where the width/height would overflow.
void SetByBounds(int left, int top, int right, int bottom);
// Shrink the rectangle by a horizontal and vertical distance on all sides.
void Inset(int horizontal, int vertical) { Inset(horizontal, vertical, horizontal, vertical); }
// Shrink the rectangle by the given insets.
void Inset(const Insets& insets);
// Shrink the rectangle by the specified amount on each side.
void Inset(int left, int top, int right, int bottom);
// Move the rectangle by a horizontal and vertical distance.
void Offset(int horizontal, int vertical);
void Offset(const Vector2d& distance) { Offset(distance.x(), distance.y()); }
void operator+=(const Vector2d& offset);
void operator-=(const Vector2d& offset);
Insets InsetsFrom(const Rect& inner) const;
// Returns true if the area of the rectangle is zero.
bool IsEmpty() const { return size_.IsEmpty(); }
// A rect is less than another rect if its origin is less than
// the other rect's origin. If the origins are equal, then the
// shortest rect is less than the other. If the origin and the
// height are equal, then the narrowest rect is less than.
// This comparison is required to use Rects in sets, or sorted
// vectors.
bool operator<(const Rect& other) const;
// Returns true if the point identified by point_x and point_y falls inside
// this rectangle. The point (x, y) is inside the rectangle, but the
// point (x + width, y + height) is not.
bool Contains(int point_x, int point_y) const;
// Returns true if the specified point is contained by this rectangle.
bool Contains(const Point& point) const { return Contains(point.x(), point.y()); }
// Returns true if this rectangle contains the specified rectangle.
bool Contains(const Rect& rect) const;
// Returns true if this rectangle intersects the specified rectangle.
// An empty rectangle doesn't intersect any rectangle.
bool Intersects(const Rect& rect) const;
// Computes the intersection of this rectangle with the given rectangle.
void Intersect(const Rect& rect);
// Computes the union of this rectangle with the given rectangle. The union
// is the smallest rectangle containing both rectangles.
void Union(const Rect& rect);
// Computes the rectangle resulting from subtracting |rect| from |*this|,
// i.e. the bounding rect of |Region(*this) - Region(rect)|.
void Subtract(const Rect& rect);
// Fits as much of the receiving rectangle into the supplied rectangle as
// possible, becoming the result. For example, if the receiver had
// a x-location of 2 and a width of 4, and the supplied rectangle had
// an x-location of 0 with a width of 5, the returned rectangle would have
// an x-location of 1 with a width of 4.
void AdjustToFit(const Rect& rect);
// Returns the center of this rectangle.
Point CenterPoint() const;
// Becomes a rectangle that has the same center point but with a size capped
// at given |size|.
void ClampToCenteredSize(const Size& size);
// Transpose x and y axis.
void Transpose();
// Splits |this| in two halves, |left_half| and |right_half|.
void SplitVertically(Rect* left_half, Rect* right_half) const;
// Returns true if this rectangle shares an entire edge (i.e., same width or
// same height) with the given rectangle, and the rectangles do not overlap.
bool SharesEdgeWith(const Rect& rect) const;
// Returns the manhattan distance from the rect to the point. If the point is
// inside the rect, returns 0.
int ManhattanDistanceToPoint(const Point& point) const;
// Returns the manhattan distance between the contents of this rect and the
// contents of the given rect. That is, if the intersection of the two rects
// is non-empty then the function returns 0. If the rects share a side, it
// returns the smallest non-zero value appropriate for int.
int ManhattanInternalDistance(const Rect& rect) const;
std::string ToString() const;
bool ApproximatelyEqual(const Rect& rect, int tolerance) const;
private:
gfx::Point origin_;
gfx::Size size_;
// Returns true iff a+b would overflow max int.
static constexpr bool AddWouldOverflow(int a, int b) {
// In this function, GCC tries to make optimizations that would only work if
// max - a wouldn't overflow but it isn't smart enough to notice that a > 0.
// So cast everything to unsigned to avoid this. As it is guaranteed that
// max - a and b are both already positive, the cast is a noop.
//
// This is intended to be: a > 0 && max - a < b
return a > 0 && b > 0 &&
static_cast<unsigned>(std::numeric_limits<int>::max() - a) < static_cast<unsigned>(b);
}
// Clamp the size to avoid integer overflow in bottom() and right().
// This returns the width given an origin and a width.
// TODO(enne): this should probably use base::ClampAdd, but that
// function is not a constexpr.
static constexpr int GetClampedValue(int origin, int size) {
return AddWouldOverflow(origin, size) ? std::numeric_limits<int>::max() - origin : size;
}
};
inline bool operator==(const Rect& lhs, const Rect& rhs) {
return lhs.origin() == rhs.origin() && lhs.size() == rhs.size();
}
inline bool operator!=(const Rect& lhs, const Rect& rhs) {
return !(lhs == rhs);
}
GFX_EXPORT Rect operator+(const Rect& lhs, const Vector2d& rhs);
GFX_EXPORT Rect operator-(const Rect& lhs, const Vector2d& rhs);
inline Rect operator+(const Vector2d& lhs, const Rect& rhs) {
return rhs + lhs;
}
GFX_EXPORT Rect IntersectRects(const Rect& a, const Rect& b);
GFX_EXPORT Rect UnionRects(const Rect& a, const Rect& b);
GFX_EXPORT Rect SubtractRects(const Rect& a, const Rect& b);
// Constructs a rectangle with |p1| and |p2| as opposite corners.
//
// This could also be thought of as "the smallest rect that contains both
// points", except that we consider points on the right/bottom edges of the
// rect to be outside the rect. So technically one or both points will not be
// contained within the rect, because they will appear on one of these edges.
GFX_EXPORT Rect BoundingRect(const Point& p1, const Point& p2);
// Scales the rect and returns the enclosing rect. Use this only the inputs are
// known to not overflow. Use ScaleToEnclosingRectSafe if the inputs are
// unknown and need to use saturated math.
inline Rect ScaleToEnclosingRect(const Rect& rect, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
// These next functions cast instead of using e.g. base::ClampFloor() because
// we haven't checked to ensure that the clamping behavior of the helper
// functions doesn't degrade performance, and callers shouldn't be passing
// values that cause overflow anyway.
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::floor(rect.x() * x_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::floor(rect.y() * y_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::ceil(rect.right() * x_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::ceil(rect.bottom() * y_scale)));
int x = static_cast<int>(std::floor(rect.x() * x_scale));
int y = static_cast<int>(std::floor(rect.y() * y_scale));
int r = rect.width() == 0 ? x : static_cast<int>(std::ceil(rect.right() * x_scale));
int b = rect.height() == 0 ? y : static_cast<int>(std::ceil(rect.bottom() * y_scale));
return Rect(x, y, r - x, b - y);
}
inline Rect ScaleToEnclosingRect(const Rect& rect, float scale) {
return ScaleToEnclosingRect(rect, scale, scale);
}
// ScaleToEnclosingRect but clamping instead of asserting if the resulting rect
// would overflow.
// TODO(pkasting): Attempt to switch ScaleTo...Rect() to this construction and
// check performance.
inline Rect ScaleToEnclosingRectSafe(const Rect& rect, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
int x = base::ClampFloor(rect.x() * x_scale);
int y = base::ClampFloor(rect.y() * y_scale);
int w = base::ClampCeil(rect.width() * x_scale);
int h = base::ClampCeil(rect.height() * y_scale);
return Rect(x, y, w, h);
}
inline Rect ScaleToEnclosingRectSafe(const Rect& rect, float scale) {
return ScaleToEnclosingRectSafe(rect, scale, scale);
}
inline Rect ScaleToEnclosedRect(const Rect& rect, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::ceil(rect.x() * x_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::ceil(rect.y() * y_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::floor(rect.right() * x_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::floor(rect.bottom() * y_scale)));
int x = static_cast<int>(std::ceil(rect.x() * x_scale));
int y = static_cast<int>(std::ceil(rect.y() * y_scale));
int r = rect.width() == 0 ? x : static_cast<int>(std::floor(rect.right() * x_scale));
int b = rect.height() == 0 ? y : static_cast<int>(std::floor(rect.bottom() * y_scale));
return Rect(x, y, r - x, b - y);
}
inline Rect ScaleToEnclosedRect(const Rect& rect, float scale) {
return ScaleToEnclosedRect(rect, scale, scale);
}
// Scales |rect| by scaling its four corner points. If the corner points lie on
// non-integral coordinate after scaling, their values are rounded to the
// nearest integer.
// This is helpful during layout when relative positions of multiple gfx::Rect
// in a given coordinate space needs to be same after scaling as it was before
// scaling. ie. this gives a lossless relative positioning of rects.
inline Rect ScaleToRoundedRect(const Rect& rect, float x_scale, float y_scale) {
if (x_scale == 1.f && y_scale == 1.f)
return rect;
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::round(rect.x() * x_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::round(rect.y() * y_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::round(rect.right() * x_scale)));
BASE_DCHECK(base::IsValueInRangeForNumericType<int>(std::round(rect.bottom() * y_scale)));
int x = static_cast<int>(std::round(rect.x() * x_scale));
int y = static_cast<int>(std::round(rect.y() * y_scale));
int r = rect.width() == 0 ? x : static_cast<int>(std::round(rect.right() * x_scale));
int b = rect.height() == 0 ? y : static_cast<int>(std::round(rect.bottom() * y_scale));
return Rect(x, y, r - x, b - y);
}
inline Rect ScaleToRoundedRect(const Rect& rect, float scale) {
return ScaleToRoundedRect(rect, scale, scale);
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Rect& rect, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_RECT_H_
| engine/third_party/accessibility/gfx/geometry/rect.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/rect.h",
"repo_id": "engine",
"token_count": 4729
} | 451 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_VECTOR2D_CONVERSIONS_H_
#include "vector2d.h"
#include "vector2d_f.h"
namespace gfx {
// Returns a Vector2d with each component from the input Vector2dF floored.
GFX_EXPORT Vector2d ToFlooredVector2d(const Vector2dF& vector2d);
// Returns a Vector2d with each component from the input Vector2dF ceiled.
GFX_EXPORT Vector2d ToCeiledVector2d(const Vector2dF& vector2d);
// Returns a Vector2d with each component from the input Vector2dF rounded.
GFX_EXPORT Vector2d ToRoundedVector2d(const Vector2dF& vector2d);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_CONVERSIONS_H_
| engine/third_party/accessibility/gfx/geometry/vector2d_conversions.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/vector2d_conversions.h",
"repo_id": "engine",
"token_count": 304
} | 452 |
# 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/toolchain/wasm.gni")
# This toolchain is only to be used by the canvaskit target below.
wasm_toolchain("canvaskit") {
extra_toolchain_args = {
# Include ICU data.
skia_use_icu = true
skia_use_client_icu = false
# Include image codecs.
skia_use_libjpeg_turbo_decode = true
skia_use_libpng_decode = true
skia_use_libwebp_decode = true
# Disable LTO.
enable_lto = false
}
}
copy("canvaskit_group") {
visibility = [ "//flutter/web_sdk:*" ]
public_deps = [ "//flutter/skia/modules/canvaskit(:canvaskit)" ]
sources = [
"$root_out_dir/canvaskit/canvaskit.js",
"$root_out_dir/canvaskit/canvaskit.js.symbols",
"$root_out_dir/canvaskit/canvaskit.wasm",
]
outputs = [ "$root_out_dir/flutter_web_sdk/canvaskit/{{source_file_part}}" ]
}
# This toolchain is only to be used by canvaskit_chromium_group below.
wasm_toolchain("canvaskit_chromium") {
extra_toolchain_args = {
# In Chromium browsers, we can use the browser's APIs to get the necessary
# ICU data.
skia_use_icu = false
skia_use_client_icu = true
skia_icu_bidi_third_party_dir = "//flutter/third_party/canvaskit/icu_bidi"
# TODO(mdebbar): Set these to false once all image decoding can be done
# using the browser's built-in codecs.
# https://github.com/flutter/flutter/issues/122331
# In Chromium browsers, we can use the browser's built-in codecs.
skia_use_libjpeg_turbo_decode = true
skia_use_libpng_decode = true
skia_use_libwebp_decode = true
# Disable LTO.
enable_lto = false
}
}
copy("canvaskit_chromium_group") {
visibility = [ "//flutter/web_sdk:*" ]
public_deps = [ "//flutter/skia/modules/canvaskit(:canvaskit_chromium)" ]
sources = [
"$root_out_dir/canvaskit_chromium/canvaskit.js",
"$root_out_dir/canvaskit_chromium/canvaskit.js.symbols",
"$root_out_dir/canvaskit_chromium/canvaskit.wasm",
]
outputs = [
"$root_out_dir/flutter_web_sdk/canvaskit/chromium/{{source_file_part}}",
]
}
# This toolchain is only to be used by skwasm_group below.
wasm_toolchain("skwasm") {
extra_toolchain_args = {
# In Chromium browsers, we can use the browser's APIs to get the necessary
# ICU data.
skia_use_icu = false
skia_use_client_icu = true
skia_icu_bidi_third_party_dir = "//flutter/third_party/canvaskit/icu_bidi"
skia_use_libjpeg_turbo_decode = false
skia_use_libpng_decode = false
skia_use_libwebp_decode = false
# We use OffscreenCanvas to produce PNG data instead of skia
skia_use_no_png_encode = true
skia_use_libpng_encode = false
# skwasm is multithreaded
wasm_use_pthreads = true
wasm_prioritize_size = true
}
}
copy("skwasm_group") {
visibility = [ "//flutter/web_sdk:*" ]
public_deps = [ "//flutter/lib/web_ui/skwasm(:skwasm)" ]
sources = [
"$root_out_dir/skwasm/skwasm.js",
"$root_out_dir/skwasm/skwasm.js.symbols",
"$root_out_dir/skwasm/skwasm.wasm",
"$root_out_dir/skwasm/skwasm.worker.js",
]
if (is_debug) {
if (!wasm_use_dwarf) {
sources += [ "$root_out_dir/skwasm/skwasm.wasm.map" ]
}
}
outputs = [ "$root_out_dir/flutter_web_sdk/canvaskit/{{source_file_part}}" ]
}
| engine/third_party/canvaskit/BUILD.gn/0 | {
"file_path": "engine/third_party/canvaskit/BUILD.gn",
"repo_id": "engine",
"token_count": 1454
} | 453 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tonic/dart_list.h"
#include "tonic/logging/dart_error.h"
namespace tonic {
DartList::DartList(Dart_Handle dart_handle) : dart_handle_(dart_handle) {
TONIC_DCHECK(Dart_IsList(dart_handle_));
intptr_t length;
is_valid_ = !CheckAndHandleError(Dart_ListLength(dart_handle_, &length));
size_ = length;
}
DartList::DartList() {
dart_handle_ = Dart_Null();
size_ = 0;
is_valid_ = false;
}
DartList::DartList(DartList&& other)
: dart_handle_(other.dart_handle_),
size_(other.size_),
is_valid_(other.is_valid_) {
other.dart_handle_ = nullptr;
other.size_ = 0;
other.is_valid_ = false;
}
void DartList::Set(size_t index, Dart_Handle value) {
CheckAndHandleError(Dart_ListSetAt(dart_handle_, index, value));
}
DartList DartConverter<DartList>::FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception) {
Dart_Handle list = Dart_GetNativeArgument(args, index);
if (CheckAndHandleError(list) || !Dart_IsList(list)) {
exception = Dart_NewApiError("Invalid Argument");
return DartList();
}
return DartList(list);
}
} // namespace tonic
| engine/third_party/tonic/dart_list.cc/0 | {
"file_path": "engine/third_party/tonic/dart_list.cc",
"repo_id": "engine",
"token_count": 578
} | 454 |
// 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 LIB_TONIC_FILE_LOADER_FILE_LOADER_H_
#define LIB_TONIC_FILE_LOADER_FILE_LOADER_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
#include "tonic/parsers/packages_map.h"
namespace tonic {
class FileLoader {
public:
explicit FileLoader(int dirfd = -1);
~FileLoader();
bool LoadPackagesMap(const std::string& packages);
// The path to the `.packages` file the packages map was loaded from.
const std::string& packages() const { return packages_; }
Dart_Handle HandleLibraryTag(Dart_LibraryTag tag,
Dart_Handle library,
Dart_Handle url);
Dart_Handle CanonicalizeURL(Dart_Handle library, Dart_Handle url);
Dart_Handle Import(Dart_Handle url);
Dart_Handle Kernel(Dart_Handle url);
void SetPackagesUrl(Dart_Handle url);
Dart_Handle FetchBytes(const std::string& url,
uint8_t*& buffer,
intptr_t& buffer_size);
static const char kFileURLPrefix[];
static const size_t kFileURLPrefixLength;
static const std::string kPathSeparator;
private:
static std::string SanitizeURIEscapedCharacters(const std::string& str);
static std::string SanitizePath(const std::string& path);
std::string GetFilePathForURL(std::string url);
std::string GetFilePathForPackageURL(std::string url);
std::string GetFilePathForFileURL(std::string url);
std::string GetFileURLForPath(const std::string& path);
bool ReadFileToString(const std::string& path, std::string* result);
std::pair<uint8_t*, intptr_t> ReadFileToBytes(const std::string& path);
int dirfd_;
std::string packages_;
std::unique_ptr<PackagesMap> packages_map_;
std::vector<uint8_t*> kernel_buffers_;
TONIC_DISALLOW_COPY_AND_ASSIGN(FileLoader);
};
} // namespace tonic
#endif // LIB_TONIC_FILE_LOADER_FILE_LOADER_H_
| engine/third_party/tonic/file_loader/file_loader.h/0 | {
"file_path": "engine/third_party/tonic/file_loader/file_loader.h",
"repo_id": "engine",
"token_count": 786
} | 455 |
// 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 <fcntl.h>
#include <sys/types.h>
#include <string>
#include <vector>
#include "filesystem/scoped_temp_dir.h"
#include "filesystem/unique_fd.h"
#include "gtest/gtest.h"
namespace filesystem {
TEST(FileDescriptor, WriteAndRead) {
files::ScopedTempDir temp_dir;
std::string path;
ASSERT_TRUE(temp_dir.NewTempFile(&path));
fxl::UniqueFD fd(open(path.c_str(), O_RDWR));
ASSERT_TRUE(fd.is_valid());
std::string string = "one, two, three";
EXPECT_TRUE(WriteFileDescriptor(fd.get(), string.data(), string.size()));
EXPECT_EQ(0, lseek(fd.get(), 0, SEEK_SET));
std::vector<char> buffer;
buffer.resize(1024);
ssize_t read = ReadFileDescriptor(fd.get(), buffer.data(), 1024);
EXPECT_EQ(static_cast<ssize_t>(string.size()), read);
EXPECT_EQ(string, buffer.data());
}
} // namespace filesystem
| engine/third_party/tonic/filesystem/tests/file_descriptor_unittest.cc/0 | {
"file_path": "engine/third_party/tonic/filesystem/tests/file_descriptor_unittest.cc",
"repo_id": "engine",
"token_count": 368
} | 456 |
// 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/third_party/tonic/dart_state.h"
#include "flutter/common/task_runners.h"
#include "flutter/runtime/dart_vm_lifecycle.h"
#include "flutter/runtime/isolate_configuration.h"
#include "flutter/testing/fixture_test.h"
namespace flutter {
namespace testing {
using DartState = FixtureTest;
TEST_F(DartState, CurrentWithNullDataDoesNotSegfault) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_snapshot = DartSnapshot::VMSnapshotFromSettings(settings);
auto isolate_snapshot = DartSnapshot::IsolateSnapshotFromSettings(settings);
auto vm_ref = DartVMRef::Create(settings, vm_snapshot, isolate_snapshot);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
TaskRunners task_runners(GetCurrentTestName(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner() //
);
auto isolate_configuration =
IsolateConfiguration::InferFromSettings(settings);
Dart_IsolateFlags isolate_flags;
Dart_IsolateFlagsInitialize(&isolate_flags);
isolate_flags.null_safety =
isolate_configuration->IsNullSafetyEnabled(*isolate_snapshot);
isolate_flags.snapshot_is_dontneed_safe = isolate_snapshot->IsDontNeedSafe();
char* error;
Dart_CreateIsolateGroup(
"main.dart", "main", vm_data->GetIsolateSnapshot()->GetDataMapping(),
vm_data->GetIsolateSnapshot()->GetInstructionsMapping(), &isolate_flags,
nullptr, nullptr, &error);
ASSERT_FALSE(error) << error;
::free(error);
ASSERT_FALSE(tonic::DartState::Current());
Dart_ShutdownIsolate();
ASSERT_TRUE(Dart_CurrentIsolate() == nullptr);
}
TEST_F(DartState, IsShuttingDown) {
ASSERT_FALSE(DartVMRef::IsInstanceRunning());
auto settings = CreateSettingsForFixture();
auto vm_ref = DartVMRef::Create(settings);
ASSERT_TRUE(vm_ref);
auto vm_data = vm_ref.GetVMData();
ASSERT_TRUE(vm_data);
TaskRunners task_runners(GetCurrentTestName(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner(), //
GetCurrentTaskRunner() //
);
auto isolate_configuration =
IsolateConfiguration::InferFromSettings(settings);
UIDartState::Context context(std::move(task_runners));
context.advisory_script_uri = "main.dart";
context.advisory_script_entrypoint = "main";
auto weak_isolate = DartIsolate::CreateRunningRootIsolate(
vm_data->GetSettings(), // settings
vm_data->GetIsolateSnapshot(), // isolate snapshot
nullptr, // platform configuration
DartIsolate::Flags{}, // flags
nullptr, // root_isolate_create_callback
settings.isolate_create_callback, // isolate create callback
settings.isolate_shutdown_callback, // isolate shutdown callback
"main", // dart entrypoint
std::nullopt, // dart entrypoint library
{}, // dart entrypoint arguments
std::move(isolate_configuration), // isolate configuration
std::move(context) // engine context
);
auto root_isolate = weak_isolate.lock();
ASSERT_TRUE(root_isolate);
tonic::DartState* dart_state = root_isolate.get();
ASSERT_FALSE(dart_state->IsShuttingDown());
ASSERT_TRUE(root_isolate->Shutdown());
ASSERT_TRUE(dart_state->IsShuttingDown());
}
} // namespace testing
} // namespace flutter
| engine/third_party/tonic/tests/dart_state_unittest.cc/0 | {
"file_path": "engine/third_party/tonic/tests/dart_state_unittest.cc",
"repo_id": "engine",
"token_count": 1597
} | 457 |
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//flutter/common/config.gni")
import("//flutter/testing/testing.gni")
if (is_fuchsia) {
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
}
declare_args() {
flutter_use_fontconfig = false
}
if (flutter_use_fontconfig) {
assert(is_linux)
}
config("txt_config") {
visibility = [ ":*" ]
include_dirs = [ "src" ]
}
config("allow_posix_names") {
if (is_win && is_clang) {
# POSIX names of many functions are marked deprecated by default;
# disable that since they are used for cross-platform compatibility.
defines = [ "_CRT_NONSTDC_NO_DEPRECATE" ]
}
}
source_set("txt") {
sources = [
"src/skia/paragraph_builder_skia.cc",
"src/skia/paragraph_builder_skia.h",
"src/skia/paragraph_skia.cc",
"src/skia/paragraph_skia.h",
"src/txt/asset_font_manager.cc",
"src/txt/asset_font_manager.h",
"src/txt/font_asset_provider.cc",
"src/txt/font_asset_provider.h",
"src/txt/font_collection.cc",
"src/txt/font_collection.h",
"src/txt/font_features.cc",
"src/txt/font_features.h",
"src/txt/font_style.h",
"src/txt/font_weight.h",
"src/txt/line_metrics.h",
"src/txt/paragraph.h",
"src/txt/paragraph_builder.cc",
"src/txt/paragraph_builder.h",
"src/txt/paragraph_style.cc",
"src/txt/paragraph_style.h",
"src/txt/placeholder_run.cc",
"src/txt/placeholder_run.h",
"src/txt/platform.h",
"src/txt/run_metrics.h",
"src/txt/test_font_manager.cc",
"src/txt/test_font_manager.h",
"src/txt/text_baseline.h",
"src/txt/text_decoration.cc",
"src/txt/text_decoration.h",
"src/txt/text_shadow.cc",
"src/txt/text_shadow.h",
"src/txt/text_style.cc",
"src/txt/text_style.h",
"src/txt/typeface_font_asset_provider.cc",
"src/txt/typeface_font_asset_provider.h",
]
public_configs = [ ":txt_config" ]
public_deps = [
"//flutter/display_list",
"//flutter/fml",
"//flutter/impeller/typographer/backends/skia:typographer_skia_backend",
"//flutter/skia",
"//flutter/third_party/harfbuzz",
"//flutter/third_party/icu",
]
deps = [
"//flutter/skia",
"//flutter/skia/modules/skparagraph",
]
libs = []
if (flutter_use_fontconfig) {
libs += [ "fontconfig" ]
}
if (is_mac || is_ios) {
sources += [
"src/txt/platform_mac.h",
"src/txt/platform_mac.mm",
]
deps += [ "//flutter/fml" ]
} else if (is_android) {
sources += [ "src/txt/platform_android.cc" ]
} else if (is_linux) {
sources += [ "src/txt/platform_linux.cc" ]
} else if (is_fuchsia) {
sources += [ "src/txt/platform_fuchsia.cc" ]
deps += [ "${fuchsia_sdk}/fidl/fuchsia.fonts" ]
} else if (is_win) {
sources += [ "src/txt/platform_windows.cc" ]
} else {
sources += [ "src/txt/platform.cc" ]
}
}
if (enable_unittests) {
test_fixtures("txt_fixtures") {
fixtures = [ "third_party/fonts/Roboto-Regular.ttf" ]
}
executable("txt_benchmarks") {
testonly = true
sources = [
"benchmarks/skparagraph_benchmarks.cc",
"benchmarks/txt_run_all_benchmarks.cc",
"tests/txt_test_utils.cc",
"tests/txt_test_utils.h",
]
deps = [
":txt",
":txt_fixtures",
"//flutter/fml",
"//flutter/skia/modules/skparagraph",
"//flutter/testing:testing_lib",
"//flutter/third_party/benchmark",
]
}
executable("txt_unittests") {
testonly = true
sources = [
"tests/font_collection_tests.cc",
"tests/paragraph_builder_skia_tests.cc",
"tests/paragraph_unittests.cc",
"tests/txt_run_all_unittests.cc",
]
if (is_mac || is_ios) {
sources += [ "tests/platform_mac_tests.cc" ]
}
public_configs = [ ":txt_config" ]
configs += [ ":allow_posix_names" ]
deps = [
":txt",
":txt_fixtures",
"//flutter/fml",
"//flutter/runtime:test_font",
"//flutter/skia/modules/skparagraph:skparagraph",
"//flutter/testing:skia",
"//flutter/testing:testing_lib",
]
# This is needed for //flutter/third_party/googletest for linking zircon
# symbols.
if (is_fuchsia) {
libs =
[ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ]
}
}
}
| engine/third_party/txt/BUILD.gn/0 | {
"file_path": "engine/third_party/txt/BUILD.gn",
"repo_id": "engine",
"token_count": 2092
} | 458 |
// 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 "third_party/skia/include/ports/SkTypeface_win.h"
#include "txt/platform.h"
namespace txt {
std::vector<std::string> GetDefaultFontFamilies() {
return {"Segoe UI", "Arial"};
}
sk_sp<SkFontMgr> GetDefaultFontManager(uint32_t font_initialization_data) {
return SkFontMgr_New_DirectWrite();
}
} // namespace txt
| engine/third_party/txt/src/txt/platform_windows.cc/0 | {
"file_path": "engine/third_party/txt/src/txt/platform_windows.cc",
"repo_id": "engine",
"token_count": 166
} | 459 |
// 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 <sstream>
#include "txt/platform_mac.h"
namespace txt {
namespace testing {
class PlatformMacTests : public ::testing::Test {
public:
PlatformMacTests() {}
void SetUp() override {}
};
TEST_F(PlatformMacTests, RegisterSystemFonts) {
DynamicFontManager dynamic_font_manager;
RegisterSystemFonts(dynamic_font_manager);
ASSERT_EQ(dynamic_font_manager.font_provider().GetFamilyCount(), 1ul);
ASSERT_NE(dynamic_font_manager.font_provider().MatchFamily(
"CupertinoSystemDisplay"),
nullptr);
ASSERT_EQ(dynamic_font_manager.font_provider()
.MatchFamily("CupertinoSystemDisplay")
->count(),
10);
}
} // namespace testing
} // namespace txt
| engine/third_party/txt/tests/platform_mac_tests.cc/0 | {
"file_path": "engine/third_party/txt/tests/platform_mac_tests.cc",
"repo_id": "engine",
"token_count": 347
} | 460 |
//---------------------------------------------------------------------------------------------
// Copyright (c) 2022 Google LLC
// Licensed under the MIT License. See License.txt in the project root for license information.
//--------------------------------------------------------------------------------------------*/
import 'key_mappings.g.dart';
int? _characterToLogicalKey(String? key) {
// We have yet to find a case where length >= 2 is useful.
if (key == null || key.length >= 2) {
return null;
}
final int result = key.toLowerCase().codeUnitAt(0);
return result;
}
/// Maps locale-sensitive keys from KeyboardEvent properties to a logical key.
class LocaleKeymap {
/// Create a [LocaleKeymap] for Windows.
LocaleKeymap.win() : _mapping = getMappingDataWin();
/// Create a [LocaleKeymap] for Linux.
LocaleKeymap.linux() : _mapping = getMappingDataLinux();
/// Create a [LocaleKeymap] for Darwin.
LocaleKeymap.darwin() : _mapping = getMappingDataDarwin();
/// Return a logical key mapped from KeyboardEvent properties.
///
/// This method handles all printable characters, including letters, digits,
/// and symbols.
///
/// Before calling this method, the caller should have eliminated cases where
/// the event key is a "key name", such as "Shift" or "AudioVolumnDown".
///
/// If the return value is null, there's no way to derive a meaningful value
/// from the printable information of the event.
int? getLogicalKey(String? eventCode, String? eventKey, int eventKeyCode) {
final int? result = _mapping[eventCode]?[eventKey];
if (result == kUseKeyCode) {
return eventKeyCode;
}
if (result == null) {
if ((eventCode ?? '').isEmpty && (eventKey ?? '').isEmpty) {
return null;
}
final int? heuristicResult = heuristicMapper(eventCode ?? '', eventKey ?? '');
if (heuristicResult != null) {
return heuristicResult;
}
// Characters: map to unicode zone.
//
// While characters are usually resolved in the last step, this can happen
// in non-latin layouts when a non-latin character is on a symbol key (ru,
// Semicolon-ж) or on an alnum key that has been assigned elsewhere (hu,
// Digit0-Ö).
final int? characterLogicalKey = _characterToLogicalKey(eventKey);
if (characterLogicalKey != null) {
return characterLogicalKey;
}
}
return result;
}
final Map<String, Map<String, int>> _mapping;
}
| engine/third_party/web_locale_keymap/lib/web_locale_keymap/locale_keymap.dart/0 | {
"file_path": "engine/third_party/web_locale_keymap/lib/web_locale_keymap/locale_keymap.dart",
"repo_id": "engine",
"token_count": 782
} | 461 |
// 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.
// ignore_for_file: avoid_print
import 'dart:io';
import 'package:args/args.dart';
import 'package:path/path.dart' as path;
const int _kChar_A = 65;
const int _kChar_a = 97;
final ArgParser argParser = ArgParser()
..addFlag(
'check',
help: 'Check mode does not write anything to disk. '
'It just checks if the generated files are still in sync or not.',
);
/// A map of properties that could safely be normalized into other properties.
///
/// For example, a NL behaves exactly the same as BK so it gets normalized to BK
/// in the generated code.
const Map<String, String> normalizationTable = <String, String>{
// NL behaves exactly the same as BK.
// See: https://www.unicode.org/reports/tr14/tr14-45.html#NL
'NL': 'BK',
// In the absence of extra data (ICU data and language dictionaries), the
// following properties will be treated as AL (alphabetic): AI, SA, SG and XX.
// See LB1: https://www.unicode.org/reports/tr14/tr14-45.html#LB1
'AI': 'AL',
'SA': 'AL',
'SG': 'AL',
'XX': 'AL',
// https://unicode.org/reports/tr14/tr14-45.html#CJ
'CJ': 'NS',
};
/// A tuple that holds a [start] and [end] of a unicode range and a [property].
class UnicodeRange {
const UnicodeRange(this.start, this.end, this.property);
final int start;
final int end;
final EnumValue property;
/// Checks if there's an overlap between this range and the [other] range.
bool isOverlapping(UnicodeRange other) {
return start <= other.end && end >= other.start;
}
/// Checks if the [other] range is adjacent to this range.
///
/// Two ranges are considered adjacent if:
/// - The new range immediately follows this range, and
/// - The new range has the same property as this range.
bool isAdjacent(UnicodeRange other) {
return other.start == end + 1 && property == other.property;
}
/// Merges the ranges of the 2 [UnicodeRange]s if they are adjacent.
UnicodeRange extendRange(UnicodeRange extension) {
assert(isAdjacent(extension));
return UnicodeRange(start, extension.end, property);
}
}
final String webUnicodeRoot = path.dirname(path.dirname(Platform.script.toFilePath()));
final String propertiesDir = path.join(webUnicodeRoot, 'properties');
final String wordProperties = path.join(propertiesDir, 'WordBreakProperty.txt');
final String lineProperties = path.join(propertiesDir, 'LineBreak.txt');
final String codegenDir = path.join(webUnicodeRoot, 'lib', 'codegen');
final String wordBreakCodegen = path.join(codegenDir, 'word_break_properties.dart');
final String lineBreakCodegen = path.join(codegenDir, 'line_break_properties.dart');
/// This script parses the unicode word/line break properties(1) and generates Dart
/// code(2) that can perform lookups in the unicode ranges to find what property
/// a letter has.
///
/// (1) The word break properties file can be downloaded from:
/// https://www.unicode.org/Public/13.0.0/ucd/auxiliary/WordBreakProperty.txt
///
/// The line break properties file can be downloaded from:
/// https://www.unicode.org/Public/13.0.0/ucd/LineBreak.txt
///
/// Both files need to be located at third_party/web_unicode/properties.
///
/// (2) The codegen'd Dart files are located at:
/// third_party/web_unicode/lib/codegen/word_break_properties.dart
/// third_party/web_unicode/lib/codegen/line_break_properties.dart
Future<void> main(List<String> arguments) async {
final ArgResults result = argParser.parse(arguments);
final bool isCheck = result['check'] as bool;
final List<PropertiesSyncer> syncers = <PropertiesSyncer>[
WordBreakPropertiesSyncer(isCheck: isCheck),
LineBreakPropertiesSyncer(isCheck: isCheck),
];
for (final PropertiesSyncer syncer in syncers) {
await syncer.perform();
}
}
/// Base class that provides common logic for syncing all kinds of unicode
/// properties (e.g. word break properties, line break properties, etc).
///
/// Subclasses implement the [template] method which receives as argument the
/// list of data parsed by [processLines].
abstract class PropertiesSyncer {
PropertiesSyncer(this._src, this._dest, {required this.isCheck});
final String _src;
final String _dest;
final bool isCheck;
String get prefix;
String get enumDocLink;
/// The default property to be used when a certain code point doesn't belong
/// to any known range.
String get defaultProperty;
Future<void> perform() async {
final List<String> lines = await File(_src).readAsLines();
final PropertyCollection data =
PropertyCollection.fromLines(lines, defaultProperty);
final String output = template(data);
if (isCheck) {
// Read from destination and compare to the generated output.
final String existing = await File(_dest).readAsString();
if (existing != output) {
final String relativeDest = path.relative(_dest, from: webUnicodeRoot);
print('ERROR: $relativeDest is out of sync.');
print('Please run "dart tool/unicode_sync_script.dart" to update it.');
exit(1);
}
} else {
final IOSink sink = File(_dest).openWrite();
sink.write(output);
}
}
String template(PropertyCollection data) {
return '''
// Copyright 2022 Google LLC
//
// For terms of use, see https://www.unicode.org/copyright.html
// AUTO-GENERATED FILE.
// Generated by: tool/unicode_sync_script.dart
// ignore_for_file: public_member_api_docs
/// For an explanation of these enum values, see:
///
/// * $enumDocLink
enum ${prefix}CharProperty {
${_getEnumValues(data.enumCollection).join('\n ')}
}
const String packed${prefix}BreakProperties =
'${_packProperties(data)}';
const int single${prefix}BreakRangesCount = ${_getSingleRangesCount(data)};
const ${prefix}CharProperty default${prefix}CharProperty = ${prefix}CharProperty.$defaultProperty;
''';
}
Iterable<String> _getEnumValues(EnumCollection enumCollection) {
return enumCollection.values.expand(
(EnumValue value) => <String>[
if (value.normalizedFrom.isNotEmpty)
'// Normalized from: ${value.normalizedFrom.join(', ')}',
'${value.enumName}, // serialized as "${value.serialized}"',
],
);
}
int _getSingleRangesCount(PropertyCollection data) {
int count = 0;
for (final UnicodeRange range in data.ranges) {
if (range.start == range.end) {
count++;
}
}
return count;
}
String _packProperties(PropertyCollection data) {
final StringBuffer buffer = StringBuffer();
for (final UnicodeRange range in data.ranges) {
buffer.write(range.start.toRadixString(36).padLeft(4, '0'));
if (range.start == range.end) {
buffer.write('!');
} else {
buffer.write(range.end.toRadixString(36).padLeft(4, '0'));
}
buffer.write(range.property.serialized);
}
return buffer.toString();
}
}
/// Syncs Unicode's word break properties.
class WordBreakPropertiesSyncer extends PropertiesSyncer {
WordBreakPropertiesSyncer({required bool isCheck})
: super(wordProperties, wordBreakCodegen, isCheck: isCheck);
@override
final String prefix = 'Word';
@override
final String enumDocLink =
'http://unicode.org/reports/tr29/#Table_Word_Break_Property_Values';
@override
final String defaultProperty = 'Unknown';
}
/// Syncs Unicode's line break properties.
class LineBreakPropertiesSyncer extends PropertiesSyncer {
LineBreakPropertiesSyncer({required bool isCheck})
: super(lineProperties, lineBreakCodegen, isCheck: isCheck);
@override
final String prefix = 'Line';
@override
final String enumDocLink =
'https://www.unicode.org/reports/tr14/tr14-45.html#DescriptionOfProperties';
@override
final String defaultProperty = 'AL';
}
/// Holds the collection of properties parsed from the unicode spec file.
class PropertyCollection {
PropertyCollection.fromLines(List<String> lines, String defaultProperty) {
final List<UnicodeRange> unprocessedRanges = lines
.map(removeCommentFromLine)
.where((String line) => line.isNotEmpty)
.map(parseLineIntoUnicodeRange)
.toList();
// Insert the default property if it doesn't exist.
final EnumValue? found = enumCollection.values.cast<EnumValue?>().firstWhere(
(EnumValue? property) => property!.name == defaultProperty,
orElse: () => null,
);
if (found == null) {
enumCollection.add(defaultProperty);
}
ranges = processRanges(unprocessedRanges, defaultProperty).toList();
}
late List<UnicodeRange> ranges;
final EnumCollection enumCollection = EnumCollection();
/// Examples:
///
/// 00C0..00D6 ; ALetter
/// 037F ; ALetter
///
/// Would be parsed into:
///
/// ```dart
/// UnicodeRange(192, 214, EnumValue('ALetter'));
/// UnicodeRange(895, 895, EnumValue('ALetter'));
/// ```
UnicodeRange parseLineIntoUnicodeRange(String line) {
final List<String> split = line.split(';');
final String rangeStr = split[0].trim();
final String propertyStr = split[1].trim();
final EnumValue property = normalizationTable.containsKey(propertyStr)
? enumCollection.add(normalizationTable[propertyStr]!, propertyStr)
: enumCollection.add(propertyStr);
return UnicodeRange(
getRangeStart(rangeStr),
getRangeEnd(rangeStr),
property,
);
}
}
/// Represents the collection of values of an enum.
class EnumCollection {
final List<EnumValue> values = <EnumValue>[];
EnumValue add(String name, [String? normalizedFrom]) {
final int index =
values.indexWhere((EnumValue value) => value.name == name);
EnumValue value;
if (index == -1) {
value = EnumValue(values.length, name);
values.add(value);
} else {
value = values[index];
}
if (normalizedFrom != null) {
value.normalizedFrom.add(normalizedFrom);
}
return value;
}
}
/// Represents a single value in an [EnumCollection].
class EnumValue {
EnumValue(this.index, this.name);
final int index;
final String name;
/// The properties that were normalized to this value.
final Set<String> normalizedFrom = <String>{};
/// Returns a serialized, compact format of the enum value.
///
/// Enum values are serialized based on their index. We start serializing them
/// to "A", "B", "C", etc until we reach "Z". Then we continue with "a", "b",
/// "c", etc.
String get serialized {
// We assign uppercase letters to the first 26 enum values.
if (index < 26) {
return String.fromCharCode(_kChar_A + index);
}
// Enum values above 26 will be assigned a lowercase letter.
return String.fromCharCode(_kChar_a + index - 26);
}
/// Returns the enum name that'll be used in the Dart code.
///
/// ```dart
/// enum CharProperty {
/// ALetter, // <-- this is the name returned by this method ("ALetter").
/// Numeric,
/// // etc...
/// }
/// ```
String get enumName {
return name.replaceAll('_', '');
}
}
/// Sorts ranges and combines adjacent ranges that have the same property and
/// can be merged.
Iterable<UnicodeRange> processRanges(
List<UnicodeRange> data,
String defaultProperty,
) {
data.sort(
// Ranges don't overlap so it's safe to sort based on the start of each
// range.
(UnicodeRange range1, UnicodeRange range2) =>
range1.start.compareTo(range2.start),
);
verifyNoOverlappingRanges(data);
return combineAdjacentRanges(data, defaultProperty);
}
/// Example:
///
/// ```
/// 0x01C4..0x0293; ALetter
/// 0x0294..0x0294; ALetter
/// 0x0295..0x02AF; ALetter
/// ```
///
/// will get combined into:
///
/// ```
/// 0x01C4..0x02AF; ALetter
/// ```
List<UnicodeRange> combineAdjacentRanges(
List<UnicodeRange> data,
String defaultProperty,
) {
final List<UnicodeRange> result = <UnicodeRange>[data.first];
for (int i = 1; i < data.length; i++) {
final UnicodeRange prev = result.last;
final UnicodeRange next = data[i];
if (prev.isAdjacent(next)) {
result.last = prev.extendRange(next);
} else if (prev.property == next.property &&
prev.property.name == defaultProperty) {
// When there's a gap between two ranges, but they both have the default
// property, it's safe to combine them.
result.last = prev.extendRange(next);
} else {
// Check if there's a gap between the previous range and this range.
result.add(next);
}
}
return result;
}
int getRangeStart(String range) {
return int.parse(range.split('..')[0], radix: 16);
}
int getRangeEnd(String range) {
if (range.contains('..')) {
return int.parse(range.split('..')[1], radix: 16);
}
return int.parse(range, radix: 16);
}
void verifyNoOverlappingRanges(List<UnicodeRange> data) {
for (int i = 1; i < data.length; i++) {
if (data[i].isOverlapping(data[i - 1])) {
throw Exception('Data contains overlapping ranges.');
}
}
}
String removeCommentFromLine(String line) {
final int poundIdx = line.indexOf('#');
return (poundIdx == -1) ? line : line.substring(0, poundIdx);
}
| engine/third_party/web_unicode/tool/unicode_sync_script.dart/0 | {
"file_path": "engine/third_party/web_unicode/tool/unicode_sync_script.dart",
"repo_id": "engine",
"token_count": 4530
} | 462 |
# 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.
name: apicheck
publish_to: none
# Do not add any dependencies that require more than what is provided in
# //third_party/dart/pkg or //third_party/dart/third_party/pkg.
# In particular, package:test is not usable here.
# If you do add packages here, make sure you can run `pub get --offline`, and
# check the .packages and .package_config to make sure all the paths are
# relative to this directory into //third_party/dart
environment:
sdk: '>=3.2.0-0 <4.0.0'
# Do not add any dependencies that require more than what is provided in
# //third_party/pkg, //third_party/dart/pkg, or
# //third_party/dart/third_party/pkg. In particular, package:test is not usable
# here.
# If you do add packages here, make sure you can run `pub get --offline`, and
# check the .packages and .package_config to make sure all the paths are
# relative to this directory into //third_party/dart
dependencies:
analyzer: any
_fe_analyzer_shared: any
pub_semver: any
dev_dependencies:
async_helper: any
expect: any
litetest: any
path: any
smith: any
dependency_overrides:
_fe_analyzer_shared:
path: ../../../third_party/dart/pkg/_fe_analyzer_shared
analyzer:
path: ../../../third_party/dart/pkg/analyzer
async:
path: ../../../third_party/dart/third_party/pkg/async
async_helper:
path: ../../../third_party/dart/pkg/async_helper
collection:
path: ../../../third_party/dart/third_party/pkg/collection
convert:
path: ../../../third_party/dart/third_party/pkg/convert
crypto:
path: ../../../third_party/dart/third_party/pkg/crypto
dart_internal:
path: ../../../third_party/dart/pkg/dart_internal
expect:
path: ../../../third_party/dart/pkg/expect
file:
path: ../../../third_party/dart/third_party/pkg/file/packages/file
glob:
path: ../../../third_party/dart/third_party/pkg/glob
litetest:
path: ../../testing/litetest
meta:
path: ../../../third_party/dart/pkg/meta
package_config:
path: ../../../third_party/dart/third_party/pkg/package_config
path:
path: ../../../third_party/dart/third_party/pkg/path
pub_semver:
path: ../../../third_party/dart/third_party/pkg/pub_semver
source_span:
path: ../../../third_party/dart/third_party/pkg/source_span
string_scanner:
path: ../../../third_party/dart/third_party/pkg/string_scanner
term_glyph:
path: ../../../third_party/dart/third_party/pkg/term_glyph
typed_data:
path: ../../../third_party/dart/third_party/pkg/typed_data
watcher:
path: ../../../third_party/dart/third_party/pkg/watcher
yaml:
path: ../../../third_party/dart/third_party/pkg/yaml
smith:
path: ../../../third_party/dart/pkg/smith
| engine/tools/api_check/pubspec.yaml/0 | {
"file_path": "engine/tools/api_check/pubspec.yaml",
"repo_id": "engine",
"token_count": 1066
} | 463 |
// 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.
// Runs clang-tidy on files with changes.
//
// Basic Usage:
// dart bin/main.dart --compile-commands <path to compile_commands.json>
// dart bin/main.dart --target-variant <engine-variant>
//
// User environment variable FLUTTER_LINT_ALL to run on all files.
import 'dart:io' as io;
import 'package:clang_tidy/clang_tidy.dart';
Future<int> main(List<String> arguments) async {
final int result = await ClangTidy.fromCommandLine(arguments).run();
if (result != 0) {
io.exit(result);
}
return result;
}
| engine/tools/clang_tidy/bin/main.dart/0 | {
"file_path": "engine/tools/clang_tidy/bin/main.dart",
"repo_id": "engine",
"token_count": 227
} | 464 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert' show utf8;
import 'dart:io';
String _basename(String path) {
return path.split(Platform.pathSeparator).last;
}
String _generateDirListing(String dirPath) {
final Directory dir = Directory(dirPath);
final List<FileSystemEntity> entities = dir.listSync();
entities.sort(
(FileSystemEntity a, FileSystemEntity b) => a.path.compareTo(b.path));
return entities
.map((FileSystemEntity entity) => _basename(entity.path))
.join('\n');
}
String _strReplaceRange(
String inputStr, int start, int end, String replacement) {
return inputStr.substring(0, start) + replacement + inputStr.substring(end);
}
String _redirectPatch(String patch) {
final RegExp inputPathExp = RegExp(r'^--- a(.*)', multiLine: true);
final RegExp outputPathExp = RegExp(r'^\+\+\+ b(.*)', multiLine: true);
final Match? inputPathMatch = inputPathExp.firstMatch(patch);
final Match? outputPathMatch = outputPathExp.firstMatch(patch);
assert(inputPathMatch != null);
assert(outputPathMatch != null);
if (inputPathMatch != null && outputPathMatch != null) {
return _strReplaceRange(
patch,
outputPathMatch.start + 5, // +5 to account for '+++ b'
outputPathMatch.end,
inputPathMatch.group(1)!,
);
}
throw Exception('Unable to find input and output paths');
}
File _makeTempFile(String prefix) {
final Directory systemTempDir = Directory.systemTemp;
final String filename = '$prefix-${DateTime.now().millisecondsSinceEpoch}';
final String path = '${systemTempDir.path}${Platform.pathSeparator}$filename';
final File result = File(path);
result.createSync();
return result;
}
/// Run the diff of the contents of a directory at [dirPath] and the contents of
/// a file at [goldenPath]. Returns 0 if there is no diff. Be aware that the
/// CWD should be inside of the git repository for the patch to be correct.
int dirContentsDiff(String goldenPath, String dirPath) {
if (!File(goldenPath).existsSync()) {
throw Exception('unable to find `$goldenPath`');
}
if (!Directory(dirPath).existsSync()) {
throw Exception('unable to find `$dirPath`');
}
int result = 0;
final File tempFile = _makeTempFile('dir_contents_diff');
try {
final String dirListing = _generateDirListing(dirPath);
tempFile.writeAsStringSync(dirListing);
final ProcessResult diffResult = Process.runSync(
'git',
<String>[
'diff',
// If you manually edit the golden file, many text editors will add
// trailing whitespace. This flag ignores that because honestly it's
// not a significant part of this test.
'--ignore-space-at-eol',
'-p',
goldenPath,
tempFile.path,
],
runInShell: true,
stdoutEncoding: utf8,
);
if (diffResult.exitCode != 0) {
print(
'Unexpected diff in $goldenPath, use `git apply` with the following patch.\n');
print(_redirectPatch(diffResult.stdout as String));
result = 1;
}
} finally {
tempFile.deleteSync();
}
return result;
}
/// The main entrypoint for the program, returns `exitCode`.
int run(List<String> args) {
if (args.length != 2) {
throw Exception('usage: <path to golden> <path to directory>');
}
final String goldenPath = args[0];
final String dirPath = args[1];
return dirContentsDiff(goldenPath, dirPath);
}
| engine/tools/dir_contents_diff/lib/dir_contents_diff.dart/0 | {
"file_path": "engine/tools/dir_contents_diff/lib/dir_contents_diff.dart",
"repo_id": "engine",
"token_count": 1225
} | 465 |
// 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 'package:args/command_runner.dart';
import '../environment.dart';
/// The base class that all commands and subcommands should inherit from.
abstract base class CommandBase extends Command<int> {
/// Constructs the base command.
CommandBase({
required this.environment
});
/// The host system environment.
final Environment environment;
}
| engine/tools/engine_tool/lib/src/commands/command.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/commands/command.dart",
"repo_id": "engine",
"token_count": 137
} | 466 |
#!/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.
""" Copies paths, creates if they do not exist.
"""
import argparse
import errno
import json
import os
import platform
import shutil
import subprocess
import sys
def EnsureParentExists(path):
dir_name, _ = os.path.split(path)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def SameStat(s1, s2):
return s1.st_ino == s2.st_ino and s1.st_dev == s2.st_dev
def SameFile(f1, f2):
if not os.path.exists(f2):
return False
s1 = os.stat(f1)
s2 = os.stat(f2)
return SameStat(s1, s2)
def CopyPath(src, dst):
try:
EnsureParentExists(dst)
shutil.copytree(src, dst)
except OSError as exc:
if exc.errno == errno.ENOTDIR:
if not SameFile(src, dst):
shutil.copyfile(src, dst)
else:
raise
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--file-list', dest='file_list', action='store', required=True)
args = parser.parse_args()
files = open(args.file_list, 'r')
files_to_copy = files.read().split()
num_files = len(files_to_copy) // 2
for i in range(num_files):
CopyPath(files_to_copy[i], files_to_copy[num_files + i])
return 0
if __name__ == '__main__':
sys.exit(main())
| engine/tools/fuchsia/copy_path.py/0 | {
"file_path": "engine/tools/fuchsia/copy_path.py",
"repo_id": "engine",
"token_count": 536
} | 467 |
# 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.
dart_toolchain = "//flutter/tools/fuchsia/dart:dartlang"
dart_root_gen_dir = get_label_info("//bogus($dart_toolchain)", "root_gen_dir")
# In order to access the target_gen_dir in the Dart toolchain from some location
# in the source tree, use the following:
# dart_target_gen_dir = get_label_info(":bogus($dart_toolchain)", "target_gen_dir")
| engine/tools/fuchsia/dart/toolchain.gni/0 | {
"file_path": "engine/tools/fuchsia/dart/toolchain.gni",
"repo_id": "engine",
"token_count": 169
} | 468 |
# 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/tools/executable_action.gni")
import("//flutter/tools/fuchsia/dart/config.gni")
import("//flutter/tools/fuchsia/dart/dart.gni")
import("//flutter/tools/fuchsia/dart/dart_package_config.gni")
import("//flutter/tools/fuchsia/dart/kernel/dart_kernel.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/cmc.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/component.gni")
# Defines a component which will run in a flutter_runner or dart_runner
#
# This template is not intended to be used directly. Users should use the
# flutter_component and dart_component actions instead.
#
# Parameters
#
# manifest (required)
# The component manifest
# Type: path
#
# main_package (required)
# The name of the package containing the main_dart
# Type: string
#
# component_name (optional)
# The name of the component.
# Type: string
# Default: target_name
#
# build_cfg (required)
# A description of how to build this component. This object needs
# to contain the following variables:
# runtime_meta: a path to the partial cmx file containing the runner
# platform_name: either 'dart_runner' or 'flutter_runner'
# is_aot: a boolean indicating if this is an AOT build
# is_product: a boolean indicating if this is a product build
# enable_asserts: whether we should enable asserts when compiling
#
# main_dart (required)
# File containing the main function of the component.
# Type: string
#
# generate_asset_manifest (optional)
# If true, will generate an asset manifest for this component
# Type: boolean
# Default: false
#
# deps
# testonly
# visibility
template("flutter_dart_component") {
assert(defined(invoker.manifest), "must specify a manifest file")
assert(defined(invoker.build_cfg), "must specify build_cfg")
assert(defined(invoker.main_dart), "Must specify main_dart")
assert(defined(invoker.main_package), "Must specify main_package")
build_cfg = invoker.build_cfg
_component_deps = []
if (defined(invoker.deps)) {
_component_deps += invoker.deps
}
if (defined(invoker.component_name)) {
_component_name = invoker.component_name
} else {
_component_name = target_name
}
_resources = []
if (defined(invoker.resources)) {
_resources = invoker.resources
}
# Flutter and Dart components need to run inside the runner which matches how
# they were compiled, for example, a JIT component must run in the JIT runner.
# We need to be able to dynamically convert the manifest files to include the
# runner requirements so that we can switch based on build modes.
_manifest_extension = get_path_info(invoker.manifest, "extension")
if (_manifest_extension == "cmx") {
# This is a v1 component, merge with the runtime_meta
_merged_target_name = "${target_name}_merged.cmx"
cmc_merge(_merged_target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
output_name = _merged_target_name
sources = [
invoker.manifest,
rebase_path(build_cfg.runtime_meta, "."),
]
}
_merged_outputs = []
_merged_outputs += get_target_outputs(":$_merged_target_name")
_manifest = _merged_outputs[0]
_manifest_output_name = "meta/" + _component_name + ".cmx"
_component_deps += [ ":$_merged_target_name" ]
} else {
# This is a v2 component.
# The v2 runners have not been implemented yet so we just leave the manifest
# as is to avoid breaking the build.
_manifest = invoker.manifest
_manifest_output_name = "meta/" + _component_name + ".cm"
}
_dart_package_config_target_name = "${target_name}_dart_package"
dart_package_config(_dart_package_config_target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
deps = _component_deps
}
_package_config_output = []
_package_config_output =
get_target_outputs(":$_dart_package_config_target_name")
_packages_path = _package_config_output[0]
_kernel_target_name = _component_name + "_kernel"
_kernel_target_dep_name = _kernel_target_name + "_gen_file"
_kernel_path = "$target_gen_dir/__untraced_dart_kernel__/${target_name}.dil"
dart_kernel(_kernel_target_name) {
kernel_path = _kernel_path
# establishes a dependency chain for the snapshot since
# the kernel is wrapped in a group
kernel_target_name = _kernel_target_dep_name
forward_variables_from(invoker,
[
"testonly",
"visibility",
"main_dart",
"main_package",
])
deps = [ ":$_dart_package_config_target_name" ]
packages_path = _packages_path
args = [
"--component-name",
_component_name,
]
# always generate a manifest for fuchsia builds. If this is an aot build
# the kernel will ignore this variable.
generate_manifest = true
platform_name = build_cfg.platform_name
product = build_cfg.is_product
is_aot = build_cfg.is_aot
}
_component_deps += [ ":$_kernel_target_name" ]
if (build_cfg.is_aot) {
_snapshot_path = "$target_gen_dir/${_component_name}_snapshot.so"
_snapshot_target_name = target_name + "_snapshot"
_stats_json_path =
"$target_gen_dir/${_component_name}/stats/symbol_sizes.json"
if (build_cfg.is_product) {
_gen_snapshot_script_target = gen_snapshot_product
} else {
_gen_snapshot_script_target = gen_snapshot
}
executable_action(_snapshot_target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
deps = [ ":$_kernel_target_dep_name" ]
inputs = [ _kernel_path ]
outputs = [
_snapshot_path,
_stats_json_path,
]
if (defined(invoker.toolchain)) {
toolchain = invoker.toolchain
} else {
toolchain = host_toolchain
}
# Construct the host toolchain version of the tool.
# host_tool = invoker.tool + "($toolchain)"
host_tool = _gen_snapshot_script_target + "($toolchain)"
# Get the path to the executable. Currently, this assumes that the tool
# does not specify output_name so that the target name is the name to use.
# If that's not the case, we'll need another argument to the script to
# specify this, since we can't know what the output name is (it might be in
# another file not processed yet).
host_executable =
get_label_info(host_tool, "root_out_dir") + "/" +
get_label_info(host_tool, "name") + host_executable_suffix
# Add the executable itself as an input.
inputs += [ host_executable ]
deps += [ host_tool ]
tool = host_executable
args = [
"--deterministic",
"--snapshot_kind=app-aot-elf",
"--elf=" + rebase_path(_snapshot_path, root_build_dir),
"--print-instructions-sizes-to=" +
rebase_path(_stats_json_path, root_build_dir),
]
# No asserts in debug or release product.
# No asserts in non-product release
# Yes asserts in non-product debug.
if (build_cfg.enable_asserts) {
args += [ "--enable_asserts" ]
}
args += [ rebase_path(_kernel_path, root_build_dir) ]
}
_component_deps += [ ":$_snapshot_target_name" ]
}
fuchsia_component(_component_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
deps = _component_deps
manifest = _manifest
manifest_output_name = _manifest_output_name
if (build_cfg.is_aot) {
_resources += [
{
path = _snapshot_path
dest = "data/${_component_name}/app_aot_snapshot.so"
},
]
} else {
_convert_kernel_target_name =
"${_kernel_target_name}_convert_kernel_manifest"
_convert_kernel_manifest_file =
# TODO(richkadel): This is prefixed by "dartlang/", which is not found.
# Is the current toolchain set incorrectly somewhere?
string_replace(
"${target_gen_dir}/${_convert_kernel_target_name}_kernel_manifest.json",
"dartlang/",
"")
# TODO(richkadel): Adds the json resource names in the manifest to the
# collection of `json_of_resources` files, read by
# `prepare_package_inputs.py`. These resources are computed (only known)
# at some point during the build/compile phase.
resources_in_json_files = [ rebase_path(_convert_kernel_manifest_file) ]
}
resources = _resources
}
group(target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
deps = [ ":" + _component_name ]
}
}
| engine/tools/fuchsia/flutter/internal/flutter_dart_component.gni/0 | {
"file_path": "engine/tools/fuchsia/flutter/internal/flutter_dart_component.gni",
"repo_id": "engine",
"token_count": 4084
} | 469 |
# 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.
# Each toolchain must define "stamp" and "copy" tools,
# but they are always the same in every toolchain.
stamp_command = "touch {{output}}"
stamp_description = "STAMP {{output}}"
# mtime on directories may not reflect the latest of a directory. For example in
# popular file systems, modifying a file in a directory does not affect mtime of
# the directory. Because of this, disable directory copy for incremental
# correctness. See https://fxbug.dev/73250.
copy_command = "if [ -d {{source}} ]; then echo 'Tool \"copy\" does not support directory copies'; exit 1; fi; "
# We use link instead of copy; the way "copy" tool is being used is
# compatible with links since Ninja is tracking changes to the source.
if (host_os == "mac") {
# `cp -af` does not correctly preserve mtime (the nanoseconds are truncated to
# microseconds) which causes spurious ninja rebuilds. As a result, shell to a
# helper to copy rather than calling cp -r. See https://fxbug.dev/56376#c5.
copy_command += "ln -f {{source}} {{output}} 2>/dev/null || (" +
rebase_path("//flutter/tools/fuchsia/toolchain/copy.py") +
" {{source}} {{output}})"
} else {
copy_command += "ln -f {{source}} {{output}} 2>/dev/null || (rm -f {{output}} && cp -af {{source}} {{output}})"
}
copy_description = "COPY {{source}} {{output}}"
| engine/tools/fuchsia/toolchain/default_tools.gni/0 | {
"file_path": "engine/tools/fuchsia/toolchain/default_tools.gni",
"repo_id": "engine",
"token_count": 468
} | 470 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.