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.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterMenuPlugin_Internal.h"
#import "flutter/shell/platform/common/platform_provided_menu.h"
#import "flutter/shell/platform/darwin/common/framework/Headers/FlutterChannels.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginMacOS.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterPluginRegistrarMacOS.h"
#import "flutter/shell/platform/darwin/macos/framework/Headers/FlutterViewController.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterDartProject_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputPlugin.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTextInputSemanticsObject.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterViewController_Internal.h"
#include "flutter/testing/autoreleasepool_test.h"
#include "flutter/testing/testing.h"
#include "gtest/gtest.h"
@interface FakePluginRegistrar : NSObject <FlutterPluginRegistrar>
@property(nonatomic, readonly) id<FlutterPlugin> plugin;
@property(nonatomic, readonly) FlutterMethodChannel* channel;
@end
@implementation FakePluginRegistrar
@synthesize messenger;
@synthesize textures;
@synthesize view;
- (void)addMethodCallDelegate:(nonnull id<FlutterPlugin>)delegate
channel:(nonnull FlutterMethodChannel*)channel {
_plugin = delegate;
_channel = channel;
[_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
[delegate handleMethodCall:call result:result];
}];
}
- (void)addApplicationDelegate:(nonnull NSObject<FlutterAppLifecycleDelegate>*)delegate {
}
- (void)registerViewFactory:(nonnull NSObject<FlutterPlatformViewFactory>*)factory
withId:(nonnull NSString*)factoryId {
}
- (void)publish:(nonnull NSObject*)value {
}
- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset {
return @"";
}
- (nonnull NSString*)lookupKeyForAsset:(nonnull NSString*)asset
fromPackage:(nonnull NSString*)package {
return @"";
}
@end
namespace flutter::testing {
// FlutterMenuPluginTest is an AutoreleasePoolTest that allocates an NSView.
//
// This supports the use of NSApplication features that rely on the assumption of a view, such as
// when modifying the application menu bar, or even accessing the NSApplication.localizedName
// property.
//
// See: https://github.com/flutter/flutter/issues/104748#issuecomment-1159336728
class FlutterMenuPluginTest : public AutoreleasePoolTest {
public:
FlutterMenuPluginTest();
~FlutterMenuPluginTest() = default;
private:
NSView* view_;
};
FlutterMenuPluginTest::FlutterMenuPluginTest() {
view_ = [[NSView alloc] initWithFrame:NSZeroRect];
view_.wantsLayer = YES;
}
TEST_F(FlutterMenuPluginTest, TestSetMenu) {
// Build a simulation of the default main menu.
NSMenu* mainMenu = [[NSMenu alloc] init];
NSMenuItem* appNameMenu = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"APP_NAME", nil)
action:nil
keyEquivalent:@""];
NSMenu* submenu =
[[NSMenu alloc] initWithTitle:NSLocalizedString(@"Prexisting APP_NAME menu", nil)];
[submenu addItem:[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"About APP_NAME", nil)
action:nil
keyEquivalent:@""]];
appNameMenu.submenu = submenu;
[mainMenu addItem:appNameMenu];
[NSApp setMainMenu:mainMenu];
FakePluginRegistrar* registrar = [[FakePluginRegistrar alloc] init];
[FlutterMenuPlugin registerWithRegistrar:registrar];
FlutterMenuPlugin* plugin = [registrar plugin];
NSDictionary* testMenus = @{
@"0" : @[
@{
@"id" : [NSNumber numberWithInt:1],
@"label" : @"APP_NAME",
@"enabled" : @(YES),
@"children" : @[
@{
@"id" : [NSNumber numberWithInt:3],
@"platformProvidedMenu" : @(static_cast<int>(flutter::PlatformProvidedMenu::kQuit)),
@"enabled" : @(YES),
},
@{
@"id" : [NSNumber numberWithInt:2],
@"label" : @"APP_NAME Info",
@"enabled" : @(YES),
@"shortcutTrigger" : [NSNumber numberWithUnsignedLongLong:0x61],
@"shortcutModifiers" : [NSNumber numberWithUnsignedInt:0],
},
],
},
@{
@"id" : [NSNumber numberWithInt:4],
@"label" : @"Help for APP_NAME",
@"enabled" : @(YES),
@"children" : @[
@{
@"id" : [NSNumber numberWithInt:5],
@"label" : @"Help me!",
@"enabled" : @(YES),
},
@{
@"id" : [NSNumber numberWithInt:6],
@"label" : @"",
@"enabled" : @(NO),
@"isDivider" : @(YES),
},
@{
@"id" : [NSNumber numberWithInt:7],
@"label" : @"Search help",
@"enabled" : @(NO),
},
],
},
],
};
__block id available = @NO;
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"Menu.isPluginAvailable"
arguments:nil]
result:^(id _Nullable result) {
available = result;
}];
EXPECT_TRUE(available);
[plugin handleMethodCall:[FlutterMethodCall methodCallWithMethodName:@"Menu.setMenus"
arguments:testMenus]
result:^(id _Nullable result){
}];
EXPECT_EQ([NSApp.mainMenu numberOfItems], 2);
NSMenuItem* firstMenu = [NSApp.mainMenu itemAtIndex:0];
EXPECT_TRUE([[firstMenu title] isEqualToString:@"flutter_desktop_darwin_unittests"]);
EXPECT_EQ([firstMenu tag], 1);
EXPECT_TRUE([firstMenu isEnabled]);
EXPECT_FALSE([firstMenu isHidden]);
EXPECT_TRUE([[firstMenu keyEquivalent] isEqualToString:@"\0"]);
EXPECT_EQ([[firstMenu submenu] numberOfItems], 1);
NSMenuItem* firstItem = [[firstMenu submenu] itemAtIndex:0];
EXPECT_TRUE([[firstItem title] isEqualToString:@"flutter_desktop_darwin_unittests Info"]);
EXPECT_TRUE([[firstItem keyEquivalent] isEqualToString:@"a"]);
EXPECT_TRUE([firstItem isEnabled]);
EXPECT_FALSE([firstItem isHidden]);
EXPECT_TRUE(
[NSStringFromSelector([firstItem action]) isEqualToString:@"flutterMenuItemSelected:"]);
EXPECT_EQ([firstItem tag], 2);
NSMenuItem* secondMenu = [NSApp.mainMenu itemAtIndex:1];
EXPECT_TRUE([[secondMenu title] isEqualToString:@"Help for flutter_desktop_darwin_unittests"]);
EXPECT_EQ([secondMenu tag], 4);
EXPECT_TRUE([secondMenu isEnabled]);
EXPECT_FALSE([secondMenu isHidden]);
EXPECT_EQ([[secondMenu submenu] numberOfItems], 3);
NSMenuItem* secondMenuFirst = [[secondMenu submenu] itemAtIndex:0];
EXPECT_TRUE([[secondMenuFirst title] isEqualToString:@"Help me!"]);
EXPECT_TRUE([secondMenuFirst isEnabled]);
EXPECT_FALSE([secondMenuFirst isHidden]);
EXPECT_TRUE(
[NSStringFromSelector([secondMenuFirst action]) isEqualToString:@"flutterMenuItemSelected:"]);
EXPECT_EQ([secondMenuFirst tag], 5);
NSMenuItem* secondMenuDivider = [[secondMenu submenu] itemAtIndex:1];
EXPECT_TRUE([[secondMenuDivider title] isEqualToString:@""]);
EXPECT_TRUE([[secondMenuDivider keyEquivalent] isEqualToString:@""]);
EXPECT_FALSE([secondMenuDivider isEnabled]);
EXPECT_FALSE([secondMenuDivider isHidden]);
EXPECT_EQ([secondMenuDivider action], nil);
EXPECT_EQ([secondMenuDivider tag], 0);
NSMenuItem* secondMenuLast = [[secondMenu submenu] itemAtIndex:2];
EXPECT_TRUE([[secondMenuLast title] isEqualToString:@"Search help"]);
EXPECT_FALSE([secondMenuLast isEnabled]);
EXPECT_FALSE([secondMenuLast isHidden]);
EXPECT_TRUE(
[NSStringFromSelector([secondMenuLast action]) isEqualToString:@"flutterMenuItemSelected:"]);
EXPECT_EQ([secondMenuLast tag], 7);
}
} // namespace flutter::testing
| engine/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterMenuPluginTest.mm",
"repo_id": "engine",
"token_count": 3491
} | 350 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterSurface.h"
#import <Metal/Metal.h>
@interface FlutterSurface () {
CGSize _size;
IOSurfaceRef _ioSurface;
id<MTLTexture> _texture;
}
@end
@implementation FlutterSurface
- (IOSurfaceRef)ioSurface {
return _ioSurface;
}
- (CGSize)size {
return _size;
}
- (int64_t)textureId {
return reinterpret_cast<int64_t>(_texture);
}
- (instancetype)initWithSize:(CGSize)size device:(id<MTLDevice>)device {
if (self = [super init]) {
self->_size = size;
self->_ioSurface = [FlutterSurface createIOSurfaceWithSize:size];
self->_texture = [FlutterSurface createTextureForIOSurface:_ioSurface size:size device:device];
}
return self;
}
static void ReleaseSurface(void* surface) {
if (surface != nullptr) {
CFBridgingRelease(surface);
}
}
- (FlutterMetalTexture)asFlutterMetalTexture {
FlutterMetalTexture res;
memset(&res, 0, sizeof(FlutterMetalTexture));
res.struct_size = sizeof(FlutterMetalTexture);
res.texture = (__bridge void*)_texture;
res.texture_id = self.textureId;
res.user_data = (void*)CFBridgingRetain(self);
res.destruction_callback = ReleaseSurface;
return res;
}
+ (FlutterSurface*)fromFlutterMetalTexture:(const FlutterMetalTexture*)texture {
return (__bridge FlutterSurface*)texture->user_data;
}
- (void)dealloc {
CFRelease(_ioSurface);
}
+ (IOSurfaceRef)createIOSurfaceWithSize:(CGSize)size {
unsigned pixelFormat = 'BGRA';
unsigned bytesPerElement = 4;
size_t bytesPerRow = IOSurfaceAlignProperty(kIOSurfaceBytesPerRow, size.width * bytesPerElement);
size_t totalBytes = IOSurfaceAlignProperty(kIOSurfaceAllocSize, size.height * bytesPerRow);
NSDictionary* options = @{
(id)kIOSurfaceWidth : @(size.width),
(id)kIOSurfaceHeight : @(size.height),
(id)kIOSurfacePixelFormat : @(pixelFormat),
(id)kIOSurfaceBytesPerElement : @(bytesPerElement),
(id)kIOSurfaceBytesPerRow : @(bytesPerRow),
(id)kIOSurfaceAllocSize : @(totalBytes),
};
IOSurfaceRef res = IOSurfaceCreate((CFDictionaryRef)options);
IOSurfaceSetValue(res, CFSTR("IOSurfaceColorSpace"), kCGColorSpaceSRGB);
return res;
}
+ (id<MTLTexture>)createTextureForIOSurface:(IOSurfaceRef)surface
size:(CGSize)size
device:(id<MTLDevice>)device {
MTLTextureDescriptor* textureDescriptor =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:size.width
height:size.height
mipmapped:NO];
textureDescriptor.usage =
MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsageShaderWrite;
// plane = 0 for BGRA.
return [device newTextureWithDescriptor:textureDescriptor iosurface:surface plane:0];
}
@end
| engine/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterSurface.mm",
"repo_id": "engine",
"token_count": 1279
} | 351 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTER_TIME_CONVERTER_MM_
#define FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTER_TIME_CONVERTER_MM_
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.h"
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterEngine_Internal.h"
@interface FlutterTimeConverter () {
__weak FlutterEngine* _engine;
}
@end
@implementation FlutterTimeConverter
- (instancetype)initWithEngine:(FlutterEngine*)engine {
self = [super init];
if (self) {
_engine = engine;
}
return self;
}
- (uint64_t)CAMediaTimeToEngineTime:(CFTimeInterval)time {
FlutterEngine* engine = _engine;
if (!engine) {
return 0;
}
return (time - CACurrentMediaTime()) * NSEC_PER_SEC + engine.embedderAPI.GetCurrentTime();
}
- (CFTimeInterval)engineTimeToCAMediaTime:(uint64_t)time {
FlutterEngine* engine = _engine;
if (!engine) {
return 0;
}
return (static_cast<int64_t>(time) - static_cast<int64_t>(engine.embedderAPI.GetCurrentTime())) /
static_cast<double>(NSEC_PER_SEC) +
CACurrentMediaTime();
}
@end
#endif // FLUTTER_SHELL_PLATFORM_DARWIN_MACOS_FRAMEWORK_SOURCE_FLUTTER_TIME_CONVERTER_MM_-
| engine/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterTimeConverter.mm",
"repo_id": "engine",
"token_count": 540
} | 352 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "flutter/shell/platform/darwin/macos/framework/Source/FlutterView.h"
#import <Metal/Metal.h>
#import "flutter/testing/testing.h"
constexpr int64_t kImplicitViewId = 0ll;
@interface TestFlutterViewDelegate : NSObject <FlutterViewDelegate>
@end
@implementation TestFlutterViewDelegate
- (void)viewDidReshape:(nonnull NSView*)view {
}
- (BOOL)viewShouldAcceptFirstResponder:(NSView*)view {
return YES;
}
@end
TEST(FlutterView, ShouldInheritContentsScaleReturnsYes) {
id<MTLDevice> device = MTLCreateSystemDefaultDevice();
id<MTLCommandQueue> queue = [device newCommandQueue];
TestFlutterViewDelegate* delegate = [[TestFlutterViewDelegate alloc] init];
FlutterThreadSynchronizer* threadSynchronizer = [[FlutterThreadSynchronizer alloc] init];
FlutterView* view = [[FlutterView alloc] initWithMTLDevice:device
commandQueue:queue
delegate:delegate
threadSynchronizer:threadSynchronizer
viewId:kImplicitViewId];
EXPECT_EQ([view layer:view.layer shouldInheritContentsScale:3.0 fromWindow:view.window], YES);
}
| engine/shell/platform/darwin/macos/framework/Source/FlutterViewTest.mm/0 | {
"file_path": "engine/shell/platform/darwin/macos/framework/Source/FlutterViewTest.mm",
"repo_id": "engine",
"token_count": 579
} | 353 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_ENGINE_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_ENGINE_H_
#include <memory>
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "flutter/shell/common/shell.h"
#include "flutter/shell/common/thread_host.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/embedder_external_texture_resolver.h"
#include "flutter/shell/platform/embedder/embedder_thread_host.h"
namespace flutter {
struct ShellArgs;
// The object that is returned to the embedder as an opaque pointer to the
// instance of the Flutter engine.
class EmbedderEngine {
public:
EmbedderEngine(
std::unique_ptr<EmbedderThreadHost> thread_host,
const TaskRunners& task_runners,
const Settings& settings,
RunConfiguration run_configuration,
const Shell::CreateCallback<PlatformView>& on_create_platform_view,
const Shell::CreateCallback<Rasterizer>& on_create_rasterizer,
std::unique_ptr<EmbedderExternalTextureResolver>
external_texture_resolver);
~EmbedderEngine();
bool LaunchShell();
bool CollectShell();
const TaskRunners& GetTaskRunners() const;
bool NotifyCreated();
bool NotifyDestroyed();
bool RunRootIsolate();
bool IsValid() const;
bool SetViewportMetrics(int64_t view_id,
const flutter::ViewportMetrics& metrics);
bool DispatchPointerDataPacket(
std::unique_ptr<flutter::PointerDataPacket> packet);
bool SendPlatformMessage(std::unique_ptr<PlatformMessage> message);
bool RegisterTexture(int64_t texture);
bool UnregisterTexture(int64_t texture);
bool MarkTextureFrameAvailable(int64_t texture);
bool SetSemanticsEnabled(bool enabled);
bool SetAccessibilityFeatures(int32_t flags);
bool DispatchSemanticsAction(int node_id,
flutter::SemanticsAction action,
fml::MallocMapping args);
bool OnVsyncEvent(intptr_t baton,
fml::TimePoint frame_start_time,
fml::TimePoint frame_target_time);
bool ReloadSystemFonts();
bool PostRenderThreadTask(const fml::closure& task);
bool RunTask(const FlutterTask* task);
bool PostTaskOnEngineManagedNativeThreads(
const std::function<void(FlutterNativeThreadType)>& closure) const;
bool ScheduleFrame();
Shell& GetShell();
private:
const std::unique_ptr<EmbedderThreadHost> thread_host_;
TaskRunners task_runners_;
RunConfiguration run_configuration_;
std::unique_ptr<ShellArgs> shell_args_;
std::unique_ptr<Shell> shell_;
std::unique_ptr<EmbedderExternalTextureResolver> external_texture_resolver_;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderEngine);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_ENGINE_H_
| engine/shell/platform/embedder/embedder_engine.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_engine.h",
"repo_id": "engine",
"token_count": 1087
} | 354 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/embedder/embedder_platform_message_response.h"
#include "flutter/fml/make_copyable.h"
namespace flutter {
EmbedderPlatformMessageResponse::EmbedderPlatformMessageResponse(
fml::RefPtr<fml::TaskRunner> runner,
const Callback& callback)
: runner_(std::move(runner)), callback_(callback) {}
EmbedderPlatformMessageResponse::~EmbedderPlatformMessageResponse() = default;
// |PlatformMessageResponse|
void EmbedderPlatformMessageResponse::Complete(
std::unique_ptr<fml::Mapping> data) {
if (!data) {
CompleteEmpty();
return;
}
runner_->PostTask(
// The static leak checker gets confused by the use of fml::MakeCopyable.
// NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks)
fml::MakeCopyable([data = std::move(data), callback = callback_]() {
callback(data->GetMapping(), data->GetSize());
}));
}
// |PlatformMessageResponse|
void EmbedderPlatformMessageResponse::CompleteEmpty() {
Complete(std::make_unique<fml::NonOwnedMapping>(nullptr, 0u));
}
} // namespace flutter
| engine/shell/platform/embedder/embedder_platform_message_response.cc/0 | {
"file_path": "engine/shell/platform/embedder/embedder_platform_message_response.cc",
"repo_id": "engine",
"token_count": 407
} | 355 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_GL_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_GL_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/gpu/gpu_surface_gl_skia.h"
#include "flutter/shell/platform/embedder/embedder_external_view_embedder.h"
#include "flutter/shell/platform/embedder/embedder_surface.h"
namespace flutter {
class EmbedderSurfaceGL final : public EmbedderSurface,
public GPUSurfaceGLDelegate {
public:
struct GLDispatchTable {
std::function<bool(void)> gl_make_current_callback; // required
std::function<bool(void)> gl_clear_current_callback; // required
std::function<bool(GLPresentInfo)> gl_present_callback; // required
std::function<intptr_t(GLFrameInfo)> gl_fbo_callback; // required
std::function<bool(void)> gl_make_resource_current_callback; // optional
std::function<SkMatrix(void)>
gl_surface_transformation_callback; // optional
std::function<void*(const char*)> gl_proc_resolver; // optional
std::function<GLFBOInfo(intptr_t)> gl_populate_existing_damage; // required
};
EmbedderSurfaceGL(
GLDispatchTable gl_dispatch_table,
bool fbo_reset_after_present,
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder);
~EmbedderSurfaceGL() override;
private:
bool valid_ = false;
GLDispatchTable gl_dispatch_table_;
bool fbo_reset_after_present_;
std::shared_ptr<EmbedderExternalViewEmbedder> external_view_embedder_;
// |EmbedderSurface|
bool IsValid() const override;
// |EmbedderSurface|
std::unique_ptr<Surface> CreateGPUSurface() override;
// |EmbedderSurface|
sk_sp<GrDirectContext> CreateResourceContext() const override;
// |GPUSurfaceGLDelegate|
std::unique_ptr<GLContextResult> GLContextMakeCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextClearCurrent() override;
// |GPUSurfaceGLDelegate|
bool GLContextPresent(const GLPresentInfo& present_info) override;
// |GPUSurfaceGLDelegate|
GLFBOInfo GLContextFBO(GLFrameInfo frame_info) const override;
// |GPUSurfaceGLDelegate|
bool GLContextFBOResetAfterPresent() const override;
// |GPUSurfaceGLDelegate|
SkMatrix GLContextSurfaceTransformation() const override;
// |GPUSurfaceGLDelegate|
GLProcResolver GetGLProcResolver() const override;
// |GPUSurfaceGLDelegate|
SurfaceFrame::FramebufferInfo GLContextFramebufferInfo() const override;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderSurfaceGL);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_EMBEDDER_SURFACE_GL_H_
| engine/shell/platform/embedder/embedder_surface_gl.h/0 | {
"file_path": "engine/shell/platform/embedder/embedder_surface_gl.h",
"repo_id": "engine",
"token_count": 1066
} | 356 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_CONFIG_BUILDER_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_CONFIG_BUILDER_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/unique_object.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/embedder/tests/embedder_test.h"
#include "flutter/shell/platform/embedder/tests/embedder_test_context_software.h"
namespace flutter {
namespace testing {
struct UniqueEngineTraits {
static FlutterEngine InvalidValue() { return nullptr; }
static bool IsValid(const FlutterEngine& value) { return value != nullptr; }
static void Free(FlutterEngine& engine) {
auto result = FlutterEngineShutdown(engine);
FML_CHECK(result == kSuccess);
}
};
using UniqueEngine = fml::UniqueObject<FlutterEngine, UniqueEngineTraits>;
class EmbedderConfigBuilder {
public:
enum class InitializationPreference {
kSnapshotsInitialize,
kAOTDataInitialize,
kMultiAOTInitialize,
kNoInitialize,
};
explicit EmbedderConfigBuilder(
EmbedderTestContext& context,
InitializationPreference preference =
InitializationPreference::kSnapshotsInitialize);
~EmbedderConfigBuilder();
FlutterProjectArgs& GetProjectArgs();
void SetRendererConfig(EmbedderTestContextType type, SkISize surface_size);
void SetSoftwareRendererConfig(SkISize surface_size = SkISize::Make(1, 1));
void SetOpenGLRendererConfig(SkISize surface_size);
void SetMetalRendererConfig(SkISize surface_size);
void SetVulkanRendererConfig(
SkISize surface_size,
std::optional<FlutterVulkanInstanceProcAddressCallback>
instance_proc_address_callback = {});
// Used to explicitly set an `open_gl.fbo_callback`. Using this method will
// cause your test to fail since the ctor for this class sets
// `open_gl.fbo_callback_with_frame_info`. This method exists as a utility to
// explicitly test this behavior.
void SetOpenGLFBOCallBack();
// Used to explicitly set an `open_gl.present`. Using this method will cause
// your test to fail since the ctor for this class sets
// `open_gl.present_with_info`. This method exists as a utility to explicitly
// test this behavior.
void SetOpenGLPresentCallBack();
void SetAssetsPath();
void SetSnapshots();
void SetAOTDataElf();
void SetIsolateCreateCallbackHook();
void SetSemanticsCallbackHooks();
// Used to set a custom log message handler.
void SetLogMessageCallbackHook();
void SetChannelUpdateCallbackHook();
// Used to set a custom log tag.
void SetLogTag(std::string tag);
void SetLocalizationCallbackHooks();
void SetExecutableName(std::string executable_name);
void SetDartEntrypoint(std::string entrypoint);
void AddCommandLineArgument(std::string arg);
void AddDartEntrypointArgument(std::string arg);
void SetPlatformTaskRunner(const FlutterTaskRunnerDescription* runner);
void SetRenderTaskRunner(const FlutterTaskRunnerDescription* runner);
void SetPlatformMessageCallback(
const std::function<void(const FlutterPlatformMessage*)>& callback);
void SetCompositor(bool avoid_backing_store_cache = false,
bool use_present_layers_callback = false);
FlutterCompositor& GetCompositor();
FlutterRendererConfig& GetRendererConfig();
void SetRenderTargetType(
EmbedderTestBackingStoreProducer::RenderTargetType type,
FlutterSoftwarePixelFormat software_pixfmt =
kFlutterSoftwarePixelFormatNative32);
UniqueEngine LaunchEngine() const;
UniqueEngine InitializeEngine() const;
// Sets up the callback for vsync, the callbacks needs to be specified on the
// text context vis `SetVsyncCallback`.
void SetupVsyncCallback();
private:
EmbedderTestContext& context_;
FlutterProjectArgs project_args_ = {};
FlutterRendererConfig renderer_config_ = {};
FlutterSoftwareRendererConfig software_renderer_config_ = {};
#ifdef SHELL_ENABLE_GL
FlutterOpenGLRendererConfig opengl_renderer_config_ = {};
#endif
#ifdef SHELL_ENABLE_VULKAN
void InitializeVulkanRendererConfig();
FlutterVulkanRendererConfig vulkan_renderer_config_ = {};
#endif
#ifdef SHELL_ENABLE_METAL
void InitializeMetalRendererConfig();
FlutterMetalRendererConfig metal_renderer_config_ = {};
#endif
std::string dart_entrypoint_;
FlutterCustomTaskRunners custom_task_runners_ = {};
FlutterCompositor compositor_ = {};
std::vector<std::string> command_line_arguments_;
std::vector<std::string> dart_entrypoint_arguments_;
std::string log_tag_;
UniqueEngine SetupEngine(bool run) const;
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderConfigBuilder);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_CONFIG_BUILDER_H_
| engine/shell/platform/embedder/tests/embedder_config_builder.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_config_builder.h",
"repo_id": "engine",
"token_count": 1602
} | 357 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_SOFTWARE_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_SOFTWARE_H_
#include "flutter/shell/platform/embedder/tests/embedder_test_compositor.h"
namespace flutter {
namespace testing {
class EmbedderTestCompositorSoftware : public EmbedderTestCompositor {
public:
explicit EmbedderTestCompositorSoftware(SkISize surface_size);
~EmbedderTestCompositorSoftware() override;
private:
bool UpdateOffscrenComposition(const FlutterLayer** layers,
size_t layers_count);
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestCompositorSoftware);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_TEST_COMPOSITOR_SOFTWARE_H_
| engine/shell/platform/embedder/tests/embedder_test_compositor_software.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_test_compositor_software.h",
"repo_id": "engine",
"token_count": 369
} | 358 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_UNITTESTS_UTIL_H_
#define FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_UNITTESTS_UTIL_H_
#define FML_USED_ON_EMBEDDER
#include <future>
#include <utility>
#include "flutter/fml/mapping.h"
#include "flutter/fml/message_loop.h"
#include "flutter/fml/paths.h"
#include "flutter/shell/platform/embedder/tests/embedder_assertions.h"
#include "flutter/shell/platform/embedder/tests/embedder_config_builder.h"
#include "flutter/shell/platform/embedder/tests/embedder_test.h"
#include "third_party/skia/include/core/SkSurface.h"
namespace flutter {
namespace testing {
sk_sp<SkSurface> CreateRenderSurface(const FlutterLayer& layer,
GrDirectContext* context);
bool RasterImagesAreSame(const sk_sp<SkImage>& a, const sk_sp<SkImage>& b);
/// @brief Prepends a prefix to the name which is unique to the test
/// context type. This is useful for tests that use
/// EmbedderTestMultiBackend and require different fixtures per
/// backend. For OpenGL, the name remains unchanged.
/// @param[in] backend The test context type used to determine the prepended
/// prefix (e.g. `vk_[name]` for Vulkan).
/// @param[in] name The name of the fixture without any special prefixes.
std::string FixtureNameForBackend(EmbedderTestContextType backend,
const std::string& name);
/// @brief Resolves a render target type for a given backend description.
/// This is useful for tests that use EmbedderTestMultiBackend.
/// @param[in] backend The test context type to resolve the render
/// target for.
/// @param[in] opengl_framebuffer Ignored for all non-OpenGL backends. Flutter
/// supports rendering to both OpenGL textures
/// and framebuffers. When false, the OpenGL
/// texture render target type is returned.
EmbedderTestBackingStoreProducer::RenderTargetType GetRenderTargetFromBackend(
EmbedderTestContextType backend,
bool opengl_framebuffer);
/// @brief Configures per-backend properties for a given backing store.
/// @param[in] backing_store The backing store to configure.
/// @param[in] backend The test context type used to decide which
/// backend the backing store will be used with.
/// @param[in] opengl_framebuffer Ignored for all non-OpenGL backends. Flutter
/// supports rendering to both OpenGL textures
/// and framebuffers. When false, the backing
/// store is configured to be an OpenGL texture.
void ConfigureBackingStore(FlutterBackingStore& backing_store,
EmbedderTestContextType backend,
bool opengl_framebuffer);
bool WriteImageToDisk(const fml::UniqueFD& directory,
const std::string& name,
const sk_sp<SkImage>& image);
bool ImageMatchesFixture(const std::string& fixture_file_name,
const sk_sp<SkImage>& scene_image);
bool ImageMatchesFixture(const std::string& fixture_file_name,
std::future<sk_sp<SkImage>>& scene_image);
bool SurfacePixelDataMatchesBytes(SkSurface* surface,
const std::vector<uint8_t>& bytes);
bool SurfacePixelDataMatchesBytes(std::future<SkSurface*>& surface_future,
const std::vector<uint8_t>& bytes);
void FilterMutationsByType(
const FlutterPlatformViewMutation** mutations,
size_t count,
FlutterPlatformViewMutationType type,
const std::function<void(const FlutterPlatformViewMutation& mutation)>&
handler);
void FilterMutationsByType(
const FlutterPlatformView* view,
FlutterPlatformViewMutationType type,
const std::function<void(const FlutterPlatformViewMutation& mutation)>&
handler);
SkMatrix GetTotalMutationTransformationMatrix(
const FlutterPlatformViewMutation** mutations,
size_t count);
SkMatrix GetTotalMutationTransformationMatrix(const FlutterPlatformView* view);
//------------------------------------------------------------------------------
/// @brief A task runner that we expect the embedder to provide but whose
/// implementation is a real FML task runner.
///
class EmbedderTestTaskRunner {
public:
using TaskExpiryCallback = std::function<void(FlutterTask)>;
EmbedderTestTaskRunner(fml::RefPtr<fml::TaskRunner> real_task_runner,
TaskExpiryCallback on_task_expired)
: identifier_(++sEmbedderTaskRunnerIdentifiers),
real_task_runner_(std::move(real_task_runner)),
on_task_expired_(std::move(on_task_expired)) {
FML_CHECK(real_task_runner_);
FML_CHECK(on_task_expired_);
task_runner_description_.struct_size = sizeof(FlutterTaskRunnerDescription);
task_runner_description_.user_data = this;
task_runner_description_.runs_task_on_current_thread_callback =
[](void* user_data) -> bool {
return reinterpret_cast<EmbedderTestTaskRunner*>(user_data)
->real_task_runner_->RunsTasksOnCurrentThread();
};
task_runner_description_.post_task_callback = [](FlutterTask task,
uint64_t target_time_nanos,
void* user_data) -> void {
auto thiz = reinterpret_cast<EmbedderTestTaskRunner*>(user_data);
auto target_time = fml::TimePoint::FromEpochDelta(
fml::TimeDelta::FromNanoseconds(target_time_nanos));
auto on_task_expired = thiz->on_task_expired_;
auto invoke_task = [task, on_task_expired]() { on_task_expired(task); };
auto real_task_runner = thiz->real_task_runner_;
real_task_runner->PostTaskForTime(invoke_task, target_time);
};
task_runner_description_.identifier = identifier_;
}
const FlutterTaskRunnerDescription& GetFlutterTaskRunnerDescription() {
return task_runner_description_;
}
private:
static std::atomic_size_t sEmbedderTaskRunnerIdentifiers;
const size_t identifier_;
fml::RefPtr<fml::TaskRunner> real_task_runner_;
TaskExpiryCallback on_task_expired_;
FlutterTaskRunnerDescription task_runner_description_ = {};
FML_DISALLOW_COPY_AND_ASSIGN(EmbedderTestTaskRunner);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_EMBEDDER_TESTS_EMBEDDER_UNITTESTS_UTIL_H_
| engine/shell/platform/embedder/tests/embedder_unittests_util.h/0 | {
"file_path": "engine/shell/platform/embedder/tests/embedder_unittests_util.h",
"repo_id": "engine",
"token_count": 2777
} | 359 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of zircon;
// ignore_for_file: native_function_body_in_non_sdk_code
// ignore_for_file: public_member_api_docs
@pragma('vm:entry-point')
base class HandleDisposition extends NativeFieldWrapperClass1 {
@pragma('vm:entry-point')
HandleDisposition(int operation, Handle handle, int type, int rights) {
_constructor(operation, handle, type, rights);
}
@pragma('vm:external-name', 'HandleDisposition_constructor')
external void _constructor(int operation, Handle handle, int type, int rights);
@pragma('vm:external-name', 'HandleDisposition_operation')
external int get operation;
@pragma('vm:external-name', 'HandleDisposition_handle')
external Handle get handle;
@pragma('vm:external-name', 'HandleDisposition_type')
external int get type;
@pragma('vm:external-name', 'HandleDisposition_rights')
external int get rights;
@pragma('vm:external-name', 'HandleDisposition_result')
external int get result;
@override
String toString() =>
'HandleDisposition(operation=$operation, handle=$handle, type=$type, rights=$rights, result=$result)';
}
| engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_disposition.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/lib/src/handle_disposition.dart",
"repo_id": "engine",
"token_count": 387
} | 360 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "system.h"
#include <array>
#include <fuchsia/io/cpp/fidl.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fd.h>
#include <lib/fdio/io.h>
#include <lib/fdio/limits.h>
#include <lib/fdio/namespace.h>
#include <lib/zx/channel.h>
#include <sys/stat.h>
#include <unistd.h>
#include <zircon/process.h>
#include <zircon/processargs.h>
#include "flutter/fml/unique_fd.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_class_library.h"
using tonic::ToDart;
namespace zircon {
namespace dart {
namespace {
constexpr char kGetSizeResult[] = "GetSizeResult";
constexpr char kHandlePairResult[] = "HandlePairResult";
constexpr char kHandleResult[] = "HandleResult";
constexpr char kReadResult[] = "ReadResult";
constexpr char kHandleInfo[] = "HandleInfo";
constexpr char kReadEtcResult[] = "ReadEtcResult";
constexpr char kWriteResult[] = "WriteResult";
constexpr char kFromFileResult[] = "FromFileResult";
constexpr char kMapResult[] = "MapResult";
class ByteDataScope {
public:
explicit ByteDataScope(Dart_Handle dart_handle) : dart_handle_(dart_handle) {
Acquire();
}
explicit ByteDataScope(size_t size) {
dart_handle_ = Dart_NewTypedData(Dart_TypedData_kByteData, size);
FML_DCHECK(!tonic::CheckAndHandleError(dart_handle_));
Acquire();
FML_DCHECK(size == size_);
}
~ByteDataScope() {
if (is_valid_) {
Release();
}
}
void* data() const { return data_; }
size_t size() const { return size_; }
Dart_Handle dart_handle() const { return dart_handle_; }
bool is_valid() const { return is_valid_; }
void Release() {
FML_DCHECK(is_valid_);
Dart_Handle result = Dart_TypedDataReleaseData(dart_handle_);
tonic::CheckAndHandleError(result);
is_valid_ = false;
data_ = nullptr;
size_ = 0;
}
private:
void Acquire() {
FML_DCHECK(size_ == 0);
FML_DCHECK(data_ == nullptr);
FML_DCHECK(!is_valid_);
Dart_TypedData_Type type;
intptr_t size;
Dart_Handle result =
Dart_TypedDataAcquireData(dart_handle_, &type, &data_, &size);
is_valid_ = !tonic::CheckAndHandleError(result) &&
type == Dart_TypedData_kByteData && data_;
if (is_valid_) {
size_ = size;
} else {
size_ = 0;
}
}
Dart_Handle dart_handle_;
bool is_valid_ = false;
size_t size_ = 0;
void* data_ = nullptr;
};
Dart_Handle MakeHandleList(const std::vector<zx_handle_t>& in_handles) {
tonic::DartClassLibrary& class_library =
tonic::DartState::Current()->class_library();
Dart_Handle handle_type = class_library.GetClass("zircon", "Handle");
Dart_Handle list = Dart_NewListOfTypeFilled(
handle_type, Handle::CreateInvalid(), in_handles.size());
if (Dart_IsError(list))
return list;
for (size_t i = 0; i < in_handles.size(); i++) {
Dart_Handle result =
Dart_ListSetAt(list, i, ToDart(Handle::Create(in_handles[i])));
if (Dart_IsError(result))
return result;
}
return list;
}
template <class... Args>
Dart_Handle ConstructDartObject(const char* class_name, Args&&... args) {
tonic::DartClassLibrary& class_library =
tonic::DartState::Current()->class_library();
Dart_Handle type =
Dart_HandleFromPersistent(class_library.GetClass("zircon", class_name));
FML_DCHECK(!tonic::CheckAndHandleError(type));
const char* cstr;
Dart_StringToCString(Dart_ToString(type), &cstr);
std::array<Dart_Handle, sizeof...(Args)> args_array{
{std::forward<Args>(args)...}};
Dart_Handle object =
Dart_New(type, Dart_EmptyString(), sizeof...(Args), args_array.data());
FML_DCHECK(!tonic::CheckAndHandleError(object));
return object;
}
Dart_Handle MakeHandleInfoList(
const std::vector<zx_handle_info_t>& in_handles) {
tonic::DartClassLibrary& class_library =
tonic::DartState::Current()->class_library();
Dart_Handle handle_info_type = class_library.GetClass("zircon", kHandleInfo);
Dart_Handle empty_handle_info = ConstructDartObject(
kHandleInfo, ToDart(Handle::CreateInvalid()), ToDart(-1), ToDart(-1));
Dart_Handle list = Dart_NewListOfTypeFilled(
handle_info_type, empty_handle_info, in_handles.size());
if (Dart_IsError(list))
return list;
for (size_t i = 0; i < in_handles.size(); i++) {
Dart_Handle handle = ToDart(Handle::Create(in_handles[i].handle));
Dart_Handle result = Dart_ListSetAt(
list, i,
ConstructDartObject(kHandleInfo, handle, ToDart(in_handles[i].type),
ToDart(in_handles[i].rights)));
if (Dart_IsError(result))
return result;
}
return list;
}
fdio_ns_t* GetNamespace() {
// Grab the fdio_ns_t* out of the isolate.
Dart_Handle zircon_lib = Dart_LookupLibrary(ToDart("dart:zircon"));
FML_DCHECK(!tonic::CheckAndHandleError(zircon_lib));
Dart_Handle namespace_type =
Dart_GetNonNullableType(zircon_lib, ToDart("_Namespace"), 0, nullptr);
FML_DCHECK(!tonic::CheckAndHandleError(namespace_type));
Dart_Handle namespace_field =
Dart_GetField(namespace_type, ToDart("_namespace"));
FML_DCHECK(!tonic::CheckAndHandleError(namespace_field));
uint64_t fdio_ns_ptr;
Dart_Handle result = Dart_IntegerToUint64(namespace_field, &fdio_ns_ptr);
FML_DCHECK(!tonic::CheckAndHandleError(result));
return reinterpret_cast<fdio_ns_t*>(fdio_ns_ptr);
}
zx_status_t FdFromPath(const char* path, fml::UniqueFD& fd) {
fml::UniqueFD dir_fd(fdio_ns_opendir(GetNamespace()));
if (!dir_fd.is_valid()) {
// TODO: can we return errno?
return ZX_ERR_IO;
}
if (path != nullptr && *path == '/') {
path++;
}
int raw_fd;
if (zx_status_t status = fdio_open_fd_at(
dir_fd.get(), path,
static_cast<uint32_t>(fuchsia::io::OpenFlags::RIGHT_READABLE),
&raw_fd);
status != ZX_OK) {
return status;
}
fd.reset(raw_fd);
return ZX_OK;
}
} // namespace
IMPLEMENT_WRAPPERTYPEINFO(zircon, System);
Dart_Handle System::ChannelCreate(uint32_t options) {
zx_handle_t out0 = 0, out1 = 0;
zx_status_t status = zx_channel_create(options, &out0, &out1);
if (status != ZX_OK) {
return ConstructDartObject(kHandlePairResult, ToDart(status));
} else {
return ConstructDartObject(kHandlePairResult, ToDart(status),
ToDart(Handle::Create(out0)),
ToDart(Handle::Create(out1)));
}
}
zx_status_t System::ConnectToService(std::string path,
fml::RefPtr<Handle> channel) {
return fdio_ns_service_connect(GetNamespace(), path.c_str(),
channel->ReleaseHandle());
}
Dart_Handle System::ChannelFromFile(std::string path) {
fml::UniqueFD fd;
if (zx_status_t status = FdFromPath(path.c_str(), fd); status != ZX_OK) {
return ConstructDartObject(kHandleResult, ToDart(status));
}
zx::handle handle;
if (zx_status_t status =
fdio_fd_transfer(fd.release(), handle.reset_and_get_address());
status != ZX_OK) {
return ConstructDartObject(kHandleResult, ToDart(status));
}
zx_info_handle_basic_t info;
if (zx_status_t status = handle.get_info(ZX_INFO_HANDLE_BASIC, &info,
sizeof(info), nullptr, nullptr);
status != ZX_OK) {
return ConstructDartObject(kHandleResult, ToDart(status));
}
if (info.type != ZX_OBJ_TYPE_CHANNEL) {
return ConstructDartObject(kHandleResult, ToDart(ZX_ERR_WRONG_TYPE));
}
return ConstructDartObject(kHandleResult, ToDart(ZX_OK),
ToDart(Handle::Create(handle.release())));
}
zx_status_t System::ChannelWrite(fml::RefPtr<Handle> channel,
const tonic::DartByteData& data,
std::vector<Handle*> handles) {
if (!channel || !channel->is_valid()) {
data.Release();
return ZX_ERR_BAD_HANDLE;
}
std::vector<zx_handle_t> zx_handles;
for (Handle* handle : handles) {
zx_handles.push_back(handle->handle());
}
zx_status_t status = zx_channel_write(channel->handle(), 0, data.data(),
data.length_in_bytes(),
zx_handles.data(), zx_handles.size());
// Handles are always consumed.
for (Handle* handle : handles) {
handle->ReleaseHandle();
}
data.Release();
return status;
}
zx_status_t System::ChannelWriteEtc(
fml::RefPtr<Handle> channel,
const tonic::DartByteData& data,
std::vector<HandleDisposition*> handle_dispositions) {
if (!channel || !channel->is_valid()) {
data.Release();
return ZX_ERR_BAD_HANDLE;
}
std::vector<zx_handle_disposition_t> zx_handle_dispositions;
for (HandleDisposition* handle : handle_dispositions) {
FML_DCHECK(handle->result() == ZX_OK);
zx_handle_dispositions.push_back({.operation = handle->operation(),
.handle = handle->handle()->handle(),
.type = handle->type(),
.rights = handle->rights(),
.result = ZX_OK});
}
zx_status_t status = zx_channel_write_etc(
channel->handle(), 0, data.data(), data.length_in_bytes(),
zx_handle_dispositions.data(), zx_handle_dispositions.size());
for (size_t i = 0; i < handle_dispositions.size(); ++i) {
handle_dispositions[i]->set_result(zx_handle_dispositions[i].result);
// Handles that are not copied (i.e. moved) are always consumed.
if (handle_dispositions[i]->operation() != ZX_HANDLE_OP_DUPLICATE) {
handle_dispositions[i]->handle()->ReleaseHandle();
}
}
data.Release();
return status;
}
Dart_Handle System::ChannelQueryAndRead(fml::RefPtr<Handle> channel) {
if (!channel || !channel->is_valid()) {
return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE));
}
uint32_t actual_bytes = 0;
uint32_t actual_handles = 0;
// Query the size of the next message.
zx_status_t status = zx_channel_read(channel->handle(), 0, nullptr, nullptr,
0, 0, &actual_bytes, &actual_handles);
if (status != ZX_ERR_BUFFER_TOO_SMALL) {
// An empty message or an error.
return ConstructDartObject(kReadResult, ToDart(status));
}
// Allocate space for the bytes and handles.
ByteDataScope bytes(actual_bytes);
FML_DCHECK(bytes.is_valid());
std::vector<zx_handle_t> handles(actual_handles);
// Make the call to actually get the message.
status = zx_channel_read(channel->handle(), 0, bytes.data(), handles.data(),
bytes.size(), handles.size(), &actual_bytes,
&actual_handles);
FML_DCHECK(status != ZX_OK || bytes.size() == actual_bytes);
bytes.Release();
if (status == ZX_OK) {
FML_DCHECK(handles.size() == actual_handles);
// return a ReadResult object.
return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(),
ToDart(actual_bytes), MakeHandleList(handles));
} else {
return ConstructDartObject(kReadResult, ToDart(status));
}
}
Dart_Handle System::ChannelQueryAndReadEtc(fml::RefPtr<Handle> channel) {
if (!channel || !channel->is_valid()) {
return ConstructDartObject(kReadEtcResult, ToDart(ZX_ERR_BAD_HANDLE));
}
uint32_t actual_bytes = 0;
uint32_t actual_handles = 0;
// Query the size of the next message.
zx_status_t status = zx_channel_read(channel->handle(), 0, nullptr, nullptr,
0, 0, &actual_bytes, &actual_handles);
if (status != ZX_ERR_BUFFER_TOO_SMALL) {
// An empty message or an error.
return ConstructDartObject(kReadEtcResult, ToDart(status));
}
// Allocate space for the bytes and handles.
ByteDataScope bytes(actual_bytes);
FML_DCHECK(bytes.is_valid());
std::vector<zx_handle_info_t> handles(actual_handles);
// Make the call to actually get the message.
status = zx_channel_read_etc(channel->handle(), 0, bytes.data(),
handles.data(), bytes.size(), handles.size(),
&actual_bytes, &actual_handles);
FML_DCHECK(status != ZX_OK || bytes.size() == actual_bytes);
bytes.Release();
if (status == ZX_OK) {
FML_DCHECK(handles.size() == actual_handles);
// return a ReadResult object.
return ConstructDartObject(kReadEtcResult, ToDart(status),
bytes.dart_handle(), ToDart(actual_bytes),
MakeHandleInfoList(handles));
} else {
return ConstructDartObject(kReadEtcResult, ToDart(status));
}
}
Dart_Handle System::EventpairCreate(uint32_t options) {
zx_handle_t out0 = 0, out1 = 0;
zx_status_t status = zx_eventpair_create(0, &out0, &out1);
if (status != ZX_OK) {
return ConstructDartObject(kHandlePairResult, ToDart(status));
} else {
return ConstructDartObject(kHandlePairResult, ToDart(status),
ToDart(Handle::Create(out0)),
ToDart(Handle::Create(out1)));
}
}
Dart_Handle System::SocketCreate(uint32_t options) {
zx_handle_t out0 = 0, out1 = 0;
zx_status_t status = zx_socket_create(options, &out0, &out1);
if (status != ZX_OK) {
return ConstructDartObject(kHandlePairResult, ToDart(status));
} else {
return ConstructDartObject(kHandlePairResult, ToDart(status),
ToDart(Handle::Create(out0)),
ToDart(Handle::Create(out1)));
}
}
Dart_Handle System::SocketWrite(fml::RefPtr<Handle> socket,
const tonic::DartByteData& data,
int options) {
if (!socket || !socket->is_valid()) {
data.Release();
return ConstructDartObject(kWriteResult, ToDart(ZX_ERR_BAD_HANDLE));
}
size_t actual;
zx_status_t status = zx_socket_write(socket->handle(), options, data.data(),
data.length_in_bytes(), &actual);
data.Release();
return ConstructDartObject(kWriteResult, ToDart(status), ToDart(actual));
}
Dart_Handle System::SocketRead(fml::RefPtr<Handle> socket, size_t size) {
if (!socket || !socket->is_valid()) {
return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE));
}
ByteDataScope bytes(size);
size_t actual;
zx_status_t status =
zx_socket_read(socket->handle(), 0, bytes.data(), size, &actual);
bytes.Release();
if (status == ZX_OK) {
FML_DCHECK(actual <= size);
return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(),
ToDart(actual));
}
return ConstructDartObject(kReadResult, ToDart(status));
}
Dart_Handle System::VmoCreate(uint64_t size, uint32_t options) {
zx_handle_t vmo = ZX_HANDLE_INVALID;
zx_status_t status = zx_vmo_create(size, options, &vmo);
if (status != ZX_OK) {
return ConstructDartObject(kHandleResult, ToDart(status));
} else {
return ConstructDartObject(kHandleResult, ToDart(status),
ToDart(Handle::Create(vmo)));
}
}
Dart_Handle System::VmoFromFile(std::string path) {
fml::UniqueFD fd;
if (zx_status_t status = FdFromPath(path.c_str(), fd); status != ZX_OK) {
return ConstructDartObject(kHandleResult, ToDart(status));
}
struct stat stat_struct;
if (fstat(fd.get(), &stat_struct) != 0) {
// TODO: can we return errno?
return ConstructDartObject(kFromFileResult, ToDart(ZX_ERR_IO));
}
zx::vmo vmo;
if (zx_status_t status =
fdio_get_vmo_clone(fd.get(), vmo.reset_and_get_address());
status != ZX_OK) {
return ConstructDartObject(kFromFileResult, ToDart(status));
}
return ConstructDartObject(kFromFileResult, ToDart(ZX_OK),
ToDart(Handle::Create(vmo.release())),
ToDart(stat_struct.st_size));
}
Dart_Handle System::VmoGetSize(fml::RefPtr<Handle> vmo) {
if (!vmo || !vmo->is_valid()) {
return ConstructDartObject(kGetSizeResult, ToDart(ZX_ERR_BAD_HANDLE));
}
uint64_t size;
zx_status_t status = zx_vmo_get_size(vmo->handle(), &size);
return ConstructDartObject(kGetSizeResult, ToDart(status), ToDart(size));
}
zx_status_t System::VmoSetSize(fml::RefPtr<Handle> vmo, uint64_t size) {
if (!vmo || !vmo->is_valid()) {
return ZX_ERR_BAD_HANDLE;
}
return zx_vmo_set_size(vmo->handle(), size);
}
zx_status_t System::VmoWrite(fml::RefPtr<Handle> vmo,
uint64_t offset,
const tonic::DartByteData& data) {
if (!vmo || !vmo->is_valid()) {
data.Release();
return ZX_ERR_BAD_HANDLE;
}
zx_status_t status =
zx_vmo_write(vmo->handle(), data.data(), offset, data.length_in_bytes());
data.Release();
return status;
}
Dart_Handle System::VmoRead(fml::RefPtr<Handle> vmo,
uint64_t offset,
size_t size) {
if (!vmo || !vmo->is_valid()) {
return ConstructDartObject(kReadResult, ToDart(ZX_ERR_BAD_HANDLE));
}
// TODO: constrain size?
ByteDataScope bytes(size);
zx_status_t status = zx_vmo_read(vmo->handle(), bytes.data(), offset, size);
bytes.Release();
if (status == ZX_OK) {
return ConstructDartObject(kReadResult, ToDart(status), bytes.dart_handle(),
ToDart(size));
}
return ConstructDartObject(kReadResult, ToDart(status));
}
struct SizedRegion {
SizedRegion(void* r, size_t s) : region(r), size(s) {}
void* region;
size_t size;
};
void System::VmoMapFinalizer(void* isolate_callback_data, void* peer) {
SizedRegion* r = reinterpret_cast<SizedRegion*>(peer);
zx_vmar_unmap(zx_vmar_root_self(), reinterpret_cast<uintptr_t>(r->region),
r->size);
delete r;
}
Dart_Handle System::VmoMap(fml::RefPtr<Handle> vmo) {
if (!vmo || !vmo->is_valid())
return ConstructDartObject(kMapResult, ToDart(ZX_ERR_BAD_HANDLE));
uint64_t size;
zx_status_t status = zx_vmo_get_size(vmo->handle(), &size);
if (status != ZX_OK)
return ConstructDartObject(kMapResult, ToDart(status));
uintptr_t mapped_addr;
status = zx_vmar_map(zx_vmar_root_self(), ZX_VM_PERM_READ, 0, vmo->handle(),
0, size, &mapped_addr);
if (status != ZX_OK)
return ConstructDartObject(kMapResult, ToDart(status));
void* data = reinterpret_cast<void*>(mapped_addr);
Dart_Handle object = Dart_NewExternalTypedData(Dart_TypedData_kUint8, data,
static_cast<intptr_t>(size));
FML_DCHECK(!tonic::CheckAndHandleError(object));
SizedRegion* r = new SizedRegion(data, size);
Dart_NewFinalizableHandle(object, reinterpret_cast<void*>(r),
static_cast<intptr_t>(size) + sizeof(*r),
System::VmoMapFinalizer);
return ConstructDartObject(kMapResult, ToDart(ZX_OK), object);
}
uint64_t System::ClockGetMonotonic() {
return zx_clock_get_monotonic();
}
// clang-format: off
#define FOR_EACH_STATIC_BINDING(V) \
V(System, ChannelCreate) \
V(System, ChannelFromFile) \
V(System, ChannelWrite) \
V(System, ChannelWriteEtc) \
V(System, ChannelQueryAndRead) \
V(System, ChannelQueryAndReadEtc) \
V(System, EventpairCreate) \
V(System, ConnectToService) \
V(System, SocketCreate) \
V(System, SocketWrite) \
V(System, SocketRead) \
V(System, VmoCreate) \
V(System, VmoFromFile) \
V(System, VmoGetSize) \
V(System, VmoSetSize) \
V(System, VmoRead) \
V(System, VmoWrite) \
V(System, VmoMap) \
V(System, ClockGetMonotonic)
// clang-format: on
// Tonic is missing a comma.
#define DART_REGISTER_NATIVE_STATIC_(CLASS, METHOD) \
DART_REGISTER_NATIVE_STATIC(CLASS, METHOD),
FOR_EACH_STATIC_BINDING(DART_NATIVE_CALLBACK_STATIC)
void System::RegisterNatives(tonic::DartLibraryNatives* natives) {
natives->Register({FOR_EACH_STATIC_BINDING(DART_REGISTER_NATIVE_STATIC_)});
}
} // namespace dart
} // namespace zircon
| engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/dart-pkg/zircon/sdk_ext/system.cc",
"repo_id": "engine",
"token_count": 8886
} | 361 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
library fuchsia_builtin;
import 'dart:async';
import 'dart:io';
import 'dart:_internal' show VMLibraryHooks;
// Corelib 'print' implementation.
void _print(arg) {
_Logger._printString(arg.toString());
try {
// If stdout is connected, print to it as well.
stdout.writeln(arg);
} on FileSystemException catch (_) {
// Some Fuchsia applications will not have stdout connected.
}
}
class _Logger {
@pragma('vm:external-name', 'Logger_PrintString')
external static void _printString(String s);
}
@pragma('vm:entry-point')
late String _rawScript;
Uri _scriptUri() {
if (_rawScript.startsWith('http:') ||
_rawScript.startsWith('https:') ||
_rawScript.startsWith('file:')) {
return Uri.parse(_rawScript);
} else {
return Uri.base.resolveUri(Uri.file(_rawScript));
}
}
@pragma('vm:external-name', 'ScheduleMicrotask')
external void _scheduleMicrotask(void callback());
@pragma('vm:entry-point')
_getScheduleMicrotaskClosure() => _scheduleMicrotask;
@pragma('vm:entry-point')
_setupHooks() {
VMLibraryHooks.platformScript = _scriptUri;
}
@pragma('vm:entry-point')
_getPrintClosure() => _print;
typedef EchoStringCallback = String? Function(String? str);
late EchoStringCallback? receiveEchoStringCallback;
@pragma('vm:entry-point')
String? _receiveEchoString(String? str) {
return receiveEchoStringCallback?.call(str);
}
| engine/shell/platform/fuchsia/dart_runner/embedder/builtin.dart/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/embedder/builtin.dart",
"repo_id": "engine",
"token_count": 543
} | 362 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
{
include: [ "common.shard.cml" ],
program: {
runner: "elf",
binary: "bin/app",
forward_stdout_to: "log",
forward_stderr_to: "log",
// Needed for JIT builds.
job_policy_ambient_mark_vmo_exec: "true",
},
capabilities: [
{
runner: "dart_jit_product_runner",
path: "/svc/fuchsia.component.runner.ComponentRunner",
},
],
expose: [
{
runner: "dart_jit_product_runner",
from: "self",
},
],
}
| engine/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cml/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/meta/dart_jit_product_runner.cml",
"repo_id": "engine",
"token_count": 334
} | 363 |
# dart_jit_runner
Contains the integration test for the Dart JIT runner.
### Running Tests
<!-- TODO(erkln): Replace steps once test runner script is updated to run Dart runner tests -->
#### Setup emulator and PM serve
```
fx set terminal.qemu-x64
ffx emu start --headless
fx serve
```
#### Prepare build files and build binary
```
$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto
ninja -C $ENGINE_DIR/out/fuchsia_debug_x64 flutter/shell/platform/fuchsia fuchsia_tests
```
#### Publish files to PM
```
$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_debug_x64/dart-jit-runner-integration-test-0.far
$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_debug_x64/oot_dart_jit_runner-0.far
$FUCHSIA_DIR/.jiri_root/bin/ffx repository publish $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files --package-archive $ENGINE_DIR/out/fuchsia_debug_x64/gen/flutter/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_echo_server/dart_jit_echo_server/dart_jit_echo_server.far
```
#### Run test
```
ffx test run "fuchsia-pkg://fuchsia.com/dart-jit-runner-integration-test#meta/dart-jit-runner-integration-test.cm"
```
## Notes
The `debug` runtime should be used when running the `dart_jit_runner` integration test. Snapshots will fail to generate or generate incorrectly if the wrong runtime is used.
| engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/dart_runner/tests/startup_integration_test/dart_jit_runner/README.md",
"repo_id": "engine",
"token_count": 560
} | 364 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "flutter/display_list/skia/dl_sk_canvas.h"
#include "flutter/fml/macros.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkCanvasVirtualEnforcer.h"
#include "third_party/skia/include/utils/SkNWayCanvas.h"
#include "third_party/skia/include/utils/SkNoDrawCanvas.h"
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_CANVAS_SPY_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_CANVAS_SPY_H_
namespace flutter {
class DidDrawCanvas;
//------------------------------------------------------------------------------
/// Facilitates spying on drawing commands to an SkCanvas.
///
/// This is used to determine whether anything was drawn into
/// a canvas so it is possible to implement optimizations that
/// are specific to empty canvases.
class CanvasSpy {
public:
explicit CanvasSpy(SkCanvas* target_canvas);
//----------------------------------------------------------------------------
/// @brief Returns true if any non transparent content has been drawn
/// into
/// the spying canvas. Note that this class does tries to detect
/// empty canvases but in some cases may return true even for
/// empty canvases (e.g when a transparent image is drawn into the
/// canvas).
bool DidDrawIntoCanvas();
//----------------------------------------------------------------------------
/// @brief The returned canvas delegate all operations to the target
/// canvas
/// while spying on them.
DlCanvas* GetSpyingCanvas();
//----------------------------------------------------------------------------
/// @brief The underlying Skia canvas that implements the spying
/// (mainly for testing)
SkCanvas* GetRawSpyingCanvas();
private:
std::unique_ptr<SkNWayCanvas> n_way_canvas_;
std::unique_ptr<DidDrawCanvas> did_draw_canvas_;
DlSkCanvasAdapter adapter_;
FML_DISALLOW_COPY_AND_ASSIGN(CanvasSpy);
};
class DidDrawCanvas final : public SkCanvasVirtualEnforcer<SkNoDrawCanvas> {
public:
DidDrawCanvas(int width, int height);
~DidDrawCanvas() override;
bool DidDrawIntoCanvas();
private:
bool did_draw_ = false;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void willSave() override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
bool onDoSaveBehind(const SkRect*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void willRestore() override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void didConcat44(const SkM44&) override;
void didScale(SkScalar, SkScalar) override;
void didTranslate(SkScalar, SkScalar) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawDRRect(const SkRRect&, const SkRRect&, const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
virtual void onDrawTextBlob(const SkTextBlob* blob,
SkScalar x,
SkScalar y,
const SkPaint& paint) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
virtual void onDrawPatch(const SkPoint cubics[12],
const SkColor colors[4],
const SkPoint texCoords[4],
SkBlendMode,
const SkPaint& paint) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawPaint(const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawBehind(const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawPoints(PointMode,
size_t count,
const SkPoint pts[],
const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawRect(const SkRect&, const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawRegion(const SkRegion&, const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawOval(const SkRect&, const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawArc(const SkRect&,
SkScalar,
SkScalar,
bool,
const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawRRect(const SkRRect&, const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawPath(const SkPath&, const SkPaint&) override;
#ifdef SK_SUPPORT_LEGACY_ONDRAWIMAGERECT
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawImage(const SkImage*,
SkScalar left,
SkScalar top,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawImageRect(const SkImage*,
const SkRect* src,
const SkRect& dst,
const SkPaint*,
SrcRectConstraint) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawImageLattice(const SkImage*,
const Lattice&,
const SkRect&,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawAtlas(const SkImage*,
const SkRSXform[],
const SkRect[],
const SkColor[],
int,
SkBlendMode,
const SkRect*,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawEdgeAAImageSet(const ImageSetEntry[],
int count,
const SkPoint[],
const SkMatrix[],
const SkPaint*,
SrcRectConstraint) override;
#endif
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawImage2(const SkImage*,
SkScalar left,
SkScalar top,
const SkSamplingOptions&,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawImageRect2(const SkImage*,
const SkRect& src,
const SkRect& dst,
const SkSamplingOptions&,
const SkPaint*,
SrcRectConstraint) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawImageLattice2(const SkImage*,
const Lattice&,
const SkRect&,
SkFilterMode,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawVerticesObject(const SkVertices*,
SkBlendMode,
const SkPaint&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawAtlas2(const SkImage*,
const SkRSXform[],
const SkRect[],
const SkColor[],
int,
SkBlendMode,
const SkSamplingOptions&,
const SkRect*,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawShadowRec(const SkPath&, const SkDrawShadowRec&) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onClipRect(const SkRect&, SkClipOp, ClipEdgeStyle) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onClipRRect(const SkRRect&, SkClipOp, ClipEdgeStyle) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onClipPath(const SkPath&, SkClipOp, ClipEdgeStyle) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onClipRegion(const SkRegion&, SkClipOp) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawPicture(const SkPicture*,
const SkMatrix*,
const SkPaint*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawDrawable(SkDrawable*, const SkMatrix*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawAnnotation(const SkRect&, const char[], SkData*) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawEdgeAAQuad(const SkRect&,
const SkPoint[4],
SkCanvas::QuadAAFlags,
const SkColor4f&,
SkBlendMode) override;
// |SkCanvasVirtualEnforcer<SkNoDrawCanvas>|
void onDrawEdgeAAImageSet2(const ImageSetEntry[],
int count,
const SkPoint[],
const SkMatrix[],
const SkSamplingOptions&,
const SkPaint*,
SrcRectConstraint) override;
void MarkDrawIfNonTransparentPaint(const SkPaint& paint);
FML_DISALLOW_COPY_AND_ASSIGN(DidDrawCanvas);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_CANVAS_SPY_H_
| engine/shell/platform/fuchsia/flutter/canvas_spy.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/canvas_spy.h",
"repo_id": "engine",
"token_count": 4267
} | 365 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <ostream>
#include "focus_delegate.h"
namespace flutter_runner {
void FocusDelegate::WatchLoop(std::function<void(bool)> callback) {
if (watch_loop_) {
FML_LOG(ERROR) << "FocusDelegate::WatchLoop() must be called once.";
return;
}
watch_loop_ = [this, /*copy*/ callback](auto focus_state) {
callback(is_focused_ = focus_state.focused());
Complete(std::exchange(next_focus_request_, nullptr),
is_focused_ ? "[true]" : "[false]");
view_ref_focused_->Watch(/*copy*/ watch_loop_);
};
view_ref_focused_->Watch(/*copy*/ watch_loop_);
}
bool FocusDelegate::HandlePlatformMessage(
rapidjson::Value request,
fml::RefPtr<flutter::PlatformMessageResponse> response) {
auto method = request.FindMember("method");
if (method == request.MemberEnd() || !method->value.IsString()) {
return false;
}
if (method->value == "View.focus.getCurrent") {
Complete(std::move(response), is_focused_ ? "[true]" : "[false]");
} else if (method->value == "View.focus.getNext") {
if (next_focus_request_) {
FML_LOG(ERROR) << "An outstanding PlatformMessageResponse already exists "
"for the next focus state!";
Complete(std::move(response), "[null]");
} else {
next_focus_request_ = std::move(response);
}
} else if (method->value == "View.focus.request") {
auto args_it = request.FindMember("args");
if (args_it == request.MemberEnd() || !args_it->value.IsObject()) {
FML_LOG(ERROR) << "No arguments found.";
return false;
}
const auto& args = args_it->value;
auto view_ref = args.FindMember("viewRef");
if (!view_ref->value.IsUint64()) {
FML_LOG(ERROR) << "Argument 'viewRef' is not a uint64";
return false;
}
zx_handle_t handle = view_ref->value.GetUint64();
zx_handle_t out_handle;
zx_status_t status =
zx_handle_duplicate(handle, ZX_RIGHT_SAME_RIGHTS, &out_handle);
if (status != ZX_OK) {
FML_LOG(ERROR) << "Argument 'viewRef' is not valid";
return false;
}
auto ref = fuchsia::ui::views::ViewRef({
.reference = zx::eventpair(out_handle),
});
return RequestFocusByViewRef(std::move(ref), std::move(response));
} else if (method->value == "View.focus.requestById") {
auto args_it = request.FindMember("args");
if (args_it == request.MemberEnd() || !args_it->value.IsObject()) {
FML_LOG(ERROR) << "No arguments found.";
return false;
}
const auto& args = args_it->value;
auto view_id = args.FindMember("viewId");
if (!view_id->value.IsUint64()) {
FML_LOG(ERROR) << "Argument 'viewId' is not a uint64";
return false;
}
auto id = view_id->value.GetUint64();
if (child_view_view_refs_.count(id) != 1) {
FML_LOG(ERROR) << "Argument 'viewId' (" << id
<< ") does not refer to a valid ChildView";
Complete(std::move(response), "[1]");
return true;
}
return RequestFocusById(id, std::move(response));
} else {
return false;
}
// All of our methods complete the platform message response.
return true;
}
void FocusDelegate::OnChildViewViewRef(uint64_t view_id,
fuchsia::ui::views::ViewRef view_ref) {
FML_CHECK(child_view_view_refs_.count(view_id) == 0);
child_view_view_refs_[view_id] = std::move(view_ref);
}
void FocusDelegate::OnDisposeChildView(uint64_t view_id) {
FML_CHECK(child_view_view_refs_.count(view_id) == 1);
child_view_view_refs_.erase(view_id);
}
void FocusDelegate::Complete(
fml::RefPtr<flutter::PlatformMessageResponse> response,
std::string value) {
if (response) {
response->Complete(std::make_unique<fml::DataMapping>(
std::vector<uint8_t>(value.begin(), value.end())));
}
}
bool FocusDelegate::RequestFocusById(
uint64_t view_id,
fml::RefPtr<flutter::PlatformMessageResponse> response) {
fuchsia::ui::views::ViewRef ref;
auto status = child_view_view_refs_[view_id].Clone(&ref);
if (status != ZX_OK) {
FML_LOG(ERROR) << "Failed to clone ViewRef";
return false;
}
return RequestFocusByViewRef(std::move(ref), std::move(response));
}
bool FocusDelegate::RequestFocusByViewRef(
fuchsia::ui::views::ViewRef view_ref,
fml::RefPtr<flutter::PlatformMessageResponse> response) {
focuser_->RequestFocus(
std::move(view_ref),
[this, response = std::move(response)](
fuchsia::ui::views::Focuser_RequestFocus_Result result) {
int result_code =
result.is_err()
? static_cast<
std::underlying_type_t<fuchsia::ui::views::Error>>(
result.err())
: 0;
Complete(std::move(response), "[" + std::to_string(result_code) + "]");
});
return true;
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/focus_delegate.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/focus_delegate.cc",
"repo_id": "engine",
"token_count": 2033
} | 366 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Testing the stateful Fuchsia Input3 keyboard interactions. This test case
// is not intended to be exhaustive: it is intended to capture the tests that
// demonstrate how we think Input3 interaction should work, and possibly
// regression tests if we catch some behavior that needs to be guarded long
// term. Pragmatically, this should be enough to ensure no specific bug
// happens twice.
#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 <gtest/gtest.h>
#include <zircon/time.h>
#include <vector>
namespace flutter_runner {
namespace {
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;
using fuchsia::ui::input3::KeyMeaning;
class KeyboardTest : public testing::Test {
protected:
static void SetUpTestCase() { testing::Test::SetUpTestCase(); }
// Creates a new key event for testing.
KeyEvent NewKeyEvent(KeyEventType event_type, Key key) {
KeyEvent event;
// Assume events are delivered with correct timing.
event.set_timestamp(++timestamp_);
event.set_type(event_type);
event.set_key(key);
return event;
}
KeyEvent NewKeyEventWithMeaning(KeyEventType event_type,
KeyMeaning key_meaning) {
KeyEvent event;
// Assume events are delivered with correct timing.
event.set_timestamp(++timestamp_);
event.set_type(event_type);
event.set_key_meaning(std::move(key_meaning));
return event;
}
// Makes the keyboard consume all the provided `events`. The end state of
// the keyboard is as if all of the specified events happened between the
// start state of the keyboard and its end state. Returns false if any of
// the event was not consumed.
bool ConsumeEvents(Keyboard* keyboard, const std::vector<KeyEvent>& events) {
for (const auto& event : events) {
KeyEvent e;
event.Clone(&e);
if (keyboard->ConsumeEvent(std::move(e)) == false) {
return false;
}
}
return true;
}
// Converts a pressed key to usage value.
uint32_t ToUsage(Key key) { return static_cast<uint64_t>(key) & 0xFFFFFFFF; }
private:
zx_time_t timestamp_ = 0;
};
// Checks whether the HID usage, page and ID values are reported correctly.
TEST_F(KeyboardTest, UsageValues) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::SYNC, Key::CAPS_LOCK));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
// Values for Caps Lock.
// See spec at:
// https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.input/keys.fidl;l=177;drc=e3b39f2b57e720770773b857feca4f770ee0619e
EXPECT_EQ(0x07u, keyboard.LastHIDUsagePage());
EXPECT_EQ(0x39u, keyboard.LastHIDUsageID());
EXPECT_EQ(0x70039u, keyboard.LastHIDUsage());
// Try also an usage that is not on page 7. This one is on page 0x0C.
// See spec at:
// https://cs.opensource.google/fuchsia/fuchsia/+/main:sdk/fidl/fuchsia.input/keys.fidl;l=339;drc=e3b39f2b57e720770773b857feca4f770ee0619e
// Note that Fuchsia does not define constants for every key you may think of,
// rather only those that we had the need for. However it is not an issue
// to add more keys if needed.
keys.clear();
keys.emplace_back(NewKeyEvent(KeyEventType::SYNC, Key::MEDIA_MUTE));
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(0x0Cu, keyboard.LastHIDUsagePage());
EXPECT_EQ(0xE2u, keyboard.LastHIDUsageID());
EXPECT_EQ(0xC00E2u, keyboard.LastHIDUsage());
// Don't crash when a key with only a meaning comes in.
keys.clear();
keys.emplace_back(NewKeyEventWithMeaning(KeyEventType::SYNC,
KeyMeaning::WithCodepoint(32)));
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(0x0u, keyboard.LastHIDUsagePage());
EXPECT_EQ(0x0u, keyboard.LastHIDUsageID());
EXPECT_EQ(0x0u, keyboard.LastHIDUsage());
EXPECT_EQ(0x20u, keyboard.LastCodePoint());
keys.clear();
auto key =
NewKeyEventWithMeaning(KeyEventType::SYNC, KeyMeaning::WithCodepoint(65));
key.set_key(Key::A);
keys.emplace_back(std::move(key));
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(0x07u, keyboard.LastHIDUsagePage());
EXPECT_EQ(0x04u, keyboard.LastHIDUsageID());
EXPECT_EQ(0x70004u, keyboard.LastHIDUsage());
EXPECT_EQ(65u, keyboard.LastCodePoint());
}
// This test checks that if a caps lock has been pressed when we didn't have
// focus, the effect of caps lock remains. Only this first test case is
// commented to explain how the test case works.
TEST_F(KeyboardTest, CapsLockSync) {
// Place the key events since the beginning of time into `keys`.
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::SYNC, Key::CAPS_LOCK));
// Replay them on the keyboard.
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
// Verify the state of the keyboard's public API:
// - check that the key sync had no code point (it was a caps lock press).
// - check that the registered usage was that of caps lock.
// - check that the net effect is that the caps lock modifier is locked
// active.
EXPECT_EQ(0u, keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::CAPS_LOCK), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierCapsLock, keyboard.Modifiers());
}
TEST_F(KeyboardTest, CapsLockPress) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::CAPS_LOCK));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(0u, keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::CAPS_LOCK), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierCapsLock, keyboard.Modifiers());
}
TEST_F(KeyboardTest, CapsLockPressRelease) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::CAPS_LOCK));
keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::CAPS_LOCK));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(0u, keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::CAPS_LOCK), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierCapsLock, keyboard.Modifiers());
}
TEST_F(KeyboardTest, ShiftA) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::LEFT_SHIFT));
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(static_cast<uint32_t>('A'), keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierLeftShift, keyboard.Modifiers());
}
TEST_F(KeyboardTest, ShiftAWithRelease) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::LEFT_SHIFT));
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A));
keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::A));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(static_cast<uint32_t>('A'), keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierLeftShift, keyboard.Modifiers());
}
TEST_F(KeyboardTest, ShiftAWithReleaseShift) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::LEFT_SHIFT));
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A));
keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::LEFT_SHIFT));
keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::A));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(static_cast<uint32_t>('a'), keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierNone, keyboard.Modifiers());
}
TEST_F(KeyboardTest, LowcaseA) {
std::vector<KeyEvent> keys;
keys.emplace_back(NewKeyEvent(KeyEventType::PRESSED, Key::A));
keys.emplace_back(NewKeyEvent(KeyEventType::RELEASED, Key::A));
Keyboard keyboard;
ASSERT_TRUE(ConsumeEvents(&keyboard, keys));
EXPECT_EQ(static_cast<uint32_t>('a'), keyboard.LastCodePoint());
EXPECT_EQ(ToUsage(Key::A), keyboard.LastHIDUsage());
EXPECT_EQ(kModifierNone, keyboard.Modifiers());
}
} // namespace
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/keyboard_unittest.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/keyboard_unittest.cc",
"repo_id": "engine",
"token_count": 3210
} | 367 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "task_runner_adapter.h"
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/zx/time.h>
#include "flutter/fml/message_loop_impl.h"
namespace flutter_runner {
class CompatTaskRunner : public fml::TaskRunner {
public:
CompatTaskRunner(async_dispatcher_t* dispatcher)
: fml::TaskRunner(nullptr), forwarding_target_(dispatcher) {
FML_DCHECK(forwarding_target_);
}
void PostTask(const fml::closure& task) override {
async::PostTask(forwarding_target_, task);
}
void PostTaskForTime(const fml::closure& task,
fml::TimePoint target_time) override {
async::PostTaskForTime(
forwarding_target_, task,
zx::time(target_time.ToEpochDelta().ToNanoseconds()));
}
void PostDelayedTask(const fml::closure& task,
fml::TimeDelta delay) override {
async::PostDelayedTask(forwarding_target_, task,
zx::duration(delay.ToNanoseconds()));
}
bool RunsTasksOnCurrentThread() override {
return forwarding_target_ == async_get_default_dispatcher();
}
private:
async_dispatcher_t* forwarding_target_;
FML_DISALLOW_COPY_AND_ASSIGN(CompatTaskRunner);
FML_FRIEND_MAKE_REF_COUNTED(CompatTaskRunner);
FML_FRIEND_REF_COUNTED_THREAD_SAFE(CompatTaskRunner);
};
fml::RefPtr<fml::TaskRunner> CreateFMLTaskRunner(
async_dispatcher_t* dispatcher) {
return fml::MakeRefCounted<CompatTaskRunner>(dispatcher);
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/task_runner_adapter.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/task_runner_adapter.cc",
"repo_id": "engine",
"token_count": 643
} | 368 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_VIEW_REF_FOCUSED_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_VIEW_REF_FOCUSED_H_
#include <fuchsia/ui/views/cpp/fidl.h>
using ViewRefFocused = fuchsia::ui::views::ViewRefFocused;
namespace flutter_runner::testing {
class FakeViewRefFocused : public ViewRefFocused {
public:
using WatchCallback = ViewRefFocused::WatchCallback;
std::size_t times_watched = 0;
void Watch(WatchCallback callback) override {
callback_ = std::move(callback);
++times_watched;
}
void ScheduleCallback(bool focused) {
fuchsia::ui::views::FocusState focus_state;
focus_state.set_focused(focused);
callback_(std::move(focus_state));
}
private:
WatchCallback callback_;
};
} // namespace flutter_runner::testing
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_FLUTTER_TESTS_FAKES_VIEW_REF_FOCUSED_H_
| engine/shell/platform/fuchsia/flutter/tests/fakes/view_ref_focused.h/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/fakes/view_ref_focused.h",
"repo_id": "engine",
"token_count": 392
} | 369 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
assert(is_fuchsia)
import("//flutter/tools/fuchsia/fuchsia_archive.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/package.gni")
group("tests") {
testonly = true
deps = [ ":mouse-input-test" ]
}
executable("mouse-input-test-bin") {
testonly = true
output_name = "mouse-input-test"
sources = [ "mouse-input-test.cc" ]
# This is needed for //flutter/third_party/googletest for linking zircon
# symbols.
libs = [ "${fuchsia_arch_root}/sysroot/lib/libzircon.so" ]
deps = [
"${fuchsia_sdk}/fidl/fuchsia.accessibility.semantics",
"${fuchsia_sdk}/fidl/fuchsia.buildinfo",
"${fuchsia_sdk}/fidl/fuchsia.component",
"${fuchsia_sdk}/fidl/fuchsia.fonts",
"${fuchsia_sdk}/fidl/fuchsia.intl",
"${fuchsia_sdk}/fidl/fuchsia.kernel",
"${fuchsia_sdk}/fidl/fuchsia.memorypressure",
"${fuchsia_sdk}/fidl/fuchsia.metrics",
"${fuchsia_sdk}/fidl/fuchsia.net.interfaces",
"${fuchsia_sdk}/fidl/fuchsia.tracing.provider",
"${fuchsia_sdk}/fidl/fuchsia.ui.app",
"${fuchsia_sdk}/fidl/fuchsia.ui.display.singleton",
"${fuchsia_sdk}/fidl/fuchsia.ui.input",
"${fuchsia_sdk}/fidl/fuchsia.ui.pointerinjector",
"${fuchsia_sdk}/fidl/fuchsia.ui.test.input",
"${fuchsia_sdk}/fidl/fuchsia.ui.test.scene",
"${fuchsia_sdk}/fidl/fuchsia.web",
"${fuchsia_sdk}/pkg/async",
"${fuchsia_sdk}/pkg/async-loop-testing",
"${fuchsia_sdk}/pkg/fidl_cpp",
"${fuchsia_sdk}/pkg/sys_component_cpp_testing",
"${fuchsia_sdk}/pkg/zx",
"mouse-input-view:package",
"//flutter/fml",
"//flutter/shell/platform/fuchsia/flutter/tests/integration/utils:portable_ui_test",
"//flutter/third_party/googletest:gtest",
"//flutter/third_party/googletest:gtest_main",
]
}
fuchsia_test_archive("mouse-input-test") {
testonly = true
deps = [
":mouse-input-test-bin",
# "OOT" copies of the runners used by tests, to avoid conflicting with the
# runners in the base fuchsia image.
# TODO(fxbug.dev/106575): Fix this with subpackages.
"//flutter/shell/platform/fuchsia/flutter:oot_flutter_jit_runner",
]
binary = "$target_name"
cml_file = rebase_path("meta/$target_name.cml")
}
| engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/BUILD.gn/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/mouse-input/BUILD.gn",
"repo_id": "engine",
"token_count": 1095
} | 370 |
# touch-input
`touch-input-test` exercises touch through a child view (in this case, the `touch-input-view` Dart component) and asserting
the precise location of the touch event. We validate a touch event as valid through two ways:
- By attaching the child view, injecting touch, and validating that the view reports the touch event back with the correct coordinates.
- By embedding a child view into a parent view, injecting touch into both views, and validating that each view reports its touch event back with the correct coordinates.
```shell
Injecting the tap event
[touch-input-test.cm] INFO: [portable_ui_test.cc(193)] Injecting tap at (-500, -500)
View receives the event
[flutter_jit_runner] INFO: touch-input-view.cm(flutter): touch-input-view received tap: PointerData(embedderId: 0, timeStamp: 0:01:03.623259,
change: PointerChange.add, kind: PointerDeviceKind.touch, signalKind: PointerSignalKind.none, device: -4294967295, pointerIdentifier: 0,
physicalX: 319.99998331069946, physicalY: 199.99999284744263, physicalDeltaX: 0.0, physicalDeltaY: 0.0, buttons: 0, synthesized: false,
pressure: 0.0, pressureMin: 0.0, pressureMax: 0.0, distance: 0.0, distanceMax: 0.0, size: 0.0, radiusMajor: 0.0, radiusMinor: 0.0,
radiusMin: 0.0, radiusMax: 0.0, orientation: 0.0, tilt: 0.0, platformData: 0, scrollDeltaX: 0.0, scrollDeltaY: 0.0, panX: 0.0, panY: 0.0,
panDeltaX: 0.0, panDeltaY: 0.0, scale: 0.0, rotation: 0.0)
Successfully received response from view
[touch-input-test.cm] INFO: [touch-input-test.cc(162)] Received ReportTouchInput event
[touch-input-test.cm] INFO: [touch-input-test.cc(255)] Expecting event for component touch-input-view at (320, 200)
[touch-input-test.cm] INFO: [touch-input-test.cc(257)] Received event for component touch-input-view at (320, 200), accounting for pixel scale of 1
```
Some interesting details (thanks to abrusher@):
There exists two coordinate spaces within our testing realm. The first is `touch-input-view`'s "logical" coordinate space. This
is determined based on `touch-input-view`'s size and is the space in which it sees incoming events. The second is the "injector"
coordinate space, which spans [-1000, 1000] on both axes.
The size/position of a view doesn't always match the bounds of a display exactly. As a result, Scenic has a separate coordinate space
to specify the location at which to inject a touch event. This is always fixed to the display bounds. Scenic knows how to map this
coordinate space onto the client view's space.
For example, if we inject at (-500, -500) `touch-input-view` will see a touch event at the middle of the upper-left quadrant of the screen.
## Running the Test
Reference the Flutter integration test [documentation](https://github.com/flutter/engine/blob/main/shell/platform/fuchsia/flutter/tests/integration/README.md) at //flutter/shell/platform/fuchsia/flutter/tests/integration/README.md
## Playing around with `touch-input-view`
Build Fuchsia with `terminal.qemu-x64`
```shell
fx set terminal.qemu-x64 && fx build
```
Build flutter/engine
```shell
$ENGINE_DIR/flutter/tools/gn --fuchsia --no-lto && ninja -C $ENGINE_DIR/out/fuchsia_debug_x64 flutter/shell/platform/fuchsia/flutter/tests/
integration/touch_input:tests
```
Start a Fuchsia package server
```shell
cd "$FUCHSIA_DIR"
fx serve
```
Publish `touch-input-view`
```shell
$FUCHSIA_DIR/.jiri_root/bin/fx pm publish -a -repo $FUCHSIA_DIR/$(cat $FUCHSIA_DIR/.fx-build-dir)/amber-files -f $ENGINE_DIR/out/
fuchsia_debug_x64/gen/flutter/shell/platform/fuchsia/flutter/tests/integration/touch-input/touch-input-view/touch-input-view/touch-input-view.far
```
Launch Fuchsia emulator in a graphical environment
```shell
ffx emu start
```
**Before proceeding, make sure you have successfully completed the "Set a Password" screen**
Add `touch-input-view`
```shell
ffx session add fuchsia-pkg://fuchsia.com/touch-input-view#meta/touch-input-view.cm
```
| engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/README.md/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/touch-input/README.md",
"repo_id": "engine",
"token_count": 1262
} | 371 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "screenshot.h"
#include <lib/zx/vmar.h>
#include <map>
#include <ostream>
#include <utility>
#include <vector>
#include "flutter/fml/logging.h"
namespace fuchsia_test_utils {
namespace {
constexpr uint64_t kBytesPerPixel = 4;
} // namespace
Screenshot::Screenshot(const zx::vmo& screenshot_vmo,
uint64_t width,
uint64_t height,
int rotation)
: width_(width), height_(height) {
FML_CHECK(rotation == 0 || rotation == 90 || rotation == 270);
if (rotation == 90 || rotation == 270) {
std::swap(width_, height_);
}
// Populate |screenshot_| from |screenshot_vmo|.
uint64_t vmo_size;
screenshot_vmo.get_prop_content_size(&vmo_size);
FML_CHECK(vmo_size == kBytesPerPixel * width_ * height_);
uint8_t* vmo_host = nullptr;
auto status = zx::vmar::root_self()->map(
ZX_VM_PERM_READ, /*vmar_offset*/ 0, screenshot_vmo,
/*vmo_offset*/ 0, vmo_size, reinterpret_cast<uintptr_t*>(&vmo_host));
FML_CHECK(status == ZX_OK);
ExtractScreenshotFromVMO(vmo_host);
// map the pointer.
uintptr_t address = reinterpret_cast<uintptr_t>(vmo_host);
status = zx::vmar::root_self()->unmap(address, vmo_size);
FML_CHECK(status == ZX_OK);
}
std::ostream& operator<<(std::ostream& stream, const Pixel& pixel) {
return stream << "{Pixel:" << " r:" << static_cast<unsigned int>(pixel.red)
<< " g:" << static_cast<unsigned int>(pixel.green)
<< " b:" << static_cast<unsigned int>(pixel.blue)
<< " a:" << static_cast<unsigned int>(pixel.alpha) << "}";
}
Pixel Screenshot::GetPixelAt(uint64_t x, uint64_t y) const {
FML_CHECK(x >= 0 && x < width_ && y >= 0 && y < height_)
<< "Index out of bounds";
return screenshot_[y][x];
}
std::map<Pixel, uint32_t> Screenshot::Histogram() const {
std::map<Pixel, uint32_t> histogram;
FML_CHECK(screenshot_.size() == height_ && screenshot_[0].size() == width_);
for (size_t i = 0; i < height_; i++) {
for (size_t j = 0; j < width_; j++) {
histogram[screenshot_[i][j]]++;
}
}
return histogram;
}
void Screenshot::ExtractScreenshotFromVMO(uint8_t* screenshot_vmo) {
FML_CHECK(screenshot_vmo);
for (size_t i = 0; i < height_; i++) {
// The head index of the ith row in the screenshot is |i* width_*
// KbytesPerPixel|.
screenshot_.push_back(GetPixelsInRow(screenshot_vmo, i));
}
}
std::vector<Pixel> Screenshot::GetPixelsInRow(uint8_t* screenshot_vmo,
size_t row_index) {
std::vector<Pixel> row;
for (size_t col_idx = 0;
col_idx < static_cast<size_t>(width_ * kBytesPerPixel);
col_idx += kBytesPerPixel) {
// Each row in the screenshot has |kBytesPerPixel * width_| elements.
// Therefore in order to reach the first pixel of the |row_index| row, we
// have to jump |row_index * width_ * kBytesPerPixel| positions.
auto pixel_start_index = row_index * width_ * kBytesPerPixel;
// Every |kBytesPerPixel| bytes represents the BGRA values of a pixel. Skip
// |kBytesPerPixel| bytes to get to the BGRA values of the next pixel. Each
// row in a screenshot has |kBytesPerPixel * width_| bytes of data.
// Example:-
// auto data = TakeScreenshot();
// data[0-3] -> RGBA of pixel 0.
// data[4-7] -> RGBA pf pixel 1.
row.emplace_back(screenshot_vmo[pixel_start_index + col_idx],
screenshot_vmo[pixel_start_index + col_idx + 1],
screenshot_vmo[pixel_start_index + col_idx + 2],
screenshot_vmo[pixel_start_index + col_idx + 3]);
}
return row;
}
} // namespace fuchsia_test_utils
| engine/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/tests/integration/utils/screenshot.cc",
"repo_id": "engine",
"token_count": 1588
} | 372 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <gtest/gtest.h>
#include <string>
#include "flutter/fml/task_runner.h"
#include "flutter/shell/common/thread_host.h"
#include "fml/make_copyable.h"
#include "fml/message_loop.h"
#include "fml/synchronization/waitable_event.h"
#include "fml/time/time_delta.h"
#include "fml/time/time_point.h"
#include "vsync_waiter.h"
namespace flutter_runner {
TEST(VSyncWaiterFuchsia, FrameScheduledForStartTime) {
using flutter::ThreadHost;
std::string prefix = "vsync_waiter_test";
fml::MessageLoop::EnsureInitializedForCurrentThread();
auto platform_task_runner = fml::MessageLoop::GetCurrent().GetTaskRunner();
ThreadHost thread_host =
ThreadHost(prefix, flutter::ThreadHost::Type::kRaster |
flutter::ThreadHost::Type::kUi |
flutter::ThreadHost::Type::kIo);
const flutter::TaskRunners task_runners(
prefix, // Dart thread labels
platform_task_runner, // platform
thread_host.raster_thread->GetTaskRunner(), // raster
thread_host.ui_thread->GetTaskRunner(), // ui
thread_host.io_thread->GetTaskRunner() // io
);
// await vsync will invoke the callback right away, but vsync waiter will post
// the task for frame_start time.
VsyncWaiter vsync_waiter(
[](FireCallbackCallback callback) {
const auto now = fml::TimePoint::Now();
const auto frame_start = now + fml::TimeDelta::FromMilliseconds(20);
const auto frame_end = now + fml::TimeDelta::FromMilliseconds(36);
callback(frame_start, frame_end);
},
/*secondary callback*/ nullptr, task_runners);
fml::AutoResetWaitableEvent latch;
task_runners.GetUITaskRunner()->PostTask([&]() {
vsync_waiter.AsyncWaitForVsync(
[&](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
const auto now = fml::TimePoint::Now();
EXPECT_GT(now, recorder->GetVsyncStartTime());
latch.Signal();
});
});
latch.Wait();
}
} // namespace flutter_runner
| engine/shell/platform/fuchsia/flutter/vsync_waiter_unittest.cc/0 | {
"file_path": "engine/shell/platform/fuchsia/flutter/vsync_waiter_unittest.cc",
"repo_id": "engine",
"token_count": 905
} | 373 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_FILES_H_
#define FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_FILES_H_
#include <string>
namespace dart_utils {
// Reads the contents of the file at the given path or file descriptor and
// stores the data in result. Returns true if the file was read successfully,
// otherwise returns false. If this function returns false, |result| will be
// the empty string.
bool ReadFileToString(const std::string& path, std::string* result);
bool ReadFileToStringAt(int dirfd,
const std::string& path,
std::string* result);
// Writes the given data to the file at the given path. Returns true if the data
// was successfully written, otherwise returns false.
bool WriteFile(const std::string& path, const char* data, ssize_t size);
} // namespace dart_utils
#endif // FLUTTER_SHELL_PLATFORM_FUCHSIA_RUNTIME_DART_UTILS_FILES_H_
| engine/shell/platform/fuchsia/runtime/dart/utils/files.h/0 | {
"file_path": "engine/shell/platform/fuchsia/runtime/dart/utils/files.h",
"repo_id": "engine",
"token_count": 378
} | 374 |
# Running the Fuchsia unit tests locally
These instructions assume you have set `$FUCHSIA_DIR` to your Fuchsia checkout
and `$ENGINE_DIR` to the `src/` folder of your Engine checkout. For example for
zsh, add these lines to your `~/.zprofile`:
```sh
export FUCHSIA_DIR=~/fuchsia
export ENGINE_DIR=~/engine/src
```
1. In a separate terminal, start a Fuchsia package server:
```sh
cd "$FUCHSIA_DIR"
fx serve
```
2. Run the unit tests:
```sh
$ENGINE_DIR/flutter/tools/fuchsia/devshell/run_unit_tests.sh
```
- Pass `--unopt` to turn off C++ compiler optimizations.
- Pass `--count N` to do N test runs. Useful for testing for flakes.
- Pass `--goma` to accelerate the build if you're a Googler.
- Pass `--package-filter` to run a specific test package instead of all the test packages. For example:
```sh
$ENGINE_DIR/flutter/tools/fuchsia/devshell/run_unit_tests.sh --package-filter flow_tests-0.far
```
- Pass `--gtest-filter` to run specific tests from the test package instead of all the tests. For example:
```sh
$ENGINE_DIR/flutter/tools/fuchsia/devshell/run_unit_tests.sh --package-filter flutter_runner_tests-0.far --gtest-filter "*FlatlandConnection*"
```
| engine/shell/platform/fuchsia/unit_tests.md/0 | {
"file_path": "engine/shell/platform/fuchsia/unit_tests.md",
"repo_id": "engine",
"token_count": 407
} | 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/glfw/event_loop.h"
#include <atomic>
#include <utility>
namespace flutter {
EventLoop::EventLoop(std::thread::id main_thread_id,
const TaskExpiredCallback& on_task_expired)
: main_thread_id_(main_thread_id), on_task_expired_(on_task_expired) {}
EventLoop::~EventLoop() = default;
bool EventLoop::RunsTasksOnCurrentThread() const {
return std::this_thread::get_id() == main_thread_id_;
}
void EventLoop::WaitForEvents(std::chrono::nanoseconds max_wait) {
const auto now = TaskTimePoint::clock::now();
std::vector<FlutterTask> expired_tasks;
// Process expired tasks.
{
std::lock_guard<std::mutex> lock(task_queue_mutex_);
while (!task_queue_.empty()) {
const auto& top = task_queue_.top();
// If this task (and all tasks after this) has not yet expired, there is
// nothing more to do. Quit iterating.
if (top.fire_time > now) {
break;
}
// Make a record of the expired task. Do NOT service the task here
// because we are still holding onto the task queue mutex. We don't want
// other threads to block on posting tasks onto this thread till we are
// done processing expired tasks.
expired_tasks.push_back(task_queue_.top().task);
// Remove the tasks from the delayed tasks queue.
task_queue_.pop();
}
}
// Fire expired tasks.
{
// Flushing tasks here without holing onto the task queue mutex.
for (const auto& task : expired_tasks) {
on_task_expired_(&task);
}
}
// Sleep till the next task needs to be processed. If a new task comes
// along, the wait will be resolved early because PostTask calls Wake().
{
TaskTimePoint next_wake;
{
std::lock_guard<std::mutex> lock(task_queue_mutex_);
TaskTimePoint max_wake_timepoint =
max_wait == std::chrono::nanoseconds::max() ? TaskTimePoint::max()
: now + max_wait;
TaskTimePoint next_event_timepoint = task_queue_.empty()
? TaskTimePoint::max()
: task_queue_.top().fire_time;
next_wake = std::min(max_wake_timepoint, next_event_timepoint);
}
WaitUntil(next_wake);
}
}
EventLoop::TaskTimePoint EventLoop::TimePointFromFlutterTime(
uint64_t flutter_target_time_nanos) {
const auto now = TaskTimePoint::clock::now();
const int64_t flutter_duration =
flutter_target_time_nanos - FlutterEngineGetCurrentTime();
return now + std::chrono::nanoseconds(flutter_duration);
}
void EventLoop::PostTask(FlutterTask flutter_task,
uint64_t flutter_target_time_nanos) {
static std::atomic_uint64_t sGlobalTaskOrder(0);
Task task;
task.order = ++sGlobalTaskOrder;
task.fire_time = TimePointFromFlutterTime(flutter_target_time_nanos);
task.task = flutter_task;
{
std::lock_guard<std::mutex> lock(task_queue_mutex_);
task_queue_.push(task);
// Make sure the queue mutex is unlocked before waking up the loop. In case
// the wake causes this thread to be descheduled for the primary thread to
// process tasks, the acquisition of the lock on that thread while holding
// the lock here momentarily till the end of the scope is a pessimization.
}
Wake();
}
} // namespace flutter
| engine/shell/platform/glfw/event_loop.cc/0 | {
"file_path": "engine/shell/platform/glfw/event_loop.cc",
"repo_id": "engine",
"token_count": 1363
} | 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.
#include "flutter/shell/platform/glfw/text_input_plugin.h"
#include <cstdint>
#include <iostream>
#include "flutter/shell/platform/common/json_method_codec.h"
static constexpr char kSetEditingStateMethod[] = "TextInput.setEditingState";
static constexpr char kClearClientMethod[] = "TextInput.clearClient";
static constexpr char kSetClientMethod[] = "TextInput.setClient";
static constexpr char kShowMethod[] = "TextInput.show";
static constexpr char kHideMethod[] = "TextInput.hide";
static constexpr char kMultilineInputType[] = "TextInputType.multiline";
static constexpr char kUpdateEditingStateMethod[] =
"TextInputClient.updateEditingState";
static constexpr char kPerformActionMethod[] = "TextInputClient.performAction";
static constexpr char kTextInputAction[] = "inputAction";
static constexpr char kTextInputType[] = "inputType";
static constexpr char kTextInputTypeName[] = "name";
static constexpr char kComposingBaseKey[] = "composingBase";
static constexpr char kComposingExtentKey[] = "composingExtent";
static constexpr char kSelectionAffinityKey[] = "selectionAffinity";
static constexpr char kAffinityDownstream[] = "TextAffinity.downstream";
static constexpr char kSelectionBaseKey[] = "selectionBase";
static constexpr char kSelectionExtentKey[] = "selectionExtent";
static constexpr char kSelectionIsDirectionalKey[] = "selectionIsDirectional";
static constexpr char kTextKey[] = "text";
static constexpr char kChannelName[] = "flutter/textinput";
static constexpr char kBadArgumentError[] = "Bad Arguments";
static constexpr char kInternalConsistencyError[] =
"Internal Consistency Error";
namespace flutter {
void TextInputPlugin::CharHook(GLFWwindow* window, unsigned int code_point) {
if (active_model_ == nullptr) {
return;
}
active_model_->AddCodePoint(code_point);
SendStateUpdate(*active_model_);
}
void TextInputPlugin::KeyboardHook(GLFWwindow* window,
int key,
int scancode,
int action,
int mods) {
if (active_model_ == nullptr) {
return;
}
if (action == GLFW_PRESS || action == GLFW_REPEAT) {
switch (key) {
case GLFW_KEY_LEFT:
if (active_model_->MoveCursorBack()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_RIGHT:
if (active_model_->MoveCursorForward()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_END:
active_model_->MoveCursorToEnd();
SendStateUpdate(*active_model_);
break;
case GLFW_KEY_HOME:
active_model_->MoveCursorToBeginning();
SendStateUpdate(*active_model_);
break;
case GLFW_KEY_BACKSPACE:
if (active_model_->Backspace()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_DELETE:
if (active_model_->Delete()) {
SendStateUpdate(*active_model_);
}
break;
case GLFW_KEY_ENTER:
EnterPressed(active_model_.get());
break;
default:
break;
}
}
}
TextInputPlugin::TextInputPlugin(flutter::BinaryMessenger* messenger)
: channel_(std::make_unique<flutter::MethodChannel<rapidjson::Document>>(
messenger,
kChannelName,
&flutter::JsonMethodCodec::GetInstance())),
active_model_(nullptr) {
channel_->SetMethodCallHandler(
[this](
const flutter::MethodCall<rapidjson::Document>& call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) {
HandleMethodCall(call, std::move(result));
});
}
TextInputPlugin::~TextInputPlugin() = default;
void TextInputPlugin::HandleMethodCall(
const flutter::MethodCall<rapidjson::Document>& method_call,
std::unique_ptr<flutter::MethodResult<rapidjson::Document>> result) {
const std::string& method = method_call.method_name();
if (method.compare(kShowMethod) == 0 || method.compare(kHideMethod) == 0) {
// These methods are no-ops.
} else if (method.compare(kClearClientMethod) == 0) {
active_model_ = nullptr;
} else if (method.compare(kSetClientMethod) == 0) {
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
// TODO(awdavies): There's quite a wealth of arguments supplied with this
// method, and they should be inspected/used.
const rapidjson::Value& client_id_json = args[0];
const rapidjson::Value& client_config = args[1];
if (client_id_json.IsNull()) {
result->Error(kBadArgumentError, "Could not set client, ID is null.");
return;
}
if (client_config.IsNull()) {
result->Error(kBadArgumentError,
"Could not set client, missing arguments.");
return;
}
client_id_ = client_id_json.GetInt();
input_action_ = "";
auto input_action_json = client_config.FindMember(kTextInputAction);
if (input_action_json != client_config.MemberEnd() &&
input_action_json->value.IsString()) {
input_action_ = input_action_json->value.GetString();
}
input_type_ = "";
auto input_type_info_json = client_config.FindMember(kTextInputType);
if (input_type_info_json != client_config.MemberEnd() &&
input_type_info_json->value.IsObject()) {
auto input_type_json =
input_type_info_json->value.FindMember(kTextInputTypeName);
if (input_type_json != input_type_info_json->value.MemberEnd() &&
input_type_json->value.IsString()) {
input_type_ = input_type_json->value.GetString();
}
}
active_model_ = std::make_unique<TextInputModel>();
} else if (method.compare(kSetEditingStateMethod) == 0) {
if (!method_call.arguments() || method_call.arguments()->IsNull()) {
result->Error(kBadArgumentError, "Method invoked without args");
return;
}
const rapidjson::Document& args = *method_call.arguments();
if (active_model_ == nullptr) {
result->Error(
kInternalConsistencyError,
"Set editing state has been invoked, but no client is set.");
return;
}
auto text = args.FindMember(kTextKey);
if (text == args.MemberEnd() || text->value.IsNull()) {
result->Error(kBadArgumentError,
"Set editing state has been invoked, but without text.");
return;
}
auto selection_base = args.FindMember(kSelectionBaseKey);
auto selection_extent = args.FindMember(kSelectionExtentKey);
if (selection_base == args.MemberEnd() || selection_base->value.IsNull() ||
selection_extent == args.MemberEnd() ||
selection_extent->value.IsNull()) {
result->Error(kInternalConsistencyError,
"Selection base/extent values invalid.");
return;
}
// Flutter uses -1/-1 for invalid; translate that to 0/0 for the model.
int base = selection_base->value.GetInt();
int extent = selection_extent->value.GetInt();
if (base == -1 && extent == -1) {
base = extent = 0;
}
active_model_->SetText(text->value.GetString());
active_model_->SetSelection(TextRange(base, extent));
} else {
result->NotImplemented();
return;
}
// All error conditions return early, so if nothing has gone wrong indicate
// success.
result->Success();
}
void TextInputPlugin::SendStateUpdate(const TextInputModel& model) {
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(client_id_, allocator);
TextRange selection = model.selection();
rapidjson::Value editing_state(rapidjson::kObjectType);
editing_state.AddMember(kComposingBaseKey, -1, allocator);
editing_state.AddMember(kComposingExtentKey, -1, allocator);
editing_state.AddMember(kSelectionAffinityKey, kAffinityDownstream,
allocator);
editing_state.AddMember(kSelectionBaseKey, selection.base(), allocator);
editing_state.AddMember(kSelectionExtentKey, selection.extent(), allocator);
editing_state.AddMember(kSelectionIsDirectionalKey, false, allocator);
editing_state.AddMember(
kTextKey, rapidjson::Value(model.GetText(), allocator).Move(), allocator);
args->PushBack(editing_state, allocator);
channel_->InvokeMethod(kUpdateEditingStateMethod, std::move(args));
}
void TextInputPlugin::EnterPressed(TextInputModel* model) {
if (input_type_ == kMultilineInputType) {
model->AddCodePoint('\n');
SendStateUpdate(*model);
}
auto args = std::make_unique<rapidjson::Document>(rapidjson::kArrayType);
auto& allocator = args->GetAllocator();
args->PushBack(client_id_, allocator);
args->PushBack(rapidjson::Value(input_action_, allocator).Move(), allocator);
channel_->InvokeMethod(kPerformActionMethod, std::move(args));
}
} // namespace flutter
| engine/shell/platform/glfw/text_input_plugin.cc/0 | {
"file_path": "engine/shell/platform/glfw/text_input_plugin.cc",
"repo_id": "engine",
"token_count": 3484
} | 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.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_binary_messenger.h"
#include "flutter/shell/platform/linux/fl_binary_messenger_private.h"
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/linux/fl_engine_private.h"
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_codec.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h"
#include <gmodule.h>
static constexpr char kControlChannelName[] = "dev.flutter/channel-buffers";
static constexpr char kResizeMethod[] = "resize";
static constexpr char kOverflowMethod[] = "overflow";
G_DEFINE_QUARK(fl_binary_messenger_codec_error_quark,
fl_binary_messenger_codec_error)
G_DECLARE_FINAL_TYPE(FlBinaryMessengerImpl,
fl_binary_messenger_impl,
FL,
BINARY_MESSENGER_IMPL,
GObject)
G_DECLARE_FINAL_TYPE(FlBinaryMessengerResponseHandleImpl,
fl_binary_messenger_response_handle_impl,
FL,
BINARY_MESSENGER_RESPONSE_HANDLE_IMPL,
FlBinaryMessengerResponseHandle)
G_DEFINE_INTERFACE(FlBinaryMessenger, fl_binary_messenger, G_TYPE_OBJECT)
struct _FlBinaryMessengerImpl {
GObject parent_instance;
GWeakRef engine;
// PlatformMessageHandler keyed by channel name.
GHashTable* platform_message_handlers;
};
static void fl_binary_messenger_impl_iface_init(
FlBinaryMessengerInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlBinaryMessengerImpl,
fl_binary_messenger_impl,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_binary_messenger_get_type(),
fl_binary_messenger_impl_iface_init))
static void fl_binary_messenger_response_handle_class_init(
FlBinaryMessengerResponseHandleClass* klass) {}
G_DEFINE_TYPE(FlBinaryMessengerResponseHandle,
fl_binary_messenger_response_handle,
G_TYPE_OBJECT)
static void fl_binary_messenger_response_handle_init(
FlBinaryMessengerResponseHandle* self) {}
struct _FlBinaryMessengerResponseHandleImpl {
FlBinaryMessengerResponseHandle parent_instance;
// Messenger sending response on.
FlBinaryMessengerImpl* messenger;
// Handle to send the response with. This is cleared to nullptr when it is
// used.
const FlutterPlatformMessageResponseHandle* response_handle;
};
G_DEFINE_TYPE(FlBinaryMessengerResponseHandleImpl,
fl_binary_messenger_response_handle_impl,
fl_binary_messenger_response_handle_get_type())
static void fl_binary_messenger_default_init(
FlBinaryMessengerInterface* iface) {}
static void fl_binary_messenger_response_handle_impl_dispose(GObject* object) {
FlBinaryMessengerResponseHandleImpl* self =
FL_BINARY_MESSENGER_RESPONSE_HANDLE_IMPL(object);
g_autoptr(FlEngine) engine =
FL_ENGINE(g_weak_ref_get(&self->messenger->engine));
if (self->response_handle != nullptr && engine != nullptr) {
g_critical("FlBinaryMessengerResponseHandle was not responded to");
}
g_clear_object(&self->messenger);
self->response_handle = nullptr;
G_OBJECT_CLASS(fl_binary_messenger_response_handle_impl_parent_class)
->dispose(object);
}
static void fl_binary_messenger_response_handle_impl_class_init(
FlBinaryMessengerResponseHandleImplClass* klass) {
G_OBJECT_CLASS(klass)->dispose =
fl_binary_messenger_response_handle_impl_dispose;
}
static void fl_binary_messenger_response_handle_impl_init(
FlBinaryMessengerResponseHandleImpl* self) {}
static FlBinaryMessengerResponseHandleImpl*
fl_binary_messenger_response_handle_impl_new(
FlBinaryMessengerImpl* messenger,
const FlutterPlatformMessageResponseHandle* response_handle) {
FlBinaryMessengerResponseHandleImpl* self =
FL_BINARY_MESSENGER_RESPONSE_HANDLE_IMPL(g_object_new(
fl_binary_messenger_response_handle_impl_get_type(), nullptr));
self->messenger = FL_BINARY_MESSENGER_IMPL(g_object_ref(messenger));
self->response_handle = response_handle;
return self;
}
typedef struct {
FlBinaryMessengerMessageHandler message_handler;
gpointer message_handler_data;
GDestroyNotify message_handler_destroy_notify;
} PlatformMessageHandler;
static PlatformMessageHandler* platform_message_handler_new(
FlBinaryMessengerMessageHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
PlatformMessageHandler* self = static_cast<PlatformMessageHandler*>(
g_malloc0(sizeof(PlatformMessageHandler)));
self->message_handler = handler;
self->message_handler_data = user_data;
self->message_handler_destroy_notify = destroy_notify;
return self;
}
static void platform_message_handler_free(gpointer data) {
PlatformMessageHandler* self = static_cast<PlatformMessageHandler*>(data);
if (self->message_handler_destroy_notify) {
self->message_handler_destroy_notify(self->message_handler_data);
}
g_free(self);
}
static void engine_weak_notify_cb(gpointer user_data,
GObject* where_the_object_was) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(user_data);
// Disconnect any handlers.
// Take the reference in case a handler tries to modify this table.
g_autoptr(GHashTable) handlers = self->platform_message_handlers;
self->platform_message_handlers = g_hash_table_new_full(
g_str_hash, g_str_equal, g_free, platform_message_handler_free);
g_hash_table_remove_all(handlers);
}
static gboolean fl_binary_messenger_platform_message_cb(
FlEngine* engine,
const gchar* channel,
GBytes* message,
const FlutterPlatformMessageResponseHandle* response_handle,
void* user_data) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(user_data);
PlatformMessageHandler* handler = static_cast<PlatformMessageHandler*>(
g_hash_table_lookup(self->platform_message_handlers, channel));
if (handler == nullptr) {
return FALSE;
}
g_autoptr(FlBinaryMessengerResponseHandleImpl) handle =
fl_binary_messenger_response_handle_impl_new(self, response_handle);
handler->message_handler(FL_BINARY_MESSENGER(self), channel, message,
FL_BINARY_MESSENGER_RESPONSE_HANDLE(handle),
handler->message_handler_data);
return TRUE;
}
static void fl_binary_messenger_impl_dispose(GObject* object) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(object);
{
g_autoptr(FlEngine) engine = FL_ENGINE(g_weak_ref_get(&self->engine));
if (engine) {
g_object_weak_unref(G_OBJECT(engine), engine_weak_notify_cb, self);
}
}
g_weak_ref_clear(&self->engine);
g_clear_pointer(&self->platform_message_handlers, g_hash_table_unref);
G_OBJECT_CLASS(fl_binary_messenger_impl_parent_class)->dispose(object);
}
static void set_message_handler_on_channel(
FlBinaryMessenger* messenger,
const gchar* channel,
FlBinaryMessengerMessageHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(messenger);
// Don't set handlers if engine already gone.
g_autoptr(FlEngine) engine = FL_ENGINE(g_weak_ref_get(&self->engine));
if (engine == nullptr) {
if (handler != nullptr) {
g_warning(
"Attempted to set message handler on an FlBinaryMessenger without an "
"engine");
}
if (destroy_notify != nullptr) {
destroy_notify(user_data);
}
return;
}
if (handler != nullptr) {
g_hash_table_replace(
self->platform_message_handlers, g_strdup(channel),
platform_message_handler_new(handler, user_data, destroy_notify));
} else {
g_hash_table_remove(self->platform_message_handlers, channel);
}
}
static gboolean do_unref(gpointer value) {
g_object_unref(value);
return G_SOURCE_REMOVE;
}
// Note: This function can be called from any thread.
static gboolean send_response(FlBinaryMessenger* messenger,
FlBinaryMessengerResponseHandle* response_handle_,
GBytes* response,
GError** error) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(messenger);
g_return_val_if_fail(
FL_IS_BINARY_MESSENGER_RESPONSE_HANDLE_IMPL(response_handle_), FALSE);
FlBinaryMessengerResponseHandleImpl* response_handle =
FL_BINARY_MESSENGER_RESPONSE_HANDLE_IMPL(response_handle_);
g_return_val_if_fail(response_handle->messenger == self, FALSE);
g_return_val_if_fail(response_handle->response_handle != nullptr, FALSE);
FlEngine* engine = FL_ENGINE(g_weak_ref_get(&self->engine));
if (engine == nullptr) {
return TRUE;
}
gboolean result = false;
if (response_handle->response_handle == nullptr) {
g_set_error(
error, FL_BINARY_MESSENGER_ERROR,
FL_BINARY_MESSENGER_ERROR_ALREADY_RESPONDED,
"Attempted to respond to a message that is already responded to");
result = FALSE;
} else {
result = fl_engine_send_platform_message_response(
engine, response_handle->response_handle, response, error);
response_handle->response_handle = nullptr;
}
// This guarantees that the dispose method for the engine is executed
// on the platform thread in the rare chance this is the last ref.
g_idle_add(do_unref, engine);
return result;
}
static void platform_message_ready_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
GTask* task = G_TASK(user_data);
g_task_return_pointer(task, result, g_object_unref);
}
static void send_on_channel(FlBinaryMessenger* messenger,
const gchar* channel,
GBytes* message,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(messenger);
g_autoptr(FlEngine) engine = FL_ENGINE(g_weak_ref_get(&self->engine));
if (engine == nullptr) {
return;
}
fl_engine_send_platform_message(
engine, channel, message, cancellable,
callback != nullptr ? platform_message_ready_cb : nullptr,
callback != nullptr ? g_task_new(self, cancellable, callback, user_data)
: nullptr);
}
static GBytes* send_on_channel_finish(FlBinaryMessenger* messenger,
GAsyncResult* result,
GError** error) {
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(messenger);
g_return_val_if_fail(g_task_is_valid(result, self), FALSE);
g_autoptr(GTask) task = G_TASK(result);
GAsyncResult* r = G_ASYNC_RESULT(g_task_propagate_pointer(task, nullptr));
g_autoptr(FlEngine) engine = FL_ENGINE(g_weak_ref_get(&self->engine));
if (engine == nullptr) {
return nullptr;
}
return fl_engine_send_platform_message_finish(engine, r, error);
}
// Completes method call and returns TRUE if the call was successful.
static gboolean finish_method(GObject* object,
GAsyncResult* result,
GError** error) {
g_autoptr(GBytes) response = fl_binary_messenger_send_on_channel_finish(
FL_BINARY_MESSENGER(object), result, error);
if (response == nullptr) {
return FALSE;
}
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
return fl_method_codec_decode_response(FL_METHOD_CODEC(codec), response,
error) != nullptr;
}
// Called when a response is received for the resize channel message.
static void resize_channel_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(GError) error = nullptr;
if (!finish_method(object, result, &error)) {
g_warning("Failed to resize channel: %s", error->message);
}
}
static void resize_channel(FlBinaryMessenger* messenger,
const gchar* channel,
int64_t new_size) {
FML_DCHECK(new_size >= 0);
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlValue) args = fl_value_new_list();
fl_value_append_take(args, fl_value_new_string(channel));
fl_value_append_take(args, fl_value_new_int(new_size));
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), kResizeMethod, args, nullptr);
fl_binary_messenger_send_on_channel(messenger, kControlChannelName, message,
nullptr, resize_channel_response_cb,
nullptr);
}
// Called when a response is received for the warns on overflow message.
static void set_warns_on_channel_overflow_response_cb(GObject* object,
GAsyncResult* result,
gpointer user_data) {
g_autoptr(GError) error = nullptr;
if (!finish_method(object, result, &error)) {
g_warning("Failed to set warns on channel overflow: %s", error->message);
}
}
static void set_warns_on_channel_overflow(FlBinaryMessenger* messenger,
const gchar* channel,
bool warns) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(FlValue) args = fl_value_new_list();
fl_value_append_take(args, fl_value_new_string(channel));
fl_value_append_take(args, fl_value_new_bool(!warns));
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), kOverflowMethod, args, nullptr);
fl_binary_messenger_send_on_channel(
messenger, kControlChannelName, message, nullptr,
set_warns_on_channel_overflow_response_cb, nullptr);
}
static void fl_binary_messenger_impl_class_init(
FlBinaryMessengerImplClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_binary_messenger_impl_dispose;
}
static void fl_binary_messenger_impl_iface_init(
FlBinaryMessengerInterface* iface) {
iface->set_message_handler_on_channel = set_message_handler_on_channel;
iface->send_response = send_response;
iface->send_on_channel = send_on_channel;
iface->send_on_channel_finish = send_on_channel_finish;
iface->resize_channel = resize_channel;
iface->set_warns_on_channel_overflow = set_warns_on_channel_overflow;
}
static void fl_binary_messenger_impl_init(FlBinaryMessengerImpl* self) {
self->platform_message_handlers = g_hash_table_new_full(
g_str_hash, g_str_equal, g_free, platform_message_handler_free);
}
FlBinaryMessenger* fl_binary_messenger_new(FlEngine* engine) {
g_return_val_if_fail(FL_IS_ENGINE(engine), nullptr);
FlBinaryMessengerImpl* self = FL_BINARY_MESSENGER_IMPL(
g_object_new(fl_binary_messenger_impl_get_type(), nullptr));
// Added to stop compiler complaining about an unused function.
FL_IS_BINARY_MESSENGER_IMPL(self);
g_weak_ref_init(&self->engine, G_OBJECT(engine));
g_object_weak_ref(G_OBJECT(engine), engine_weak_notify_cb, self);
fl_engine_set_platform_message_handler(
engine, fl_binary_messenger_platform_message_cb, self, NULL);
return FL_BINARY_MESSENGER(self);
}
G_MODULE_EXPORT void fl_binary_messenger_set_message_handler_on_channel(
FlBinaryMessenger* self,
const gchar* channel,
FlBinaryMessengerMessageHandler handler,
gpointer user_data,
GDestroyNotify destroy_notify) {
g_return_if_fail(FL_IS_BINARY_MESSENGER(self));
g_return_if_fail(channel != nullptr);
FL_BINARY_MESSENGER_GET_IFACE(self)->set_message_handler_on_channel(
self, channel, handler, user_data, destroy_notify);
}
// Note: This function can be called from any thread.
G_MODULE_EXPORT gboolean fl_binary_messenger_send_response(
FlBinaryMessenger* self,
FlBinaryMessengerResponseHandle* response_handle,
GBytes* response,
GError** error) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(self), FALSE);
g_return_val_if_fail(FL_IS_BINARY_MESSENGER_RESPONSE_HANDLE(response_handle),
FALSE);
return FL_BINARY_MESSENGER_GET_IFACE(self)->send_response(
self, response_handle, response, error);
}
G_MODULE_EXPORT void fl_binary_messenger_send_on_channel(
FlBinaryMessenger* self,
const gchar* channel,
GBytes* message,
GCancellable* cancellable,
GAsyncReadyCallback callback,
gpointer user_data) {
g_return_if_fail(FL_IS_BINARY_MESSENGER(self));
g_return_if_fail(channel != nullptr);
FL_BINARY_MESSENGER_GET_IFACE(self)->send_on_channel(
self, channel, message, cancellable, callback, user_data);
}
G_MODULE_EXPORT GBytes* fl_binary_messenger_send_on_channel_finish(
FlBinaryMessenger* self,
GAsyncResult* result,
GError** error) {
g_return_val_if_fail(FL_IS_BINARY_MESSENGER(self), FALSE);
return FL_BINARY_MESSENGER_GET_IFACE(self)->send_on_channel_finish(
self, result, error);
}
G_MODULE_EXPORT void fl_binary_messenger_resize_channel(FlBinaryMessenger* self,
const gchar* channel,
int64_t new_size) {
g_return_if_fail(FL_IS_BINARY_MESSENGER(self));
return FL_BINARY_MESSENGER_GET_IFACE(self)->resize_channel(self, channel,
new_size);
}
G_MODULE_EXPORT void fl_binary_messenger_set_warns_on_channel_overflow(
FlBinaryMessenger* self,
const gchar* channel,
bool warns) {
g_return_if_fail(FL_IS_BINARY_MESSENGER(self));
return FL_BINARY_MESSENGER_GET_IFACE(self)->set_warns_on_channel_overflow(
self, channel, warns);
}
| engine/shell/platform/linux/fl_binary_messenger.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_binary_messenger.cc",
"repo_id": "engine",
"token_count": 7600
} | 378 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_method_codec.h"
#include <gmodule.h>
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h"
static constexpr char kMethodKey[] = "method";
static constexpr char kArgsKey[] = "args";
struct _FlJsonMethodCodec {
FlMethodCodec parent_instance;
FlJsonMessageCodec* codec;
};
G_DEFINE_TYPE(FlJsonMethodCodec,
fl_json_method_codec,
fl_method_codec_get_type())
static void fl_json_method_codec_dispose(GObject* object) {
FlJsonMethodCodec* self = FL_JSON_METHOD_CODEC(object);
g_clear_object(&self->codec);
G_OBJECT_CLASS(fl_json_method_codec_parent_class)->dispose(object);
}
// Implements FlMethodCodec::encode_method_call.
static GBytes* fl_json_method_codec_encode_method_call(FlMethodCodec* codec,
const gchar* name,
FlValue* args,
GError** error) {
FlJsonMethodCodec* self = FL_JSON_METHOD_CODEC(codec);
g_autoptr(FlValue) message = fl_value_new_map();
fl_value_set_take(message, fl_value_new_string(kMethodKey),
fl_value_new_string(name));
fl_value_set_take(message, fl_value_new_string(kArgsKey),
args != nullptr ? fl_value_ref(args) : fl_value_new_null());
return fl_message_codec_encode_message(FL_MESSAGE_CODEC(self->codec), message,
error);
}
// Implements FlMethodCodec::decode_method_call.
static gboolean fl_json_method_codec_decode_method_call(FlMethodCodec* codec,
GBytes* message,
gchar** name,
FlValue** args,
GError** error) {
FlJsonMethodCodec* self = FL_JSON_METHOD_CODEC(codec);
g_autoptr(FlValue) value = fl_message_codec_decode_message(
FL_MESSAGE_CODEC(self->codec), message, error);
if (value == nullptr) {
return FALSE;
}
if (fl_value_get_type(value) != FL_VALUE_TYPE_MAP) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Expected JSON map in method response, got %d instead",
fl_value_get_type(value));
return FALSE;
}
FlValue* method_value = fl_value_lookup_string(value, kMethodKey);
if (method_value == nullptr) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Missing JSON method field in method response");
return FALSE;
}
if (fl_value_get_type(method_value) != FL_VALUE_TYPE_STRING) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Expected JSON string for method name, got %d instead",
fl_value_get_type(method_value));
return FALSE;
}
FlValue* args_value = fl_value_lookup_string(value, kArgsKey);
*name = g_strdup(fl_value_get_string(method_value));
*args = args_value != nullptr ? fl_value_ref(args_value) : nullptr;
return TRUE;
}
// Implements FlMethodCodec::encode_success_envelope.
static GBytes* fl_json_method_codec_encode_success_envelope(
FlMethodCodec* codec,
FlValue* result,
GError** error) {
FlJsonMethodCodec* self = FL_JSON_METHOD_CODEC(codec);
g_autoptr(FlValue) message = fl_value_new_list();
fl_value_append_take(
message, result != nullptr ? fl_value_ref(result) : fl_value_new_null());
return fl_message_codec_encode_message(FL_MESSAGE_CODEC(self->codec), message,
error);
}
// Implements FlMethodCodec::encode_error_envelope.
static GBytes* fl_json_method_codec_encode_error_envelope(
FlMethodCodec* codec,
const gchar* code,
const gchar* error_message,
FlValue* details,
GError** error) {
FlJsonMethodCodec* self = FL_JSON_METHOD_CODEC(codec);
g_autoptr(FlValue) message = fl_value_new_list();
fl_value_append_take(message, fl_value_new_string(code));
fl_value_append_take(message, error_message != nullptr
? fl_value_new_string(error_message)
: fl_value_new_null());
fl_value_append_take(message, details != nullptr ? fl_value_ref(details)
: fl_value_new_null());
return fl_message_codec_encode_message(FL_MESSAGE_CODEC(self->codec), message,
error);
}
// Implements FlMethodCodec::decode_response.
static FlMethodResponse* fl_json_method_codec_decode_response(
FlMethodCodec* codec,
GBytes* message,
GError** error) {
FlJsonMethodCodec* self = FL_JSON_METHOD_CODEC(codec);
g_autoptr(FlValue) value = fl_message_codec_decode_message(
FL_MESSAGE_CODEC(self->codec), message, error);
if (value == nullptr) {
return nullptr;
}
if (fl_value_get_type(value) != FL_VALUE_TYPE_LIST) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Expected JSON list in method response, got %d instead",
fl_value_get_type(value));
return nullptr;
}
size_t length = fl_value_get_length(value);
if (length == 1) {
return FL_METHOD_RESPONSE(
fl_method_success_response_new(fl_value_get_list_value(value, 0)));
} else if (length == 3) {
FlValue* code_value = fl_value_get_list_value(value, 0);
if (fl_value_get_type(code_value) != FL_VALUE_TYPE_STRING) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Error code wrong type");
return nullptr;
}
const gchar* code = fl_value_get_string(code_value);
FlValue* message_value = fl_value_get_list_value(value, 1);
if (fl_value_get_type(message_value) != FL_VALUE_TYPE_STRING &&
fl_value_get_type(message_value) != FL_VALUE_TYPE_NULL) {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Error message wrong type");
return nullptr;
}
const gchar* message =
fl_value_get_type(message_value) == FL_VALUE_TYPE_STRING
? fl_value_get_string(message_value)
: nullptr;
FlValue* args = fl_value_get_list_value(value, 2);
if (fl_value_get_type(args) == FL_VALUE_TYPE_NULL) {
args = nullptr;
}
return FL_METHOD_RESPONSE(
fl_method_error_response_new(code, message, args));
} else {
g_set_error(error, FL_MESSAGE_CODEC_ERROR, FL_MESSAGE_CODEC_ERROR_FAILED,
"Got response envelope of length %zi, expected 1 (success) or "
"3 (error)",
length);
return nullptr;
}
}
static void fl_json_method_codec_class_init(FlJsonMethodCodecClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_json_method_codec_dispose;
FL_METHOD_CODEC_CLASS(klass)->encode_method_call =
fl_json_method_codec_encode_method_call;
FL_METHOD_CODEC_CLASS(klass)->decode_method_call =
fl_json_method_codec_decode_method_call;
FL_METHOD_CODEC_CLASS(klass)->encode_success_envelope =
fl_json_method_codec_encode_success_envelope;
FL_METHOD_CODEC_CLASS(klass)->encode_error_envelope =
fl_json_method_codec_encode_error_envelope;
FL_METHOD_CODEC_CLASS(klass)->decode_response =
fl_json_method_codec_decode_response;
}
static void fl_json_method_codec_init(FlJsonMethodCodec* self) {
self->codec = fl_json_message_codec_new();
}
G_MODULE_EXPORT FlJsonMethodCodec* fl_json_method_codec_new() {
return static_cast<FlJsonMethodCodec*>(
g_object_new(fl_json_method_codec_get_type(), nullptr));
}
| engine/shell/platform/linux/fl_json_method_codec.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_json_method_codec.cc",
"repo_id": "engine",
"token_count": 3744
} | 379 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/fl_keyboard_view_delegate.h"
G_DEFINE_INTERFACE(FlKeyboardViewDelegate,
fl_keyboard_view_delegate,
G_TYPE_OBJECT)
static void fl_keyboard_view_delegate_default_init(
FlKeyboardViewDelegateInterface* iface) {}
void fl_keyboard_view_delegate_send_key_event(FlKeyboardViewDelegate* self,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data) {
g_return_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self));
g_return_if_fail(event != nullptr);
FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->send_key_event(
self, event, callback, user_data);
}
gboolean fl_keyboard_view_delegate_text_filter_key_press(
FlKeyboardViewDelegate* self,
FlKeyEvent* event) {
g_return_val_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self), false);
g_return_val_if_fail(event != nullptr, false);
return FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->text_filter_key_press(
self, event);
}
FlBinaryMessenger* fl_keyboard_view_delegate_get_messenger(
FlKeyboardViewDelegate* self) {
g_return_val_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self), nullptr);
return FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->get_messenger(self);
}
void fl_keyboard_view_delegate_redispatch_event(
FlKeyboardViewDelegate* self,
std::unique_ptr<FlKeyEvent> event) {
g_return_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self));
g_return_if_fail(event != nullptr);
return FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->redispatch_event(
self, std::move(event));
}
void fl_keyboard_view_delegate_subscribe_to_layout_change(
FlKeyboardViewDelegate* self,
KeyboardLayoutNotifier notifier) {
g_return_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self));
return FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->subscribe_to_layout_change(
self, std::move(notifier));
}
guint fl_keyboard_view_delegate_lookup_key(FlKeyboardViewDelegate* self,
const GdkKeymapKey* key) {
g_return_val_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self), 0);
return FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->lookup_key(self, key);
}
GHashTable* fl_keyboard_view_delegate_get_keyboard_state(
FlKeyboardViewDelegate* self) {
g_return_val_if_fail(FL_IS_KEYBOARD_VIEW_DELEGATE(self), nullptr);
return FL_KEYBOARD_VIEW_DELEGATE_GET_IFACE(self)->get_keyboard_state(self);
}
| engine/shell/platform/linux/fl_keyboard_view_delegate.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_keyboard_view_delegate.cc",
"repo_id": "engine",
"token_count": 1205
} | 380 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_pixel_buffer_texture.h"
#include <epoxy/gl.h>
#include <gmodule.h>
#include "flutter/shell/platform/linux/fl_pixel_buffer_texture_private.h"
typedef struct {
int64_t id;
GLuint texture_id;
} FlPixelBufferTexturePrivate;
static void fl_pixel_buffer_texture_iface_init(FlTextureInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlPixelBufferTexture,
fl_pixel_buffer_texture,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_texture_get_type(),
fl_pixel_buffer_texture_iface_init);
G_ADD_PRIVATE(FlPixelBufferTexture))
// Implements FlTexture::set_id
static void fl_pixel_buffer_texture_set_id(FlTexture* texture, int64_t id) {
FlPixelBufferTexture* self = FL_PIXEL_BUFFER_TEXTURE(texture);
FlPixelBufferTexturePrivate* priv =
reinterpret_cast<FlPixelBufferTexturePrivate*>(
fl_pixel_buffer_texture_get_instance_private(self));
priv->id = id;
}
// Implements FlTexture::set_id
static int64_t fl_pixel_buffer_texture_get_id(FlTexture* texture) {
FlPixelBufferTexture* self = FL_PIXEL_BUFFER_TEXTURE(texture);
FlPixelBufferTexturePrivate* priv =
reinterpret_cast<FlPixelBufferTexturePrivate*>(
fl_pixel_buffer_texture_get_instance_private(self));
return priv->id;
}
static void fl_pixel_buffer_texture_iface_init(FlTextureInterface* iface) {
iface->set_id = fl_pixel_buffer_texture_set_id;
iface->get_id = fl_pixel_buffer_texture_get_id;
}
static void fl_pixel_buffer_texture_dispose(GObject* object) {
FlPixelBufferTexture* self = FL_PIXEL_BUFFER_TEXTURE(object);
FlPixelBufferTexturePrivate* priv =
reinterpret_cast<FlPixelBufferTexturePrivate*>(
fl_pixel_buffer_texture_get_instance_private(self));
if (priv->texture_id) {
glDeleteTextures(1, &priv->texture_id);
priv->texture_id = 0;
}
G_OBJECT_CLASS(fl_pixel_buffer_texture_parent_class)->dispose(object);
}
static void check_gl_error(int line) {
GLenum err = glGetError();
if (err) {
g_warning("glGetError %x (%s:%d)\n", err, __FILE__, line);
}
}
gboolean fl_pixel_buffer_texture_populate(FlPixelBufferTexture* texture,
uint32_t width,
uint32_t height,
FlutterOpenGLTexture* opengl_texture,
GError** error) {
FlPixelBufferTexture* self = FL_PIXEL_BUFFER_TEXTURE(texture);
FlPixelBufferTexturePrivate* priv =
reinterpret_cast<FlPixelBufferTexturePrivate*>(
fl_pixel_buffer_texture_get_instance_private(self));
const uint8_t* buffer = nullptr;
if (!FL_PIXEL_BUFFER_TEXTURE_GET_CLASS(self)->copy_pixels(
self, &buffer, &width, &height, error)) {
return FALSE;
}
if (priv->texture_id == 0) {
glGenTextures(1, &priv->texture_id);
check_gl_error(__LINE__);
glBindTexture(GL_TEXTURE_2D, priv->texture_id);
check_gl_error(__LINE__);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
check_gl_error(__LINE__);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
check_gl_error(__LINE__);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
check_gl_error(__LINE__);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
check_gl_error(__LINE__);
} else {
glBindTexture(GL_TEXTURE_2D, priv->texture_id);
check_gl_error(__LINE__);
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, buffer);
check_gl_error(__LINE__);
opengl_texture->target = GL_TEXTURE_2D;
opengl_texture->name = priv->texture_id;
opengl_texture->format = GL_RGBA8;
opengl_texture->destruction_callback = nullptr;
opengl_texture->user_data = nullptr;
opengl_texture->width = width;
opengl_texture->height = height;
return TRUE;
}
static void fl_pixel_buffer_texture_class_init(
FlPixelBufferTextureClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_pixel_buffer_texture_dispose;
}
static void fl_pixel_buffer_texture_init(FlPixelBufferTexture* self) {}
| engine/shell/platform/linux/fl_pixel_buffer_texture.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_pixel_buffer_texture.cc",
"repo_id": "engine",
"token_count": 1784
} | 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/linux/fl_scrolling_manager.h"
static constexpr int kMicrosecondsPerMillisecond = 1000;
struct _FlScrollingManager {
GObject parent_instance;
FlScrollingViewDelegate* view_delegate;
gdouble last_x;
gdouble last_y;
gboolean pan_started;
gdouble pan_x;
gdouble pan_y;
gboolean zoom_started;
gboolean rotate_started;
gdouble scale;
gdouble rotation;
};
G_DEFINE_TYPE(FlScrollingManager, fl_scrolling_manager, G_TYPE_OBJECT);
static void fl_scrolling_manager_dispose(GObject* object) {
FlScrollingManager* self = FL_SCROLLING_MANAGER(object);
if (self->view_delegate != nullptr) {
g_object_remove_weak_pointer(
object, reinterpret_cast<gpointer*>(&self->view_delegate));
self->view_delegate = nullptr;
}
G_OBJECT_CLASS(fl_scrolling_manager_parent_class)->dispose(object);
}
static void fl_scrolling_manager_class_init(FlScrollingManagerClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_scrolling_manager_dispose;
}
static void fl_scrolling_manager_init(FlScrollingManager* self) {}
FlScrollingManager* fl_scrolling_manager_new(
FlScrollingViewDelegate* view_delegate) {
g_return_val_if_fail(FL_IS_SCROLLING_VIEW_DELEGATE(view_delegate), nullptr);
FlScrollingManager* self = FL_SCROLLING_MANAGER(
g_object_new(fl_scrolling_manager_get_type(), nullptr));
self->view_delegate = view_delegate;
g_object_add_weak_pointer(
G_OBJECT(view_delegate),
reinterpret_cast<gpointer*>(&(self->view_delegate)));
self->pan_started = FALSE;
self->zoom_started = FALSE;
self->rotate_started = FALSE;
return self;
}
void fl_scrolling_manager_set_last_mouse_position(FlScrollingManager* self,
gdouble x,
gdouble y) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->last_x = x;
self->last_y = y;
}
void fl_scrolling_manager_handle_scroll_event(FlScrollingManager* self,
GdkEventScroll* scroll_event,
gint scale_factor) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
GdkEvent* event = reinterpret_cast<GdkEvent*>(scroll_event);
guint event_time = gdk_event_get_time(event);
gdouble event_x = 0.0, event_y = 0.0;
gdk_event_get_coords(event, &event_x, &event_y);
gdouble scroll_delta_x = 0.0, scroll_delta_y = 0.0;
GdkScrollDirection event_direction = GDK_SCROLL_SMOOTH;
if (gdk_event_get_scroll_direction(event, &event_direction)) {
if (event_direction == GDK_SCROLL_UP) {
scroll_delta_x = 0;
scroll_delta_y = -1;
} else if (event_direction == GDK_SCROLL_DOWN) {
scroll_delta_x = 0;
scroll_delta_y = 1;
} else if (event_direction == GDK_SCROLL_LEFT) {
scroll_delta_x = -1;
scroll_delta_y = 0;
} else if (event_direction == GDK_SCROLL_RIGHT) {
scroll_delta_x = 1;
scroll_delta_y = 0;
}
} else {
gdk_event_get_scroll_deltas(event, &scroll_delta_x, &scroll_delta_y);
}
// The multiplier is taken from the Chromium source
// (ui/events/x/events_x_utils.cc).
const int kScrollOffsetMultiplier = 53;
scroll_delta_x *= kScrollOffsetMultiplier * scale_factor;
scroll_delta_y *= kScrollOffsetMultiplier * scale_factor;
if (gdk_device_get_source(gdk_event_get_source_device(event)) ==
GDK_SOURCE_TOUCHPAD) {
scroll_delta_x *= -1;
scroll_delta_y *= -1;
if (gdk_event_is_scroll_stop_event(event)) {
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, event_time * kMicrosecondsPerMillisecond,
event_x * scale_factor, event_y * scale_factor, kPanZoomEnd,
self->pan_x, self->pan_y, 0, 0);
self->pan_started = FALSE;
} else {
if (!self->pan_started) {
self->pan_x = 0;
self->pan_y = 0;
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, event_time * kMicrosecondsPerMillisecond,
event_x * scale_factor, event_y * scale_factor, kPanZoomStart, 0, 0,
0, 0);
self->pan_started = TRUE;
}
self->pan_x += scroll_delta_x;
self->pan_y += scroll_delta_y;
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, event_time * kMicrosecondsPerMillisecond,
event_x * scale_factor, event_y * scale_factor, kPanZoomUpdate,
self->pan_x, self->pan_y, 1, 0);
}
} else {
self->last_x = event_x * scale_factor;
self->last_y = event_y * scale_factor;
fl_scrolling_view_delegate_send_mouse_pointer_event(
self->view_delegate,
FlutterPointerPhase::kMove /* arbitrary value, phase will be ignored as
this is a discrete scroll event */
,
event_time * kMicrosecondsPerMillisecond, event_x * scale_factor,
event_y * scale_factor, scroll_delta_x, scroll_delta_y, 0);
}
}
void fl_scrolling_manager_handle_rotation_begin(FlScrollingManager* self) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->rotate_started = TRUE;
if (!self->zoom_started) {
self->scale = 1;
self->rotation = 0;
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, g_get_real_time(), self->last_x, self->last_y,
kPanZoomStart, 0, 0, 0, 0);
}
}
void fl_scrolling_manager_handle_rotation_update(FlScrollingManager* self,
gdouble rotation) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->rotation = rotation;
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, g_get_real_time(), self->last_x, self->last_y,
kPanZoomUpdate, 0, 0, self->scale, self->rotation);
}
void fl_scrolling_manager_handle_rotation_end(FlScrollingManager* self) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->rotate_started = FALSE;
if (!self->zoom_started) {
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, g_get_real_time(), self->last_x, self->last_y,
kPanZoomEnd, 0, 0, 0, 0);
}
}
void fl_scrolling_manager_handle_zoom_begin(FlScrollingManager* self) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->zoom_started = TRUE;
if (!self->rotate_started) {
self->scale = 1;
self->rotation = 0;
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, g_get_real_time(), self->last_x, self->last_y,
kPanZoomStart, 0, 0, 0, 0);
}
}
void fl_scrolling_manager_handle_zoom_update(FlScrollingManager* self,
gdouble scale) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->scale = scale;
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, g_get_real_time(), self->last_x, self->last_y,
kPanZoomUpdate, 0, 0, self->scale, self->rotation);
}
void fl_scrolling_manager_handle_zoom_end(FlScrollingManager* self) {
g_return_if_fail(FL_IS_SCROLLING_MANAGER(self));
self->zoom_started = FALSE;
if (!self->rotate_started) {
fl_scrolling_view_delegate_send_pointer_pan_zoom_event(
self->view_delegate, g_get_real_time(), self->last_x, self->last_y,
kPanZoomEnd, 0, 0, 0, 0);
}
}
| engine/shell/platform/linux/fl_scrolling_manager.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_scrolling_manager.cc",
"repo_id": "engine",
"token_count": 3348
} | 382 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h"
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_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 method call using StandardMethodCodec to a hex string.
static gchar* encode_method_call(const gchar* name, FlValue* args) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), name, args, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return bytes_to_hex_string(message);
}
// Encodes a success envelope response using StandardMethodCodec to a hex
// string.
static gchar* encode_success_envelope(FlValue* result) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_success_envelope(
FL_METHOD_CODEC(codec), result, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return bytes_to_hex_string(message);
}
// Encodes a error envelope response using StandardMethodCodec to a hex string.
static gchar* encode_error_envelope(const gchar* error_code,
const gchar* error_message,
FlValue* details) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), error_code, error_message, details, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
return bytes_to_hex_string(message);
}
// Decodes a method call using StandardMethodCodec with a hex string.
static void decode_method_call(const char* hex_string,
gchar** name,
FlValue** args) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) message = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
gboolean result = fl_method_codec_decode_method_call(
FL_METHOD_CODEC(codec), message, name, args, &error);
EXPECT_TRUE(result);
EXPECT_EQ(error, nullptr);
}
// Decodes a method call using StandardMethodCodec. Expect the given error.
static void decode_error_method_call(const char* hex_string,
GQuark domain,
gint code) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) message = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
gboolean result = fl_method_codec_decode_method_call(
FL_METHOD_CODEC(codec), message, &name, &args, &error);
EXPECT_FALSE(result);
EXPECT_EQ(name, nullptr);
EXPECT_EQ(args, nullptr);
EXPECT_TRUE(g_error_matches(error, domain, code));
}
// Decodes a response using StandardMethodCodec. Expect the response is a
// result.
static void decode_response_with_success(const char* hex_string,
FlValue* result) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) message = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
ASSERT_NE(response, nullptr);
EXPECT_EQ(error, nullptr);
EXPECT_TRUE(FL_IS_METHOD_SUCCESS_RESPONSE(response));
EXPECT_TRUE(fl_value_equal(fl_method_success_response_get_result(
FL_METHOD_SUCCESS_RESPONSE(response)),
result));
}
// Decodes a response using StandardMethodCodec. Expect the response contains
// the given error.
static void decode_response_with_error(const char* hex_string,
const gchar* code,
const gchar* error_message,
FlValue* details) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) message = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
ASSERT_NE(response, nullptr);
EXPECT_EQ(error, nullptr);
EXPECT_TRUE(FL_IS_METHOD_ERROR_RESPONSE(response));
EXPECT_STREQ(
fl_method_error_response_get_code(FL_METHOD_ERROR_RESPONSE(response)),
code);
if (error_message == nullptr) {
EXPECT_EQ(fl_method_error_response_get_message(
FL_METHOD_ERROR_RESPONSE(response)),
nullptr);
} else {
EXPECT_STREQ(fl_method_error_response_get_message(
FL_METHOD_ERROR_RESPONSE(response)),
error_message);
}
if (details == nullptr) {
EXPECT_EQ(fl_method_error_response_get_details(
FL_METHOD_ERROR_RESPONSE(response)),
nullptr);
} else {
EXPECT_TRUE(fl_value_equal(fl_method_error_response_get_details(
FL_METHOD_ERROR_RESPONSE(response)),
details));
}
}
static void decode_error_response(const char* hex_string,
GQuark domain,
gint code) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) message = hex_string_to_bytes(hex_string);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
EXPECT_EQ(response, nullptr);
EXPECT_TRUE(g_error_matches(error, domain, code));
}
TEST(FlStandardMethodCodecTest, EncodeMethodCallNullptrArgs) {
g_autofree gchar* hex_string = encode_method_call("hello", nullptr);
EXPECT_STREQ(hex_string, "070568656c6c6f00");
}
TEST(FlStandardMethodCodecTest, EncodeMethodCallNullArgs) {
g_autoptr(FlValue) value = fl_value_new_null();
g_autofree gchar* hex_string = encode_method_call("hello", value);
EXPECT_STREQ(hex_string, "070568656c6c6f00");
}
TEST(FlStandardMethodCodecTest, EncodeMethodCallStringArgs) {
g_autoptr(FlValue) args = fl_value_new_string("world");
g_autofree gchar* hex_string = encode_method_call("hello", args);
EXPECT_STREQ(hex_string, "070568656c6c6f0705776f726c64");
}
TEST(FlStandardMethodCodecTest, EncodeMethodCallListArgs) {
g_autoptr(FlValue) args = fl_value_new_list();
fl_value_append_take(args, fl_value_new_string("count"));
fl_value_append_take(args, fl_value_new_int(42));
g_autofree gchar* hex_string = encode_method_call("hello", args);
EXPECT_STREQ(hex_string, "070568656c6c6f0c020705636f756e74032a000000");
}
TEST(FlStandardMethodCodecTest, DecodeMethodCallNullArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("070568656c6c6f00", &name, &args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_NULL);
}
TEST(FlStandardMethodCodecTest, DecodeMethodCallStringArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("070568656c6c6f0705776f726c64", &name, &args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(args), "world");
}
TEST(FlStandardMethodCodecTest, DecodeMethodCallListArgs) {
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
decode_method_call("070568656c6c6f0c020705636f756e74032a000000", &name,
&args);
EXPECT_STREQ(name, "hello");
ASSERT_EQ(fl_value_get_type(args), FL_VALUE_TYPE_LIST);
EXPECT_EQ(fl_value_get_length(args), static_cast<size_t>(2));
FlValue* arg0 = fl_value_get_list_value(args, 0);
ASSERT_EQ(fl_value_get_type(arg0), FL_VALUE_TYPE_STRING);
EXPECT_STREQ(fl_value_get_string(arg0), "count");
FlValue* arg1 = fl_value_get_list_value(args, 1);
ASSERT_EQ(fl_value_get_type(arg1), FL_VALUE_TYPE_INT);
EXPECT_EQ(fl_value_get_int(arg1), 42);
}
TEST(FlStandardMethodCodecTest, DecodeMethodCallNoData) {
decode_error_method_call("", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMethodCodecTest, DecodeMethodCallNullMethodName) {
decode_error_method_call("000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlStandardMethodCodecTest, DecodeMethodCallMissingArgs) {
decode_error_method_call("070568656c6c6f", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMethodCodecTest, EncodeSuccessEnvelopeNullptr) {
g_autofree gchar* hex_string = encode_success_envelope(nullptr);
EXPECT_STREQ(hex_string, "0000");
}
TEST(FlStandardMethodCodecTest, EncodeSuccessEnvelopeNull) {
g_autoptr(FlValue) result = fl_value_new_null();
g_autofree gchar* hex_string = encode_success_envelope(result);
EXPECT_STREQ(hex_string, "0000");
}
TEST(FlStandardMethodCodecTest, EncodeSuccessEnvelopeString) {
g_autoptr(FlValue) result = fl_value_new_string("hello");
g_autofree gchar* hex_string = encode_success_envelope(result);
EXPECT_STREQ(hex_string, "00070568656c6c6f");
}
TEST(FlStandardMethodCodecTest, EncodeSuccessEnvelopeList) {
g_autoptr(FlValue) result = fl_value_new_list();
fl_value_append_take(result, fl_value_new_string("count"));
fl_value_append_take(result, fl_value_new_int(42));
g_autofree gchar* hex_string = encode_success_envelope(result);
EXPECT_STREQ(hex_string, "000c020705636f756e74032a000000");
}
TEST(FlStandardMethodCodecTest, EncodeErrorEnvelopeEmptyCode) {
g_autofree gchar* hex_string = encode_error_envelope("", nullptr, nullptr);
EXPECT_STREQ(hex_string, "0107000000");
}
TEST(FlStandardMethodCodecTest, EncodeErrorEnvelopeNonMessageOrDetails) {
g_autofree gchar* hex_string =
encode_error_envelope("error", nullptr, nullptr);
EXPECT_STREQ(hex_string, "0107056572726f720000");
}
TEST(FlStandardMethodCodecTest, EncodeErrorEnvelopeMessage) {
g_autofree gchar* hex_string =
encode_error_envelope("error", "message", nullptr);
EXPECT_STREQ(hex_string, "0107056572726f7207076d65737361676500");
}
TEST(FlStandardMethodCodecTest, EncodeErrorEnvelopeDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
g_autofree gchar* hex_string =
encode_error_envelope("error", nullptr, details);
EXPECT_STREQ(hex_string, "0107056572726f72000c020705636f756e74032a000000");
}
TEST(FlStandardMethodCodecTest, EncodeErrorEnvelopeMessageAndDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
g_autofree gchar* hex_string =
encode_error_envelope("error", "message", details);
EXPECT_STREQ(
hex_string,
"0107056572726f7207076d6573736167650c020705636f756e74032a000000");
}
TEST(FlStandardMethodCodecTest, DecodeResponseSuccessNull) {
g_autoptr(FlValue) result = fl_value_new_null();
decode_response_with_success("0000", result);
}
TEST(FlStandardMethodCodecTest, DecodeResponseSuccessString) {
g_autoptr(FlValue) result = fl_value_new_string("hello");
decode_response_with_success("00070568656c6c6f", result);
}
TEST(FlStandardMethodCodecTest, DecodeResponseSuccessList) {
g_autoptr(FlValue) result = fl_value_new_list();
fl_value_append_take(result, fl_value_new_string("count"));
fl_value_append_take(result, fl_value_new_int(42));
decode_response_with_success("000c020705636f756e74032a000000", result);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorEmptyCode) {
decode_response_with_error("0107000000", "", nullptr, nullptr);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorNoMessageOrDetails) {
decode_response_with_error("0107056572726f720000", "error", nullptr, nullptr);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorMessage) {
decode_response_with_error("0107056572726f7207076d65737361676500", "error",
"message", nullptr);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
decode_response_with_error("0107056572726f72000c020705636f756e74032a000000",
"error", nullptr, details);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorMessageAndDetails) {
g_autoptr(FlValue) details = fl_value_new_list();
fl_value_append_take(details, fl_value_new_string("count"));
fl_value_append_take(details, fl_value_new_int(42));
decode_response_with_error(
"0107056572726f7207076d6573736167650c020705636f756e74032a000000", "error",
"message", details);
}
TEST(FlStandardMethodCodecTest, DecodeResponseSuccessNoData) {
decode_error_response("00", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMethodCodecTest, DecodeResponseSuccessExtraData) {
decode_error_response("000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorNoData) {
decode_error_response("01", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorMissingMessageAndDetails) {
decode_error_response("0107056572726f72", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorMissingDetails) {
decode_error_response("0107056572726f7200", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_OUT_OF_DATA);
}
TEST(FlStandardMethodCodecTest, DecodeResponseErrorExtraData) {
decode_error_response("0107056572726f72000000", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
TEST(FlStandardMethodCodecTest, DecodeResponseNotImplemented) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) message = g_bytes_new(nullptr, 0);
g_autoptr(GError) error = nullptr;
g_autoptr(FlMethodResponse) response =
fl_method_codec_decode_response(FL_METHOD_CODEC(codec), message, &error);
ASSERT_NE(response, nullptr);
EXPECT_EQ(error, nullptr);
EXPECT_TRUE(FL_IS_METHOD_NOT_IMPLEMENTED_RESPONSE(response));
}
TEST(FlStandardMethodCodecTest, DecodeResponseUnknownEnvelope) {
decode_error_response("02", FL_MESSAGE_CODEC_ERROR,
FL_MESSAGE_CODEC_ERROR_FAILED);
}
| engine/shell/platform/linux/fl_standard_method_codec_test.cc/0 | {
"file_path": "engine/shell/platform/linux/fl_standard_method_codec_test.cc",
"repo_id": "engine",
"token_count": 6570
} | 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_LINUX_FL_TEXTURE_REGISTRAR_PRIVATE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_REGISTRAR_PRIVATE_H_
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_engine.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_texture_registrar.h"
G_BEGIN_DECLS
/**
* fl_texture_registrar_new:
* @engine: an #FlEngine.
*
* Creates a new #FlTextureRegistrar.
*
* Returns: a new #FlTextureRegistrar.
*/
FlTextureRegistrar* fl_texture_registrar_new(FlEngine* engine);
/**
* fl_texture_registrar_lookup_texture:
* @registrar: an #FlTextureRegistrar.
* @texture_id: ID of texture.
*
* Looks for the texture with the given ID.
*
* Returns: an #FlTexture or %NULL if no texture with this ID.
*/
FlTexture* fl_texture_registrar_lookup_texture(FlTextureRegistrar* registrar,
int64_t texture_id);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_FL_TEXTURE_REGISTRAR_PRIVATE_H_
| engine/shell/platform/linux/fl_texture_registrar_private.h/0 | {
"file_path": "engine/shell/platform/linux/fl_texture_registrar_private.h",
"repo_id": "engine",
"token_count": 475
} | 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_LINUX_PUBLIC_FLUTTER_LINUX_FL_DART_PROJECT_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_DART_PROJECT_H_
#include <glib-object.h>
#include <gmodule.h>
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_FINAL_TYPE(FlDartProject, fl_dart_project, FL, DART_PROJECT, GObject)
/**
* FlDartProject:
*
* #FlDartProject represents a Dart project. It is used to provide information
* about the application when creating an #FlView.
*/
/**
* fl_dart_project_new:
*
* Creates a Flutter project for the currently running executable. The following
* data files are required relative to the location of the executable:
* - data/flutter_assets/ (as built by the Flutter tool).
* - data/icudtl.dat (provided as a resource by the Flutter tool).
* - lib/libapp.so (as built by the Flutter tool when in AOT mode).
*
* Returns: a new #FlDartProject.
*/
FlDartProject* fl_dart_project_new();
/**
* fl_dart_project_set_aot_library_path:
* @project: an #FlDartProject.
* @path: the absolute path to the AOT library in the Flutter application.
*
* Sets the path to the AOT library in the Flutter application, which is
* the path to libapp.so. By default this is lib/libapp.so relative to the
* executable directory.
*/
void fl_dart_project_set_aot_library_path(FlDartProject* project,
const gchar* path);
/**
* fl_dart_project_get_aot_library_path:
* @project: an #FlDartProject.
*
* Gets the path to the AOT library in the Flutter application.
*
* Returns: (type filename): an absolute file path, e.g.
* "/projects/my_dart_project/lib/libapp.so".
*/
const gchar* fl_dart_project_get_aot_library_path(FlDartProject* project);
/**
* fl_dart_project_set_assets_path:
* @project: an #FlDartProject.
* @path: the absolute path to the assets directory.
*
* Sets the path to the directory containing the assets used in the Flutter
* application. By default, this is the data/flutter_assets subdirectory
* relative to the executable directory.
*/
void fl_dart_project_set_assets_path(FlDartProject* project, gchar* path);
/**
* fl_dart_project_get_assets_path:
* @project: an #FlDartProject.
*
* Gets the path to the directory containing the assets used in the Flutter
* application.
*
* Returns: (type filename): an absolute directory path, e.g.
* "/projects/my_dart_project/data/flutter_assets".
*/
const gchar* fl_dart_project_get_assets_path(FlDartProject* project);
/**
* fl_dart_project_set_icu_data_path:
* @project: an #FlDartProject.
* @path: the absolute path to the ICU data file.
*
* Sets the path to the ICU data file used in the Flutter application. By
* default, this is data/icudtl.dat relative to the executable directory.
*/
void fl_dart_project_set_icu_data_path(FlDartProject* project, gchar* path);
/**
* fl_dart_project_get_icu_data_path:
* @project: an #FlDartProject.
*
* Gets the path to the ICU data file in the Flutter application.
*
* Returns: (type filename): an absolute file path, e.g.
* "/projects/my_dart_project/data/icudtl.dat".
*/
const gchar* fl_dart_project_get_icu_data_path(FlDartProject* project);
/**
* fl_dart_project_set_dart_entrypoint_arguments:
* @project: an #FlDartProject.
* @argv: a pointer to a NULL-terminated array of C strings containing the
* command line arguments.
*
* Sets the command line arguments to be passed through to the Dart
* entrypoint function.
*/
void fl_dart_project_set_dart_entrypoint_arguments(FlDartProject* project,
char** argv);
/**
* fl_dart_project_get_dart_entrypoint_arguments:
* @project: an #FlDartProject.
*
* Gets the command line arguments to be passed through to the Dart entrypoint
* function.
*
* Returns: a NULL-terminated array of strings containing the command line
* arguments to be passed to the Dart entrypoint.
*/
gchar** fl_dart_project_get_dart_entrypoint_arguments(FlDartProject* project);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_DART_PROJECT_H_
| engine/shell/platform/linux/public/flutter_linux/fl_dart_project.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_dart_project.h",
"repo_id": "engine",
"token_count": 1539
} | 385 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_H_
#define FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_H_
#if !defined(__FLUTTER_LINUX_INSIDE__) && !defined(FLUTTER_LINUX_COMPILATION)
#error "Only <flutter_linux/flutter_linux.h> can be included directly."
#endif
#include <glib-object.h>
#include <gmodule.h>
#include <stdint.h>
G_BEGIN_DECLS
G_MODULE_EXPORT
G_DECLARE_INTERFACE(FlTexture, fl_texture, FL, TEXTURE, GObject)
/**
* FlTexture:
*
* #FlTexture represents a texture.
*
* You can derive #FlTextureGL for populating hardware-accelerated textures or
* instantiate #FlPixelBufferTexture for populating pixel buffers. Do NOT
* directly implement this interface.
*/
struct _FlTextureInterface {
GTypeInterface g_iface;
void (*set_id)(FlTexture* texture, int64_t id);
int64_t (*get_id)(FlTexture* texture);
};
/**
* fl_texture_get_id:
* @texture: a #FlTexture.
*
* Get the ID for this texture, which can be passed to Flutter code to refer to
* this texture.
*
* Returns: a texture ID.
*/
int64_t fl_texture_get_id(FlTexture* texture);
G_END_DECLS
#endif // FLUTTER_SHELL_PLATFORM_LINUX_PUBLIC_FLUTTER_LINUX_FL_TEXTURE_H_
| engine/shell/platform/linux/public/flutter_linux/fl_texture.h/0 | {
"file_path": "engine/shell/platform/linux/public/flutter_linux/fl_texture.h",
"repo_id": "engine",
"token_count": 489
} | 386 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is a historical legacy, predating the proc table API. It has been
// updated to continue to work with the proc table, but new tests should not
// rely on replacements set up here, but instead use test-local replacements
// for any functions relevant to that test.
//
// Over time existing tests should be migrated and this file should be removed.
#include <cstring>
#include <unordered_map>
#include <utility>
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/linux/fl_method_codec_private.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_json_message_codec.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_method_response.h"
#include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h"
#include "gtest/gtest.h"
const int32_t kFlutterSemanticsNodeIdBatchEnd = -1;
const int32_t kFlutterSemanticsCustomActionIdBatchEnd = -1;
struct _FlutterEngineTexture {
bool has_new_frame;
};
struct _FlutterEngine {
bool running = false;
FlutterPlatformMessageCallback platform_message_callback;
FlutterTaskRunnerPostTaskCallback platform_post_task_callback;
void* user_data;
std::unordered_map<int64_t, _FlutterEngineTexture> textures;
_FlutterEngine(FlutterPlatformMessageCallback platform_message_callback,
FlutterTaskRunnerPostTaskCallback platform_post_task_callback,
void* user_data)
: platform_message_callback(platform_message_callback),
platform_post_task_callback(platform_post_task_callback),
user_data(user_data) {}
};
struct _FlutterPlatformMessageResponseHandle {
FlutterDataCallback data_callback;
void* user_data;
std::string channel;
bool released;
// Constructor for a response handle generated by the engine.
explicit _FlutterPlatformMessageResponseHandle(std::string channel)
: data_callback(nullptr),
user_data(nullptr),
channel(std::move(channel)),
released(false) {}
// Constructor for a response handle generated by the shell.
_FlutterPlatformMessageResponseHandle(FlutterDataCallback data_callback,
void* user_data)
: data_callback(data_callback), user_data(user_data), released(false) {}
};
struct _FlutterTaskRunner {
uint64_t task;
std::string channel;
const FlutterPlatformMessageResponseHandle* response_handle;
uint8_t* message;
size_t message_size;
_FlutterTaskRunner(
uint64_t task,
const std::string& channel,
const FlutterPlatformMessageResponseHandle* response_handle,
const uint8_t* message,
size_t message_size)
: task(task),
channel(channel),
response_handle(response_handle),
message_size(message_size) {
if (message_size > 0) {
this->message = static_cast<uint8_t*>(malloc(message_size));
memcpy(this->message, message, message_size);
} else {
this->message = nullptr;
}
}
~_FlutterTaskRunner() {
if (response_handle != nullptr) {
EXPECT_TRUE(response_handle->released);
delete response_handle;
}
free(message);
}
};
namespace {
// Send a response from the engine.
static void send_response(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const std::string& channel,
const FlutterPlatformMessageResponseHandle* response_handle,
const uint8_t* message,
size_t message_size) {
if (response_handle == nullptr) {
return;
}
FlutterTask task;
task.runner = new _FlutterTaskRunner(1234, channel, response_handle, message,
message_size);
task.task = task.runner->task;
engine->platform_post_task_callback(task, 0, engine->user_data);
}
// Send a message from the engine.
static void send_message(FLUTTER_API_SYMBOL(FlutterEngine) engine,
const std::string& channel,
const uint8_t* message,
size_t message_size) {
FlutterTask task;
task.runner =
new _FlutterTaskRunner(1234, channel, nullptr, message, message_size);
task.task = task.runner->task;
engine->platform_post_task_callback(task, 0, engine->user_data);
}
static void invoke_method(FLUTTER_API_SYMBOL(FlutterEngine) engine,
const std::string& channel,
const gchar* name,
FlValue* args) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GError) error = nullptr;
g_autoptr(GBytes) message = fl_method_codec_encode_method_call(
FL_METHOD_CODEC(codec), name, args, &error);
EXPECT_NE(message, nullptr);
EXPECT_EQ(error, nullptr);
FlutterTask task;
task.runner = new _FlutterTaskRunner(
1234, channel, nullptr,
static_cast<const uint8_t*>(g_bytes_get_data(message, nullptr)),
g_bytes_get_size(message));
task.task = task.runner->task;
engine->platform_post_task_callback(task, 0, engine->user_data);
}
FlutterEngineResult FlutterEngineCreateAOTData(
const FlutterEngineAOTDataSource* source,
FlutterEngineAOTData* data_out) {
*data_out = nullptr;
return kSuccess;
}
FlutterEngineResult FlutterEngineCollectAOTData(FlutterEngineAOTData data) {
return kSuccess;
}
FlutterEngineResult FlutterEngineInitialize(size_t version,
const FlutterRendererConfig* config,
const FlutterProjectArgs* args,
void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) *
engine_out) {
EXPECT_NE(config, nullptr);
EXPECT_NE(args, nullptr);
EXPECT_NE(args->platform_message_callback, nullptr);
EXPECT_NE(args->custom_task_runners, nullptr);
EXPECT_NE(args->custom_task_runners->platform_task_runner, nullptr);
EXPECT_NE(args->custom_task_runners->platform_task_runner->post_task_callback,
nullptr);
EXPECT_NE(user_data, nullptr);
EXPECT_EQ(config->type, kOpenGL);
*engine_out = new _FlutterEngine(
args->platform_message_callback,
args->custom_task_runners->platform_task_runner->post_task_callback,
user_data);
return kSuccess;
}
FlutterEngineResult FlutterEngineRunInitialized(
FLUTTER_API_SYMBOL(FlutterEngine) engine) {
engine->running = true;
return kSuccess;
}
FlutterEngineResult FlutterEngineRun(size_t version,
const FlutterRendererConfig* config,
const FlutterProjectArgs* args,
void* user_data,
FLUTTER_API_SYMBOL(FlutterEngine) *
engine_out) {
EXPECT_NE(config, nullptr);
EXPECT_NE(args, nullptr);
EXPECT_NE(user_data, nullptr);
EXPECT_NE(engine_out, nullptr);
FlutterEngineResult result =
FlutterEngineInitialize(version, config, args, user_data, engine_out);
if (result != kSuccess) {
return result;
}
return FlutterEngineRunInitialized(*engine_out);
}
FlutterEngineResult FlutterEngineShutdown(FLUTTER_API_SYMBOL(FlutterEngine)
engine) {
delete engine;
return kSuccess;
}
FlutterEngineResult FlutterEngineDeinitialize(FLUTTER_API_SYMBOL(FlutterEngine)
engine) {
return kSuccess;
}
FlutterEngineResult FlutterEngineSendWindowMetricsEvent(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterWindowMetricsEvent* event) {
EXPECT_TRUE(engine->running);
return kSuccess;
}
FlutterEngineResult FlutterEngineSendPointerEvent(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPointerEvent* events,
size_t events_count) {
return kSuccess;
}
FlutterEngineResult FlutterEngineSendKeyEvent(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterKeyEvent* event,
FlutterKeyEventCallback callback,
void* user_data) {
return kSuccess;
}
FLUTTER_EXPORT
FlutterEngineResult FlutterEngineSendPlatformMessage(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessage* message) {
EXPECT_TRUE(engine->running);
if (strcmp(message->channel, "test/echo") == 0) {
// Responds with the same message received.
send_response(engine, message->channel, message->response_handle,
message->message, message->message_size);
} else if (strcmp(message->channel, "test/send-message") == 0) {
// Triggers the engine to send a message.
send_response(engine, message->channel, message->response_handle, nullptr,
0);
send_message(engine, "test/messages", message->message,
message->message_size);
} else if (strcmp(message->channel, "test/standard-method") == 0) {
g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();
g_autoptr(GBytes) m = g_bytes_new(message->message, message->message_size);
g_autofree gchar* name = nullptr;
g_autoptr(FlValue) args = nullptr;
g_autoptr(GError) error = nullptr;
EXPECT_TRUE(fl_method_codec_decode_method_call(FL_METHOD_CODEC(codec), m,
&name, &args, &error));
EXPECT_EQ(error, nullptr);
g_autoptr(GBytes) response = nullptr;
if (strcmp(name, "Echo") == 0) {
// Returns args as a success result.
response = fl_method_codec_encode_success_envelope(FL_METHOD_CODEC(codec),
args, &error);
EXPECT_EQ(error, nullptr);
} else if (strcmp(name, "Error") == 0) {
// Returns an error result.
const gchar* code = nullptr;
const gchar* message = nullptr;
FlValue* details = nullptr;
if (fl_value_get_length(args) >= 2) {
FlValue* code_value = fl_value_get_list_value(args, 0);
EXPECT_EQ(fl_value_get_type(code_value), FL_VALUE_TYPE_STRING);
code = fl_value_get_string(code_value);
FlValue* message_value = fl_value_get_list_value(args, 1);
message = fl_value_get_type(message_value) == FL_VALUE_TYPE_STRING
? fl_value_get_string(message_value)
: nullptr;
}
if (fl_value_get_length(args) >= 3) {
details = fl_value_get_list_value(args, 2);
}
response = fl_method_codec_encode_error_envelope(
FL_METHOD_CODEC(codec), code, message, details, &error);
EXPECT_EQ(error, nullptr);
} else if (strcmp(name, "InvokeMethod") == 0) {
// Gets the engine to call the shell.
if (fl_value_get_length(args) == 3) {
FlValue* channel_value = fl_value_get_list_value(args, 0);
EXPECT_EQ(fl_value_get_type(channel_value), FL_VALUE_TYPE_STRING);
const gchar* channel = fl_value_get_string(channel_value);
FlValue* name_value = fl_value_get_list_value(args, 1);
EXPECT_EQ(fl_value_get_type(name_value), FL_VALUE_TYPE_STRING);
const gchar* name = fl_value_get_string(name_value);
FlValue* method_args = fl_value_get_list_value(args, 2);
invoke_method(engine, channel, name, method_args);
}
response = fl_method_codec_encode_success_envelope(FL_METHOD_CODEC(codec),
nullptr, &error);
EXPECT_EQ(error, nullptr);
} else {
// Returns "not implemented".
response = g_bytes_new(nullptr, 0);
}
send_response(
engine, message->channel, message->response_handle,
static_cast<const uint8_t*>(g_bytes_get_data(response, nullptr)),
g_bytes_get_size(response));
} else if (strcmp(message->channel, "test/nullptr-response") == 0) {
// Sends a null response.
send_response(engine, message->channel, message->response_handle, nullptr,
0);
} else if (strcmp(message->channel, "test/standard-event") == 0) {
// Send a message so the shell can check the events sent.
send_message(engine, "test/events", message->message,
message->message_size);
} else if (strcmp(message->channel, "test/failure") == 0) {
// Generates an internal error.
return kInternalInconsistency;
} else if (strcmp(message->channel, "test/key-event-handled") == 0 ||
strcmp(message->channel, "test/key-event-not-handled") == 0) {
bool value = strcmp(message->channel, "test/key-event-handled") == 0;
g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new();
g_autoptr(FlValue) handledValue = fl_value_new_map();
fl_value_set_string_take(handledValue, "handled", fl_value_new_bool(value));
g_autoptr(GBytes) response = fl_message_codec_encode_message(
FL_MESSAGE_CODEC(codec), handledValue, nullptr);
send_response(
engine, message->channel, message->response_handle,
static_cast<const uint8_t*>(g_bytes_get_data(response, nullptr)),
g_bytes_get_size(response));
} else if (strcmp(message->channel, "test/key-event-delayed") == 0) {
static std::unique_ptr<const FlutterPlatformMessageResponseHandle>
delayed_response_handle = nullptr;
g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new();
g_autoptr(FlValue) handledValue = fl_value_new_map();
fl_value_set_string_take(handledValue, "handled", fl_value_new_bool(true));
g_autoptr(GBytes) response = fl_message_codec_encode_message(
FL_MESSAGE_CODEC(codec), handledValue, nullptr);
if (delayed_response_handle == nullptr) {
delayed_response_handle.reset(message->response_handle);
} else {
send_response(
engine, message->channel, message->response_handle,
static_cast<const uint8_t*>(g_bytes_get_data(response, nullptr)),
g_bytes_get_size(response));
send_response(
engine, message->channel, delayed_response_handle.release(),
static_cast<const uint8_t*>(g_bytes_get_data(response, nullptr)),
g_bytes_get_size(response));
}
}
return kSuccess;
}
FlutterEngineResult FlutterPlatformMessageCreateResponseHandle(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterDataCallback data_callback,
void* user_data,
FlutterPlatformMessageResponseHandle** response_out) {
EXPECT_TRUE(engine->running);
EXPECT_NE(data_callback, nullptr);
EXPECT_NE(user_data, nullptr);
_FlutterPlatformMessageResponseHandle* handle =
new _FlutterPlatformMessageResponseHandle(data_callback, user_data);
*response_out = handle;
return kSuccess;
}
FlutterEngineResult FlutterPlatformMessageReleaseResponseHandle(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterPlatformMessageResponseHandle* response) {
EXPECT_NE(engine, nullptr);
EXPECT_NE(response, nullptr);
EXPECT_TRUE(engine->running);
EXPECT_FALSE(response->released);
response->released = true;
return kSuccess;
}
FlutterEngineResult FlutterEngineSendPlatformMessageResponse(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
const FlutterPlatformMessageResponseHandle* handle,
const uint8_t* data,
size_t data_length) {
EXPECT_NE(engine, nullptr);
EXPECT_NE(handle, nullptr);
EXPECT_TRUE(engine->running);
// Send a message so the shell can check the responses received.
if (handle->channel != "test/responses") {
send_message(engine, "test/responses", data, data_length);
}
EXPECT_FALSE(handle->released);
delete handle;
return kSuccess;
}
FlutterEngineResult FlutterEngineRunTask(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterTask* task) {
EXPECT_NE(engine, nullptr);
EXPECT_NE(task, nullptr);
EXPECT_NE(task->runner, nullptr);
FlutterTaskRunner runner = task->runner;
EXPECT_NE(runner, nullptr);
const FlutterPlatformMessageResponseHandle* response_handle =
runner->response_handle;
if (response_handle != nullptr) {
EXPECT_NE(response_handle->data_callback, nullptr);
response_handle->data_callback(runner->message, runner->message_size,
response_handle->user_data);
} else {
_FlutterPlatformMessageResponseHandle* handle =
new _FlutterPlatformMessageResponseHandle(runner->channel);
FlutterPlatformMessage message;
message.struct_size = sizeof(FlutterPlatformMessage);
message.channel = runner->channel.c_str();
message.message = runner->message;
message.message_size = runner->message_size;
message.response_handle = handle;
engine->platform_message_callback(&message, engine->user_data);
}
delete runner;
return kSuccess;
}
bool FlutterEngineRunsAOTCompiledDartCode() {
return false;
}
FlutterEngineResult FlutterEngineUpdateLocales(FLUTTER_API_SYMBOL(FlutterEngine)
engine,
const FlutterLocale** locales,
size_t locales_count) {
return kSuccess;
}
FlutterEngineResult FlutterEngineUpdateSemanticsEnabled(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
bool enabled) {
return kSuccess;
}
FlutterEngineResult FlutterEngineUpdateAccessibilityFeatures(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
FlutterAccessibilityFeature features) {
return kSuccess;
}
FlutterEngineResult FlutterEngineDispatchSemanticsAction(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
uint64_t id,
FlutterSemanticsAction action,
const uint8_t* data,
size_t data_length) {
return kSuccess;
}
FlutterEngineResult FlutterEngineRegisterExternalTexture(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier) {
_FlutterEngineTexture texture;
texture.has_new_frame = false;
engine->textures[texture_identifier] = texture;
return kSuccess;
}
FlutterEngineResult FlutterEngineMarkExternalTextureFrameAvailable(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier) {
auto val = engine->textures.find(texture_identifier);
if (val == std::end(engine->textures)) {
return kInvalidArguments;
}
val->second.has_new_frame = true;
return kSuccess;
}
FlutterEngineResult FlutterEngineUnregisterExternalTexture(
FLUTTER_API_SYMBOL(FlutterEngine) engine,
int64_t texture_identifier) {
auto val = engine->textures.find(texture_identifier);
if (val == std::end(engine->textures)) {
return kInvalidArguments;
}
engine->textures.erase(texture_identifier);
return kSuccess;
}
} // namespace
FlutterEngineResult FlutterEngineGetProcAddresses(
FlutterEngineProcTable* table) {
if (!table) {
return kInvalidArguments;
}
FlutterEngineProcTable empty_table = {};
*table = empty_table;
table->CreateAOTData = &FlutterEngineCreateAOTData;
table->CollectAOTData = &FlutterEngineCollectAOTData;
table->Run = &FlutterEngineRun;
table->Shutdown = &FlutterEngineShutdown;
table->Initialize = &FlutterEngineInitialize;
table->Deinitialize = &FlutterEngineDeinitialize;
table->RunInitialized = &FlutterEngineRunInitialized;
table->SendWindowMetricsEvent = &FlutterEngineSendWindowMetricsEvent;
table->SendPointerEvent = &FlutterEngineSendPointerEvent;
table->SendKeyEvent = &FlutterEngineSendKeyEvent;
table->SendPlatformMessage = &FlutterEngineSendPlatformMessage;
table->PlatformMessageCreateResponseHandle =
&FlutterPlatformMessageCreateResponseHandle;
table->PlatformMessageReleaseResponseHandle =
&FlutterPlatformMessageReleaseResponseHandle;
table->SendPlatformMessageResponse =
&FlutterEngineSendPlatformMessageResponse;
table->RunTask = &FlutterEngineRunTask;
table->UpdateLocales = &FlutterEngineUpdateLocales;
table->UpdateSemanticsEnabled = &FlutterEngineUpdateSemanticsEnabled;
table->DispatchSemanticsAction = &FlutterEngineDispatchSemanticsAction;
table->RunsAOTCompiledDartCode = &FlutterEngineRunsAOTCompiledDartCode;
table->RegisterExternalTexture = &FlutterEngineRegisterExternalTexture;
table->MarkExternalTextureFrameAvailable =
&FlutterEngineMarkExternalTextureFrameAvailable;
table->UnregisterExternalTexture = &FlutterEngineUnregisterExternalTexture;
table->UpdateAccessibilityFeatures =
&FlutterEngineUpdateAccessibilityFeatures;
return kSuccess;
}
| engine/shell/platform/linux/testing/mock_engine.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_engine.cc",
"repo_id": "engine",
"token_count": 8309
} | 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/shell/platform/linux/testing/mock_texture_registrar.h"
struct _FlMockTextureRegistrar {
GObject parent_instance;
FlTexture* texture;
gboolean frame_available;
};
static void fl_mock_texture_registrar_iface_init(
FlTextureRegistrarInterface* iface);
G_DEFINE_TYPE_WITH_CODE(
FlMockTextureRegistrar,
fl_mock_texture_registrar,
G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE(fl_texture_registrar_get_type(),
fl_mock_texture_registrar_iface_init))
static gboolean register_texture(FlTextureRegistrar* registrar,
FlTexture* texture) {
FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar);
if (self->texture != nullptr) {
return FALSE;
}
self->texture = FL_TEXTURE(g_object_ref(texture));
return TRUE;
}
static FlTexture* lookup_texture(FlTextureRegistrar* registrar,
int64_t texture_id) {
FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar);
if (self->texture != nullptr &&
fl_texture_get_id(self->texture) == texture_id) {
return self->texture;
}
return nullptr;
}
static gboolean mark_texture_frame_available(FlTextureRegistrar* registrar,
FlTexture* texture) {
FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar);
if (lookup_texture(registrar, fl_texture_get_id(texture)) == nullptr) {
return FALSE;
}
self->frame_available = TRUE;
return TRUE;
}
static gboolean unregister_texture(FlTextureRegistrar* registrar,
FlTexture* texture) {
FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(registrar);
if (self->texture != texture) {
return FALSE;
}
g_clear_object(&self->texture);
return TRUE;
}
static void fl_mock_texture_registrar_iface_init(
FlTextureRegistrarInterface* iface) {
iface->register_texture = register_texture;
iface->lookup_texture = lookup_texture;
iface->mark_texture_frame_available = mark_texture_frame_available;
iface->unregister_texture = unregister_texture;
}
static void fl_mock_texture_registrar_dispose(GObject* object) {
FlMockTextureRegistrar* self = FL_MOCK_TEXTURE_REGISTRAR(object);
g_clear_object(&self->texture);
G_OBJECT_CLASS(fl_mock_texture_registrar_parent_class)->dispose(object);
}
static void fl_mock_texture_registrar_class_init(
FlMockTextureRegistrarClass* klass) {
G_OBJECT_CLASS(klass)->dispose = fl_mock_texture_registrar_dispose;
}
static void fl_mock_texture_registrar_init(FlMockTextureRegistrar* self) {}
FlMockTextureRegistrar* fl_mock_texture_registrar_new() {
return FL_MOCK_TEXTURE_REGISTRAR(
g_object_new(fl_mock_texture_registrar_get_type(), nullptr));
}
FlTexture* fl_mock_texture_registrar_get_texture(FlMockTextureRegistrar* self) {
return self->texture;
}
gboolean fl_mock_texture_registrar_get_frame_available(
FlMockTextureRegistrar* self) {
return self->frame_available;
}
| engine/shell/platform/linux/testing/mock_texture_registrar.cc/0 | {
"file_path": "engine/shell/platform/linux/testing/mock_texture_registrar.cc",
"repo_id": "engine",
"token_count": 1272
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_DART_PROJECT_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_DART_PROJECT_H_
#include <string>
#include <vector>
namespace flutter {
// A set of Flutter and Dart assets used to initialize a Flutter engine.
class DartProject {
public:
// Creates a DartProject from a series of absolute paths.
// The three paths are:
// - assets_path: Path to the assets directory as built by the Flutter tool.
// - icu_data_path: Path to the icudtl.dat file.
// - aot_library_path: Path to the AOT snapshot file.
//
// The paths may either be absolute or relative to the directory containing
// the running executable.
explicit DartProject(const std::wstring& assets_path,
const std::wstring& icu_data_path,
const std::wstring& aot_library_path) {
assets_path_ = assets_path;
icu_data_path_ = icu_data_path;
aot_library_path_ = aot_library_path;
}
// Creates a DartProject from a directory path. The directory should contain
// the following top-level items:
// - icudtl.dat (provided as a resource by the Flutter tool)
// - flutter_assets (as built by the Flutter tool)
// - app.so, for an AOT build (as built by the Flutter tool)
//
// The path can either be absolute, or relative to the directory containing
// the running executable.
explicit DartProject(const std::wstring& path) {
assets_path_ = path + L"\\flutter_assets";
icu_data_path_ = path + L"\\icudtl.dat";
aot_library_path_ = path + L"\\app.so";
}
~DartProject() = default;
// Sets the Dart entrypoint to the specified value.
//
// If not set, the default entrypoint (main) is used. Custom Dart entrypoints
// must be decorated with `@pragma('vm:entry-point')`.
void set_dart_entrypoint(const std::string& entrypoint) {
if (entrypoint.empty()) {
return;
}
dart_entrypoint_ = entrypoint;
}
// Returns the Dart entrypoint.
const std::string& dart_entrypoint() const { return dart_entrypoint_; }
// Sets the command line arguments that should be passed to the Dart
// entrypoint.
void set_dart_entrypoint_arguments(std::vector<std::string> arguments) {
dart_entrypoint_arguments_ = std::move(arguments);
}
// Returns any command line arguments that should be passed to the Dart
// entrypoint.
const std::vector<std::string>& dart_entrypoint_arguments() const {
return dart_entrypoint_arguments_;
}
private:
// Accessors for internals are private, so that they can be changed if more
// flexible options for project structures are needed later without it
// being a breaking change. Provide access to internal classes that need
// them.
friend class FlutterEngine;
friend class FlutterViewController;
friend class DartProjectTest;
const std::wstring& assets_path() const { return assets_path_; }
const std::wstring& icu_data_path() const { return icu_data_path_; }
const std::wstring& aot_library_path() const { return aot_library_path_; }
// The path to the assets directory.
std::wstring assets_path_;
// The path to the ICU data.
std::wstring icu_data_path_;
// The path to the AOT library. This will always return a path, but non-AOT
// builds will not be expected to actually have a library at that path.
std::wstring aot_library_path_;
// The Dart entrypoint to launch.
std::string dart_entrypoint_;
// The list of arguments to pass through to the Dart entrypoint.
std::vector<std::string> dart_entrypoint_arguments_;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_DART_PROJECT_H_
| engine/shell/platform/windows/client_wrapper/include/flutter/dart_project.h/0 | {
"file_path": "engine/shell/platform/windows/client_wrapper/include/flutter/dart_project.h",
"repo_id": "engine",
"token_count": 1268
} | 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_WINDOWS_CURSOR_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_CURSOR_HANDLER_H_
#include <unordered_map>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/binary_messenger.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/encodable_value.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_channel.h"
#include "flutter/shell/platform/windows/public/flutter_windows.h"
#include "flutter/shell/platform/windows/window_binding_handler.h"
namespace flutter {
class FlutterWindowsEngine;
// Handler for the cursor system channel.
class CursorHandler {
public:
explicit CursorHandler(flutter::BinaryMessenger* messenger,
flutter::FlutterWindowsEngine* engine);
private:
// Called when a method is called on |channel_|;
void HandleMethodCall(
const flutter::MethodCall<EncodableValue>& method_call,
std::unique_ptr<flutter::MethodResult<EncodableValue>> result);
// The MethodChannel used for communication with the Flutter engine.
std::unique_ptr<flutter::MethodChannel<EncodableValue>> channel_;
// The Flutter engine that will be notified for cursor updates.
FlutterWindowsEngine* engine_;
// The cache map for custom cursors.
std::unordered_map<std::string, HCURSOR> custom_cursors_;
FML_DISALLOW_COPY_AND_ASSIGN(CursorHandler);
};
// Create a cursor from a rawBGRA buffer and the cursor info.
HCURSOR GetCursorFromBuffer(const std::vector<uint8_t>& buffer,
double hot_x,
double hot_y,
int width,
int height);
// Get the corresponding mask bitmap from the source bitmap.
void GetMaskBitmaps(HBITMAP bitmap, HBITMAP& mask_bitmap);
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_CURSOR_HANDLER_H_
| engine/shell/platform/windows/cursor_handler.h/0 | {
"file_path": "engine/shell/platform/windows/cursor_handler.h",
"repo_id": "engine",
"token_count": 777
} | 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.
#include "flutter/shell/platform/windows/egl/surface.h"
#include "flutter/shell/platform/windows/egl/egl.h"
namespace flutter {
namespace egl {
Surface::Surface(EGLDisplay display, EGLContext context, EGLSurface surface)
: display_(display), context_(context), surface_(surface) {}
Surface::~Surface() {
Destroy();
}
bool Surface::IsValid() const {
return is_valid_;
}
bool Surface::Destroy() {
if (surface_ != EGL_NO_SURFACE) {
// Ensure the surface is not current before destroying it.
if (::eglMakeCurrent(display_, EGL_NO_SURFACE, EGL_NO_SURFACE,
EGL_NO_CONTEXT) != EGL_TRUE) {
WINDOWS_LOG_EGL_ERROR;
return false;
}
if (::eglDestroySurface(display_, surface_) != EGL_TRUE) {
WINDOWS_LOG_EGL_ERROR;
return false;
}
}
is_valid_ = false;
surface_ = EGL_NO_SURFACE;
return true;
}
bool Surface::IsCurrent() const {
return display_ == ::eglGetCurrentDisplay() &&
surface_ == ::eglGetCurrentSurface(EGL_DRAW) &&
surface_ == ::eglGetCurrentSurface(EGL_READ) &&
context_ == ::eglGetCurrentContext();
}
bool Surface::MakeCurrent() const {
if (::eglMakeCurrent(display_, surface_, surface_, context_) != EGL_TRUE) {
WINDOWS_LOG_EGL_ERROR;
return false;
}
return true;
}
bool Surface::SwapBuffers() const {
if (::eglSwapBuffers(display_, surface_) != EGL_TRUE) {
WINDOWS_LOG_EGL_ERROR;
return false;
}
return true;
}
const EGLSurface& Surface::GetHandle() const {
return surface_;
}
} // namespace egl
} // namespace flutter
| engine/shell/platform/windows/egl/surface.cc/0 | {
"file_path": "engine/shell/platform/windows/egl/surface.cc",
"repo_id": "engine",
"token_count": 689
} | 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.
#include "flutter/shell/platform/windows/flutter_project_bundle.h"
#include <filesystem>
#include "flutter/fml/logging.h"
#include "flutter/shell/platform/common/engine_switches.h" // nogncheck
#include "flutter/shell/platform/common/path_utils.h"
namespace flutter {
FlutterProjectBundle::FlutterProjectBundle(
const FlutterDesktopEngineProperties& properties)
: assets_path_(properties.assets_path),
icu_path_(properties.icu_data_path) {
if (properties.aot_library_path != nullptr) {
aot_library_path_ = std::filesystem::path(properties.aot_library_path);
}
if (properties.dart_entrypoint && properties.dart_entrypoint[0] != '\0') {
dart_entrypoint_ = properties.dart_entrypoint;
}
for (int i = 0; i < properties.dart_entrypoint_argc; i++) {
dart_entrypoint_arguments_.push_back(
std::string(properties.dart_entrypoint_argv[i]));
}
// Resolve any relative paths.
if (assets_path_.is_relative() || icu_path_.is_relative() ||
(!aot_library_path_.empty() && aot_library_path_.is_relative())) {
std::filesystem::path executable_location = GetExecutableDirectory();
if (executable_location.empty()) {
FML_LOG(ERROR)
<< "Unable to find executable location to resolve resource paths.";
assets_path_ = std::filesystem::path();
icu_path_ = std::filesystem::path();
} else {
assets_path_ = std::filesystem::path(executable_location) / assets_path_;
icu_path_ = std::filesystem::path(executable_location) / icu_path_;
if (!aot_library_path_.empty()) {
aot_library_path_ =
std::filesystem::path(executable_location) / aot_library_path_;
}
}
}
}
bool FlutterProjectBundle::HasValidPaths() {
return !assets_path_.empty() && !icu_path_.empty();
}
// Attempts to load AOT data from the given path, which must be absolute and
// non-empty. Logs and returns nullptr on failure.
UniqueAotDataPtr FlutterProjectBundle::LoadAotData(
const FlutterEngineProcTable& engine_procs) {
if (aot_library_path_.empty()) {
FML_LOG(ERROR)
<< "Attempted to load AOT data, but no aot_library_path was provided.";
return UniqueAotDataPtr(nullptr, nullptr);
}
if (!std::filesystem::exists(aot_library_path_)) {
FML_LOG(ERROR) << "Can't load AOT data from "
<< aot_library_path_.u8string() << "; no such file.";
return UniqueAotDataPtr(nullptr, nullptr);
}
std::string path_string = aot_library_path_.u8string();
FlutterEngineAOTDataSource source = {};
source.type = kFlutterEngineAOTDataSourceTypeElfPath;
source.elf_path = path_string.c_str();
FlutterEngineAOTData data = nullptr;
auto result = engine_procs.CreateAOTData(&source, &data);
if (result != kSuccess) {
FML_LOG(ERROR) << "Failed to load AOT data from: " << path_string;
return UniqueAotDataPtr(nullptr, nullptr);
}
return UniqueAotDataPtr(data, engine_procs.CollectAOTData);
}
FlutterProjectBundle::~FlutterProjectBundle() {}
void FlutterProjectBundle::SetSwitches(
const std::vector<std::string>& switches) {
engine_switches_ = switches;
}
const std::vector<std::string> FlutterProjectBundle::GetSwitches() {
if (engine_switches_.size() == 0) {
return GetSwitchesFromEnvironment();
}
std::vector<std::string> switches;
switches.insert(switches.end(), engine_switches_.begin(),
engine_switches_.end());
auto env_switches = GetSwitchesFromEnvironment();
switches.insert(switches.end(), env_switches.begin(), env_switches.end());
return switches;
}
} // namespace flutter
| engine/shell/platform/windows/flutter_project_bundle.cc/0 | {
"file_path": "engine/shell/platform/windows/flutter_project_bundle.cc",
"repo_id": "engine",
"token_count": 1367
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_VIEW_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_VIEW_H_
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/plugin_registrar.h"
#include "flutter/shell/platform/common/geometry.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/windows/accessibility_bridge_windows.h"
#include "flutter/shell/platform/windows/flutter_windows_engine.h"
#include "flutter/shell/platform/windows/public/flutter_windows.h"
#include "flutter/shell/platform/windows/window_binding_handler.h"
#include "flutter/shell/platform/windows/window_binding_handler_delegate.h"
#include "flutter/shell/platform/windows/window_state.h"
#include "flutter/shell/platform/windows/windows_proc_table.h"
namespace flutter {
// A unique identifier for a view.
using FlutterViewId = int64_t;
// An OS-windowing neutral abstration for a Flutter view that works
// with win32 HWNDs.
class FlutterWindowsView : public WindowBindingHandlerDelegate {
public:
// Creates a FlutterWindowsView with the given implementor of
// WindowBindingHandler.
FlutterWindowsView(
FlutterViewId view_id,
FlutterWindowsEngine* engine,
std::unique_ptr<WindowBindingHandler> window_binding,
std::shared_ptr<WindowsProcTable> windows_proc_table = nullptr);
virtual ~FlutterWindowsView();
// Get the view's unique identifier.
FlutterViewId view_id() const;
// Creates rendering surface for Flutter engine to draw into.
// Should be called before calling FlutterEngineRun using this view.
void CreateRenderSurface();
// Destroys current rendering surface if one has been allocated.
void DestroyRenderSurface();
// Get the EGL surface that backs the Flutter view.
//
// This might be nullptr or an invalid surface.
egl::WindowSurface* surface() const;
// Return the currently configured HWND.
virtual HWND GetWindowHandle() const;
// Returns the engine backing this view.
FlutterWindowsEngine* GetEngine() const;
// Tells the engine to generate a new frame
void ForceRedraw();
// Callback to clear a previously presented software bitmap.
virtual bool ClearSoftwareBitmap();
// Callback for presenting a software bitmap.
virtual bool PresentSoftwareBitmap(const void* allocation,
size_t row_bytes,
size_t height);
// Send initial bounds to embedder. Must occur after engine has initialized.
void SendInitialBounds();
// Set the text of the alert, and create it if it does not yet exist.
void AnnounceAlert(const std::wstring& text);
// |WindowBindingHandlerDelegate|
void OnHighContrastChanged() override;
// Called on the raster thread when |CompositorOpenGL| receives an empty
// frame. Returns true if the frame can be presented.
//
// This destroys and then re-creates the view's surface if a resize is
// pending.
bool OnEmptyFrameGenerated();
// Called on the raster thread when |CompositorOpenGL| receives a frame.
// Returns true if the frame can be presented.
//
// This destroys and then re-creates the view's surface if a resize is pending
// and |width| and |height| match the target size.
bool OnFrameGenerated(size_t width, size_t height);
// Called on the raster thread after |CompositorOpenGL| presents a frame.
//
// This completes a view resize if one is pending.
virtual void OnFramePresented();
// Sets the cursor that should be used when the mouse is over the Flutter
// content. See mouse_cursor.dart for the values and meanings of cursor_name.
void UpdateFlutterCursor(const std::string& cursor_name);
// Sets the cursor directly from a cursor handle.
void SetFlutterCursor(HCURSOR cursor);
// |WindowBindingHandlerDelegate|
bool OnWindowSizeChanged(size_t width, size_t height) override;
// |WindowBindingHandlerDelegate|
void OnWindowRepaint() override;
// |WindowBindingHandlerDelegate|
void OnPointerMove(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
int modifiers_state) override;
// |WindowBindingHandlerDelegate|
void OnPointerDown(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
FlutterPointerMouseButtons button) override;
// |WindowBindingHandlerDelegate|
void OnPointerUp(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id,
FlutterPointerMouseButtons button) override;
// |WindowBindingHandlerDelegate|
void OnPointerLeave(double x,
double y,
FlutterPointerDeviceKind device_kind,
int32_t device_id = 0) override;
// |WindowBindingHandlerDelegate|
virtual void OnPointerPanZoomStart(int32_t device_id) override;
// |WindowBindingHandlerDelegate|
virtual void OnPointerPanZoomUpdate(int32_t device_id,
double pan_x,
double pan_y,
double scale,
double rotation) override;
// |WindowBindingHandlerDelegate|
virtual void OnPointerPanZoomEnd(int32_t device_id) override;
// |WindowBindingHandlerDelegate|
void OnText(const std::u16string&) override;
// |WindowBindingHandlerDelegate|
void OnKey(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback) override;
// |WindowBindingHandlerDelegate|
void OnComposeBegin() override;
// |WindowBindingHandlerDelegate|
void OnComposeCommit() override;
// |WindowBindingHandlerDelegate|
void OnComposeEnd() override;
// |WindowBindingHandlerDelegate|
void OnComposeChange(const std::u16string& text, int cursor_pos) override;
// |WindowBindingHandlerDelegate|
void OnScroll(double x,
double y,
double delta_x,
double delta_y,
int scroll_offset_multiplier,
FlutterPointerDeviceKind device_kind,
int32_t device_id) override;
// |WindowBindingHandlerDelegate|
void OnScrollInertiaCancel(int32_t device_id) override;
// |WindowBindingHandlerDelegate|
virtual void OnUpdateSemanticsEnabled(bool enabled) override;
// |WindowBindingHandlerDelegate|
virtual gfx::NativeViewAccessible GetNativeViewAccessible() override;
// Notifies the delegate of the updated the cursor rect in Flutter root view
// coordinates.
virtual void OnCursorRectUpdated(const Rect& rect);
// Notifies the delegate that the system IME composing state should be reset.
virtual void OnResetImeComposing();
// Called when a WM_ONCOMPOSITIONCHANGED message is received.
void OnDwmCompositionChanged();
// Get a pointer to the alert node for this view.
ui::AXPlatformNodeWin* AlertNode() const;
// |WindowBindingHandlerDelegate|
virtual ui::AXFragmentRootDelegateWin* GetAxFragmentRootDelegate() override;
// Called to re/set the accessibility bridge pointer.
virtual void UpdateSemanticsEnabled(bool enabled);
std::weak_ptr<AccessibilityBridgeWindows> accessibility_bridge() {
return accessibility_bridge_;
}
// |WindowBindingHandlerDelegate|
void OnWindowStateEvent(HWND hwnd, WindowStateEvent event) override;
protected:
virtual void NotifyWinEventWrapper(ui::AXPlatformNodeWin* node,
ax::mojom::Event event);
// Create an AccessibilityBridgeWindows using this view.
virtual std::shared_ptr<AccessibilityBridgeWindows>
CreateAccessibilityBridge();
private:
// Allows setting the surface in tests.
friend class ViewModifier;
// Struct holding the state of an individual pointer. The engine doesn't keep
// track of which buttons have been pressed, so it's the embedding's
// responsibility.
struct PointerState {
// The device kind.
FlutterPointerDeviceKind device_kind = kFlutterPointerDeviceKindMouse;
// A virtual pointer ID that is unique across all device kinds.
int32_t pointer_id = 0;
// True if the last event sent to Flutter had at least one button pressed.
bool flutter_state_is_down = false;
// True if kAdd has been sent to Flutter. Used to determine whether
// to send a kAdd event before sending an incoming pointer event, since
// Flutter expects pointers to be added before events are sent for them.
bool flutter_state_is_added = false;
// The currently pressed buttons, as represented in FlutterPointerEvent.
uint64_t buttons = 0;
// The x position where the last pan/zoom started.
double pan_zoom_start_x = 0;
// The y position where the last pan/zoom started.
double pan_zoom_start_y = 0;
};
// States a resize event can be in.
enum class ResizeState {
// When a resize event has started but is in progress.
kResizeStarted,
// After a resize event starts and the framework has been notified to
// generate a frame for the right size.
kFrameGenerated,
// Default state for when no resize is in progress. Also used to indicate
// that during a resize event, a frame with the right size has been rendered
// and the buffers have been swapped.
kDone,
};
// Resize the surface to the desired size.
//
// If the dimensions have changed, this destroys the original surface and
// creates a new one.
//
// This must be run on the raster thread. This binds the surface to the
// current thread.
//
// Width and height are the surface's desired physical pixel dimensions.
bool ResizeRenderSurface(size_t width, size_t height);
// Sends a window metrics update to the Flutter engine using current window
// dimensions in physical
void SendWindowMetrics(size_t width, size_t height, double dpiscale) const;
// Reports a mouse movement to Flutter engine.
void SendPointerMove(double x, double y, PointerState* state);
// Reports mouse press to Flutter engine.
void SendPointerDown(double x, double y, PointerState* state);
// Reports mouse release to Flutter engine.
void SendPointerUp(double x, double y, PointerState* state);
// Reports mouse left the window client area.
//
// Win32 api doesn't have "mouse enter" event. Therefore, there is no
// SendPointerEnter method. A mouse enter event is tracked then the "move"
// event is called.
void SendPointerLeave(double x, double y, PointerState* state);
void SendPointerPanZoomStart(int32_t device_id, double x, double y);
void SendPointerPanZoomUpdate(int32_t device_id,
double pan_x,
double pan_y,
double scale,
double rotation);
void SendPointerPanZoomEnd(int32_t device_id);
// Reports a keyboard character to Flutter engine.
void SendText(const std::u16string&);
// Reports a raw keyboard message to Flutter engine.
void SendKey(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
KeyEventCallback callback);
// Reports an IME compose begin event.
//
// Triggered when the user begins editing composing text using a multi-step
// input method such as in CJK text input.
void SendComposeBegin();
// Reports an IME compose commit event.
//
// Triggered when the user commits the current composing text while using a
// multi-step input method such as in CJK text input. Composing continues with
// the next keypress.
void SendComposeCommit();
// Reports an IME compose end event.
//
// Triggered when the user commits the composing text while using a multi-step
// input method such as in CJK text input.
void SendComposeEnd();
// Reports an IME composing region change event.
//
// Triggered when the user edits the composing text while using a multi-step
// input method such as in CJK text input.
void SendComposeChange(const std::u16string& text, int cursor_pos);
// Reports scroll wheel events to Flutter engine.
void SendScroll(double x,
double y,
double delta_x,
double delta_y,
int scroll_offset_multiplier,
FlutterPointerDeviceKind device_kind,
int32_t device_id);
// Reports scroll inertia cancel events to Flutter engine.
void SendScrollInertiaCancel(int32_t device_id, double x, double y);
// Creates a PointerState object unless it already exists.
PointerState* GetOrCreatePointerState(FlutterPointerDeviceKind device_kind,
int32_t device_id);
// Sets |event_data|'s phase to either kMove or kHover depending on the
// current primary mouse button state.
void SetEventPhaseFromCursorButtonState(FlutterPointerEvent* event_data,
const PointerState* state) const;
// Sends a pointer event to the Flutter engine based on given data. Since
// all input messages are passed in physical pixel values, no translation is
// needed before passing on to engine.
void SendPointerEventWithData(const FlutterPointerEvent& event_data,
PointerState* state);
// If true, rendering to the window should synchronize with the vsync
// to prevent screen tearing.
bool NeedsVsync() const;
// The view's unique identifier.
FlutterViewId view_id_;
// The engine associated with this view.
FlutterWindowsEngine* engine_ = nullptr;
// Mocks win32 APIs.
std::shared_ptr<WindowsProcTable> windows_proc_table_;
// The EGL surface backing the view.
//
// Null if using software rasterization, the surface hasn't been created yet,
// or if surface creation failed.
std::unique_ptr<egl::WindowSurface> surface_ = nullptr;
// Keeps track of pointer states in relation to the window.
std::unordered_map<int32_t, std::unique_ptr<PointerState>> pointer_states_;
// Currently configured WindowBindingHandler for view.
std::unique_ptr<WindowBindingHandler> binding_handler_;
// Resize events are synchronized using this mutex and the corresponding
// condition variable.
std::mutex resize_mutex_;
std::condition_variable resize_cv_;
// Indicates the state of a window resize event. Platform thread will be
// blocked while this is not done. Guarded by resize_mutex_.
ResizeState resize_status_ = ResizeState::kDone;
// Target for the window width. Valid when resize_pending_ is set. Guarded by
// resize_mutex_.
size_t resize_target_width_ = 0;
// Target for the window width. Valid when resize_pending_ is set. Guarded by
// resize_mutex_.
size_t resize_target_height_ = 0;
// True when flutter's semantics tree is enabled.
bool semantics_enabled_ = false;
// The accessibility bridge associated with this view.
std::shared_ptr<AccessibilityBridgeWindows> accessibility_bridge_;
FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindowsView);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_VIEW_H_
| engine/shell/platform/windows/flutter_windows_view.h/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_view.h",
"repo_id": "engine",
"token_count": 5415
} | 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 "keyboard_utils.h"
#include "flutter/fml/logging.h"
namespace flutter {
std::u16string EncodeUtf16(char32_t character) {
// Algorithm: https://en.wikipedia.org/wiki/UTF-16#Description
std::u16string result;
// Invalid value.
FML_DCHECK(!(character >= 0xD800 && character <= 0xDFFF) &&
!(character > 0x10FFFF));
if ((character >= 0xD800 && character <= 0xDFFF) || (character > 0x10FFFF)) {
return result;
}
if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
result.push_back((char16_t)character);
return result;
}
uint32_t remnant = character - 0x10000;
result.push_back((remnant >> 10) + 0xD800);
result.push_back((remnant & 0x3FF) + 0xDC00);
return result;
}
} // namespace flutter
| engine/shell/platform/windows/keyboard_utils.cc/0 | {
"file_path": "engine/shell/platform/windows/keyboard_utils.cc",
"repo_id": "engine",
"token_count": 341
} | 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 "flutter/shell/platform/windows/settings_plugin.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/task_runner.h"
#include "flutter/shell/platform/windows/testing/test_binary_messenger.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
class MockSettingsPlugin : public SettingsPlugin {
public:
explicit MockSettingsPlugin(BinaryMessenger* messenger,
TaskRunner* task_runner)
: SettingsPlugin(messenger, task_runner) {}
virtual ~MockSettingsPlugin() = default;
bool is_high_contrast() { return is_high_contrast_; }
// |SettingsPlugin|
MOCK_METHOD(bool, GetAlwaysUse24HourFormat, (), (override));
MOCK_METHOD(float, GetTextScaleFactor, (), (override));
MOCK_METHOD(PlatformBrightness, GetPreferredBrightness, (), (override));
MOCK_METHOD(void, WatchPreferredBrightnessChanged, (), (override));
MOCK_METHOD(void, WatchTextScaleFactorChanged, (), (override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockSettingsPlugin);
};
} // namespace
TEST(SettingsPluginTest, SendSettingsSendsMessage) {
bool message_is_sent = false;
TestBinaryMessenger messenger(
[&message_is_sent](const std::string& channel, const uint8_t* message,
size_t message_size,
BinaryReply reply) { message_is_sent = true; });
::testing::NiceMock<MockSettingsPlugin> settings_plugin(&messenger, nullptr);
settings_plugin.SendSettings();
EXPECT_TRUE(message_is_sent);
}
TEST(SettingsPluginTest, SendSettingsGetsSettings) {
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
::testing::NiceMock<MockSettingsPlugin> settings_plugin(&messenger, nullptr);
EXPECT_CALL(settings_plugin, GetAlwaysUse24HourFormat).Times(1);
EXPECT_CALL(settings_plugin, GetTextScaleFactor).Times(1);
EXPECT_CALL(settings_plugin, GetPreferredBrightness).Times(1);
settings_plugin.SendSettings();
}
TEST(SettingsPluginTest, StartWatchingStartsWatchingChanges) {
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
::testing::NiceMock<MockSettingsPlugin> settings_plugin(&messenger, nullptr);
EXPECT_CALL(settings_plugin, WatchPreferredBrightnessChanged).Times(1);
EXPECT_CALL(settings_plugin, WatchTextScaleFactorChanged).Times(1);
settings_plugin.StartWatching();
}
TEST(SettingsPluginTest, HighContrastModeHonored) {
int times = 0;
TestBinaryMessenger messenger(
[×](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
ASSERT_EQ(channel, "flutter/settings");
times++;
});
::testing::NiceMock<MockSettingsPlugin> settings_plugin(&messenger, nullptr);
settings_plugin.UpdateHighContrastMode(true);
EXPECT_TRUE(settings_plugin.is_high_contrast());
settings_plugin.UpdateHighContrastMode(false);
EXPECT_FALSE(settings_plugin.is_high_contrast());
EXPECT_EQ(times, 2);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/settings_plugin_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/settings_plugin_unittests.cc",
"repo_id": "engine",
"token_count": 1277
} | 395 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_DIRECT_MANIPULATION_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_DIRECT_MANIPULATION_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/direct_manipulation.h"
#include "gmock/gmock.h"
namespace flutter {
namespace testing {
/// Mock for the |DirectManipulationOwner| base class.
class MockDirectManipulationOwner : public DirectManipulationOwner {
public:
explicit MockDirectManipulationOwner(FlutterWindow* window)
: DirectManipulationOwner(window){};
virtual ~MockDirectManipulationOwner() = default;
MOCK_METHOD(void, SetContact, (UINT contact_id), (override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockDirectManipulationOwner);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_MOCK_DIRECT_MANIPULATION_H_
| engine/shell/platform/windows/testing/mock_direct_manipulation.h/0 | {
"file_path": "engine/shell/platform/windows/testing/mock_direct_manipulation.h",
"repo_id": "engine",
"token_count": 355
} | 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.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_H_
#include <string>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/testing/windows_test_context.h"
#include "flutter/testing/thread_test.h"
namespace flutter {
namespace testing {
/// A GoogleTest test fixture for Windows tests.
///
/// Supports looking up the test fixture data defined in the GN `test_fixtures`
/// associated with the unit test executable target. This typically includes
/// the kernel bytecode `kernel_blob.bin` compiled from the Dart file specified
/// in the test fixture's `dart_main` property, as well as any other data files
/// used in tests, such as image files used in a screenshot golden test.
///
/// This test class can be used in GoogleTest tests using the standard
/// `TEST_F(WindowsTest, TestName)` macro.
class WindowsTest : public ThreadTest {
public:
WindowsTest();
// Returns the path to test fixture data such as kernel bytecode or images
// used by the C++ side of the test.
std::string GetFixturesDirectory() const;
// Returns the test context associated with this fixture.
WindowsTestContext& GetContext();
private:
WindowsTestContext context_;
FML_DISALLOW_COPY_AND_ASSIGN(WindowsTest);
};
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_WINDOWS_TEST_H_
| engine/shell/platform/windows/testing/windows_test.h/0 | {
"file_path": "engine/shell/platform/windows/testing/windows_test.h",
"repo_id": "engine",
"token_count": 466
} | 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.
#include "flutter/shell/platform/windows/window_proc_delegate_manager.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
#ifdef _WIN32
#define FLUTTER_NOINLINE __declspec(noinline)
#else
#define FLUTTER_NOINLINE __attribute__((noinline))
#endif
using TestWindowProcDelegate = std::function<std::optional<
LRESULT>(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)>;
// A FlutterDesktopWindowProcCallback that forwards to a std::function provided
// as user_data.
FLUTTER_NOINLINE
bool TestWindowProcCallback(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam,
void* user_data,
LRESULT* result) {
TestWindowProcDelegate& delegate =
*static_cast<TestWindowProcDelegate*>(user_data);
auto delegate_result = delegate(hwnd, message, wparam, lparam);
if (delegate_result) {
*result = *delegate_result;
}
return delegate_result.has_value();
}
// Same as the above, but with a different address, to test multiple
// registration.
bool TestWindowProcCallback2(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam,
void* user_data,
LRESULT* result) {
return TestWindowProcCallback(hwnd, message, wparam, lparam, user_data,
result);
}
} // namespace
TEST(WindowProcDelegateManagerTest, CallsCorrectly) {
WindowProcDelegateManager manager;
HWND dummy_hwnd;
bool called = false;
TestWindowProcDelegate delegate = [&called, &dummy_hwnd](
HWND hwnd, UINT message, WPARAM wparam,
LPARAM lparam) {
called = true;
EXPECT_EQ(hwnd, dummy_hwnd);
EXPECT_EQ(message, 2);
EXPECT_EQ(wparam, 3);
EXPECT_EQ(lparam, 4);
return std::optional<LRESULT>();
};
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback, &delegate);
auto result = manager.OnTopLevelWindowProc(dummy_hwnd, 2, 3, 4);
EXPECT_TRUE(called);
EXPECT_FALSE(result);
}
TEST(WindowProcDelegateManagerTest, ReplacementRegister) {
WindowProcDelegateManager manager;
bool called_a = false;
TestWindowProcDelegate delegate_a =
[&called_a](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
called_a = true;
return std::optional<LRESULT>();
};
bool called_b = false;
TestWindowProcDelegate delegate_b =
[&called_b](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
called_b = true;
return std::optional<LRESULT>();
};
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback,
&delegate_a);
// The function pointer is the same, so this should replace, not add.
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback,
&delegate_b);
manager.OnTopLevelWindowProc(nullptr, 0, 0, 0);
EXPECT_FALSE(called_a);
EXPECT_TRUE(called_b);
}
TEST(WindowProcDelegateManagerTest, RegisterMultiple) {
WindowProcDelegateManager manager;
bool called_a = false;
TestWindowProcDelegate delegate_a =
[&called_a](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
called_a = true;
return std::optional<LRESULT>();
};
bool called_b = false;
TestWindowProcDelegate delegate_b =
[&called_b](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
called_b = true;
return std::optional<LRESULT>();
};
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback,
&delegate_a);
// Function pointer is different, so both should be called.
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback2,
&delegate_b);
manager.OnTopLevelWindowProc(nullptr, 0, 0, 0);
EXPECT_TRUE(called_a);
EXPECT_TRUE(called_b);
}
TEST(WindowProcDelegateManagerTest, Ordered) {
TestWindowProcDelegate delegate_1 = [](HWND hwnd, UINT message, WPARAM wparam,
LPARAM lparam) { return 1; };
TestWindowProcDelegate delegate_2 = [](HWND hwnd, UINT message, WPARAM wparam,
LPARAM lparam) { return 2; };
// Result should be 1 if delegate '1' is registered before delegate '2'.
{
WindowProcDelegateManager manager;
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback,
&delegate_1);
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback2,
&delegate_2);
std::optional<LRESULT> result =
manager.OnTopLevelWindowProc(nullptr, 0, 0, 0);
EXPECT_EQ(result, 1);
}
// Result should be 2 if delegate '2' is registered before delegate '1'.
{
WindowProcDelegateManager manager;
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback2,
&delegate_2);
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback,
&delegate_1);
std::optional<LRESULT> result =
manager.OnTopLevelWindowProc(nullptr, 0, 0, 0);
EXPECT_EQ(result, 2);
}
}
TEST(WindowProcDelegateManagerTest, ConflictingDelegates) {
WindowProcDelegateManager manager;
bool called_a = false;
TestWindowProcDelegate delegate_a =
[&called_a](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
called_a = true;
return std::optional<LRESULT>(1);
};
bool called_b = false;
TestWindowProcDelegate delegate_b =
[&called_b](HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) {
called_b = true;
return std::optional<LRESULT>(1);
};
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback,
&delegate_a);
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback2,
&delegate_b);
auto result = manager.OnTopLevelWindowProc(nullptr, 0, 0, 0);
EXPECT_TRUE(result);
// Exactly one of the handlers should be called since each will claim to have
// handled the message. Which one is unspecified, since the calling order is
// unspecified.
EXPECT_TRUE(called_a || called_b);
EXPECT_NE(called_a, called_b);
}
TEST(WindowProcDelegateManagerTest, Unregister) {
WindowProcDelegateManager manager;
bool called = false;
TestWindowProcDelegate delegate = [&called](HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam) {
called = true;
return std::optional<LRESULT>();
};
manager.RegisterTopLevelWindowProcDelegate(TestWindowProcCallback, &delegate);
manager.UnregisterTopLevelWindowProcDelegate(TestWindowProcCallback);
auto result = manager.OnTopLevelWindowProc(nullptr, 0, 0, 0);
EXPECT_FALSE(result);
EXPECT_FALSE(called);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/window_proc_delegate_manager_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/window_proc_delegate_manager_unittests.cc",
"repo_id": "engine",
"token_count": 3323
} | 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.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
class ServiceClient {
Completer<dynamic>? isolateStartedId;
Completer<dynamic>? isolatePausedId;
Completer<dynamic>? isolateResumeId;
ServiceClient(
this.client, {
this.isolateStartedId,
this.isolatePausedId,
this.isolateResumeId,
}) {
client.listen(_onData, onError: _onError, cancelOnError: true);
}
Future<Map<String, dynamic>> invokeRPC(String method,
[Map<String, dynamic>? params]) async {
final String key = _createKey();
final String request = json.encode(<String, dynamic>{
'jsonrpc': '2.0',
'method': method,
'params': params == null ? <String, dynamic>{} : params,
'id': key,
});
client.add(request);
final Completer<Map<String, dynamic>> completer =
Completer<Map<String, dynamic>>();
_outstandingRequests[key] = completer;
print('-> $key ($method)');
return completer.future;
}
String _createKey() {
final String key = '$_id';
_id++;
return key;
}
void _onData(dynamic message) {
final Map<String, dynamic> response =
json.decode(message as String) as Map<String, dynamic>;
final dynamic key = response['id'];
if (key != null) {
print('<- $key');
final dynamic completer = _outstandingRequests.remove(key);
assert(completer != null);
final dynamic result = response['result'];
final dynamic error = response['error'];
if (error != null) {
assert(result == null);
completer.completeError(error);
} else {
assert(result != null);
completer.complete(result);
}
} else {
if (response['method'] == 'streamNotify') {
_onServiceEvent(response['params'] as Map<String, dynamic>?);
}
}
}
void _onServiceEvent(Map<String, dynamic>? params) {
if (params == null) {
return;
}
final Map<String, dynamic>? event =
params['event'] as Map<String, dynamic>?;
if (event == null || event['type'] != 'Event') {
return;
}
final dynamic isolateId = event['isolate']['id'];
switch (params['streamId']) {
case 'Isolate':
if (event['kind'] == 'IsolateStart') {
isolateStartedId?.complete(isolateId);
}
break;
case 'Debug':
switch (event['kind']) {
case 'Resume':
isolateResumeId?.complete(isolateId);
break;
case 'PauseStart':
isolatePausedId?.complete(isolateId);
break;
}
break;
}
}
void _onError(dynamic error) {
print('WebSocket error: $error');
}
final WebSocket client;
final Map<String, Completer<dynamic>> _outstandingRequests =
<String, Completer<dynamic>>{};
int _id = 1;
}
| engine/shell/testing/observatory/service_client.dart/0 | {
"file_path": "engine/shell/testing/observatory/service_client.dart",
"repo_id": "engine",
"token_count": 1223
} | 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.
_skia_root = "//flutter/third_party/skia"
import("$_skia_root/gn/skia.gni")
import("$_skia_root/modules/skunicode/skunicode.gni")
declare_args() {
skia_use_runtime_icu = false
skunicode_tests_enabled = true
}
if (skia_use_icu || skia_use_client_icu || skia_use_libgrapheme) {
config("public_config") {
include_dirs = [ "$_skia_root/modules/skunicode/include" ]
defines = [ "SK_UNICODE_AVAILABLE" ]
if (skia_use_icu) {
defines += [ "SK_UNICODE_ICU_IMPLEMENTATION" ]
}
if (skia_use_client_icu) {
defines += [ "SK_UNICODE_CLIENT_IMPLEMENTATION" ]
}
if (skia_use_libgrapheme) {
defines += [ "SK_UNICODE_LIBGRAPHEME_IMPLEMENTATION" ]
}
}
component("skunicode") {
# Opted out of check_includes, due to (logically) being part of skia.
check_includes = false
public_configs = [ ":public_config" ]
public = skia_unicode_public
deps = [ "../..:skia" ]
defines = [ "SKUNICODE_IMPLEMENTATION=1" ]
sources = skia_unicode_sources + skia_unicode_icu_bidi_sources
defines += [ "SK_UNICODE_AVAILABLE" ]
configs += [ "../../:skia_private" ]
if (skia_use_icu) {
sources += skia_unicode_icu_sources
defines += [ "SK_UNICODE_ICU_IMPLEMENTATION" ]
# only available for Android at the moment
if (skia_use_runtime_icu && (is_android || is_linux)) {
sources += skia_unicode_runtime_icu_sources
deps += [ "//flutter/third_party/icu:headers" ]
} else {
sources += skia_unicode_builtin_icu_sources
deps += [ "//flutter/third_party/icu" ]
}
configs += [ "$_skia_root/third_party/icu/config:no_cxx" ]
}
if (skia_use_client_icu) {
sources += skia_unicode_client_icu_sources
defines += [ "SK_UNICODE_CLIENT_IMPLEMENTATION" ]
if (!skia_use_icu) {
deps += [ skia_icu_bidi_third_party_dir ]
}
}
if (skia_use_libgrapheme) {
sources += skia_unicode_libgrapheme_sources
defines += [ "SK_UNICODE_LIBGRAPHEME_IMPLEMENTATION" ]
deps += [ skia_libgrapheme_third_party_dir ]
if (!skia_use_icu) {
deps += [ skia_icu_bidi_third_party_dir ]
}
}
}
} else {
group("skunicode") {
}
group("tests") {
}
}
| engine/skia/modules/skunicode/BUILD.gn/0 | {
"file_path": "engine/skia/modules/skunicode/BUILD.gn",
"repo_id": "engine",
"token_count": 1101
} | 400 |
#!/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 subprocess
import sys
import os
buildroot_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..'))
def main():
parser = argparse.ArgumentParser(
description='Copies architecture-dependent gen_snapshot binaries to output dir'
)
parser.add_argument('--dst', type=str, required=True)
parser.add_argument('--clang-dir', type=str, default='clang_x64')
parser.add_argument('--x64-out-dir', type=str)
parser.add_argument('--arm64-out-dir', type=str)
parser.add_argument('--armv7-out-dir', type=str)
parser.add_argument('--zip', action='store_true', default=False)
args = parser.parse_args()
dst = (args.dst if os.path.isabs(args.dst) else os.path.join(buildroot_dir, args.dst))
# if dst folder does not exist create it.
if not os.path.exists(dst):
os.makedirs(dst)
if args.x64_out_dir:
x64_out_dir = (
args.x64_out_dir
if os.path.isabs(args.x64_out_dir) else os.path.join(buildroot_dir, args.x64_out_dir)
)
generate_gen_snapshot(x64_out_dir, os.path.join(dst, 'gen_snapshot_x64'))
if args.arm64_out_dir:
arm64_out_dir = (
args.arm64_out_dir
if os.path.isabs(args.arm64_out_dir) else os.path.join(buildroot_dir, args.arm64_out_dir)
)
generate_gen_snapshot(
os.path.join(arm64_out_dir, args.clang_dir), os.path.join(dst, 'gen_snapshot_arm64')
)
if args.armv7_out_dir:
armv7_out_dir = (
args.armv7_out_dir
if os.path.isabs(args.armv7_out_dir) else os.path.join(buildroot_dir, args.armv7_out_dir)
)
generate_gen_snapshot(
os.path.join(armv7_out_dir, args.clang_dir), os.path.join(dst, 'gen_snapshot_armv7')
)
if args.zip:
zip_archive(dst)
def embed_codesign_configuration(config_path, contents):
with open(config_path, 'w') as file:
file.write('\n'.join(contents) + '\n')
def zip_archive(dst):
snapshot_filepath = ['gen_snapshot_arm64', 'gen_snapshot_x64']
embed_codesign_configuration(os.path.join(dst, 'entitlements.txt'), snapshot_filepath)
subprocess.check_call([
'zip',
'-r',
'gen_snapshot.zip',
'.',
], cwd=dst)
def generate_gen_snapshot(directory, destination):
gen_snapshot_dir = os.path.join(directory, 'gen_snapshot')
if not os.path.isfile(gen_snapshot_dir):
print('Cannot find gen_snapshot at %s' % gen_snapshot_dir)
sys.exit(1)
subprocess.check_call(['xcrun', 'bitcode_strip', '-r', gen_snapshot_dir, '-o', destination])
if __name__ == '__main__':
sys.exit(main())
| engine/sky/tools/create_macos_gen_snapshots.py/0 | {
"file_path": "engine/sky/tools/create_macos_gen_snapshots.py",
"repo_id": "engine",
"token_count": 1154
} | 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_TESTING_ANDROID_NATIVE_ACTIVITY_GTEST_ACTIVITY_H_
#define FLUTTER_TESTING_ANDROID_NATIVE_ACTIVITY_GTEST_ACTIVITY_H_
#include "flutter/fml/macros.h"
#include "flutter/fml/thread.h"
#include "flutter/testing/android/native_activity/native_activity.h"
namespace flutter {
//------------------------------------------------------------------------------
/// @brief A native activity subclass an in implementation of
/// `flutter::NativeActivityMain` that return it.
///
/// This class runs a Google Test harness on a background thread and
/// redirects progress updates to `logcat` instead of STDOUT.
///
class GTestActivity final : public NativeActivity {
public:
explicit GTestActivity(ANativeActivity* activity);
~GTestActivity() override;
GTestActivity(const GTestActivity&) = delete;
GTestActivity& operator=(const GTestActivity&) = delete;
// |NativeActivity|
void OnNativeWindowCreated(ANativeWindow* window) override;
private:
fml::Thread background_thread_;
};
} // namespace flutter
#endif // FLUTTER_TESTING_ANDROID_NATIVE_ACTIVITY_GTEST_ACTIVITY_H_
| engine/testing/android/native_activity/gtest_activity.h/0 | {
"file_path": "engine/testing/android/native_activity/gtest_activity.h",
"repo_id": "engine",
"token_count": 418
} | 402 |
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.builder.sdkDownload=false
| engine/testing/android_background_image/android/gradle.properties/0 | {
"file_path": "engine/testing/android_background_image/android/gradle.properties",
"repo_id": "engine",
"token_count": 41
} | 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.
name: flutter_engine_benchmark
publish_to: none
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:
args: any
metrics_center: any
path: any
dev_dependencies:
litetest: any
dependency_overrides:
_discoveryapis_commons:
path: ../../third_party/pkg/googleapis/discoveryapis_commons
args:
path: ../../../third_party/dart/third_party/pkg/args
async_helper:
path: ../../../third_party/dart/pkg/async_helper
async:
path: ../../../third_party/dart/third_party/pkg/async
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
equatable:
path: ../../third_party/pkg/equatable
expect:
path: ../../../third_party/dart/pkg/expect
gcloud:
path: ../../third_party/pkg/gcloud
googleapis:
path: ../../third_party/pkg/googleapis/generated/googleapis
googleapis_auth:
path: ../../third_party/pkg/googleapis/googleapis_auth
http:
path: ../../../third_party/dart/third_party/pkg/http/pkgs/http
http_parser:
path: ../../../third_party/dart/third_party/pkg/http_parser
js:
path: ../../../third_party/dart/pkg/js
litetest:
path: ../litetest
meta:
path: ../../../third_party/dart/pkg/meta
metrics_center:
path: ../../third_party/pkg/flutter_packages/packages/metrics_center
path:
path: ../../../third_party/dart/third_party/pkg/path
smith:
path: ../../../third_party/dart/pkg/smith
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
web:
path: ../../../third_party/dart/third_party/pkg/web
| engine/testing/benchmark/pubspec.yaml/0 | {
"file_path": "engine/testing/benchmark/pubspec.yaml",
"repo_id": "engine",
"token_count": 967
} | 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.
// This is testing some of the named constants.
// ignore_for_file: use_named_constants
import 'dart:math' as math show sqrt;
import 'dart:math' show pi;
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('OffsetBase.>=', () {
expect(const Offset(0, 0) >= const Offset(0, -1), true);
expect(const Offset(0, 0) >= const Offset(-1, 0), true);
expect(const Offset(0, 0) >= const Offset(-1, -1), true);
expect(const Offset(0, 0) >= const Offset(0, 0), true);
expect(const Offset(0, 0) >= const Offset(0, double.nan), false);
expect(const Offset(0, 0) >= const Offset(double.nan, 0), false);
expect(const Offset(0, 0) >= const Offset(10, -10), false);
});
test('OffsetBase.<=', () {
expect(const Offset(0, 0) <= const Offset(0, 1), true);
expect(const Offset(0, 0) <= const Offset(1, 0), true);
expect(const Offset(0, 0) <= const Offset(0, 0), true);
expect(const Offset(0, 0) <= const Offset(0, double.nan), false);
expect(const Offset(0, 0) <= const Offset(double.nan, 0), false);
expect(const Offset(0, 0) <= const Offset(10, -10), false);
});
test('OffsetBase.>', () {
expect(const Offset(0, 0) > const Offset(-1, -1), true);
expect(const Offset(0, 0) > const Offset(0, -1), false);
expect(const Offset(0, 0) > const Offset(-1, 0), false);
expect(const Offset(0, 0) > const Offset(double.nan, -1), false);
});
test('OffsetBase.<', () {
expect(const Offset(0, 0) < const Offset(1, 1), true);
expect(const Offset(0, 0) < const Offset(0, 1), false);
expect(const Offset(0, 0) < const Offset(1, 0), false);
expect(const Offset(0, 0) < const Offset(double.nan, 1), false);
});
test('OffsetBase.==', () {
expect(const Offset(0, 0), equals(const Offset(0, 0)));
expect(const Offset(0, 0), notEquals(const Offset(1, 0)));
expect(const Offset(0, 0), notEquals(const Offset(0, 1)));
});
test('Offset.direction', () {
expect(const Offset(0.0, 0.0).direction, 0.0);
expect(const Offset(0.0, 1.0).direction, pi / 2.0);
expect(const Offset(0.0, -1.0).direction, -pi / 2.0);
expect(const Offset(1.0, 0.0).direction, 0.0);
expect(const Offset(1.0, 1.0).direction, pi / 4.0);
expect(const Offset(1.0, -1.0).direction, -pi / 4.0);
expect(const Offset(-1.0, 0.0).direction, pi);
expect(const Offset(-1.0, 1.0).direction, pi * 3.0 / 4.0);
expect(const Offset(-1.0, -1.0).direction, -pi * 3.0 / 4.0);
});
test('Offset.fromDirection', () {
expect(Offset.fromDirection(0.0, 0.0), const Offset(0.0, 0.0));
expect(Offset.fromDirection(pi / 2.0).dx, closeTo(0.0, 1e-12)); // aah, floating point math. i love you so.
expect(Offset.fromDirection(pi / 2.0).dy, 1.0);
expect(Offset.fromDirection(-pi / 2.0).dx, closeTo(0.0, 1e-12));
expect(Offset.fromDirection(-pi / 2.0).dy, -1.0);
expect(Offset.fromDirection(0.0), const Offset(1.0, 0.0));
expect(Offset.fromDirection(pi / 4.0).dx, closeTo(1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(pi / 4.0).dy, closeTo(1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(-pi / 4.0).dx, closeTo(1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(-pi / 4.0).dy, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(pi).dx, -1.0);
expect(Offset.fromDirection(pi).dy, closeTo(0.0, 1e-12));
expect(Offset.fromDirection(pi * 3.0 / 4.0).dx, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(pi * 3.0 / 4.0).dy, closeTo(1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(-pi * 3.0 / 4.0).dx, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(-pi * 3.0 / 4.0).dy, closeTo(-1.0 / math.sqrt(2.0), 1e-12));
expect(Offset.fromDirection(0.0, 2.0), const Offset(2.0, 0.0));
expect(Offset.fromDirection(pi / 6, 2.0).dx, closeTo(math.sqrt(3.0), 1e-12));
expect(Offset.fromDirection(pi / 6, 2.0).dy, closeTo(1.0, 1e-12));
});
test('Size created from doubles', () {
const Size size = Size(5.0, 7.0);
expect(size.width, equals(5.0));
expect(size.height, equals(7.0));
expect(size.shortestSide, equals(5.0));
expect(size.longestSide, equals(7.0));
});
test('Size.aspectRatio', () {
expect(const Size(0.0, 0.0).aspectRatio, 0.0);
expect(const Size(-0.0, 0.0).aspectRatio, 0.0);
expect(const Size(0.0, -0.0).aspectRatio, 0.0);
expect(const Size(-0.0, -0.0).aspectRatio, 0.0);
expect(const Size(0.0, 1.0).aspectRatio, 0.0);
expect(const Size(0.0, -1.0).aspectRatio, -0.0);
expect(const Size(1.0, 0.0).aspectRatio, double.infinity);
expect(const Size(1.0, 1.0).aspectRatio, 1.0);
expect(const Size(1.0, -1.0).aspectRatio, -1.0);
expect(const Size(-1.0, 0.0).aspectRatio, -double.infinity);
expect(const Size(-1.0, 1.0).aspectRatio, -1.0);
expect(const Size(-1.0, -1.0).aspectRatio, 1.0);
expect(const Size(3.0, 4.0).aspectRatio, 3.0 / 4.0);
});
test('Rect.toString test', () {
const Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0);
expect(r.toString(), 'Rect.fromLTRB(1.0, 3.0, 5.0, 7.0)');
});
test('Rect accessors', () {
const Rect r = Rect.fromLTRB(1.0, 3.0, 5.0, 7.0);
expect(r.left, equals(1.0));
expect(r.top, equals(3.0));
expect(r.right, equals(5.0));
expect(r.bottom, equals(7.0));
});
test('Rect.fromCenter', () {
Rect rect = Rect.fromCenter(center: const Offset(1.0, 3.0), width: 5.0, height: 7.0);
expect(rect.left, -1.5);
expect(rect.top, -0.5);
expect(rect.right, 3.5);
expect(rect.bottom, 6.5);
rect = Rect.fromCenter(center: const Offset(0.0, 0.0), width: 0.0, height: 0.0);
expect(rect.left, 0.0);
expect(rect.top, 0.0);
expect(rect.right, 0.0);
expect(rect.bottom, 0.0);
rect = Rect.fromCenter(center: const Offset(double.nan, 0.0), width: 0.0, height: 0.0);
expect(rect.left, isNaN);
expect(rect.top, 0.0);
expect(rect.right, isNaN);
expect(rect.bottom, 0.0);
rect = Rect.fromCenter(center: const Offset(0.0, double.nan), width: 0.0, height: 0.0);
expect(rect.left, 0.0);
expect(rect.top, isNaN);
expect(rect.right, 0.0);
expect(rect.bottom, isNaN);
});
test('Rect created by width and height', () {
const Rect r = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0);
expect(r.left, equals(1.0));
expect(r.top, equals(3.0));
expect(r.right, equals(6.0));
expect(r.bottom, equals(10.0));
expect(r.shortestSide, equals(5.0));
expect(r.longestSide, equals(7.0));
});
test('Rect intersection', () {
const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0);
const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0);
final Rect r3 = r1.intersect(r2);
expect(r3.left, equals(50.0));
expect(r3.top, equals(50.0));
expect(r3.right, equals(100.0));
expect(r3.bottom, equals(100.0));
final Rect r4 = r2.intersect(r1);
expect(r4, equals(r3));
});
test('Rect expandToInclude overlapping rects', () {
const Rect r1 = Rect.fromLTRB(0.0, 0.0, 100.0, 100.0);
const Rect r2 = Rect.fromLTRB(50.0, 50.0, 200.0, 200.0);
final Rect r3 = r1.expandToInclude(r2);
expect(r3.left, equals(0.0));
expect(r3.top, equals(0.0));
expect(r3.right, equals(200.0));
expect(r3.bottom, equals(200.0));
final Rect r4 = r2.expandToInclude(r1);
expect(r4, equals(r3));
});
test('Rect expandToInclude crossing rects', () {
const Rect r1 = Rect.fromLTRB(50.0, 0.0, 50.0, 200.0);
const Rect r2 = Rect.fromLTRB(0.0, 50.0, 200.0, 50.0);
final Rect r3 = r1.expandToInclude(r2);
expect(r3.left, equals(0.0));
expect(r3.top, equals(0.0));
expect(r3.right, equals(200.0));
expect(r3.bottom, equals(200.0));
final Rect r4 = r2.expandToInclude(r1);
expect(r4, equals(r3));
});
test('RRect.fromRectXY', () {
const Rect baseRect = Rect.fromLTWH(1.0, 3.0, 5.0, 7.0);
final RRect r = RRect.fromRectXY(baseRect, 1.0, 1.0);
expect(r.left, equals(1.0));
expect(r.top, equals(3.0));
expect(r.right, equals(6.0));
expect(r.bottom, equals(10.0));
expect(r.shortestSide, equals(5.0));
expect(r.longestSide, equals(7.0));
});
test('RRect.contains()', () {
final RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
topLeft: const Radius.circular(0.5),
topRight: const Radius.circular(0.25),
bottomRight: const Radius.elliptical(0.25, 0.75),
);
expect(rrect.contains(const Offset(1.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.1, 1.1)), isFalse);
expect(rrect.contains(const Offset(1.15, 1.15)), isTrue);
expect(rrect.contains(const Offset(2.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.93, 1.07)), isFalse);
expect(rrect.contains(const Offset(1.97, 1.7)), isFalse);
expect(rrect.contains(const Offset(1.7, 1.97)), isTrue);
expect(rrect.contains(const Offset(1.0, 1.99)), isTrue);
});
test('RRect.contains() large radii', () {
final RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
topLeft: const Radius.circular(5000.0),
topRight: const Radius.circular(2500.0),
bottomRight: const Radius.elliptical(2500.0, 7500.0),
);
expect(rrect.contains(const Offset(1.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.1, 1.1)), isFalse);
expect(rrect.contains(const Offset(1.15, 1.15)), isTrue);
expect(rrect.contains(const Offset(2.0, 1.0)), isFalse);
expect(rrect.contains(const Offset(1.93, 1.07)), isFalse);
expect(rrect.contains(const Offset(1.97, 1.7)), isFalse);
expect(rrect.contains(const Offset(1.7, 1.97)), isTrue);
expect(rrect.contains(const Offset(1.0, 1.99)), isTrue);
});
test('RRect.scaleRadii() properly constrained radii should remain unchanged', () {
final RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
topLeft: const Radius.circular(0.5),
topRight: const Radius.circular(0.25),
bottomRight: const Radius.elliptical(0.25, 0.75),
).scaleRadii();
// check sides
expect(rrect.left, 1.0);
expect(rrect.top, 1.0);
expect(rrect.right, 2.0);
expect(rrect.bottom, 2.0);
// check corner radii
expect(rrect.tlRadiusX, 0.5);
expect(rrect.tlRadiusY, 0.5);
expect(rrect.trRadiusX, 0.25);
expect(rrect.trRadiusY, 0.25);
expect(rrect.blRadiusX, 0.0);
expect(rrect.blRadiusY, 0.0);
expect(rrect.brRadiusX, 0.25);
expect(rrect.brRadiusY, 0.75);
});
test('RRect.scaleRadii() sum of radii that exceed side length should properly scale', () {
final RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0),
topLeft: const Radius.circular(5000.0),
topRight: const Radius.circular(2500.0),
bottomRight: const Radius.elliptical(2500.0, 7500.0),
).scaleRadii();
// check sides
expect(rrect.left, 1.0);
expect(rrect.top, 1.0);
expect(rrect.right, 2.0);
expect(rrect.bottom, 2.0);
// check corner radii
expect(rrect.tlRadiusX, 0.5);
expect(rrect.tlRadiusY, 0.5);
expect(rrect.trRadiusX, 0.25);
expect(rrect.trRadiusY, 0.25);
expect(rrect.blRadiusX, 0.0);
expect(rrect.blRadiusY, 0.0);
expect(rrect.brRadiusX, 0.25);
expect(rrect.brRadiusY, 0.75);
});
test('Radius.clamp() operates as expected', () {
final RRect rrectMin = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(-100).clamp(minimum: Radius.zero));
expect(rrectMin.left, 1);
expect(rrectMin.top, 3);
expect(rrectMin.right, 5);
expect(rrectMin.bottom, 7);
expect(rrectMin.trRadius, equals(const Radius.circular(0)));
expect(rrectMin.blRadius, equals(const Radius.circular(0)));
final RRect rrectMax = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(100).clamp(maximum: const Radius.circular(10)));
expect(rrectMax.left, 1);
expect(rrectMax.top, 3);
expect(rrectMax.right, 5);
expect(rrectMax.bottom, 7);
expect(rrectMax.trRadius, equals(const Radius.circular(10)));
expect(rrectMax.blRadius, equals(const Radius.circular(10)));
final RRect rrectMix = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(-100, 100).clamp(minimum: Radius.zero, maximum: const Radius.circular(10)));
expect(rrectMix.left, 1);
expect(rrectMix.top, 3);
expect(rrectMix.right, 5);
expect(rrectMix.bottom, 7);
expect(rrectMix.trRadius, equals(const Radius.elliptical(0, 10)));
expect(rrectMix.blRadius, equals(const Radius.elliptical(0, 10)));
final RRect rrectMix1 = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(100, -100).clamp(minimum: Radius.zero, maximum: const Radius.circular(10)));
expect(rrectMix1.left, 1);
expect(rrectMix1.top, 3);
expect(rrectMix1.right, 5);
expect(rrectMix1.bottom, 7);
expect(rrectMix1.trRadius, equals(const Radius.elliptical(10, 0)));
expect(rrectMix1.blRadius, equals(const Radius.elliptical(10, 0)));
});
test('Radius.clampValues() operates as expected', () {
final RRect rrectMin = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(-100).clampValues(minimumX: 0, minimumY: 0));
expect(rrectMin.left, 1);
expect(rrectMin.top, 3);
expect(rrectMin.right, 5);
expect(rrectMin.bottom, 7);
expect(rrectMin.trRadius, equals(const Radius.circular(0)));
expect(rrectMin.blRadius, equals(const Radius.circular(0)));
final RRect rrectMax = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.circular(100).clampValues(maximumX: 10, maximumY: 20));
expect(rrectMax.left, 1);
expect(rrectMax.top, 3);
expect(rrectMax.right, 5);
expect(rrectMax.bottom, 7);
expect(rrectMax.trRadius, equals(const Radius.elliptical(10, 20)));
expect(rrectMax.blRadius, equals(const Radius.elliptical(10, 20)));
final RRect rrectMix = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(-100, 100).clampValues(minimumX: 5, minimumY: 6, maximumX: 10, maximumY: 20));
expect(rrectMix.left, 1);
expect(rrectMix.top, 3);
expect(rrectMix.right, 5);
expect(rrectMix.bottom, 7);
expect(rrectMix.trRadius, equals(const Radius.elliptical(5, 20)));
expect(rrectMix.blRadius, equals(const Radius.elliptical(5, 20)));
final RRect rrectMix2 = RRect.fromLTRBR(1, 3, 5, 7,
const Radius.elliptical(100, -100).clampValues(minimumX: 5, minimumY: 6, maximumX: 10, maximumY: 20));
expect(rrectMix2.left, 1);
expect(rrectMix2.top, 3);
expect(rrectMix2.right, 5);
expect(rrectMix2.bottom, 7);
expect(rrectMix2.trRadius, equals(const Radius.elliptical(10, 6)));
expect(rrectMix2.blRadius, equals(const Radius.elliptical(10, 6)));
});
test('RRect asserts when corner radii are negative', () {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
if (!assertsEnabled) {
return;
}
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topLeft: const Radius.circular(-1),
);
}, throwsA(isInstanceOf<AssertionError>()));
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topRight: const Radius.circular(-2),
);
}, throwsA(isInstanceOf<AssertionError>()));
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
bottomLeft: const Radius.circular(-3),
);
}, throwsA(isInstanceOf<AssertionError>()));
expect(() {
RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
bottomRight: const Radius.circular(-4),
);
}, throwsA(isInstanceOf<AssertionError>()));
});
test('RRect.inflate clamps when deflating past zero', () {
RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topLeft: const Radius.circular(1),
topRight: const Radius.circular(2),
bottomLeft: const Radius.circular(3),
bottomRight: const Radius.circular(4),
).inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 1);
expect(rrect.trRadiusY, 1);
expect(rrect.blRadiusX, 2);
expect(rrect.blRadiusY, 2);
expect(rrect.brRadiusX, 3);
expect(rrect.brRadiusY, 3);
rrect = rrect.inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 1);
expect(rrect.blRadiusY, 1);
expect(rrect.brRadiusX, 2);
expect(rrect.brRadiusY, 2);
rrect = rrect.inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 1);
expect(rrect.brRadiusY, 1);
rrect = rrect.inflate(-1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 0);
expect(rrect.brRadiusY, 0);
});
test('RRect.deflate clamps when deflating past zero', () {
RRect rrect = RRect.fromRectAndCorners(
const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0),
topLeft: const Radius.circular(1),
topRight: const Radius.circular(2),
bottomLeft: const Radius.circular(3),
bottomRight: const Radius.circular(4),
).deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 1);
expect(rrect.trRadiusY, 1);
expect(rrect.blRadiusX, 2);
expect(rrect.blRadiusY, 2);
expect(rrect.brRadiusX, 3);
expect(rrect.brRadiusY, 3);
rrect = rrect.deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 1);
expect(rrect.blRadiusY, 1);
expect(rrect.brRadiusX, 2);
expect(rrect.brRadiusY, 2);
rrect = rrect.deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 1);
expect(rrect.brRadiusY, 1);
rrect = rrect.deflate(1);
expect(rrect.tlRadiusX, 0);
expect(rrect.tlRadiusY, 0);
expect(rrect.trRadiusX, 0);
expect(rrect.trRadiusY, 0);
expect(rrect.blRadiusX, 0);
expect(rrect.blRadiusY, 0);
expect(rrect.brRadiusX, 0);
expect(rrect.brRadiusY, 0);
});
}
| engine/testing/dart/geometry_test.dart/0 | {
"file_path": "engine/testing/dart/geometry_test.dart",
"repo_id": "engine",
"token_count": 8494
} | 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.
import 'dart:isolate';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Invalid isolate URI', () async {
bool threw = false;
try {
await Isolate.spawnUri(
Uri.parse('http://127.0.0.1/foo.dart'),
<String>[],
null,
);
} on IsolateSpawnException {
threw = true;
}
expect(threw, true);
});
test('UI isolate API throws in a background isolate', () async {
void callUiApi(void message) {
PlatformDispatcher.instance.onReportTimings = (_) {};
}
final ReceivePort errorPort = ReceivePort();
await Isolate.spawn<void>(callUiApi, null, onError: errorPort.sendPort);
final List<dynamic> isolateError = await errorPort.first as List<dynamic>;
expect(isolateError[0], 'UI actions are only available on root isolate.');
});
}
| engine/testing/dart/isolate_test.dart/0 | {
"file_path": "engine/testing/dart/isolate_test.dart",
"repo_id": "engine",
"token_count": 373
} | 406 |
// Copyright 2024 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:ffi';
import 'dart:isolate';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('PlatformIsolate runOnPlatformThread, cancels pending jobs if shutdown', () async {
final Future<int> slowTask = runOnPlatformThread(() async {
await Future<void>.delayed(const Duration(seconds: 10));
return 123;
});
await runOnPlatformThread(() {
_forceShutdownIsolate();
Future<void>(() => Isolate.exit());
});
bool throws = false;
try {
await slowTask;
} catch (error) {
expect(error.toString(), contains('PlatformIsolate shutdown unexpectedly'));
throws = true;
}
expect(throws, true);
// Platform isolate automatically restarts.
final int result = await runOnPlatformThread(() => 123);
expect(result, 123);
});
}
@Native<Void Function()>(symbol: 'ForceShutdownIsolate')
external void _forceShutdownIsolate();
| engine/testing/dart/platform_isolate_shutdown_test.dart/0 | {
"file_path": "engine/testing/dart/platform_isolate_shutdown_test.dart",
"repo_id": "engine",
"token_count": 381
} | 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.
#include "flutter/testing/dart_isolate_runner.h"
#include <utility>
#include "flutter/runtime/isolate_configuration.h"
namespace flutter {
namespace testing {
AutoIsolateShutdown::AutoIsolateShutdown(std::shared_ptr<DartIsolate> isolate,
fml::RefPtr<fml::TaskRunner> runner)
: isolate_(std::move(isolate)), runner_(std::move(runner)) {}
AutoIsolateShutdown::~AutoIsolateShutdown() {
if (!isolate_->IsShuttingDown()) {
Shutdown();
}
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(runner_, [this, &latch]() {
// Delete isolate on thread.
isolate_.reset();
latch.Signal();
});
latch.Wait();
}
void AutoIsolateShutdown::Shutdown() {
if (!IsValid()) {
return;
}
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
runner_, [isolate = isolate_.get(), &latch]() {
if (!isolate->Shutdown()) {
FML_LOG(ERROR) << "Could not shutdown isolate.";
FML_CHECK(false);
}
latch.Signal();
});
latch.Wait();
}
[[nodiscard]] bool AutoIsolateShutdown::RunInIsolateScope(
const std::function<bool(void)>& closure) {
if (!IsValid()) {
return false;
}
bool result = false;
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
runner_, [this, &result, &latch, closure]() {
tonic::DartIsolateScope scope(isolate_->isolate());
tonic::DartApiScope api_scope;
if (closure) {
result = closure();
}
latch.Signal();
});
latch.Wait();
return result;
}
std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolateOnUITaskRunner(
DartVMRef& vm_ref,
const Settings& p_settings,
const TaskRunners& task_runners,
std::string entrypoint,
const std::vector<std::string>& args,
const std::string& kernel_file_path,
fml::WeakPtr<IOManager> io_manager,
const std::shared_ptr<VolatilePathTracker>& volatile_path_tracker,
std::unique_ptr<PlatformConfiguration> platform_configuration) {
FML_CHECK(task_runners.GetUITaskRunner()->RunsTasksOnCurrentThread());
if (!vm_ref) {
return nullptr;
}
auto vm_data = vm_ref.GetVMData();
if (!vm_data) {
return nullptr;
}
auto settings = p_settings;
if (!DartVM::IsRunningPrecompiledCode()) {
if (!fml::IsFile(kernel_file_path)) {
FML_LOG(ERROR) << "Could not locate kernel file.";
return nullptr;
}
auto kernel_file = fml::OpenFile(kernel_file_path.c_str(), false,
fml::FilePermission::kRead);
if (!kernel_file.is_valid()) {
FML_LOG(ERROR) << "Kernel file descriptor was invalid.";
return nullptr;
}
auto kernel_mapping = std::make_unique<fml::FileMapping>(kernel_file);
if (kernel_mapping->GetMapping() == nullptr) {
FML_LOG(ERROR) << "Could not set up kernel mapping.";
return nullptr;
}
settings.application_kernels = fml::MakeCopyable(
[kernel_mapping = std::move(kernel_mapping)]() mutable -> Mappings {
Mappings mappings;
mappings.emplace_back(std::move(kernel_mapping));
return mappings;
});
}
auto isolate_configuration =
IsolateConfiguration::InferFromSettings(settings);
UIDartState::Context context(task_runners);
context.io_manager = std::move(io_manager);
context.advisory_script_uri = "main.dart";
context.advisory_script_entrypoint = entrypoint.c_str();
context.enable_impeller = p_settings.enable_impeller;
auto isolate =
DartIsolate::CreateRunningRootIsolate(
settings, // settings
vm_data->GetIsolateSnapshot(), // isolate snapshot
std::move(platform_configuration), // platform configuration
DartIsolate::Flags{}, // flags
nullptr, // root isolate create callback
settings.isolate_create_callback, // isolate create callback
settings.isolate_shutdown_callback, // isolate shutdown callback
entrypoint, // entrypoint
std::nullopt, // library
args, // args
std::move(isolate_configuration), // isolate configuration
context // engine context
)
.lock();
if (!isolate) {
FML_LOG(ERROR) << "Could not create running isolate.";
return nullptr;
}
return std::make_unique<AutoIsolateShutdown>(
isolate, context.task_runners.GetUITaskRunner());
}
std::unique_ptr<AutoIsolateShutdown> RunDartCodeInIsolate(
DartVMRef& vm_ref,
const Settings& settings,
const TaskRunners& task_runners,
std::string entrypoint,
const std::vector<std::string>& args,
const std::string& kernel_file_path,
fml::WeakPtr<IOManager> io_manager,
std::shared_ptr<VolatilePathTracker> volatile_path_tracker,
std::unique_ptr<PlatformConfiguration> platform_configuration) {
std::unique_ptr<AutoIsolateShutdown> result;
fml::AutoResetWaitableEvent latch;
fml::TaskRunner::RunNowOrPostTask(
task_runners.GetUITaskRunner(), fml::MakeCopyable([&]() mutable {
result = RunDartCodeInIsolateOnUITaskRunner(
vm_ref, settings, task_runners, entrypoint, args, kernel_file_path,
io_manager, volatile_path_tracker,
std::move(platform_configuration));
latch.Signal();
}));
latch.Wait();
return result;
}
} // namespace testing
} // namespace flutter
| engine/testing/dart_isolate_runner.cc/0 | {
"file_path": "engine/testing/dart_isolate_runner.cc",
"repo_id": "engine",
"token_count": 2397
} | 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.
import 'dart:async';
import 'dart:collection';
import 'dart:isolate';
import 'package:async_helper/async_helper.dart';
import 'package:async_helper/async_minitest.dart';
import 'package:litetest/src/test.dart';
import 'package:litetest/src/test_suite.dart';
Future<void> main() async {
asyncStart();
test('skip', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test', () {
expect(1, equals(1));
}, skip: true);
final bool result = await lifecycle.result;
expect(result, true);
expect(buffer.toString(), equals(
'Test "Test": Skipped\nAll tests skipped.\n',
));
});
test('test', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test', () {
expect(1, equals(1));
});
final bool result = await lifecycle.result;
expect(result, true);
expect(buffer.toString(), equals(
'Test "Test": Started\nTest "Test": Passed\n',
));
});
test('multiple tests', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test1', () {
expect(1, equals(1));
});
ts.test('Test2', () {
expect(2, equals(2));
});
ts.test('Test3', () {
expect(3, equals(3));
});
final bool result = await lifecycle.result;
expect(result, true);
expect(buffer.toString(), equals('''
Test "Test1": Started
Test "Test1": Passed
Test "Test2": Started
Test "Test2": Passed
Test "Test3": Started
Test "Test3": Passed
''',
));
});
test('multiple tests with failure', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test1', () {
expect(1, equals(1));
});
ts.test('Test2', () {
expect(2, equals(3));
});
ts.test('Test3', () {
expect(3, equals(3));
});
final bool result = await lifecycle.result;
final String output = buffer.toString();
expect(result, false);
expect(output.contains('Test "Test1": Started'), true);
expect(output.contains('Test "Test1": Passed'), true);
expect(output.contains('Test "Test2": Started'), true);
expect(output.contains('Test "Test2": Failed'), true);
expect(output.contains(
'In test "Test2" Expect.deepEquals(expected: <3>, actual: <2>) fails.',
), true);
expect(output.contains('Test "Test3": Started'), true);
expect(output.contains('Test "Test3": Passed'), true);
});
test('test fail', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test', () {
expect(1, equals(2));
});
final bool result = await lifecycle.result;
final String output = buffer.toString();
expect(result, false);
expect(output.contains('Test "Test": Started'), true);
expect(output.contains('Test "Test": Failed'), true);
expect(
output.contains(
'In test "Test" Expect.deepEquals(expected: <2>, actual: <1>) fails.',
),
true,
);
});
test('async test', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test', () async {
final Completer<void> completer = Completer<void>();
Timer.run(() {
completer.complete();
});
await completer.future;
expect(1, equals(1));
});
final bool result = await lifecycle.result;
expect(result, true);
expect(buffer.toString(), equals(
'Test "Test": Started\nTest "Test": Passed\n',
));
});
test('async test fail', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test', () async {
final Completer<void> completer = Completer<void>();
Timer.run(() {
completer.complete();
});
await completer.future;
expect(1, equals(2));
});
final bool result = await lifecycle.result;
final String output = buffer.toString();
expect(result, false);
expect(output.contains('Test "Test": Started'), true);
expect(output.contains('Test "Test": Failed'), true);
expect(
output.contains(
'In test "Test" Expect.deepEquals(expected: <2>, actual: <1>) fails.',
),
true,
);
});
test('throws StateError on async test() call', () async {
final StringBuffer buffer = StringBuffer();
final TestLifecycle lifecycle = TestLifecycle();
final TestSuite ts = TestSuite(
logger: buffer,
lifecycle: lifecycle,
);
ts.test('Test', () {
expect(1, equals(1));
});
bool caughtError = false;
try {
await Future<void>(() async {
ts.test('Bad Test', () {});
});
} on StateError catch (e) {
caughtError = true;
expect(e.message.contains(
'Test "Bad Test" added after tests have started to run.',
), true);
}
expect(caughtError, true);
final bool result = await lifecycle.result;
expect(result, true);
expect(buffer.toString(), equals(
'Test "Test": Started\nTest "Test": Passed\n',
));
});
asyncEnd();
}
class TestLifecycle implements Lifecycle {
final ReceivePort port = ReceivePort();
final Completer<bool> _testCompleter = Completer<bool>();
Future<bool> get result => _testCompleter.future;
@override
void onStart() {}
@override
void onDone(Queue<Test> tests) {
bool testsSucceeded = true;
for (final Test t in tests) {
testsSucceeded = testsSucceeded && (t.state == TestState.succeeded);
}
_testCompleter.complete(testsSucceeded);
port.close();
}
}
| engine/testing/litetest/test/litetest_test.dart/0 | {
"file_path": "engine/testing/litetest/test/litetest_test.dart",
"repo_id": "engine",
"token_count": 2531
} | 409 |
# Scenario App: Android Tests and Test Runner
End-to-end tests and test infrastructure for the Flutter engine on Android.
> [!IMPORTANT]
> There are several **known issues** with this test suite:
>
> - [#144407](https://github.com/flutter/flutter/issues/144407): "Newer Android"
> tests are missing expected cropping and rotation.
> - [#144365](https://github.com/flutter/flutter/issues/144365): Tests that use
> `ExternalTextureFlutterActivity` sometimes do not render.
> - [#144232](https://github.com/flutter/flutter/issues/144232): Impeller Vulkan
> sometimes hangs on emulators.
> - [#144352](https://github.com/flutter/flutter/issues/144352): Skia Gold
> sometimes is missing expected diffs.
---
Top topics covered in this document include (but are not limited to):
- [Running the Tests](#running-the-tests)
- [Contributing](#contributing)
- [Project History](#project-history)
- [Troubleshooting](#troubleshooting)
- [Getting Help](#getting-help)
## Introduction
This package simulates a Flutter app that uses the engine (`dart:ui`) only, in
conjunction with Android-specific embedding code that simulates the use of the
engine in a real app (such as plugins and platform views).
A custom test runner, [`run_android_tests.dart`](bin/run_android_tests.dart), is
used to run the tests on a connected device or emulator, and report the results,
including screenshots (golden files) and logs from `adb logcat`.
In the following architecture diagram:
> <a
> href="https://github.com/flutter/flutter/wiki/The-Engine-architecture"
> title="The Engine architecture"> <img
> width="300"
> alt="Anatomy of a Flutter app"
> src="https://raw.githubusercontent.com/flutter/engine/main/docs/app_anatomy.svg"
> /> </a>
- The Dart app is represented by [`lib/main.dart`](../lib/main.dart).
- There is no framework code.
- `dart:ui` and the engine are the same as in a real app.
- Android-specific application code is in this directory
([`android/`](./)).
- The runner is a _custom_ test runner,
[`run_android_tests.dart`](bin/run_android_tests.dart).
### Scope of Testing
The tests in this package are end-to-end tests that _specifically_ exercise the
engine and Android-specific embedding code. They are not [unit tests][1] for the
engine or the framework, and are not designed to test the behavior of the
framework or specific plugins, but rather to simulate the use of a framework
or plugins downstream of the engine.
In other words, we test "does the engine work on Android?" without a dependency
on either the Flutter framework, Flutter tooling, or any specific plugins.
[1]: ../../../shell/platform/android
### Golden Comparisons
Many of the Android-specific interactions with the engine are visual, such as
[external textures](https://api.flutter.dev/flutter/widgets/Texture-class.html)
or [platform views](https://docs.flutter.dev/platform-integration/android/platform-views),
and as such, the tests in this package use golden screenshot file comparisons to
verify the correctness of the engine's output.
For example, in [`ExternalTextureTests_testMediaSurface`](https://flutter-engine-gold.skia.org/search?corpus=flutter-engine&include_ignored=false&left_filter=name%3DExternalTextureTests_testMediaSurface&max_rgba=0&min_rgba=0&negative=true¬_at_head=false&positive=true&reference_image_required=false&right_filter=&sort=descending&untriaged=true), a [video](app/src/main/assets/sample.mp4) is converted to an external texture and displayed in a Flutter app. The test takes a screenshot of the app and compares it to a golden file:
<img
alt="Two pictures, the top one Flutter and the bottom Android"
src="https://github.com/flutter/flutter/assets/168174/e2c34b88-d03d-4732-87e4-a86c97d006c5"
width="300"
/>
_The top picture is the Flutter app, and the bottom picture is just Android._
See also:
- [`tools/compare_goldens`](../../../tools/compare_goldens).
## Prerequisites
If you've never worked in the `flutter/engine` repository before, you will
need to setup a development environment that is quite different from a typical
Flutter app or even working on the Flutter framework. It will take roughly
30 minutes to an hour to setup an environment, depending on your familiarity
with the tools and the speed of your internet connection.
See also:
- [Setting up the Engine](https://github.com/flutter/flutter/wiki/Setting-up-the-Engine-development-environment)
- [Rebuilding the Tests](#rebuilding-the-tests)
### Android SDK
It's highly recommended to use the engine's vendored Android SDK, which once
you have the engine set up, you can find at
`$ENGINE/src/third_party/android_tools/sdk`. Testing or running with other
versions of the SDK may work, but it's _not guaranteed_, and might have
different results.
Consider also placing this directory in the `ANDROID_HOME` environment variable:
```sh
export ANDROID_HOME=$ENGINE/src/third_party/android_tools/sdk
```
### Device or Emulator
The tests in this package require a connected device or emulator to run. The
device or emulator should be running the same version of Android as the CI
configuration (there are issues with crashes and other problems on older
emulators in particular).
> [!CAUTION]
>
> [#144561](https://github.com/flutter/flutter/issues/144561): The emulator
> vendored in the engine checkout is old and [has a known issue with Vulkan](https://github.com/flutter/flutter/issues/144232).
>
> If you're working locally, you can update your copy by running:
>
> ```sh
> $ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager --install emulator
> ```
### Additional Dependencies
While not required, it is **strongly recommended** to use an IDE such as
[Android Studio](https://developer.android.com/studio) when contributing to the
Android side of the test suite, as it will provide a better development
experience such as code completion, debugging, and more:
<img
width="500"
alt="Screenshot of Android Studio with Autocompletion"
src="https://github.com/flutter/flutter/assets/168174/79b685f5-8da7-4396-abe6-9baeb29d7ce3"
/>
> [!TIP]
>
> Android Studio is expected to work _out of the box_ in this directory.
>
> If you encounter any issues, please [file a bug](#getting-help).
## Running the Tests
The [test runner](../bin/run_android_tests.dart) is a Dart script that installs
the test app and test suite on a connected device or emulator, runs the tests,
and reports the results including screenshots (golden files) and logs from
`adb logcat`.
From the `$ENGINE/src/flutter` directory, run:
```sh
dart ./testing/scenario_app/bin/run_android_tests.dart
```
By default when run locally, the test runner:
- Uses the engine-wide default graphics backend for Android.
- Uses the last built Android-specific engine artifacts (i.e. `$ENGINE/src/out/android_*/`).
- Will not diff screenshots, but does save them to a logs directory.
### Rebuilding the Tests
If you've made changes to any file in `scenario_app`, incluing the Dart code
in `lib/` or the Android code in `android/`, you will need to rebuild the
tests before running them.
To rebuild the `scenario_app` for the `android_debug_unopt_arm64` variant:
```sh
ninja -C out/android_debug_unopt_arm64 scenario_app
```
See also:
- [Compiling the Engine](https://github.com/flutter/flutter/wiki/Compiling-the-engine)
### Common Options
A list of options can be found by running:
```sh
dart ./testing/scenario_app/bin/run_android_tests.dart --help
```
Frequently used options include:
- `--out-dir`: Which engine artifacts to use (e.g.
`--out-dir=../out/android_debug_unopt_arm64`).
- `--logs-dir`: Where to save full `adb logcat` logs and screenshots.
- `--[no]-enable-impeller`: Enables/disables use of the Impeller graphics
backend.
- `--impeller-backend`: Use a specific Impeller backend (e.g.
`--impeller-backend=opengles`).
- `--force-surface-producer-surface-texture`: Force the use of `SurfaceTexture`s
for plugin code that uses `SurfaceProducer`s. This instruments the same code
path that is used for Android API versions that are <= 28 without requiring
an older emulator or device.
- `--smoke-test=<full.class.Name>`: Runs a specific test, instead of all tests.
### Advanced Options
When debugging the runner itself, you can use the `--verbose` flag to see more
detailed output, including additional options such as configuring which binary
of `adb` to use:
```sh
dart ./testing/scenario_app/bin/run_android_tests.dart --help --verbose
```
See also:
- [`bin/utils/options.dart`](../bin/utils/options.dart).
### CI Configuration
See [`ci/builders`](../../../ci/builders) and grep for `run_android_tests.dart`:
```sh
grep -r run_android_tests.dart ci/builders
```
> [!NOTE]
> The Impeller OpenGLES backend tests are only run on staging (`bringup: true`)
> and as such are **non-blocking**. We expect to stabilize and run these tests
> as part of a wider release of the Impeller OpenGLES backend.
#### Older Android
"Older Android" refers to "code paths to support older Android API levels".
Specifically, these configurations use
`--force-surface-producer-surface-texture` (see [above](#common-options) for
details).
| Backend | CI Configuration | CI History | Skia Gold |
| ----------------- | --------------------------- | ---------------------------------------------- | ------------------------- |
| Skia | [`ci/builders`][skia-st-ci] | [Presubmit][skia-try], [Postsubmit][skia-prod] | [Skia Gold][skia-st-gold] |
| Impeller OpenGLES | [`ci/builders`][imp-st-ci] | [Staging][imp-staging] | N/A |
[skia-try]: https://ci.chromium.org/ui/p/flutter/builders/try/Linux%20linux_android_emulator_skia_tests
[skia-prod]: https://ci.chromium.org/ui/p/flutter/builders/prod/Linux%20linux_android_emulator_skia_tests
[imp-staging]: https://ci.chromium.org/ui/p/flutter/builders/staging/Linux%20linux_android_emulator_opengles_tests
[impeller-try]: https://ci.chromium.org/ui/p/flutter/builders/try/Linux%20linux_android_emulator_tests
[impeller-prod]: https://ci.chromium.org/ui/p/flutter/builders/prod/Linux%20linux_android_emulator_tests
[skia-st-ci]: https://github.com/search?q=repo%3Aflutter%2Fengine+path%3Aci%2Fbuilders+%22--no-enable-impeller%22+%22run_android_tests.dart%22+%22--force-surface-producer-surface-texture%22&type=code
[skia-st-gold]: https://flutter-engine-gold.skia.org/search?left_filter=ForceSurfaceProducerSurfaceTexture%3Dtrue%26GraphicsBackend%3Dskia&negative=true&positive=true&right_filter=AndroidAPILevel%3D34%26GraphicsBackend%3Dskia
[imp-st-ci]: https://github.com/search?q=repo%3Aflutter%2Fengine+path%3Aci%2Fbuilders+%22--impeller-backend%3Dopengles%22+%22run_android_tests.dart%22+%22--force-surface-producer-surface-texture%22&type=code
[imp-st-gold]: https://flutter-engine-gold.skia.org/search?left_filter=ForceSurfaceProducerSurfaceTexture%3Dtrue%26GraphicsBackend%3Dimpeller-opengles&negative=true&positive=true&right_filter=AndroidAPILevel%3D34%26GraphicsBackend%3Dskia
#### Newer Android
| Backend | CI Configuration | CI History | Skia Gold |
| ----------------- | ---------------------------- | ------------------------------------------------------ | ------------------------ |
| Skia | [`ci/builders`][skia-ci] | [Presubmit][skia-try], [Postsubmit][skia-prod] | [Skia Gold][skia-gold] |
| Impeller OpenGLES | [`ci/builders`][imp-gles-ci] | [Staging][imp-staging] | N/A |
| Impeller Vulkan | [`ci/builders`][imp-vk-ci] | [Presubmit][impeller-try], [Postsubmit][impeller-prod] | [Skia Gold][imp-vk-gold] |
[skia-ci]: https://github.com/search?q=repo%3Aflutter%2Fengine+path%3Aci%2Fbuilders+%22--no-enable-impeller%22+%22run_android_tests.dart%22&type=code
[skia-gold]: https://flutter-engine-gold.skia.org/search?left_filter=ForceSurfaceProducerSurfaceTexture%3Dfalse%26GraphicsBackend%3Dskia&negative=true&positive=true&right_filter=AndroidAPILevel%3D34%26GraphicsBackend%3Dskia
[imp-gles-ci]: https://github.com/search?q=repo%3Aflutter%2Fengine+path%3Aci%2Fbuilders+%22--impeller-backend%3Dopengles%22+%22run_android_tests.dart%22&type=code
[imp-vk-ci]: https://github.com/search?q=repo%3Aflutter%2Fengine+path%3Aci%2Fbuilders+%22--impeller-backend%3Dvulkan%22+%22run_android_tests.dart%22&type=code
[imp-vk-gold]: https://flutter-engine-gold.skia.org/search?left_filter=ForceSurfaceProducerSurfaceTexture%3Dfalse%26GraphicsBackend%3Dimpeller-vulkan&negative=true&positive=true&right_filter=AndroidAPILevel%3D34%26GraphicsBackend%3Dskia
## Contributing
[](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3A%22e%3A+scenario-app%22)
Contributions to this package are welcome, as it is a critical part of the
engine's test suite.
### Anatomy of a Test
A "test" in practice is a combination of roughly 3 components:
1. An Android _[JUnit test][]_ that configures and launches an Android activity.
2. An Android _[activity][]_, which simulates the Android side of a plugin or
platform view.
3. A Dart _[scenario][]_, which simulates the Flutter side of an application.
[junit test]: ./app/src/androidTest/java/dev/flutter/scenariosui/DrawSolidBlueScreenTest.java
[activity]: ./app/src/main/java/dev/flutter/scenarios/ExternalTextureFlutterActivity.java
[scenario]: ../lib/src/solid_blue.dart
While every test suite has exactly one JUnit-instrumented class, each test can
have many activities and scenarios, each with their own configuration, setup,
and assertions. Not all of this is desirable, but it is the current state of
the test suite.
A test might also take a screenshot. See the _Skia Gold_ links in
[CI Configuration](#ci-configuration) for examples.
### Project History
This test suite was [originally written in 2019](https://github.com/flutter/engine/pull/10007)
with a goal of:
> \[being\] suitable for embedders to do integration testing with - it has no
> dependencies on the flutter_tools or framework, and so will not fail/flake
> based on variances in those downstream.
Unfortunately, the Android side of the test suite was never fully operational,
and the tests, even if failing, were accidentally be reported as passing on CI.
In 2024, as the team got closer to shipping our new graphics backend,
[Impeller](https://docs.flutter.dev/perf/impeller) on Android, it was clear that
we needed a reliable test suite for the engine on Android, particularly for
visual tests around external textures and platform views.
So, this package was revived and updated to be a (more) reliable test suite for
the engine on Android. It's by no means complete
([contributions welcome](#contributing)), but it did successfully catch at least
one bug that would not have been detected automatically otherwise.
_Go forth and test the engine on Android!_
## Troubleshooting
If you encounter any issues, please [file a bug](#getting-help).
### My test is failing on CI
If a test is failing on CI, it's likely that the test is failing locally as
well. Try the steps in [running the Tests](#running-the-tests) to reproduce the
failure locally, and then debug the failure as you would any other test. If this
is your first time working on the engine, you may need to setup a development
environment first (see [prerequisites](#prerequisites)).
The test runner makes extensive use of logging and screenshots to help debug
failures. If you're not sure where to start, try looking at the logs and
screenshots to see if they provide any clues (you'll need them to file a bug
anyway).
`test: Android Scenario App Integration Tests (Impeller/Vulkan)`
on [LUCI](https://ci.chromium.org/ui/p/flutter/builders/try/Linux%20Engine%20Drone/2079486/overview) produces these logs:

The files include a screenshot of each test, and a _full_ logcat log from the
device (you might find it easier trying the `stdout` of the test first, which
uses rudimentary log filtering). In the case of multiple runs, the logs are
prefixed with the test configuration and run attempt.
## Getting Help
To suggest changes, or highlight problems, please [file an issue](https://github.com/flutter/flutter/issues/new?labels=e:%20scenario-app,engine,platform-android,fyi-android,team-engine).
If you're not sure where to start, or need help debugging or contributing, you
can also reach out to [`hackers-android`](https://discord.com/channels/608014603317936148/846507907876257822) on Discord, or the Flutter engine team internally. There is
no full-time maintainer of this package, so be prepared to do some of the
legwork yourself.
| engine/testing/scenario_app/android/README.md/0 | {
"file_path": "engine/testing/scenario_app/android/README.md",
"repo_id": "engine",
"token_count": 5502
} | 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.
package dev.flutter.scenarios;
import android.content.Context;
import android.graphics.Color;
import android.view.Choreographer;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.plugin.common.MessageCodec;
import io.flutter.plugin.common.StringCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
import java.nio.ByteBuffer;
public final class TextPlatformViewFactory extends PlatformViewFactory {
TextPlatformViewFactory() {
super(
new MessageCodec<Object>() {
@Nullable
@Override
public ByteBuffer encodeMessage(@Nullable Object o) {
if (o instanceof String) {
return StringCodec.INSTANCE.encodeMessage((String) o);
}
return null;
}
@Nullable
@Override
public Object decodeMessage(@Nullable ByteBuffer byteBuffer) {
return StringCodec.INSTANCE.decodeMessage(byteBuffer);
}
});
}
@SuppressWarnings("unchecked")
@Override
@NonNull
public PlatformView create(@NonNull Context context, int id, @Nullable Object args) {
String params = (String) args;
return new TextPlatformView(context, id, params);
}
private static class TextPlatformView implements PlatformView {
final TextView textView;
@SuppressWarnings("unchecked")
TextPlatformView(@NonNull final Context context, int id, @Nullable String params) {
textView = new TextView(context);
textView.setTextSize(72);
textView.setBackgroundColor(Color.WHITE);
textView.setText(params);
// Investigate why this is needed to pass some gold tests.
Choreographer.getInstance()
.postFrameCallbackDelayed(
new Choreographer.FrameCallback() {
@Override
public void doFrame(long frameTimeNanos) {
textView.invalidate();
}
},
500);
}
@Override
@NonNull
public View getView() {
return textView;
}
@Override
public void dispose() {}
}
}
| engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TextPlatformViewFactory.java/0 | {
"file_path": "engine/testing/scenario_app/android/app/src/main/java/dev/flutter/scenarios/TextPlatformViewFactory.java",
"repo_id": "engine",
"token_count": 922
} | 411 |
import 'dart:io' as io;
import 'package:args/args.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as p;
import 'environment.dart';
/// Command line options and parser for the Android `scenario_app` test runner.
extension type const Options._(ArgResults _args) {
/// Parses the command line [args] into a set of options.
///
/// Throws a [FormatException] if command line arguments are invalid.
factory Options.parse(
List<String> args, {
required Environment environment,
required Engine? localEngine,
}) {
final ArgResults results = _parser(environment, localEngine).parse(args);
final Options options = Options._(results);
// The 'adb' tool must exist.
if (results['adb'] == null) {
throw const FormatException('The --adb option must be set.');
} else if (!io.File(options.adb).existsSync()) {
throw FormatException(
'The adb tool does not exist at ${options.adb}.',
);
}
// The 'ndk-stack' tool must exist.
if (results['ndk-stack'] == null) {
throw const FormatException('The --ndk-stack option must be set.');
} else if (!io.File(options.ndkStack).existsSync()) {
throw FormatException(
'The ndk-stack tool does not exist at ${options.ndkStack}.',
);
}
// The 'out-dir' must exist.
if (results['out-dir'] == null) {
throw const FormatException('The --out-dir option must be set.');
} else if (!io.Directory(options.outDir).existsSync()) {
throw FormatException(
'The out directory does not exist at ${options.outDir}.',
);
}
// Cannot use forceSurfaceProducerSurfaceTexture with Impeller+Vulkan.
if (options.forceSurfaceProducerSurfaceTexture &&
options.enableImpeller &&
options.impellerBackend != 'opengles') {
throw const FormatException(
'Cannot use --force-surface-producer-surface-texture with '
'--enable-impeller unless --impeller-backend="opengles" is used. See '
'https://github.com/flutter/flutter/issues/143539 for details.',
);
}
return options;
}
/// Whether usage information should be shown based on command line [args].
///
/// This is a shortcut that can be used to determine if the usage information
/// before parsing the remaining command line arguments. For example:
///
/// ```
/// void main(List<String> args) {
/// if (Options.showUsage(args)) {
/// stdout.writeln(Options.usage);
/// return;
/// }
/// final options = Options.parse(args);
/// // ...
/// }
/// ```
static bool showUsage(List<String> args) {
// If any of the arguments are '--help' or -'h'.
return args.isNotEmpty && args.any((String arg) {
return arg == '--help' || arg == '-h';
});
}
/// Whether verbose logging should be enabled based on command line [args].
///
/// This is a shortcut that can be used to determine if verbose logging should
/// be enabled before parsing the remaining command line arguments. For
/// example:
///
/// ```
/// void main(List<String> args) {
/// final bool verbose = Options.showVerbose(args);
/// // ...
/// }
/// ```
static bool showVerbose(List<String> args) {
// If any of the arguments are '--verbose' or -'v'.
return args.isNotEmpty && args.any((String arg) {
return arg == '--verbose' || arg == '-v';
});
}
/// Returns usage information for the `scenario_app` test runner.
///
/// If [verbose] is `true`, then additional options are shown.
static String usage({
required Environment environment,
required Engine? localEngineDir,
}) {
return _parser(environment, localEngineDir).usage;
}
/// Parses the command line [args] into a set of options.
///
/// Unlike [_miniParser], this parser includes all options.
static ArgParser _parser(Environment environment, Engine? localEngine) {
final bool hideUnusualOptions = !environment.showVerbose;
return ArgParser(usageLineLength: 120)
..addFlag(
'verbose',
abbr: 'v',
help: 'Enable verbose logging',
negatable: false,
)
..addFlag(
'help',
abbr: 'h',
help: 'Print usage information',
negatable: false,
)
..addFlag(
'use-skia-gold',
help:
'Whether to use Skia Gold to compare screenshots. Defaults to true '
'on CI and false otherwise.',
defaultsTo: environment.isCi,
hide: hideUnusualOptions,
)
..addFlag(
'enable-impeller',
help:
'Whether to enable Impeller as the graphics backend. If true, the '
'test runner will use --impeller-backend if set, otherwise the '
'default backend will be used. To explicitly run with the Skia '
'backend, set this to false (--no-enable-impeller).',
)
..addFlag(
'force-surface-producer-surface-texture',
help:
'Whether to force the use of SurfaceTexture as the SurfaceProducer '
'rendering strategy. This is used to emulate the behavior of older '
'devices that do not support ImageReader, or to explicitly test '
'SurfaceTexture path for rendering plugins still using the older '
'createSurfaceTexture() API.'
'\n'
'Cannot be used with --enable-impeller unless --impeller-backend='
'"opengles" is used. See '
'https://github.com/flutter/flutter/issues/143539 for details.',
negatable: false
)
..addFlag(
'prefix-logs-per-run',
help: 'Whether to prefix logs with a per-run unique identifier.',
defaultsTo: environment.isCi,
hide: hideUnusualOptions,
)
..addOption(
'impeller-backend',
help: 'The graphics backend to use when --enable-impeller is true. '
'Unlike the similar option when launching an app, there is no '
'fallback; that is, either Vulkan or OpenGLES must be specified. ',
allowed: <String>['vulkan', 'opengles'],
defaultsTo: 'vulkan',
)
..addOption(
'logs-dir',
help: 'Path to a directory where logs and screenshots are stored.',
defaultsTo: environment.logsDir,
)
..addOption(
'adb',
help: 'Path to the Android Debug Bridge (adb) executable. '
'If the current working directory is within the engine repository, '
'defaults to ./third_party/android_tools/sdk/platform-tools/adb.',
defaultsTo: localEngine != null
? p.join(
localEngine.srcDir.path,
'third_party',
'android_tools',
'sdk',
'platform-tools',
'adb',
)
: null,
valueHelp: 'path/to/adb',
hide: hideUnusualOptions,
)
..addOption(
'ndk-stack',
help:
'Path to the NDK stack tool. Defaults to the checked-in version in '
'third_party/android_tools if the current working directory is '
'within the engine repository on a supported platform.',
defaultsTo: localEngine != null &&
(io.Platform.isLinux ||
io.Platform.isMacOS ||
io.Platform.isWindows)
? p.join(
localEngine.srcDir.path,
'third_party',
'android_tools',
'ndk',
'prebuilt',
() {
if (io.Platform.isLinux) {
return 'linux-x86_64';
} else if (io.Platform.isMacOS) {
return 'darwin-x86_64';
} else if (io.Platform.isWindows) {
return 'windows-x86_64';
} else {
// Unreachable.
throw UnsupportedError(
'Unsupported platform: ${io.Platform.operatingSystem}',
);
}
}(),
'bin',
'ndk-stack',
)
: null,
valueHelp: 'path/to/ndk-stack',
hide: hideUnusualOptions,
)
..addOption(
'out-dir',
help: 'Path to a out/{variant} directory where the APKs are built. '
'Defaults to the latest updated out/ directory that starts with '
'"android_" if the current working directory is within the engine '
'repository.',
defaultsTo: environment.isCi ? null : localEngine
?.outputs()
.where((Output o) => p.basename(o.path.path).startsWith('android_'))
.firstOrNull
?.path
.path,
mandatory: environment.isCi,
valueHelp: 'path/to/out/android_variant',
)
..addOption(
'smoke-test',
help: 'Fully qualified class name of a single test to run. For example '
'try "dev.flutter.scenarios.EngineLaunchE2ETest" or '
'"dev.flutter.scenariosui.ExternalTextureTests".',
valueHelp: 'package.ClassName',
)
..addOption(
'output-contents-golden',
help: 'Path to a file that contains the expected filenames of golden '
'files. If the current working directory is within the engine '
'repository, defaults to ./testing/scenario_app/android/'
'expected_golden_output.txt.',
defaultsTo: localEngine != null
? p.join(
localEngine.flutterDir.path,
'testing',
'scenario_app',
'android',
'expected_golden_output.txt',
)
: null,
valueHelp: 'path/to/golden.txt',
);
}
/// Whether verbose logging should be enabled.
bool get verbose => _args['verbose'] as bool;
/// Whether usage information should be shown.
bool get help => _args['help'] as bool;
/// Whether to use Skia Gold to compare screenshots.
bool get useSkiaGold => _args['use-skia-gold'] as bool;
/// Whether to enable Impeller as the graphics backend.
bool get enableImpeller => _args['enable-impeller'] as bool;
/// The graphics backend to use when --enable-impeller is true.
String get impellerBackend => _args['impeller-backend'] as String;
/// Path to a directory where logs and screenshots are stored.
String get logsDir {
final String? logsDir = _args['logs-dir'] as String?;
return logsDir ?? p.join(outDir, 'logs');
}
/// Path to the Android Debug Bridge (adb) executable.
String get adb => _args['adb'] as String;
/// Path to the NDK stack tool.
String get ndkStack => _args['ndk-stack'] as String;
/// Path to a out/{variant} directory where the APKs are built.
String get outDir => _args['out-dir'] as String;
/// Fully qualified class name of a single test to run.
String? get smokeTest => _args['smoke-test'] as String?;
/// Path to a file that contains the expected filenames of golden files.
String? get outputContentsGolden => _args['output-contents-golden'] as String;
/// Whether to force the use of `SurfaceTexture` for `SurfaceProducer`.
///
/// Always returns `false` if `--enable-impeller` is `true` and
/// `--impeller-backend` is not `opengles`.
bool get forceSurfaceProducerSurfaceTexture {
if (enableImpeller && impellerBackend != 'opengles') {
return false;
}
return _args['force-surface-producer-surface-texture'] as bool;
}
/// Whether to prefix logs with a per-run unique identifier.
bool get prefixLogsPerRun => _args['prefix-logs-per-run'] as bool;
}
| engine/testing/scenario_app/bin/utils/options.dart/0 | {
"file_path": "engine/testing/scenario_app/bin/utils/options.dart",
"repo_id": "engine",
"token_count": 4897
} | 412 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
<key>UISceneConfigurations</key>
<dict>
<key>UIWindowSceneSessionRoleApplication</key>
<array>
<dict>
<key>UISceneConfigurationName</key>
<string>Default Configuration</string>
<key>UISceneDelegateClassName</key>
<string>SceneDelegate</string>
<key>UISceneStoryboardFile</key>
<string>Main</string>
</dict>
</array>
</dict>
</dict>
</dict>
</plist>
| engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/Info.plist/0 | {
"file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/Info.plist",
"repo_id": "engine",
"token_count": 307
} | 413 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "TextPlatformView.h"
@protocol TestGestureRecognizerDelegate <NSObject>
- (void)gestureTouchesBegan;
- (void)gestureTouchesEnded;
@end
@interface TestTapGestureRecognizer : UITapGestureRecognizer
@property(weak, nonatomic)
NSObject<TestGestureRecognizerDelegate>* testTapGestureRecognizerDelegate;
@end
@implementation TestTapGestureRecognizer
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
[self.testTapGestureRecognizerDelegate gestureTouchesBegan];
[super touchesBegan:touches withEvent:event];
}
- (void)touchesEnded:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
[self.testTapGestureRecognizerDelegate gestureTouchesEnded];
[super touchesEnded:touches withEvent:event];
}
@end
@implementation TextPlatformViewFactory {
NSObject<FlutterBinaryMessenger>* _messenger;
}
- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
self = [super init];
if (self) {
_messenger = messenger;
}
return self;
}
- (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args {
TextPlatformView* textPlatformView = [[TextPlatformView alloc] initWithFrame:frame
viewIdentifier:viewId
arguments:args
binaryMessenger:_messenger];
return textPlatformView;
}
- (NSObject<FlutterMessageCodec>*)createArgsCodec {
return [FlutterStringCodec sharedInstance];
}
@end
@interface TextPlatformView () <TestGestureRecognizerDelegate>
@end
@implementation TextPlatformView {
UIView* _containerView;
UITextView* _textView;
FlutterMethodChannel* _channel;
BOOL _viewCreated;
}
- (instancetype)initWithFrame:(CGRect)frame
viewIdentifier:(int64_t)viewId
arguments:(id _Nullable)args
binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
if ([super init]) {
_containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250, 100)];
_containerView.backgroundColor = UIColor.lightGrayColor;
_containerView.clipsToBounds = YES;
_containerView.accessibilityIdentifier = @"platform_view";
_textView = [[UITextView alloc] initWithFrame:CGRectMake(50.0, 50.0, 250, 100)];
_textView.backgroundColor = UIColor.lightGrayColor;
_textView.textColor = UIColor.blueColor;
[_textView setFont:[UIFont systemFontOfSize:52]];
_textView.text = args;
_textView.autoresizingMask =
(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[_containerView addSubview:_textView];
TestTapGestureRecognizer* gestureRecognizer =
[[TestTapGestureRecognizer alloc] initWithTarget:self action:@selector(platformViewTapped)];
[_textView addGestureRecognizer:gestureRecognizer];
gestureRecognizer.testTapGestureRecognizerDelegate = self;
_textView.accessibilityLabel = @"";
_viewCreated = NO;
}
return self;
}
- (UIView*)view {
// Makes sure the engine only calls this method once.
if (_viewCreated) {
abort();
}
_viewCreated = YES;
return _containerView;
}
- (void)platformViewTapped {
_textView.accessibilityLabel =
[_textView.accessibilityLabel stringByAppendingString:@"-platformViewTapped"];
}
- (void)gestureTouchesBegan {
_textView.accessibilityLabel =
[_textView.accessibilityLabel stringByAppendingString:@"-gestureTouchesBegan"];
}
- (void)gestureTouchesEnded {
_textView.accessibilityLabel =
[_textView.accessibilityLabel stringByAppendingString:@"-gestureTouchesEnded"];
}
@end
| engine/testing/scenario_app/ios/Scenarios/Scenarios/TextPlatformView.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/TextPlatformView.m",
"repo_id": "engine",
"token_count": 1615
} | 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.
#import "GoldenImage.h"
#import <XCTest/XCTest.h>
#import <os/log.h>
#include <sys/sysctl.h>
@interface GoldenImage ()
@end
@implementation GoldenImage
- (instancetype)initWithGoldenNamePrefix:(NSString*)prefix {
self = [super init];
if (self) {
_goldenName = [prefix stringByAppendingString:_platformName()];
NSBundle* bundle = [NSBundle bundleForClass:[self class]];
NSURL* goldenURL = [bundle URLForResource:_goldenName withExtension:@"png"];
NSData* data = [NSData dataWithContentsOfURL:goldenURL];
_image = [[UIImage alloc] initWithData:data];
}
return self;
}
- (BOOL)compareGoldenToImage:(UIImage*)image rmesThreshold:(double)rmesThreshold {
if (!self.image || !image) {
os_log_error(OS_LOG_DEFAULT, "GOLDEN DIFF FAILED: image does not exists.");
return NO;
}
CGImageRef imageRefA = [self.image CGImage];
CGImageRef imageRefB = [image CGImage];
NSUInteger widthA = CGImageGetWidth(imageRefA);
NSUInteger heightA = CGImageGetHeight(imageRefA);
NSUInteger widthB = CGImageGetWidth(imageRefB);
NSUInteger heightB = CGImageGetHeight(imageRefB);
if (widthA != widthB || heightA != heightB) {
os_log_error(OS_LOG_DEFAULT, "GOLDEN DIFF FAILED: images sizes do not match.");
return NO;
}
NSUInteger bytesPerPixel = 4;
NSUInteger size = widthA * heightA * bytesPerPixel;
NSMutableData* rawA = [NSMutableData dataWithLength:size];
NSMutableData* rawB = [NSMutableData dataWithLength:size];
if (!rawA || !rawB) {
os_log_error(OS_LOG_DEFAULT, "GOLDEN DIFF FAILED: image data length do not match.");
return NO;
}
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
NSUInteger bytesPerRow = bytesPerPixel * widthA;
NSUInteger bitsPerComponent = 8;
CGContextRef contextA =
CGBitmapContextCreate(rawA.mutableBytes, widthA, heightA, bitsPerComponent, bytesPerRow,
colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGContextDrawImage(contextA, CGRectMake(0, 0, widthA, heightA), imageRefA);
CGContextRelease(contextA);
CGContextRef contextB =
CGBitmapContextCreate(rawB.mutableBytes, widthA, heightA, bitsPerComponent, bytesPerRow,
colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(contextB, CGRectMake(0, 0, widthA, heightA), imageRefB);
CGContextRelease(contextB);
const char* apos = rawA.mutableBytes;
const char* bpos = rawB.mutableBytes;
double sum = 0.0;
for (size_t i = 0; i < size; ++i, ++apos, ++bpos) {
// Skip transparent pixels.
if (*apos == 0 && *bpos == 0 && i % 4 == 0) {
i += 3;
apos += 3;
bpos += 3;
} else {
double aval = *apos;
double bval = *bpos;
double diff = aval - bval;
sum += diff * diff;
}
}
double rmse = sqrt(sum / size);
if (rmse > rmesThreshold) {
os_log_error(
OS_LOG_DEFAULT,
"GOLDEN DIFF FAILED: image diff greater than threshold. Current diff: %@, threshold: %@",
@(rmse), @(rmesThreshold));
return NO;
}
return YES;
}
NS_INLINE NSString* _platformName() {
NSString* systemVersion = UIDevice.currentDevice.systemVersion;
NSString* simulatorName =
[[NSProcessInfo processInfo].environment objectForKey:@"SIMULATOR_DEVICE_NAME"];
if (simulatorName) {
return [NSString stringWithFormat:@"%@_%@_simulator", simulatorName, systemVersion];
}
size_t size;
sysctlbyname("hw.model", NULL, &size, NULL, 0);
char* answer = malloc(size);
sysctlbyname("hw.model", answer, &size, NULL, 0);
NSString* results = [NSString stringWithUTF8String:answer];
free(answer);
return results;
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenImage.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenImage.m",
"repo_id": "engine",
"token_count": 1476
} | 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.
import 'dart:ui';
import 'scenario.dart';
/// Shows a text that is shown in app extension.
class DarwinAppExtensionScenario extends Scenario {
/// Creates the DarwinAppExtensionScenario scenario.
DarwinAppExtensionScenario(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())
..pushStyle(TextStyle(fontSize: 80))
..addText('flutter Scenarios app extension.')
..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();
}
}
| engine/testing/scenario_app/lib/src/darwin_app_extension_scenario.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/src/darwin_app_extension_scenario.dart",
"repo_id": "engine",
"token_count": 423
} | 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.
import 'dart:io' as io;
// It's bad to import a file from `bin` into `tool`.
// However this tool is not very important, so delete it if necessary.
import '../bin/utils/adb_logcat_filtering.dart';
/// A tiny tool to read saved `adb logcat` output and perform some analysis.
///
/// This tool is not meant to be a full-fledged logcat reader. It's just a
/// simple tool that uses the [AdbLogLine] extension type to parse results of
/// `adb logcat` and explain what log tag names are most common.
void main(List<String> args) {
if (args case [final String path]) {
final List<AdbLogLine> parsed = io.File(path)
.readAsLinesSync()
.map(AdbLogLine.tryParse)
.whereType<AdbLogLine>()
// Filter out all debug logs.
.where((AdbLogLine line) => line.severity != 'D')
.toList();
final Map<String, int> tagCounts = <String, int>{};
for (final AdbLogLine line in parsed) {
tagCounts[line.name] = (tagCounts[line.name] ?? 0) + 1;
}
// Print in order of most common to least common.
final List<MapEntry<String, int>> sorted = tagCounts.entries.toList()
..sort((MapEntry<String, int> a, MapEntry<String, int> b) => b.value.compareTo(a.value));
for (final MapEntry<String, int> entry in sorted) {
print("'${entry.key}', // ${entry.value}");
}
return;
}
print('Usage: logcat_reader.dart <path-to-logcat-output>');
io.exitCode = 1;
}
| engine/testing/scenario_app/tool/logcat_reader.dart/0 | {
"file_path": "engine/testing/scenario_app/tool/logcat_reader.dart",
"repo_id": "engine",
"token_count": 583
} | 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/testing/test_metal_surface_impl.h"
#include <Metal/Metal.h>
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "flutter/testing/test_metal_context.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkRefCnt.h"
#include "third_party/skia/include/core/SkSize.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GpuTypes.h"
#include "third_party/skia/include/gpu/GrBackendSurface.h"
#include "third_party/skia/include/gpu/ganesh/SkSurfaceGanesh.h"
namespace flutter {
void TestMetalSurfaceImpl::Init(const TestMetalContext::TextureInfo& texture_info,
const SkISize& surface_size) {
id<MTLTexture> texture = (__bridge id<MTLTexture>)texture_info.texture;
GrMtlTextureInfo skia_texture_info;
skia_texture_info.fTexture.reset([texture retain]);
GrBackendTexture backend_texture(surface_size.width(), surface_size.height(),
skgpu::Mipmapped::kNo, skia_texture_info);
sk_sp<SkSurface> surface = SkSurfaces::WrapBackendTexture(
test_metal_context_.GetSkiaContext().get(), backend_texture, kTopLeft_GrSurfaceOrigin, 1,
kBGRA_8888_SkColorType, nullptr, nullptr);
if (!surface) {
FML_LOG(ERROR) << "Could not create Skia surface from a Metal texture.";
return;
}
surface_ = std::move(surface);
texture_info_ = texture_info;
is_valid_ = true;
}
TestMetalSurfaceImpl::TestMetalSurfaceImpl(const TestMetalContext& test_metal_context,
int64_t texture_id,
const SkISize& surface_size)
: test_metal_context_(test_metal_context) {
TestMetalContext::TextureInfo texture_info =
const_cast<TestMetalContext&>(test_metal_context_).GetTextureInfo(texture_id);
Init(texture_info, surface_size);
}
TestMetalSurfaceImpl::TestMetalSurfaceImpl(const TestMetalContext& test_metal_context,
const SkISize& surface_size)
: test_metal_context_(test_metal_context) {
if (surface_size.isEmpty()) {
FML_LOG(ERROR) << "Size of test Metal surface was empty.";
return;
}
TestMetalContext::TextureInfo texture_info =
const_cast<TestMetalContext&>(test_metal_context_).CreateMetalTexture(surface_size);
Init(texture_info, surface_size);
}
sk_sp<SkImage> TestMetalSurfaceImpl::GetRasterSurfaceSnapshot() {
if (!IsValid()) {
return nullptr;
}
if (!surface_) {
FML_LOG(ERROR) << "Aborting snapshot because of on-screen surface "
"acquisition failure.";
return nullptr;
}
auto device_snapshot = surface_->makeImageSnapshot();
if (!device_snapshot) {
FML_LOG(ERROR) << "Could not create the device snapshot while attempting "
"to snapshot the Metal surface.";
return nullptr;
}
auto host_snapshot = device_snapshot->makeRasterImage();
if (!host_snapshot) {
FML_LOG(ERROR) << "Could not create the host snapshot while attempting to "
"snapshot the Metal surface.";
return nullptr;
}
return host_snapshot;
}
// |TestMetalSurface|
TestMetalSurfaceImpl::~TestMetalSurfaceImpl() = default;
// |TestMetalSurface|
bool TestMetalSurfaceImpl::IsValid() const {
return is_valid_;
}
// |TestMetalSurface|
sk_sp<GrDirectContext> TestMetalSurfaceImpl::GetGrContext() const {
return IsValid() ? test_metal_context_.GetSkiaContext() : nullptr;
}
// |TestMetalSurface|
sk_sp<SkSurface> TestMetalSurfaceImpl::GetSurface() const {
return IsValid() ? surface_ : nullptr;
}
// |TestMetalSurface|
TestMetalContext::TextureInfo TestMetalSurfaceImpl::GetTextureInfo() {
return IsValid() ? texture_info_ : TestMetalContext::TextureInfo();
}
} // namespace flutter
| engine/testing/test_metal_surface_impl.mm/0 | {
"file_path": "engine/testing/test_metal_surface_impl.mm",
"repo_id": "engine",
"token_count": 1588
} | 418 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_ACTIVE_POPUP_H_
#define UI_ACCESSIBILITY_AX_ACTIVE_POPUP_H_
#include <optional>
#include "ax/ax_export.h"
#include "base/macros.h"
namespace ui {
AX_EXPORT std::optional<int32_t> GetActivePopupAxUniqueId();
AX_EXPORT void SetActivePopupAxUniqueId(std::optional<int32_t> ax_unique_id);
AX_EXPORT void ClearActivePopupAxUniqueId();
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_ACTIVE_POPUP_H_
| engine/third_party/accessibility/ax/ax_active_popup.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_active_popup.h",
"repo_id": "engine",
"token_count": 223
} | 419 |
// 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 UI_ACCESSIBILITY_AX_MODE_H_
#define UI_ACCESSIBILITY_AX_MODE_H_
#include <cstdint>
#include <ostream>
#include <string>
#include "ax_base_export.h"
namespace ui {
class AX_BASE_EXPORT AXMode {
public:
static constexpr uint32_t kFirstModeFlag = 1 << 0;
// Native accessibility APIs, specific to each platform, are enabled.
// When this mode is set that indicates the presence of a third-party
// client accessing Chrome via accessibility APIs. However, unless one
// of the modes below is set, the contents of web pages will not be
// accessible.
static constexpr uint32_t kNativeAPIs = 1 << 0;
// The renderer process will generate an accessibility tree containing
// basic information about all nodes, including role, name, value,
// state, and location. This is the minimum mode required in order for
// web contents to be accessible, and the remaining modes are meaningless
// unless this one is set.
//
// Note that sometimes this mode will be set when kNativeAPI is not, when the
// content layer embedder is providing accessibility support via some other
// mechanism other than what's implemented in content/browser.
static constexpr uint32_t kWebContents = 1 << 1;
// The accessibility tree will contain inline text boxes, which are
// necessary to expose information about line breaks and word boundaries.
// Without this mode, you can retrieve the plaintext value of a text field
// but not the information about how it's broken down into lines.
//
// Note that when this mode is off it's still possible to request inline
// text boxes for a specific node on-demand, asynchronously.
static constexpr uint32_t kInlineTextBoxes = 1 << 2;
// The accessibility tree will contain extra accessibility
// attributes typically only needed by screen readers and other
// assistive technology for blind users. Examples include text style
// attributes, table cell information, live region properties, range
// values, and relationship attributes.
static constexpr uint32_t kScreenReader = 1 << 3;
// The accessibility tree will contain the HTML tag name and HTML attributes
// for all accessibility nodes that come from web content.
static constexpr uint32_t kHTML = 1 << 4;
// The accessibility tree will contain automatic image annotations.
static constexpr uint32_t kLabelImages = 1 << 5;
// The accessibility tree will contain enough information to export
// an accessible PDF.
static constexpr uint32_t kPDF = 1 << 6;
// Update this to include the last supported mode flag. If you add
// another, be sure to update the stream insertion operator for
// logging and debugging.
static constexpr uint32_t kLastModeFlag = 1 << 6;
constexpr AXMode() : flags_(0) {}
constexpr AXMode(uint32_t flags) : flags_(flags) {}
bool has_mode(uint32_t flag) const { return (flags_ & flag) > 0; }
void set_mode(uint32_t flag, bool value) {
flags_ = value ? (flags_ | flag) : (flags_ & ~flag);
}
uint32_t mode() const { return flags_; }
bool operator==(AXMode rhs) const { return flags_ == rhs.flags_; }
bool is_mode_off() const { return flags_ == 0; }
bool operator!=(AXMode rhs) const { return !(*this == rhs); }
AXMode& operator|=(const AXMode& rhs) {
flags_ |= rhs.flags_;
return *this;
}
std::string ToString() const;
private:
uint32_t flags_;
};
static constexpr AXMode kAXModeWebContentsOnly(AXMode::kWebContents |
AXMode::kInlineTextBoxes |
AXMode::kScreenReader |
AXMode::kHTML);
static constexpr AXMode kAXModeComplete(AXMode::kNativeAPIs |
AXMode::kWebContents |
AXMode::kInlineTextBoxes |
AXMode::kScreenReader | AXMode::kHTML);
// For debugging, test assertions, etc.
AX_BASE_EXPORT std::ostream& operator<<(std::ostream& stream,
const AXMode& mode);
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_MODE_H_
| engine/third_party/accessibility/ax/ax_mode.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_mode.h",
"repo_id": "engine",
"token_count": 1442
} | 420 |
// 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.
#include "ax_relative_bounds.h"
#include <cmath>
#include "ax_enum_util.h"
#include "base/string_utils.h"
using base::NumberToString;
namespace ui {
AXRelativeBounds::AXRelativeBounds() : offset_container_id(-1) {}
AXRelativeBounds::~AXRelativeBounds() {}
AXRelativeBounds::AXRelativeBounds(const AXRelativeBounds& other) {
offset_container_id = other.offset_container_id;
bounds = other.bounds;
if (other.transform)
transform = std::make_unique<gfx::Transform>(*other.transform);
}
AXRelativeBounds& AXRelativeBounds::operator=(AXRelativeBounds other) {
offset_container_id = other.offset_container_id;
bounds = other.bounds;
if (other.transform)
transform = std::make_unique<gfx::Transform>(*other.transform);
else
transform.reset(nullptr);
return *this;
}
bool AXRelativeBounds::operator==(const AXRelativeBounds& other) const {
if (offset_container_id != other.offset_container_id)
return false;
if (bounds != other.bounds)
return false;
if (!transform && !other.transform)
return true;
if ((transform && !other.transform) || (!transform && other.transform))
return false;
return *transform == *other.transform;
}
bool AXRelativeBounds::operator!=(const AXRelativeBounds& other) const {
return !operator==(other);
}
std::string AXRelativeBounds::ToString() const {
std::string result;
if (offset_container_id != -1)
result += "offset_container_id=" +
NumberToString(static_cast<int>(round(offset_container_id))) +
" ";
result += "(" + NumberToString(static_cast<int>(round(bounds.x()))) + ", " +
NumberToString(static_cast<int>(round(bounds.y()))) + ")-(" +
NumberToString(static_cast<int>(round(bounds.width()))) + ", " +
NumberToString(static_cast<int>(round(bounds.height()))) + ")";
if (transform && !transform->IsIdentity())
result += " transform=" + transform->ToString();
return result;
}
std::ostream& operator<<(std::ostream& stream, const AXRelativeBounds& bounds) {
return stream << bounds.ToString();
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_relative_bounds.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_relative_bounds.cc",
"repo_id": "engine",
"token_count": 798
} | 421 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_AX_TREE_MANAGER_H_
#define UI_ACCESSIBILITY_AX_TREE_MANAGER_H_
#include "ax_export.h"
#include "ax_node.h"
#include "ax_tree.h"
#include "ax_tree_id.h"
namespace ui {
// Abstract interface for a class that owns an AXTree and manages its
// connections to other AXTrees in the same page or desktop (parent and child
// trees).
class AX_EXPORT AXTreeManager {
public:
virtual ~AXTreeManager() = default;
// Returns the AXNode with the given |node_id| from the tree that has the
// given |tree_id|. This allows for callers to access nodes outside of their
// own tree. Returns nullptr if |tree_id| or |node_id| is not found.
virtual AXNode* GetNodeFromTree(const AXTreeID tree_id,
const AXNode::AXID node_id) const = 0;
// Returns the AXNode in the current tree that has the given |node_id|.
// Returns nullptr if |node_id| is not found.
virtual AXNode* GetNodeFromTree(const AXNode::AXID node_id) const = 0;
// Returns the tree id of the tree managed by this AXTreeManager.
virtual AXTreeID GetTreeID() const = 0;
// Returns the tree id of the parent tree.
// Returns AXTreeIDUnknown if this tree doesn't have a parent tree.
virtual AXTreeID GetParentTreeID() const = 0;
// Returns the AXNode that is at the root of the current tree.
virtual AXNode* GetRootAsAXNode() const = 0;
// If this tree has a parent tree, returns the node in the parent tree that
// hosts the current tree. Returns nullptr if this tree doesn't have a parent
// tree.
virtual AXNode* GetParentNodeFromParentTreeAsAXNode() const = 0;
virtual AXTree* GetTree() const = 0;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_TREE_MANAGER_H_
| engine/third_party/accessibility/ax/ax_tree_manager.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_manager.h",
"repo_id": "engine",
"token_count": 622
} | 422 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_H_
#include <cstdint>
#include <map>
#include <memory>
#include <new>
#include <ostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "ax/ax_clipping_behavior.h"
#include "ax/ax_coordinate_system.h"
#include "ax/ax_enums.h"
#include "ax/ax_export.h"
#include "ax/ax_node_position.h"
#include "ax/ax_offscreen_result.h"
#include "ax/ax_position.h"
#include "ax/ax_tree.h"
#include "ax/ax_tree_id.h"
#include "ax_unique_id.h"
#include "base/macros.h"
#include "gfx/geometry/rect.h"
#include "gfx/native_widget_types.h"
namespace ui {
struct AXActionData;
struct AXNodeData;
struct AXTreeData;
class AXPlatformNode;
using TextAttribute = std::pair<std::string, std::string>;
using TextAttributeList = std::vector<TextAttribute>;
// A TextAttributeMap is a map between the text offset in UTF-16 characters in
// the node hypertext and the TextAttributeList that starts at that location.
// An empty TextAttributeList signifies a return to the default node
// TextAttributeList.
using TextAttributeMap = std::map<int, TextAttributeList>;
// An object that wants to be accessible should derive from this class.
// AXPlatformNode subclasses use this interface to query all of the information
// about the object in order to implement native accessibility APIs.
//
// Note that AXPlatformNode has support for accessibility trees where some
// of the objects in the tree are not implemented using AXPlatformNode.
// For example, you may have a native window with platform-native widgets
// in it, but in that window you have custom controls that use AXPlatformNode
// to provide accessibility. That's why GetParent, ChildAtIndex, HitTestSync,
// and GetFocus all return a gfx::NativeViewAccessible - so you can return a
// native accessible if necessary, and AXPlatformNode::GetNativeViewAccessible
// otherwise.
class AX_EXPORT AXPlatformNodeDelegate {
public:
virtual ~AXPlatformNodeDelegate() = default;
// Get the accessibility data that should be exposed for this node.
// Virtually all of the information is obtained from this structure
// (role, state, name, cursor position, etc.) - the rest of this interface
// is mostly to implement support for walking the accessibility tree.
virtual const AXNodeData& GetData() const = 0;
// Get the accessibility tree data for this node.
virtual const AXTreeData& GetTreeData() const = 0;
// 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.
virtual std::u16string GetInnerText() const = 0;
// Get the unignored selection from the tree
virtual const AXTree::Selection GetUnignoredSelection() const = 0;
// Creates a text position rooted at this object.
virtual AXNodePosition::AXPositionInstance CreateTextPositionAt(
int offset) const = 0;
// Get the accessibility node for the NSWindow the node is contained in. This
// method is only meaningful on macOS.
virtual gfx::NativeViewAccessible GetNSWindow() = 0;
// Get the node for this delegate, which may be an AXPlatformNode or it may
// be a native accessible object implemented by another class.
virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0;
// Get the parent of the node, which may be an AXPlatformNode or it may
// be a native accessible object implemented by another class.
virtual gfx::NativeViewAccessible GetParent() = 0;
// Get the index in parent. Typically this is the AXNode's index_in_parent_.
// This should return -1 if the index in parent is unknown.
virtual int GetIndexInParent() = 0;
// Get the number of children of this node.
virtual int GetChildCount() const = 0;
// Get the child of a node given a 0-based index.
virtual gfx::NativeViewAccessible ChildAtIndex(int index) = 0;
// Returns true if it has a modal dialog.
virtual bool HasModalDialog() const = 0;
// Gets the first child of a node, or nullptr if no children exist.
virtual gfx::NativeViewAccessible GetFirstChild() = 0;
// Gets the last child of a node, or nullptr if no children exist.
virtual gfx::NativeViewAccessible GetLastChild() = 0;
// Gets the next sibling of a given node, or nullptr if no such node exists.
virtual gfx::NativeViewAccessible GetNextSibling() = 0;
// Gets the previous sibling of a given node, or nullptr if no such node
// exists.
virtual gfx::NativeViewAccessible GetPreviousSibling() = 0;
// Returns true if an ancestor of this node (not including itself) is a
// leaf node, meaning that this node is not actually exposed to any
// platform's accessibility layer.
virtual bool IsChildOfLeaf() const = 0;
// Returns true if this current node is editable and the root editable node is
// a plain text field.
virtual bool IsChildOfPlainTextField() const = 0;
// Returns true if this is a leaf node, meaning all its
// children should not be exposed to any platform's native accessibility
// layer.
virtual bool IsLeaf() const = 0;
// Returns true if this is a top-level browser window that doesn't have a
// parent accessible node, or its parent is the application accessible node on
// platforms that have one.
virtual bool IsToplevelBrowserWindow() = 0;
// If this object is exposed to the platform's accessibility layer, returns
// this object. Otherwise, returns the platform leaf under which this object
// is found.
virtual gfx::NativeViewAccessible GetClosestPlatformObject() const = 0;
class ChildIterator {
public:
virtual ~ChildIterator() = default;
virtual bool operator==(const ChildIterator& rhs) const = 0;
virtual bool operator!=(const ChildIterator& rhs) const = 0;
virtual void operator++() = 0;
virtual void operator++(int) = 0;
virtual void operator--() = 0;
virtual void operator--(int) = 0;
virtual gfx::NativeViewAccessible GetNativeViewAccessible() const = 0;
virtual int GetIndexInParent() const = 0;
virtual AXPlatformNodeDelegate& operator*() const = 0;
virtual AXPlatformNodeDelegate* operator->() const = 0;
};
virtual std::unique_ptr<AXPlatformNodeDelegate::ChildIterator>
ChildrenBegin() = 0;
virtual std::unique_ptr<AXPlatformNodeDelegate::ChildIterator>
ChildrenEnd() = 0;
// Returns the accessible name for the node.
virtual std::string GetName() const = 0;
// Returns the text of this node and represent the text of descendant nodes
// with a special character in place of every embedded object. This represents
// the concept of text in ATK and IA2 APIs.
virtual std::u16string GetHypertext() const = 0;
// Set the selection in the hypertext of this node. Depending on the
// implementation, this may mean the new selection will span multiple nodes.
virtual bool SetHypertextSelection(int start_offset, int end_offset) = 0;
// Compute the text attributes map for the node associated with this
// delegate, given a set of default text attributes that apply to the entire
// node. A text attribute map associates a list of text attributes with a
// given hypertext offset in this node.
virtual TextAttributeMap ComputeTextAttributeMap(
const TextAttributeList& default_attributes) const = 0;
// Get the inherited font family name for text attributes. We need this
// because inheritance works differently between the different delegate
// implementations.
virtual std::string GetInheritedFontFamilyName() const = 0;
// Return the bounds of this node in the coordinate system indicated. If the
// clipping behavior is set to clipped, clipping is applied. If an offscreen
// result address is provided, it will be populated depending on whether the
// returned bounding box is onscreen or offscreen.
virtual gfx::Rect GetBoundsRect(
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result = nullptr) const = 0;
virtual gfx::Rect GetClippedScreenBoundsRect(
AXOffscreenResult* offscreen_result = nullptr) const = 0;
// Return the bounds of the text range given by text offsets relative to
// GetHypertext in the coordinate system indicated. If the clipping behavior
// is set to clipped, clipping is applied. If an offscreen result address is
// provided, it will be populated depending on whether the returned bounding
// box is onscreen or offscreen.
virtual gfx::Rect GetHypertextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result = nullptr) const = 0;
// Return the bounds of the text range given by text offsets relative to
// GetInnerText in the coordinate system indicated. If the clipping behavior
// is set to clipped, clipping is applied. If an offscreen result address is
// provided, it will be populated depending on whether the returned bounding
// box is onscreen or offscreen.
virtual gfx::Rect GetInnerTextRangeBoundsRect(
const int start_offset,
const int end_offset,
const AXCoordinateSystem coordinate_system,
const AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result = nullptr) const = 0;
// Do a *synchronous* hit test of the given location in global screen physical
// pixel coordinates, and the node within this node's subtree (inclusive)
// that's hit, if any.
//
// If the result is anything other than this object or NULL, it will be
// hit tested again recursively - that allows hit testing to work across
// implementation classes. It's okay to take advantage of this and return
// only an immediate child and not the deepest descendant.
//
// This function is mainly used by accessibility debugging software.
// Platforms with touch accessibility use a different asynchronous interface.
virtual gfx::NativeViewAccessible HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const = 0;
// Return the node within this node's subtree (inclusive) that currently has
// focus, or return nullptr if this subtree is not connected to the top
// document through its ancestry chain.
virtual gfx::NativeViewAccessible GetFocus() = 0;
// Get whether this node is offscreen.
virtual bool IsOffscreen() const = 0;
// Get whether this node is a minimized window.
virtual bool IsMinimized() const = 0;
// See AXNode::IsText().
virtual bool IsText() const = 0;
// Get whether this node is in web content.
virtual bool IsWebContent() const = 0;
// Returns true if the caret or selection is visible on this object.
virtual bool HasVisibleCaretOrSelection() const = 0;
// Get another node from this same tree.
virtual AXPlatformNode* GetFromNodeID(int32_t id) = 0;
// Get a node from a different tree using a tree ID and node ID.
// Note that this is only guaranteed to work if the other tree is of the
// same type, i.e. it won't work between web and views or vice-versa.
virtual AXPlatformNode* GetFromTreeIDAndNodeID(const ui::AXTreeID& ax_tree_id,
int32_t id) = 0;
// Given a node ID attribute (one where IsNodeIdIntAttribute is true), return
// a target nodes for which this delegate's node has that relationship
// attribute or NULL if there is no such relationship.
virtual AXPlatformNode* GetTargetNodeForRelation(
ax::mojom::IntAttribute attr) = 0;
// Given a node ID attribute (one where IsNodeIdIntListAttribute is true),
// return a vector of all target nodes for which this delegate's node has that
// relationship attribute.
virtual std::vector<AXPlatformNode*> GetTargetNodesForRelation(
ax::mojom::IntListAttribute attr) = 0;
// Given a node ID attribute (one where IsNodeIdIntAttribute is true), return
// a set of all source nodes that have that relationship attribute between
// them and this delegate's node.
virtual std::set<AXPlatformNode*> GetReverseRelations(
ax::mojom::IntAttribute attr) = 0;
// Given a node ID list attribute (one where IsNodeIdIntListAttribute is
// true), return a set of all source nodes that have that relationship
// attribute between them and this delegate's node.
virtual std::set<AXPlatformNode*> GetReverseRelations(
ax::mojom::IntListAttribute attr) = 0;
// Return the string representation of the unique ID assigned by the author,
// otherwise return an empty string. The author ID must be persistent across
// any instance of the application, regardless of locale. The author ID should
// be unique among sibling accessibility nodes and is best if unique across
// the application, however, not meeting this requirement is non-fatal.
virtual std::u16string GetAuthorUniqueId() const = 0;
virtual const AXUniqueId& GetUniqueId() const = 0;
// Finds the previous or next offset from the provided offset, that matches
// the provided boundary type.
//
// This method finds text boundaries in the text used for platform text APIs.
// Implementations may use side-channel data such as line or word indices to
// produce appropriate results. It may optionally return no value, indicating
// that the delegate does not have all the information required to calculate
// this value and it is the responsibility of the AXPlatformNode itself to
// calculate it.
virtual std::optional<int> FindTextBoundary(
ax::mojom::TextBoundary boundary,
int offset,
ax::mojom::MoveDirection direction,
ax::mojom::TextAffinity affinity) const = 0;
// Return a vector of all the descendants of this delegate's node. This method
// is only meaningful for Windows UIA.
virtual const std::vector<gfx::NativeViewAccessible> GetUIADescendants()
const = 0;
// Return a string representing the language code.
//
// For web content, this will consider the language declared in the DOM, and
// may eventually attempt to automatically detect the language from the text.
//
// This language code will be BCP 47.
//
// Returns empty string if no appropriate language was found or if this node
// uses the default interface language.
virtual std::string GetLanguage() const = 0;
//
// Tables. All of these should be called on a node that's a table-like
// role, otherwise they return nullopt.
//
virtual bool IsTable() const = 0;
virtual std::optional<int> GetTableColCount() const = 0;
virtual std::optional<int> GetTableRowCount() const = 0;
virtual std::optional<int> GetTableAriaColCount() const = 0;
virtual std::optional<int> GetTableAriaRowCount() const = 0;
virtual std::optional<int> GetTableCellCount() const = 0;
virtual std::optional<bool> GetTableHasColumnOrRowHeaderNode() const = 0;
virtual std::vector<int32_t> GetColHeaderNodeIds() const = 0;
virtual std::vector<int32_t> GetColHeaderNodeIds(int col_index) const = 0;
virtual std::vector<int32_t> GetRowHeaderNodeIds() const = 0;
virtual std::vector<int32_t> GetRowHeaderNodeIds(int row_index) const = 0;
virtual AXPlatformNode* GetTableCaption() const = 0;
// Table row-like nodes.
virtual bool IsTableRow() const = 0;
virtual std::optional<int> GetTableRowRowIndex() const = 0;
// Table cell-like nodes.
virtual bool IsTableCellOrHeader() const = 0;
virtual std::optional<int> GetTableCellIndex() const = 0;
virtual std::optional<int> GetTableCellColIndex() const = 0;
virtual std::optional<int> GetTableCellRowIndex() const = 0;
virtual std::optional<int> GetTableCellColSpan() const = 0;
virtual std::optional<int> GetTableCellRowSpan() const = 0;
virtual std::optional<int> GetTableCellAriaColIndex() const = 0;
virtual std::optional<int> GetTableCellAriaRowIndex() const = 0;
virtual std::optional<int32_t> GetCellId(int row_index,
int col_index) const = 0;
virtual std::optional<int32_t> CellIndexToId(int cell_index) const = 0;
// Helper methods to check if a cell is an ARIA-1.1+ 'cell' or 'gridcell'
virtual bool IsCellOrHeaderOfARIATable() const = 0;
virtual bool IsCellOrHeaderOfARIAGrid() const = 0;
// Ordered-set-like and item-like nodes.
virtual bool IsOrderedSetItem() const = 0;
virtual bool IsOrderedSet() const = 0;
virtual std::optional<int> GetPosInSet() const = 0;
virtual std::optional<int> GetSetSize() const = 0;
//
// Events.
//
// Return the platform-native GUI object that should be used as a target
// for accessibility events.
virtual gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() = 0;
//
// Actions.
//
// Perform an accessibility action, switching on the ax::mojom::Action
// provided in |data|.
virtual bool AccessibilityPerformAction(const AXActionData& data) = 0;
//
// Localized strings.
//
virtual std::u16string GetLocalizedRoleDescriptionForUnlabeledImage()
const = 0;
virtual std::u16string GetLocalizedStringForImageAnnotationStatus(
ax::mojom::ImageAnnotationStatus status) const = 0;
virtual std::u16string GetLocalizedStringForLandmarkType() const = 0;
virtual std::u16string GetLocalizedStringForRoleDescription() const = 0;
virtual std::u16string GetStyleNameAttributeAsLocalizedString() const = 0;
//
// Testing.
//
// Accessibility objects can have the "hot tracked" state set when
// the mouse is hovering over them, but this makes tests flaky because
// the test behaves differently when the mouse happens to be over an
// element. The default value should be false if not in testing mode.
virtual bool ShouldIgnoreHoveredStateForTesting() = 0;
// If this object is exposed to the platform's accessibility layer, returns
// this object. Otherwise, returns the platform leaf or lowest unignored
// ancestor under which this object is found.
//
// (An ignored node means that the node should not be exposed to platform
// APIs: See `IsIgnored`.)
virtual gfx::NativeViewAccessible GetLowestPlatformAncestor() const = 0;
// Creates a string representation of this delegate's data.
std::string ToString() { return GetData().ToString(); }
// Returns a string representation of the subtree of delegates rooted at this
// delegate.
std::string SubtreeToString() { return SubtreeToStringHelper(0u); }
friend std::ostream& operator<<(std::ostream& stream,
AXPlatformNodeDelegate& delegate) {
return stream << delegate.ToString();
}
protected:
AXPlatformNodeDelegate() = default;
virtual std::string SubtreeToStringHelper(size_t level) = 0;
private:
BASE_DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeDelegate);
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node_delegate.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_delegate.h",
"repo_id": "engine",
"token_count": 5489
} | 423 |
// 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 UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_UNITTEST_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_UNITTEST_H_
#include "gtest/gtest.h"
#include "ax/ax_enums.h"
#include "ax/ax_node.h"
#include "ax/ax_node_data.h"
#include "ax/ax_tree_id.h"
#include "ax/ax_tree_update.h"
#include "ax/test_ax_tree_manager.h"
namespace ui {
class AXPlatformNodeTest : public testing::Test, public TestAXTreeManager {
public:
AXPlatformNodeTest();
~AXPlatformNodeTest() override;
AXPlatformNodeTest(const AXPlatformNodeTest&) = delete;
AXPlatformNodeTest& operator=(const AXPlatformNodeTest&) = delete;
protected:
// Initialize given an AXTreeUpdate.
void Init(const AXTreeUpdate& initial_state);
// Convenience functions to initialize directly from a few AXNodeData objects.
void Init(const ui::AXNodeData& node1,
const ui::AXNodeData& node2 = ui::AXNodeData(),
const ui::AXNodeData& node3 = ui::AXNodeData(),
const ui::AXNodeData& node4 = ui::AXNodeData(),
const ui::AXNodeData& node5 = ui::AXNodeData(),
const ui::AXNodeData& node6 = ui::AXNodeData(),
const ui::AXNodeData& node7 = ui::AXNodeData(),
const ui::AXNodeData& node8 = ui::AXNodeData(),
const ui::AXNodeData& node9 = ui::AXNodeData(),
const ui::AXNodeData& node10 = ui::AXNodeData(),
const ui::AXNodeData& node11 = ui::AXNodeData(),
const ui::AXNodeData& node12 = ui::AXNodeData());
AXTreeUpdate BuildTextField();
AXTreeUpdate BuildTextFieldWithSelectionRange(int32_t start, int32_t stop);
AXTreeUpdate BuildContentEditable();
AXTreeUpdate BuildContentEditableWithSelectionRange(int32_t start,
int32_t end);
AXTreeUpdate Build3X3Table();
AXTreeUpdate BuildAriaColumnAndRowCountGrids();
AXTreeUpdate BuildListBox(
bool option_1_is_selected,
bool option_2_is_selected,
bool option_3_is_selected,
const std::vector<ax::mojom::State>& additional_state);
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_UNITTEST_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node_unittest.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_unittest.h",
"repo_id": "engine",
"token_count": 953
} | 424 |
// 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_PLATFORM_UIA_REGISTRAR_WIN_H_
#define UI_ACCESSIBILITY_PLATFORM_UIA_REGISTRAR_WIN_H_
#include <objbase.h>
#include <uiautomation.h>
#include "ax/ax_export.h"
#include "base/macros.h"
#include "base/no_destructor.h"
namespace ui {
// {3761326A-34B2-465A-835D-7A3D8F4EFB92}
static const GUID kUiaEventTestCompleteSentinelGuid = {
0x3761326a,
0x34b2,
0x465a,
{0x83, 0x5d, 0x7a, 0x3d, 0x8f, 0x4e, 0xfb, 0x92}};
// {cc7eeb32-4b62-4f4c-aff6-1c2e5752ad8e}
static const GUID kUiaPropertyUniqueIdGuid = {
0xcc7eeb32,
0x4b62,
0x4f4c,
{0xaf, 0xf6, 0x1c, 0x2e, 0x57, 0x52, 0xad, 0x8e}};
class AX_EXPORT UiaRegistrarWin {
public:
UiaRegistrarWin();
~UiaRegistrarWin();
PROPERTYID GetUiaUniqueIdPropertyId() const;
EVENTID GetUiaTestCompleteEventId() const;
static const UiaRegistrarWin& GetInstance();
private:
PROPERTYID uia_unique_id_property_id_ = 0;
EVENTID uia_test_complete_event_id_ = 0;
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_UIA_REGISTRAR_WIN_H_
| engine/third_party/accessibility/ax/platform/uia_registrar_win.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/uia_registrar_win.h",
"repo_id": "engine",
"token_count": 562
} | 425 |
// 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_SHARED_IMPL_H_
#define BASE_NUMERICS_SAFE_MATH_SHARED_IMPL_H_
#include <cassert>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <type_traits>
#include "ax_build/build_config.h"
#include "base/numerics/safe_conversions.h"
#if defined(OS_ASMJS)
// Optimized safe math instructions are incompatible with asmjs.
#define BASE_HAS_OPTIMIZED_SAFE_MATH (0)
// Where available use builtin math overflow support on Clang and GCC.
#elif !defined(__native_client__) && \
((defined(__clang__) && \
((__clang_major__ > 3) || \
(__clang_major__ == 3 && __clang_minor__ >= 4))) || \
(defined(__GNUC__) && __GNUC__ >= 5))
#include "base/numerics/safe_math_clang_gcc_impl.h"
#define BASE_HAS_OPTIMIZED_SAFE_MATH (1)
#else
#define BASE_HAS_OPTIMIZED_SAFE_MATH (0)
#endif
namespace base {
namespace internal {
// These are the non-functioning boilerplate implementations of the optimized
// safe math routines.
#if !BASE_HAS_OPTIMIZED_SAFE_MATH
template <typename T, typename U>
struct CheckedAddFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct CheckedSubFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct CheckedMulFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr bool Do(T, U, V*) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<bool>();
}
};
template <typename T, typename U>
struct ClampedAddFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T, typename U>
struct ClampedSubFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T, typename U>
struct ClampedMulFastOp {
static const bool is_supported = false;
template <typename V>
static constexpr V Do(T, U) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<V>();
}
};
template <typename T>
struct ClampedNegFastOp {
static const bool is_supported = false;
static constexpr T Do(T) {
// Force a compile failure if instantiated.
return CheckOnFailure::template HandleFailure<T>();
}
};
#endif // BASE_HAS_OPTIMIZED_SAFE_MATH
#undef BASE_HAS_OPTIMIZED_SAFE_MATH
// This is used for UnsignedAbs, where we need to support floating-point
// template instantiations even though we don't actually support the operations.
// However, there is no corresponding implementation of e.g. SafeUnsignedAbs,
// so the float versions will not compile.
template <typename Numeric,
bool IsInteger = std::is_integral<Numeric>::value,
bool IsFloat = std::is_floating_point<Numeric>::value>
struct UnsignedOrFloatForSize;
template <typename Numeric>
struct UnsignedOrFloatForSize<Numeric, true, false> {
using type = typename std::make_unsigned<Numeric>::type;
};
template <typename Numeric>
struct UnsignedOrFloatForSize<Numeric, false, true> {
using type = Numeric;
};
// Wrap the unary operations to allow SFINAE when instantiating integrals versus
// floating points. These don't perform any overflow checking. Rather, they
// exhibit well-defined overflow semantics and rely on the caller to detect
// if an overflow occurred.
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr T NegateWrapper(T value) {
using UnsignedT = typename std::make_unsigned<T>::type;
// This will compile to a NEG on Intel, and is normal negation on ARM.
return static_cast<T>(UnsignedT(0) - static_cast<UnsignedT>(value));
}
template <
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr T NegateWrapper(T value) {
return -value;
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr typename std::make_unsigned<T>::type InvertWrapper(T value) {
return ~value;
}
template <typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
constexpr T AbsWrapper(T value) {
return static_cast<T>(SafeUnsignedAbs(value));
}
template <
typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* = nullptr>
constexpr T AbsWrapper(T value) {
return value < 0 ? -value : value;
}
template <template <typename, typename, typename> class M,
typename L,
typename R>
struct MathWrapper {
using math = M<typename UnderlyingType<L>::type,
typename UnderlyingType<R>::type,
void>;
using type = typename math::result_type;
};
// These variadic templates work out the return types.
// TODO(jschuh): Rip all this out once we have C++14 non-trailing auto support.
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
struct ResultType;
template <template <typename, typename, typename> class M,
typename L,
typename R>
struct ResultType<M, L, R> {
using type = typename MathWrapper<M, L, R>::type;
};
template <template <typename, typename, typename> class M,
typename L,
typename R,
typename... Args>
struct ResultType {
using type =
typename ResultType<M, typename ResultType<M, L, R>::type, Args...>::type;
};
// The following macros are just boilerplate for the standard arithmetic
// operator overloads and variadic function templates. A macro isn't the nicest
// solution, but it beats rewriting these over and over again.
#define BASE_NUMERIC_ARITHMETIC_VARIADIC(CLASS, CL_ABBR, OP_NAME) \
template <typename L, typename R, typename... Args> \
constexpr CLASS##Numeric< \
typename ResultType<CLASS##OP_NAME##Op, L, R, Args...>::type> \
CL_ABBR##OP_NAME(const L lhs, const R rhs, const Args... args) { \
return CL_ABBR##MathOp<CLASS##OP_NAME##Op, L, R, Args...>(lhs, rhs, \
args...); \
}
#define BASE_NUMERIC_ARITHMETIC_OPERATORS(CLASS, CL_ABBR, OP_NAME, OP, CMP_OP) \
/* Binary arithmetic operator for all CLASS##Numeric operations. */ \
template <typename L, typename R, \
typename std::enable_if<Is##CLASS##Op<L, R>::value>::type* = \
nullptr> \
constexpr CLASS##Numeric< \
typename MathWrapper<CLASS##OP_NAME##Op, L, R>::type> \
operator OP(const L lhs, const R rhs) { \
return decltype(lhs OP rhs)::template MathOp<CLASS##OP_NAME##Op>(lhs, \
rhs); \
} \
/* Assignment arithmetic operator implementation from CLASS##Numeric. */ \
template <typename L> \
template <typename R> \
constexpr CLASS##Numeric<L>& CLASS##Numeric<L>::operator CMP_OP( \
const R rhs) { \
return MathOp<CLASS##OP_NAME##Op>(rhs); \
} \
/* Variadic arithmetic functions that return CLASS##Numeric. */ \
BASE_NUMERIC_ARITHMETIC_VARIADIC(CLASS, CL_ABBR, OP_NAME)
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_MATH_SHARED_IMPL_H_
| engine/third_party/accessibility/base/numerics/safe_math_shared_impl.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/safe_math_shared_impl.h",
"repo_id": "engine",
"token_count": 3766
} | 426 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/win/enum_variant.h"
#include <wrl/client.h>
#include <algorithm>
#include "base/logging.h"
namespace base {
namespace win {
EnumVariant::EnumVariant(ULONG count) : current_index_(0) {
for (ULONG i = 0; i < count; ++i)
items_.emplace_back(ScopedVariant::kEmptyVariant);
}
EnumVariant::~EnumVariant() = default;
VARIANT* EnumVariant::ItemAt(ULONG index) {
BASE_DCHECK(index < items_.size());
// This is a hack to return a mutable pointer to the ScopedVariant, even
// though the original intent of the AsInput method was to allow only readonly
// access to the wrapped variant.
return items_[index].AsInput();
}
HRESULT EnumVariant::Next(ULONG requested_count,
VARIANT* out_elements,
ULONG* out_elements_received) {
if (!out_elements)
return E_INVALIDARG;
BASE_DCHECK(current_index_ <= items_.size());
ULONG available_count = static_cast<ULONG>(items_.size()) - current_index_;
ULONG count = std::min(requested_count, available_count);
for (ULONG i = 0; i < count; ++i)
out_elements[i] = items_[current_index_ + i].Copy();
current_index_ += count;
// The caller can choose not to get the number of received elements by setting
// |out_elements_received| to nullptr.
if (out_elements_received)
*out_elements_received = count;
return (count == requested_count ? S_OK : S_FALSE);
}
HRESULT EnumVariant::Skip(ULONG skip_count) {
ULONG count = skip_count;
if (current_index_ + count > static_cast<ULONG>(items_.size()))
count = static_cast<ULONG>(items_.size()) - current_index_;
current_index_ += count;
return (count == skip_count ? S_OK : S_FALSE);
}
HRESULT EnumVariant::Reset() {
current_index_ = 0;
return S_OK;
}
HRESULT EnumVariant::Clone(IEnumVARIANT** out_cloned_object) {
if (!out_cloned_object)
return E_INVALIDARG;
size_t count = items_.size();
Microsoft::WRL::ComPtr<EnumVariant> other =
Microsoft::WRL::Make<EnumVariant>(static_cast<ULONG>(count));
for (size_t i = 0; i < count; ++i)
other->items_[i] = static_cast<const VARIANT&>(items_[i]);
other->Skip(current_index_);
return other.CopyTo(IID_PPV_ARGS(out_cloned_object));
}
} // namespace win
} // namespace base
| engine/third_party/accessibility/base/win/enum_variant.cc/0 | {
"file_path": "engine/third_party/accessibility/base/win/enum_variant.cc",
"repo_id": "engine",
"token_count": 915
} | 427 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/common/config.gni")
source_set("gfx") {
visibility = [ "//flutter/third_party/accessibility/*" ]
include_dirs = [ "//flutter/third_party/accessibility" ]
sources = [
"geometry/insets.cc",
"geometry/insets.h",
"geometry/insets_f.cc",
"geometry/insets_f.h",
"geometry/point.cc",
"geometry/point.h",
"geometry/point_conversions.cc",
"geometry/point_conversions.h",
"geometry/point_f.cc",
"geometry/point_f.h",
"geometry/rect.cc",
"geometry/rect.h",
"geometry/rect_conversions.cc",
"geometry/rect_conversions.h",
"geometry/rect_f.cc",
"geometry/rect_f.h",
"geometry/size.cc",
"geometry/size.h",
"geometry/size_conversions.cc",
"geometry/size_conversions.h",
"geometry/size_f.cc",
"geometry/size_f.h",
"geometry/vector2d.cc",
"geometry/vector2d.h",
"geometry/vector2d_conversions.cc",
"geometry/vector2d_conversions.h",
"geometry/vector2d_f.cc",
"geometry/vector2d_f.h",
"gfx_export.h",
"native_widget_types.h",
"range/gfx_range_export.h",
"range/range.cc",
"range/range.h",
"transform.cc",
"transform.h",
]
if (is_mac) {
sources += [
"mac/coordinate_conversion.h",
"mac/coordinate_conversion.mm",
]
}
deps = [
"//flutter/third_party/accessibility/ax_build",
"//flutter/third_party/accessibility/base",
]
}
| engine/third_party/accessibility/gfx/BUILD.gn/0 | {
"file_path": "engine/third_party/accessibility/gfx/BUILD.gn",
"repo_id": "engine",
"token_count": 698
} | 428 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_GEOMETRY_RECT_CONVERSIONS_H_
#define UI_GFX_GEOMETRY_RECT_CONVERSIONS_H_
#include "rect.h"
#include "rect_f.h"
namespace gfx {
// Returns the smallest Rect that encloses the given RectF.
GFX_EXPORT Rect ToEnclosingRect(const RectF& rect);
// Similar to ToEnclosingRect(), but for each edge, if the distance between the
// edge and the nearest integer grid is smaller than |error|, the edge is
// snapped to the integer grid. Unlike ToNearestRect() which only accepts
// integer rect with or without floating point error, this function also accepts
// non-integer rect.
GFX_EXPORT Rect ToEnclosingRectIgnoringError(const RectF& rect, float error);
// Returns the largest Rect that is enclosed by the given RectF.
GFX_EXPORT Rect ToEnclosedRect(const RectF& rect);
// Similar to ToEnclosedRect(), but for each edge, if the distance between the
// edge and the nearest integer grid is smaller than |error|, the edge is
// snapped to the integer grid. Unlike ToNearestRect() which only accepts
// integer rect with or without floating point error, this function also accepts
// non-integer rect.
GFX_EXPORT Rect ToEnclosedRectIgnoringError(const RectF& rect, float error);
// Returns the Rect after snapping the corners of the RectF to an integer grid.
// This should only be used when the RectF you provide is expected to be an
// integer rect with floating point error. If it is an arbitrary RectF, then
// you should use a different method.
GFX_EXPORT Rect ToNearestRect(const RectF& rect);
// Returns true if the Rect produced after snapping the corners of the RectF
// to an integer grid is within |distance|.
GFX_EXPORT bool IsNearestRectWithinDistance(const gfx::RectF& rect,
float distance);
// Returns the Rect after rounding the corners of the RectF to an integer grid.
GFX_EXPORT gfx::Rect ToRoundedRect(const gfx::RectF& rect);
// Returns a Rect obtained by flooring the values of the given RectF.
// Please prefer the previous two functions in new code.
GFX_EXPORT Rect ToFlooredRectDeprecated(const RectF& rect);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_RECT_CONVERSIONS_H_
| engine/third_party/accessibility/gfx/geometry/rect_conversions.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/rect_conversions.h",
"repo_id": "engine",
"token_count": 693
} | 429 |
// 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 float vector class. This class is used to indicate a
// distance in two dimensions between two points. Subtracting two points should
// produce a vector, and adding a vector to a point produces the point at the
// vector's distance from the original point.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_F_H_
#define UI_GFX_GEOMETRY_VECTOR2D_F_H_
#include <iosfwd>
#include <memory>
#include <string>
#include "gfx/gfx_export.h"
namespace gfx {
class GFX_EXPORT Vector2dF {
public:
constexpr Vector2dF() : x_(0), y_(0) {}
constexpr Vector2dF(float x, float y) : x_(x), y_(y) {}
constexpr float x() const { return x_; }
void set_x(float x) { x_ = x; }
constexpr float y() const { return y_; }
void set_y(float y) { y_ = y; }
// True if both components of the vector are 0.
bool IsZero() const;
// Add the components of the |other| vector to the current vector.
void Add(const Vector2dF& other);
// Subtract the components of the |other| vector from the current vector.
void Subtract(const Vector2dF& other);
void operator+=(const Vector2dF& other) { Add(other); }
void operator-=(const Vector2dF& other) { Subtract(other); }
void SetToMin(const Vector2dF& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void SetToMax(const Vector2dF& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
// Gives the square of the diagonal length of the vector.
double LengthSquared() const;
// Gives the diagonal length of the vector.
float Length() const;
// Scale the x and y components of the vector by |scale|.
void Scale(float scale) { Scale(scale, scale); }
// Scale the x and y components of the vector by |x_scale| and |y_scale|
// respectively.
void Scale(float x_scale, float y_scale);
std::string ToString() const;
private:
float x_;
float y_;
};
inline constexpr bool operator==(const Vector2dF& lhs, const Vector2dF& rhs) {
return lhs.x() == rhs.x() && lhs.y() == rhs.y();
}
inline constexpr bool operator!=(const Vector2dF& lhs, const Vector2dF& rhs) {
return !(lhs == rhs);
}
inline constexpr Vector2dF operator-(const Vector2dF& v) {
return Vector2dF(-v.x(), -v.y());
}
inline Vector2dF operator+(const Vector2dF& lhs, const Vector2dF& rhs) {
Vector2dF result = lhs;
result.Add(rhs);
return result;
}
inline Vector2dF operator-(const Vector2dF& lhs, const Vector2dF& rhs) {
Vector2dF result = lhs;
result.Add(-rhs);
return result;
}
// Return the cross product of two vectors.
GFX_EXPORT double CrossProduct(const Vector2dF& lhs, const Vector2dF& rhs);
// Return the dot product of two vectors.
GFX_EXPORT double DotProduct(const Vector2dF& lhs, const Vector2dF& rhs);
// Return a vector that is |v| scaled by the given scale factors along each
// axis.
GFX_EXPORT Vector2dF ScaleVector2d(const Vector2dF& v,
float x_scale,
float y_scale);
// Return a vector that is |v| scaled by the given scale factor.
inline Vector2dF ScaleVector2d(const Vector2dF& v, float scale) {
return ScaleVector2d(v, 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 Vector2dF& vector, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_F_H_
| engine/third_party/accessibility/gfx/geometry/vector2d_f.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/vector2d_f.h",
"repo_id": "engine",
"token_count": 1350
} | 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.
_source_location = "//flutter/third_party/libjpeg-turbo/src"
if (current_cpu == "arm") {
import("//build/config/arm.gni")
}
if (is_fuchsia) {
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
}
if ((current_cpu == "x86" || current_cpu == "x64") && is_fuchsia &&
!using_fuchsia_sdk) {
import("//third_party/yasm/yasm_assemble.gni")
yasm_assemble("simd_asm") {
defines = []
if (current_cpu == "x86") {
sources = [
"$_source_location/simd/jccolor-mmx.asm",
"$_source_location/simd/jccolor-sse2.asm",
"$_source_location/simd/jcgray-mmx.asm",
"$_source_location/simd/jcgray-sse2.asm",
"$_source_location/simd/jchuff-sse2.asm",
"$_source_location/simd/jcsample-mmx.asm",
"$_source_location/simd/jcsample-sse2.asm",
"$_source_location/simd/jdcolor-mmx.asm",
"$_source_location/simd/jdcolor-sse2.asm",
"$_source_location/simd/jdmerge-mmx.asm",
"$_source_location/simd/jdmerge-sse2.asm",
"$_source_location/simd/jdsample-mmx.asm",
"$_source_location/simd/jdsample-sse2.asm",
"$_source_location/simd/jfdctflt-3dn.asm",
"$_source_location/simd/jfdctflt-sse.asm",
"$_source_location/simd/jfdctfst-mmx.asm",
"$_source_location/simd/jfdctfst-sse2.asm",
"$_source_location/simd/jfdctint-mmx.asm",
"$_source_location/simd/jfdctint-sse2.asm",
"$_source_location/simd/jidctflt-3dn.asm",
"$_source_location/simd/jidctflt-sse.asm",
"$_source_location/simd/jidctflt-sse2.asm",
"$_source_location/simd/jidctfst-mmx.asm",
"$_source_location/simd/jidctfst-sse2.asm",
"$_source_location/simd/jidctint-mmx.asm",
"$_source_location/simd/jidctint-sse2.asm",
"$_source_location/simd/jidctred-mmx.asm",
"$_source_location/simd/jidctred-sse2.asm",
"$_source_location/simd/jquant-3dn.asm",
"$_source_location/simd/jquant-mmx.asm",
"$_source_location/simd/jquant-sse.asm",
"$_source_location/simd/jquantf-sse2.asm",
"$_source_location/simd/jquanti-sse2.asm",
"$_source_location/simd/jsimdcpu.asm",
]
defines += [
"__x86__",
"PIC",
]
} else if (current_cpu == "x64") {
sources = [
"$_source_location/simd/jccolor-sse2-64.asm",
"$_source_location/simd/jcgray-sse2-64.asm",
"$_source_location/simd/jchuff-sse2-64.asm",
"$_source_location/simd/jcsample-sse2-64.asm",
"$_source_location/simd/jdcolor-sse2-64.asm",
"$_source_location/simd/jdmerge-sse2-64.asm",
"$_source_location/simd/jdsample-sse2-64.asm",
"$_source_location/simd/jfdctflt-sse-64.asm",
"$_source_location/simd/jfdctfst-sse2-64.asm",
"$_source_location/simd/jfdctint-sse2-64.asm",
"$_source_location/simd/jidctflt-sse2-64.asm",
"$_source_location/simd/jidctfst-sse2-64.asm",
"$_source_location/simd/jidctint-sse2-64.asm",
"$_source_location/simd/jidctred-sse2-64.asm",
"$_source_location/simd/jquantf-sse2-64.asm",
"$_source_location/simd/jquanti-sse2-64.asm",
]
defines += [
"__x86_64__",
"PIC",
]
}
defines += [ "ELF" ]
}
}
config("libjpeg_config") {
include_dirs = [ _source_location ]
}
static_library("simd") {
configs += [ ":libjpeg_config" ]
if (!is_fuchsia || using_fuchsia_sdk) {
sources = [ "$_source_location/jsimd_none.c" ]
} else if (current_cpu == "x86") {
deps = [ ":simd_asm" ]
sources = [ "$_source_location/simd/jsimd_i386.c" ]
} else if (current_cpu == "x64") {
deps = [ ":simd_asm" ]
sources = [ "$_source_location/simd/jsimd_x86_64.c" ]
} else if (current_cpu == "arm" && arm_version >= 7 &&
(arm_use_neon || arm_optionally_use_neon)) {
sources = [
"$_source_location/simd/jsimd_arm.c",
"$_source_location/simd/jsimd_arm_neon.S",
]
} else if (current_cpu == "arm64") {
sources = [
"$_source_location/simd/jsimd_arm64.c",
"$_source_location/simd/jsimd_arm64_neon.S",
]
} else {
sources = [ "$_source_location/jsimd_none.c" ]
}
}
static_library("libjpeg") {
sources = [
"$_source_location/jcapimin.c",
"$_source_location/jcapistd.c",
"$_source_location/jccoefct.c",
"$_source_location/jccolor.c",
"$_source_location/jcdctmgr.c",
"$_source_location/jchuff.c",
"$_source_location/jcinit.c",
"$_source_location/jcmainct.c",
"$_source_location/jcmarker.c",
"$_source_location/jcmaster.c",
"$_source_location/jcomapi.c",
"$_source_location/jcparam.c",
"$_source_location/jcphuff.c",
"$_source_location/jcprepct.c",
"$_source_location/jcsample.c",
"$_source_location/jdapimin.c",
"$_source_location/jdapistd.c",
"$_source_location/jdatadst.c",
"$_source_location/jdatasrc.c",
"$_source_location/jdcoefct.c",
"$_source_location/jdcolor.c",
"$_source_location/jddctmgr.c",
"$_source_location/jdhuff.c",
"$_source_location/jdinput.c",
"$_source_location/jdmainct.c",
"$_source_location/jdmarker.c",
"$_source_location/jdmaster.c",
"$_source_location/jdmerge.c",
"$_source_location/jdphuff.c",
"$_source_location/jdpostct.c",
"$_source_location/jdsample.c",
"$_source_location/jerror.c",
"$_source_location/jfdctflt.c",
"$_source_location/jfdctfst.c",
"$_source_location/jfdctint.c",
"$_source_location/jidctflt.c",
"$_source_location/jidctfst.c",
"$_source_location/jidctint.c",
"$_source_location/jidctred.c",
"$_source_location/jmemmgr.c",
"$_source_location/jmemnobs.c",
"$_source_location/jquant1.c",
"$_source_location/jquant2.c",
"$_source_location/jutils.c",
]
defines = [
"WITH_SIMD",
"NO_GETENV",
]
configs += [ ":libjpeg_config" ]
public_configs = [ ":libjpeg_config" ]
deps = [ ":simd" ]
}
| engine/third_party/libjpeg-turbo/BUILD.gn/0 | {
"file_path": "engine/third_party/libjpeg-turbo/BUILD.gn",
"repo_id": "engine",
"token_count": 3044
} | 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.
// This file adds defines about the platform we're currently building on.
// Operating System:
// OS_WIN / OS_MACOSX / OS_LINUX / OS_POSIX (MACOSX or LINUX) /
// OS_NACL (NACL_SFI or NACL_NONSFI) / OS_NACL_SFI / OS_NACL_NONSFI
// Compiler:
// COMPILER_MSVC / COMPILER_GCC
// Processor:
// ARCH_CPU_X86 / ARCH_CPU_X86_64 / ARCH_CPU_X86_FAMILY (X86 or X86_64)
// ARCH_CPU_32_BITS / ARCH_CPU_64_BITS
#ifndef TONIC_COMMON_BUILD_CONFIG_H_
#define TONIC_COMMON_BUILD_CONFIG_H_
#if defined(__Fuchsia__)
#define OS_FUCHSIA 1
#elif defined(ANDROID)
#define OS_ANDROID 1
#elif defined(__APPLE__)
// only include TargetConditions after testing ANDROID as some android builds
// on mac don't have this header available and it's not needed unless the target
// is really mac/ios.
#include <TargetConditionals.h>
#define OS_MACOSX 1
#if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#define OS_IOS 1
#endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
#elif defined(__linux__)
#define OS_LINUX 1
// include a system header to pull in features.h for glibc/uclibc macros.
#include <unistd.h>
#if defined(__GLIBC__) && !defined(__UCLIBC__)
// we really are using glibc, not uClibc pretending to be glibc
#define LIBC_GLIBC 1
#endif
#elif defined(_WIN32)
#define OS_WIN 1
#elif defined(__FreeBSD__)
#define OS_FREEBSD 1
#elif defined(__OpenBSD__)
#define OS_OPENBSD 1
#elif defined(__sun)
#define OS_SOLARIS 1
#elif defined(__QNXNTO__)
#define OS_QNX 1
#else
#error Please add support for your platform in tonic/common/build_config.h
#endif
// For access to standard BSD features, use OS_BSD instead of a
// more specific macro.
#if defined(OS_FREEBSD) || defined(OS_OPENBSD)
#define OS_BSD 1
#endif
// For access to standard POSIXish features, use OS_POSIX instead of a
// more specific macro.
#if defined(OS_MACOSX) || defined(OS_LINUX) || defined(OS_FREEBSD) || \
defined(OS_OPENBSD) || defined(OS_SOLARIS) || defined(OS_ANDROID) || \
defined(OS_NACL) || defined(OS_QNX)
#define OS_POSIX 1
#endif
// Processor architecture detection. For more info on what's defined, see:
// http://msdn.microsoft.com/en-us/library/b0084kay.aspx
// http://www.agner.org/optimize/calling_conventions.pdf
// or with gcc, run: "echo | gcc -E -dM -"
#if defined(_M_X64) || defined(__x86_64__)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86_64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(_M_IX86) || defined(__i386__)
#define ARCH_CPU_X86_FAMILY 1
#define ARCH_CPU_X86 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__ARMEL__)
#define ARCH_CPU_ARM_FAMILY 1
#define ARCH_CPU_ARMEL 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__aarch64__)
#define ARCH_CPU_ARM_FAMILY 1
#define ARCH_CPU_ARM64 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__pnacl__)
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#elif defined(__MIPSEL__)
#if defined(__LP64__)
#define ARCH_CPU_MIPS64_FAMILY 1
#define ARCH_CPU_MIPS64EL 1
#define ARCH_CPU_64_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#else
#define ARCH_CPU_MIPS_FAMILY 1
#define ARCH_CPU_MIPSEL 1
#define ARCH_CPU_32_BITS 1
#define ARCH_CPU_LITTLE_ENDIAN 1
#endif
#else
#error Please add support for your architecture in build/build_config.h
#endif
#endif // TONIC_COMMON_BUILD_CONFIG_H_
| engine/third_party/tonic/common/build_config.h/0 | {
"file_path": "engine/third_party/tonic/common/build_config.h",
"repo_id": "engine",
"token_count": 1437
} | 432 |
// 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_message_handler.h"
#include "third_party/dart/runtime/include/dart_api.h"
#include "third_party/dart/runtime/include/dart_native_api.h"
#include "third_party/dart/runtime/include/dart_tools_api.h"
#include "tonic/common/macros.h"
#include "tonic/dart_state.h"
#include "tonic/logging/dart_error.h"
namespace tonic {
DartMessageHandler::DartMessageHandler()
: handled_first_message_(false),
isolate_exited_(false),
isolate_had_uncaught_exception_error_(false),
isolate_had_fatal_error_(false),
isolate_last_error_(kNoError),
task_dispatcher_(nullptr) {}
DartMessageHandler::~DartMessageHandler() {
task_dispatcher_ = nullptr;
}
void DartMessageHandler::Initialize(TaskDispatcher dispatcher) {
// Only can be called once.
TONIC_CHECK(!task_dispatcher_ && dispatcher);
task_dispatcher_ = dispatcher;
Dart_SetMessageNotifyCallback(MessageNotifyCallback);
}
void DartMessageHandler::OnMessage(DartState* dart_state) {
auto task_dispatcher_ = dart_state->message_handler().task_dispatcher_;
// Schedule a task to run on the message loop thread.
auto weak_dart_state = dart_state->GetWeakPtr();
task_dispatcher_([weak_dart_state]() {
if (auto dart_state = weak_dart_state.lock()) {
dart_state->message_handler().OnHandleMessage(dart_state.get());
}
});
}
void DartMessageHandler::UnhandledError(Dart_Handle error) {
TONIC_DCHECK(Dart_CurrentIsolate());
TONIC_DCHECK(Dart_IsError(error));
isolate_last_error_ = GetErrorHandleType(error);
// Remember that we had an uncaught exception error.
isolate_had_uncaught_exception_error_ = true;
if (Dart_IsFatalError(error)) {
isolate_had_fatal_error_ = true;
// Stop handling messages.
Dart_SetMessageNotifyCallback(nullptr);
// Shut down the isolate.
Dart_ShutdownIsolate();
}
}
void DartMessageHandler::OnHandleMessage(DartState* dart_state) {
if (isolate_had_fatal_error_) {
// Don't handle any more messages.
return;
}
DartIsolateScope scope(dart_state->isolate());
DartApiScope dart_api_scope;
Dart_Handle result = Dart_Null();
bool error = false;
// On the first message, check if we should pause on isolate start.
if (!handled_first_message()) {
set_handled_first_message(true);
if (Dart_ShouldPauseOnStart()) {
// Mark that we are paused on isolate start.
Dart_SetPausedOnStart(true);
}
}
if (Dart_IsPausedOnStart()) {
// We are paused on isolate start. Only handle service messages until we are
// requested to resume.
if (Dart_HasServiceMessages()) {
bool resume = Dart_HandleServiceMessages();
if (!resume) {
return;
}
Dart_SetPausedOnStart(false);
// We've resumed, handle normal messages that are in the queue.
result = Dart_HandleMessage();
error = CheckAndHandleError(result);
dart_state->MessageEpilogue(result);
if (!Dart_CurrentIsolate()) {
isolate_exited_ = true;
return;
}
}
} else if (Dart_IsPausedOnExit()) {
// We are paused on isolate exit. Only handle service messages until we are
// requested to resume.
if (Dart_HasServiceMessages()) {
bool resume = Dart_HandleServiceMessages();
if (!resume) {
return;
}
Dart_SetPausedOnExit(false);
}
} else {
// We are processing messages normally.
result = Dart_HandleMessage();
// If the Dart program has set a return code, then it is intending to shut
// down by way of a fatal error, and so there is no need to emit a log
// message.
if (dart_state->has_set_return_code() && Dart_IsError(result) &&
Dart_IsFatalError(result)) {
error = true;
} else {
error = CheckAndHandleError(result);
}
dart_state->MessageEpilogue(result);
if (!Dart_CurrentIsolate()) {
isolate_exited_ = true;
return;
}
}
if (error) {
UnhandledError(result);
} else if (!Dart_HasLivePorts()) {
// The isolate has no live ports and would like to exit.
if (!Dart_IsPausedOnExit() && Dart_ShouldPauseOnExit()) {
// Mark that we are paused on exit.
Dart_SetPausedOnExit(true);
} else {
isolate_exited_ = true;
}
}
}
void DartMessageHandler::MessageNotifyCallback(Dart_Isolate dest_isolate) {
auto dart_state = DartState::From(dest_isolate);
TONIC_CHECK(dart_state);
dart_state->message_handler().OnMessage(dart_state);
}
} // namespace tonic
| engine/third_party/tonic/dart_message_handler.cc/0 | {
"file_path": "engine/third_party/tonic/dart_message_handler.cc",
"repo_id": "engine",
"token_count": 1714
} | 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.
#include "tonic/file_loader/file_loader.h"
#include <iostream>
#include <memory>
#include <utility>
#include "tonic/common/macros.h"
#include "tonic/converter/dart_converter.h"
#include "tonic/filesystem/filesystem/file.h"
#include "tonic/filesystem/filesystem/path.h"
#include "tonic/parsers/packages_map.h"
namespace tonic {
const std::string FileLoader::kPathSeparator = "/";
const char FileLoader::kFileURLPrefix[] = "file://";
const size_t FileLoader::kFileURLPrefixLength =
sizeof(FileLoader::kFileURLPrefix) - 1;
std::string FileLoader::SanitizePath(const std::string& url) {
return SanitizeURIEscapedCharacters(url);
}
bool FileLoader::ReadFileToString(const std::string& path,
std::string* result) {
TONIC_DCHECK(dirfd_ == -1);
return filesystem::ReadFileToString(path, result);
}
std::pair<uint8_t*, intptr_t> FileLoader::ReadFileToBytes(
const std::string& path) {
TONIC_DCHECK(dirfd_ == -1);
return filesystem::ReadFileToBytes(path);
}
} // namespace tonic
| engine/third_party/tonic/file_loader/file_loader_posix.cc/0 | {
"file_path": "engine/third_party/tonic/file_loader/file_loader_posix.cc",
"repo_id": "engine",
"token_count": 446
} | 434 |
// Copyright 2021 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_isolate_runner.h"
#include "flutter/testing/fixture_test.h"
#include "tonic/dart_args.h"
#include "tonic/dart_wrappable.h"
namespace flutter {
namespace testing {
class MyNativeClass : public RefCountedDartWrappable<MyNativeClass> {
DEFINE_WRAPPERTYPEINFO();
FML_FRIEND_MAKE_REF_COUNTED(MyNativeClass);
MyNativeClass(intptr_t value) : _value(value){};
public:
intptr_t _value = 0;
static void Create(Dart_Handle path_handle, intptr_t value) {
auto path = fml::MakeRefCounted<MyNativeClass>(value);
path->AssociateWithDartWrapper(path_handle);
}
// Dummy test functions:
static int32_t MyTestFunction(MyNativeClass* ptr,
int32_t x,
Dart_Handle handle) {
return ptr->_value + x;
}
Dart_Handle MyTestMethod(int64_t x) { return Dart_NewInteger(_value + x); }
};
IMPLEMENT_WRAPPERTYPEINFO("Lib", MyNativeClass)
class FfiNativeTest : public FixtureTest {
public:
FfiNativeTest()
: settings_(CreateSettingsForFixture()),
vm_(DartVMRef::Create(settings_)),
thread_(CreateNewThread()),
task_runners_(GetCurrentTestName(),
thread_,
thread_,
thread_,
thread_) {}
~FfiNativeTest() = default;
[[nodiscard]] bool RunWithEntrypoint(const std::string& entrypoint) {
if (running_isolate_) {
return false;
}
auto isolate =
RunDartCodeInIsolate(vm_, settings_, task_runners_, entrypoint, {},
GetDefaultKernelFilePath());
if (!isolate || isolate->get()->GetPhase() != DartIsolate::Phase::Running) {
return false;
}
running_isolate_ = std::move(isolate);
return true;
}
template <typename C, typename Signature, Signature function>
void DoCallThroughTest(const char* testName, const char* testEntry) {
auto weak_persistent_value = tonic::DartWeakPersistentValue();
fml::AutoResetWaitableEvent event;
AddFfiNativeCallback(
testName, reinterpret_cast<void*>(
tonic::FfiDispatcher<C, Signature, function>::Call));
AddFfiNativeCallback(
"CreateNative",
reinterpret_cast<void*>(
tonic::FfiDispatcher<void, decltype(&MyNativeClass::Create),
&MyNativeClass::Create>::Call));
AddNativeCallback("SignalDone",
CREATE_NATIVE_ENTRY([&](Dart_NativeArguments args) {
// Clear on initiative of Dart.
weak_persistent_value.Clear();
event.Signal();
}));
ASSERT_TRUE(RunWithEntrypoint(testEntry));
event.Wait();
running_isolate_->Shutdown();
}
template <typename C, typename Signature, Signature function>
void DoSerialiseTest(bool leaf,
const char* returnFfi,
const char* returnDart,
const char* argsFfi,
const char* argsDart) {
auto dispatcher = tonic::FfiDispatcher<C, Signature, function>();
EXPECT_EQ(dispatcher.AllowedAsLeafCall(), leaf);
EXPECT_STREQ(dispatcher.GetReturnFfiRepresentation(), returnFfi);
EXPECT_STREQ(dispatcher.GetReturnDartRepresentation(), returnDart);
{
std::ostringstream stream_;
dispatcher.WriteFfiArguments(&stream_);
EXPECT_STREQ(stream_.str().c_str(), argsFfi);
}
{
std::ostringstream stream_;
dispatcher.WriteDartArguments(&stream_);
EXPECT_STREQ(stream_.str().c_str(), argsDart);
}
}
protected:
Settings settings_;
DartVMRef vm_;
std::unique_ptr<AutoIsolateShutdown> running_isolate_;
fml::RefPtr<fml::TaskRunner> thread_;
TaskRunners task_runners_;
FML_DISALLOW_COPY_AND_ASSIGN(FfiNativeTest);
};
//
// Call bindings.
//
// Call and serialise a simple function through the Tonic FFI bindings.
void Nop() {}
TEST_F(FfiNativeTest, FfiBindingCallNop) {
DoCallThroughTest<void, decltype(&Nop), &Nop>("Nop", "callNop");
}
TEST_F(FfiNativeTest, SerialiseNop) {
DoSerialiseTest<void, decltype(&Nop), &Nop>(
/*leaf=*/true, "Void", "void", "", "");
}
// Call and serialise function with bool.
bool EchoBool(bool arg) {
EXPECT_TRUE(arg);
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoBool) {
DoCallThroughTest<void, decltype(&EchoBool), &EchoBool>("EchoBool",
"callEchoBool");
}
TEST_F(FfiNativeTest, SerialiseEchoBool) {
DoSerialiseTest<void, decltype(&EchoBool), &EchoBool>(
/*leaf=*/true, "Bool", "bool", "Bool", "bool");
}
// Call and serialise function with intptr_t.
intptr_t EchoIntPtr(intptr_t arg) {
EXPECT_EQ(arg, 23);
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoIntPtr) {
DoCallThroughTest<void, decltype(&EchoIntPtr), &EchoIntPtr>("EchoIntPtr",
"callEchoIntPtr");
}
TEST_F(FfiNativeTest, SerialiseEchoIntPtr) {
if (sizeof(intptr_t) == 8) {
DoSerialiseTest<void, decltype(&EchoIntPtr), &EchoIntPtr>(
/*leaf=*/true, "Int64", "int", "Int64", "int");
} else {
EXPECT_EQ(sizeof(intptr_t), 4ul);
DoSerialiseTest<void, decltype(&EchoIntPtr), &EchoIntPtr>(
/*leaf=*/true, "Int32", "int", "Int32", "int");
}
}
// Call and serialise function with double.
double EchoDouble(double arg) {
EXPECT_EQ(arg, 23.0);
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoDouble) {
DoCallThroughTest<void, decltype(&EchoDouble), &EchoDouble>("EchoDouble",
"callEchoDouble");
}
TEST_F(FfiNativeTest, SerialiseEchoDouble) {
DoSerialiseTest<void, decltype(&EchoDouble), &EchoDouble>(
/*leaf=*/true, "Double", "double", "Double", "double");
}
// Call and serialise function with Dart_Handle.
Dart_Handle EchoHandle(Dart_Handle str) {
const char* c_str = nullptr;
Dart_StringToCString(str, &c_str);
EXPECT_STREQ(c_str, "Hello EchoHandle");
return str;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoHandle) {
DoCallThroughTest<void, decltype(&EchoHandle), &EchoHandle>("EchoHandle",
"callEchoHandle");
}
TEST_F(FfiNativeTest, SerialiseEchoHandle) {
DoSerialiseTest<void, decltype(&EchoHandle), &EchoHandle>(
/*leaf=*/false, "Handle", "Object", "Handle", "Object");
}
// Call and serialise function with std::string.
std::string EchoString(std::string arg) {
EXPECT_STREQ(arg.c_str(), "Hello EchoString");
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoString) {
DoCallThroughTest<void, decltype(&EchoString), &EchoString>("EchoString",
"callEchoString");
}
TEST_F(FfiNativeTest, SerialiseEchoString) {
DoSerialiseTest<void, decltype(&EchoString), &EchoString>(
/*leaf=*/false, "Handle", "String", "Handle", "String");
}
// Call and serialise function with std::u16string.
std::u16string EchoU16String(std::u16string arg) {
EXPECT_EQ(arg, u"Hello EchoU16String");
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoU16String) {
DoCallThroughTest<void, decltype(&EchoU16String), &EchoU16String>(
"EchoU16String", "callEchoU16String");
}
TEST_F(FfiNativeTest, SerialiseEchoU16String) {
DoSerialiseTest<void, decltype(&EchoU16String), &EchoU16String>(
/*leaf=*/false, "Handle", "String", "Handle", "String");
}
// Call and serialise function with std::vector.
std::vector<std::string> EchoVector(const std::vector<std::string>& arg) {
EXPECT_STREQ(arg[0].c_str(), "Hello EchoVector");
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoVector) {
DoCallThroughTest<void, decltype(&EchoVector), &EchoVector>("EchoVector",
"callEchoVector");
}
TEST_F(FfiNativeTest, SerialiseEchoVector) {
DoSerialiseTest<void, decltype(&EchoVector), &EchoVector>(
/*leaf=*/false, "Handle", "List", "Handle", "List");
}
// Call and serialise function with DartWrappable.
intptr_t EchoWrappable(MyNativeClass* arg) {
EXPECT_EQ(arg->_value, 0x1234);
return arg->_value;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoWrappable) {
DoCallThroughTest<void, decltype(&EchoWrappable), &EchoWrappable>(
"EchoWrappable", "callEchoWrappable");
}
TEST_F(FfiNativeTest, SerialiseEchoWrappable) {
if (sizeof(intptr_t) == 8) {
DoSerialiseTest<void, decltype(&EchoWrappable), &EchoWrappable>(
/*leaf=*/true, "Int64", "int", "Pointer", "Pointer");
} else {
EXPECT_EQ(sizeof(intptr_t), 4ul);
DoSerialiseTest<void, decltype(&EchoWrappable), &EchoWrappable>(
/*leaf=*/true, "Int32", "int", "Pointer", "Pointer");
}
}
// Call and serialise function with TypedList<..>.
tonic::Float32List EchoTypedList(tonic::Float32List arg) {
EXPECT_NEAR(arg[1], 3.14, 0.01);
return arg;
}
TEST_F(FfiNativeTest, FfiBindingCallEchoTypedList) {
DoCallThroughTest<void, decltype(&EchoTypedList), &EchoTypedList>(
"EchoTypedList", "callEchoTypedList");
}
TEST_F(FfiNativeTest, SerialiseEchoTypedList) {
DoSerialiseTest<void, decltype(&EchoTypedList), &EchoTypedList>(
/*leaf=*/false, "Handle", "Object", "Handle", "Object");
}
// Call and serialise a static class member function.
TEST_F(FfiNativeTest, FfiBindingCallClassMemberFunction) {
DoCallThroughTest<void, decltype(&MyNativeClass::MyTestFunction),
&MyNativeClass::MyTestFunction>(
"MyNativeClass::MyTestFunction", "callMyTestFunction");
}
TEST_F(FfiNativeTest, SerialiseClassMemberFunction) {
DoSerialiseTest<void, decltype(&MyNativeClass::MyTestFunction),
&MyNativeClass::MyTestFunction>(
/*leaf=*/false, "Int32", "int", "Pointer, Int32, Handle",
"Pointer, int, Object");
}
// Call and serialise an instance method.
TEST_F(FfiNativeTest, FfiBindingCallClassMemberMethod) {
DoCallThroughTest<MyNativeClass, decltype(&MyNativeClass::MyTestMethod),
&MyNativeClass::MyTestMethod>("MyNativeClass::MyTestMethod",
"callMyTestMethod");
}
TEST_F(FfiNativeTest, SerialiseClassMemberMethod) {
DoSerialiseTest<MyNativeClass, decltype(&MyNativeClass::MyTestMethod),
&MyNativeClass::MyTestMethod>(
/*leaf=*/false, "Handle", "Object", "Pointer, Int64", "Pointer, int");
}
} // namespace testing
} // namespace flutter
| engine/third_party/tonic/tests/ffi_native_unittest.cc/0 | {
"file_path": "engine/third_party/tonic/tests/ffi_native_unittest.cc",
"repo_id": "engine",
"token_count": 4682
} | 435 |
/*
* 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.
*/
#ifndef LIB_TXT_SRC_PARAGRAPH_H_
#define LIB_TXT_SRC_PARAGRAPH_H_
#include "flutter/display_list/dl_builder.h"
#include "line_metrics.h"
#include "paragraph_style.h"
#include "third_party/skia/include/core/SkFont.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/skia/modules/skparagraph/include/Metrics.h"
#include "third_party/skia/modules/skparagraph/include/Paragraph.h"
class SkCanvas;
namespace txt {
// Interface for text layout engines. The current implementation is based on
// Skia's SkShaper/SkParagraph text layout module.
class Paragraph {
public:
enum Affinity { UPSTREAM, DOWNSTREAM };
// Options for various types of bounding boxes provided by
// GetRectsForRange(...).
enum class RectHeightStyle {
// Provide tight bounding boxes that fit heights per run.
kTight,
// The height of the boxes will be the maximum height of all runs in the
// line. All rects in the same line will be the same height.
kMax,
// Extends the top and/or bottom edge of the bounds to fully cover any line
// spacing. The top edge of each line should be the same as the bottom edge
// of the line above. There should be no gaps in vertical coverage given any
// ParagraphStyle line_height.
//
// The top and bottom of each rect will cover half of the
// space above and half of the space below the line.
kIncludeLineSpacingMiddle,
// The line spacing will be added to the top of the rect.
kIncludeLineSpacingTop,
// The line spacing will be added to the bottom of the rect.
kIncludeLineSpacingBottom,
// Calculate boxes based on the strut's metrics.
kStrut
};
enum class RectWidthStyle {
// Provide tight bounding boxes that fit widths to the runs of each line
// independently.
kTight,
// Extends the width of the last rect of each line to match the position of
// the widest rect over all the lines.
kMax
};
struct PositionWithAffinity {
const size_t position;
const Affinity affinity;
PositionWithAffinity(size_t p, Affinity a) : position(p), affinity(a) {}
};
struct TextBox {
SkRect rect;
TextDirection direction;
TextBox(SkRect r, TextDirection d) : rect(r), direction(d) {}
};
template <typename T>
struct Range {
Range() : start(), end() {}
Range(T s, T e) : start(s), end(e) {}
T start, end;
bool operator==(const Range<T>& other) const {
return start == other.start && end == other.end;
}
T width() const { return end - start; }
void Shift(T delta) {
start += delta;
end += delta;
}
};
virtual ~Paragraph() = default;
// Returns the width provided in the Layout() method. This is the maximum
// width any line in the laid out paragraph can occupy. We expect that
// GetMaxWidth() >= GetLayoutWidth().
virtual double GetMaxWidth() = 0;
// Returns the height of the laid out paragraph. NOTE this is not a tight
// bounding height of the glyphs, as some glyphs do not reach as low as they
// can.
virtual double GetHeight() = 0;
// Returns the width of the longest line as found in Layout(), which is
// defined as the horizontal distance from the left edge of the leftmost glyph
// to the right edge of the rightmost glyph. We expect that
// GetLongestLine() <= GetMaxWidth().
virtual double GetLongestLine() = 0;
// Returns the actual max width of the longest line after Layout().
virtual double GetMinIntrinsicWidth() = 0;
// Returns the total width covered by the paragraph without linebreaking.
virtual double GetMaxIntrinsicWidth() = 0;
// Distance from top of paragraph to the Alphabetic baseline of the first
// line. Used for alphabetic fonts (A-Z, a-z, greek, etc.)
virtual double GetAlphabeticBaseline() = 0;
// Distance from top of paragraph to the Ideographic baseline of the first
// line. Used for ideographic fonts (Chinese, Japanese, Korean, etc.)
virtual double GetIdeographicBaseline() = 0;
// Checks if the layout extends past the maximum lines and had to be
// truncated.
virtual bool DidExceedMaxLines() = 0;
// Layout calculates the positioning of all the glyphs. Must call this method
// before Painting and getting any statistics from this class.
virtual void Layout(double width) = 0;
// Paints the laid out text onto the supplied DisplayListBuilder at
// (x, y) offset from the origin. Only valid after Layout() is called.
virtual bool Paint(flutter::DisplayListBuilder* builder,
double x,
double y) = 0;
// Returns a vector of bounding boxes that enclose all text between start and
// end glyph indexes, including start and excluding end.
virtual std::vector<TextBox> GetRectsForRange(
size_t start,
size_t end,
RectHeightStyle rect_height_style,
RectWidthStyle rect_width_style) = 0;
// Returns a vector of bounding boxes that bound all inline placeholders in
// the paragraph.
//
// There will be one box for each inline placeholder. The boxes will be in the
// same order as they were added to the paragraph. The bounds will always be
// tight and should fully enclose the area where the placeholder should be.
//
// More granular boxes may be obtained through GetRectsForRange, which will
// return bounds on both text as well as inline placeholders.
virtual std::vector<TextBox> GetRectsForPlaceholders() = 0;
// Returns the index of the glyph that corresponds to the provided coordinate,
// with the top left corner as the origin, and +y direction as down.
virtual PositionWithAffinity GetGlyphPositionAtCoordinate(double dx,
double dy) = 0;
virtual bool GetGlyphInfoAt(
unsigned offset,
skia::textlayout::Paragraph::GlyphInfo* glyphInfo) const = 0;
virtual bool GetClosestGlyphInfoAtCoordinate(
double dx,
double dy,
skia::textlayout::Paragraph::GlyphInfo* glyphInfo) const = 0;
// Finds the first and last glyphs that define a word containing the glyph at
// index offset.
virtual Range<size_t> GetWordBoundary(size_t offset) = 0;
virtual std::vector<LineMetrics>& GetLineMetrics() = 0;
virtual bool GetLineMetricsAt(
int lineNumber,
skia::textlayout::LineMetrics* lineMetrics) const = 0;
// Returns the total number of visible lines in the paragraph.
virtual size_t GetNumberOfLines() const = 0;
// Returns the zero-indexed line number that contains the given code unit
// offset. Returns -1 if the given offset is out of bounds, or points to a
// codepoint that is logically after the last visible codepoint.
//
// If the offset points to a hard line break, this method returns the line
// number of the line this hard line break breaks, intead of the new line it
// creates.
virtual int GetLineNumberAt(size_t utf16Offset) const = 0;
};
} // namespace txt
#endif // LIB_TXT_SRC_PARAGRAPH_H_
| engine/third_party/txt/src/txt/paragraph.h/0 | {
"file_path": "engine/third_party/txt/src/txt/paragraph.h",
"repo_id": "engine",
"token_count": 2351
} | 436 |
//---------------------------------------------------------------------------------------------
// Copyright (c) 2022 Google LLC
// Licensed under the MIT License. See License.txt in the project root for license information.
//--------------------------------------------------------------------------------------------*/
import 'package:test/test.dart';
import 'package:web_locale_keymap/web_locale_keymap.dart';
import 'test_cases.g.dart';
void main() {
group('Win', () {
testWin(LocaleKeymap.win());
});
group('Linux', () {
testLinux(LocaleKeymap.linux());
});
group('Darwin', () {
testDarwin(LocaleKeymap.darwin());
});
}
| engine/third_party/web_locale_keymap/test/layout_mapping_test.dart/0 | {
"file_path": "engine/third_party/web_locale_keymap/test/layout_mapping_test.dart",
"repo_id": "engine",
"token_count": 178
} | 437 |
# `build_bucket_golden_scraper`
Given logging on Flutter's CI, scrapes the log for golden file changes.
```shell
$ dart bin/main.dart <path to log file, which can be http or a file>
Wrote 3 golden file changes:
testing/resources/performance_overlay_gold_60fps.png
testing/resources/performance_overlay_gold_90fps.png
testing/resources/performance_overlay_gold_120fps.png
```
It can also be run with `--dry-run` to just print what it _would_ do:
```shell
$ dart bin/main.dart --dry-run <path to log file, which can be http or a file>
Found 3 golden file changes:
testing/resources/performance_overlay_gold_60fps.png
testing/resources/performance_overlay_gold_90fps.png
testing/resources/performance_overlay_gold_120fps.png
Run again without --dry-run to apply these changes.
```
You're recommended to still use `git diff` to verify the changes look good.
## Upgrading `git diff`
By default, `git diff` is not very helpful for binary files. You can install
[`imagemagick`](https://imagemagick.org/) and configure your local git client
to make `git diff` show a PNG diff:
```shell
# On MacOS.
$ brew install imagemagick
# Create a comparison script.
$ cat > ~/bin/git-imgdiff <<EOF
#!/bin/sh
echo "Comparing $2 and $5"
# Find a temporary directory to store the diff.
if [ -z "$TMPDIR" ]; then
TMPDIR=/tmp
fi
compare \
"$2" "$5" \
/tmp/git-imgdiff-diff.png
# Display the diff.
open /tmp/git-imgdiff-diff.png
EOF
# Setup git.
git config --global core.attributesfile '~/.gitattributes'
# Add the following to ~/.gitattributes.
cat >> ~/.gitattributes <<EOF
*.png diff=imgdiff
*.jpg diff=imgdiff
*.gif diff=imgdiff
EOF
git config --global diff.imgdiff.command '~/bin/git-imgdiff'
```
## Motivation
Due to <https://github.com/flutter/flutter/issues/53784>, on non-Linux OSes
there is no way to get golden-file changes locally for a variety of engine
tests.
This tool, given log output from a Flutter CI run, will scrape the log for:
```txt
Golden file mismatch. Please check the difference between /b/s/w/ir/cache/builder/src/flutter/testing/resources/performance_overlay_gold_90fps.png and /b/s/w/ir/cache/builder/src/flutter/testing/resources/performance_overlay_gold_90fps_new.png, and replace the former with the latter if the difference looks good.
S
See also the base64 encoded /b/s/w/ir/cache/builder/src/flutter/testing/resources/performance_overlay_gold_90fps_new.png:
iVBORw0KGgoAAAANSUhEUgAAA+gAAAPoCAYAAABNo9TkAAAABHNCSVQICAgIfAhkiAAAIABJREFUeJzs3elzFWeeJ/rnHB3tSEILktgEBrPvYBbbUF4K24X3t (...omitted)
```
And convert the base64 encoded image into a PNG file, and overwrite the old
golden file with the new one.
| engine/tools/build_bucket_golden_scraper/README.md/0 | {
"file_path": "engine/tools/build_bucket_golden_scraper/README.md",
"repo_id": "engine",
"token_count": 909
} | 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.
import 'dart:convert' show LineSplitter, utf8;
import 'dart:io' as io;
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
import 'package:process_runner/process_runner.dart';
import 'options.dart';
/// The url prefix for issues that must be attached to the directive in files
/// that disables linting.
const String issueUrlPrefix = 'https://github.com/flutter/flutter/issues';
/// Lint actions to apply to a file.
enum LintAction {
/// Run the linter over the file.
lint,
/// Ignore files under third_party/.
skipThirdParty,
/// Ignore due to a well-formed FLUTTER_NOLINT comment.
skipNoLint,
/// Fail due to a malformed FLUTTER_NOLINT comment.
failMalformedNoLint,
/// Ignore because the file doesn't exist locally.
skipMissing,
}
/// A compilation command and methods to generate the lint command and job for
/// it.
class Command {
/// Generate a [Command] from a [Map].
Command.fromMap(Map<String, dynamic> map) :
directory = io.Directory(map['directory'] as String).absolute,
command = map['command'] as String {
filePath = path.normalize(path.join(
directory.path,
map['file'] as String,
));
}
/// The working directory of the command.
final io.Directory directory;
/// The compilation command.
final String command ;
/// The file on which the command operates.
late final String filePath;
static final RegExp _pathRegex = RegExp(r'\S*clang/bin/clang(\+\+)?');
static final RegExp _argRegex = RegExp(r'-MF\s+\S+\s+');
// Filter out any extra commands that were appended to the compile command.
static final RegExp _extraCommandRegex = RegExp(r'&&.*$');
String? _tidyArgs;
/// The command line arguments of the command.
String get tidyArgs {
return _tidyArgs ??= (() {
String result = command;
result = result.replaceAll(r'\s+', ' ');
// Remove everything that comes before the compiler command.
result = result.split(' ')
.skipWhile((String s) => !_pathRegex.hasMatch(s))
.join(' ');
result = result.replaceAll(_pathRegex, '');
result = result.replaceAll(_argRegex, '');
result = result.replaceAll(_extraCommandRegex, '');
return result;
})();
}
String? _tidyPath;
/// The command but with clang-tidy instead of clang.
String get tidyPath {
return _tidyPath ??= _pathRegex.stringMatch(command)?.replaceAll(
'clang/bin/clang',
'clang/bin/clang-tidy',
).replaceAll('clang-tidy++', 'clang-tidy') ?? '';
}
/// Whether this command operates on any of the files in `queries`.
bool containsAny(List<io.File> queries) {
return queries.indexWhere(
(io.File query) => path.equals(query.path, filePath),
) != -1;
}
static final RegExp _nolintRegex = RegExp(
r'//\s*FLUTTER_NOLINT(: https://github.com/flutter/flutter/issues/\d+)?',
);
/// The type of lint that is appropriate for this command.
late final Future<LintAction> lintAction = getLintAction(filePath);
/// Determine the lint action for the file at `path`.
@visibleForTesting
static Future<LintAction> getLintAction(String filePath) async {
if (path.split(filePath).contains('third_party')) {
return LintAction.skipThirdParty;
}
final io.File file = io.File(filePath);
if (!file.existsSync()) {
return LintAction.skipMissing;
}
final Stream<String> lines = file.openRead()
.transform(utf8.decoder)
.transform(const LineSplitter());
return lintActionFromContents(lines);
}
/// Determine the lint action for the file with contents `lines`.
@visibleForTesting
static Future<LintAction> lintActionFromContents(Stream<String> lines) async {
// Check for FlUTTER_NOLINT at top of file.
await for (final String line in lines) {
final RegExpMatch? match = _nolintRegex.firstMatch(line);
if (match != null) {
return match.group(1) != null
? LintAction.skipNoLint
: LintAction.failMalformedNoLint;
} else if (line.isNotEmpty && line[0] != '\n' && line[0] != '/') {
// Quick out once we find a line that isn't empty or a comment. The
// FLUTTER_NOLINT must show up before the first real code.
return LintAction.lint;
}
}
return LintAction.lint;
}
/// The job for the process runner for the lint needed for this command.
WorkerJob createLintJob(Options options) {
final List<String> args = <String>[
filePath,
'--warnings-as-errors=${options.warningsAsErrors ?? '*'}',
if (options.checks != null)
options.checks!,
if (options.fix) ...<String>[
'--fix',
'--format-style=file',
],
if (options.enableCheckProfile)
'--enable-check-profile',
'--',
];
args.addAll(tidyArgs.split(' '));
final String clangTidyPath = options.clangTidyPath?.path ?? tidyPath;
return WorkerJob(
<String>[clangTidyPath, ...args],
workingDirectory: directory,
name: 'clang-tidy on $filePath',
printOutput: options.verbose,
);
}
}
| engine/tools/clang_tidy/lib/src/command.dart/0 | {
"file_path": "engine/tools/clang_tidy/lib/src/command.dart",
"repo_id": "engine",
"token_count": 1939
} | 439 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:kernel/const_finder.dart';
void main(List<String> args) {
final ArgParser parser = ArgParser();
parser
..addSeparator('Finds constant instances of a specified class from the\n'
'specified package, and outputs JSON like the following:')
..addSeparator('''
{
"constantInstances": [
{
"codePoint": 59470,
"fontFamily": "MaterialIcons",
"fontPackage": null,
"matchTextDirection": false
}
],
"nonConstantInstances": [
{
"file": "file:///Path/to/hello_world/lib/file.dart",
"line": 19,
"column": 11
}
]
}''')
..addSeparator('Where the "constantInstances" is a list of objects containing\n'
'the properties passed to the const constructor of the class, and\n'
'"nonConstantInstances" is a list of source locations of non-constant\n'
'creation of the specified class. Non-constant creation cannot be\n'
'statically evaluated by this tool, and callers may wish to treat them\n'
'as errors. The non-constant creation may include entries that are not\n'
'reachable at runtime.')
..addSeparator('Required arguments:')
..addOption('kernel-file',
valueHelp: 'path/to/main.dill',
help: 'The path to a kernel file to parse, which was created from the '
'main-package-uri library.',
mandatory: true)
..addOption('class-library-uri',
mandatory: true,
help: 'The package: URI of the class to find.',
valueHelp: 'package:flutter/src/widgets/icon_data.dart')
..addOption('class-name',
help: 'The class name for the class to find.',
valueHelp: 'IconData',
mandatory: true)
..addSeparator('Optional arguments:')
..addFlag('pretty',
negatable: false,
help: 'Pretty print JSON output (defaults to false).')
..addFlag('help',
abbr: 'h',
negatable: false,
help: 'Print usage and exit')
..addOption('annotation-class-name',
help: 'The class name of the annotation for classes that should be '
'ignored.',
valueHelp: 'StaticIconProvider')
..addOption('annotation-class-library-uri',
help: 'The package: URI of the class of the annotation for classes '
'that should be ignored.',
valueHelp: 'package:flutter/src/material/icons.dart');
final ArgResults argResults = parser.parse(args);
T getArg<T>(String name) => argResults[name] as T;
final String? annotationClassName = getArg<String?>('annotation-class-name');
final String? annotationClassLibraryUri = getArg<String?>('annotation-class-library-uri');
final bool annotationClassNameProvided = annotationClassName != null;
final bool annotationClassLibraryUriProvided = annotationClassLibraryUri != null;
if (annotationClassNameProvided != annotationClassLibraryUriProvided) {
throw StateError(
'If either "--annotation-class-name" or "--annotation-class-library-uri" are provided they both must be',
);
}
if (getArg<bool>('help')) {
stdout.writeln(parser.usage);
exit(0);
}
final ConstFinder finder = ConstFinder(
kernelFilePath: getArg<String>('kernel-file'),
classLibraryUri: getArg<String>('class-library-uri'),
className: getArg<String>('class-name'),
annotationClassName: annotationClassName,
annotationClassLibraryUri: annotationClassLibraryUri,
);
final JsonEncoder encoder = getArg<bool>('pretty')
? const JsonEncoder.withIndent(' ')
: const JsonEncoder();
stdout.writeln(encoder.convert(finder.findInstances()));
}
| engine/tools/const_finder/bin/main.dart/0 | {
"file_path": "engine/tools/const_finder/bin/main.dart",
"repo_id": "engine",
"token_count": 1449
} | 440 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as p;
void main() {
// Find a path to `dir_contents_diff.dart` from the working directory.
final String pkgPath = io.File.fromUri(io.Platform.script).parent.parent.path;
final String binPath = p.join(
pkgPath,
'bin',
'dir_contents_diff.dart',
);
// As a sanity check, ensure that the file exists.
if (!io.File(binPath).existsSync()) {
io.stderr.writeln('Unable to find $binPath');
io.exitCode = 1;
return;
}
// Runs `../bin/dir_contents_diff.dart` with the given arguments.
(int, String) runSync(String goldenPath, String dirPath) {
final io.ProcessResult result = io.Process.runSync(
io.Platform.resolvedExecutable,
<String>[binPath, goldenPath, dirPath],
);
return (result.exitCode, result.stdout ?? result.stderr);
}
test('lists files and diffs successfully', () {
final String goldenPath = p.join(pkgPath, 'test', 'file_ok.txt');
final String dirPath = p.join(pkgPath, 'test', 'fixtures');
final (int exitCode, String output) = runSync(goldenPath, dirPath);
if (exitCode != 0) {
io.stderr.writeln('Expected exit code 0, got $exitCode');
io.stderr.writeln(output);
}
expect(exitCode, 0);
});
test('lists files and diffs successfully, even with an EOF newline', () {
final String goldenPath = p.join(pkgPath, 'test', 'file_ok_eof_newline.txt');
final String dirPath = p.join(pkgPath, 'test', 'fixtures');
final (int exitCode, String output) = runSync(goldenPath, dirPath);
if (exitCode != 0) {
io.stderr.writeln('Expected exit code 0, got $exitCode');
io.stderr.writeln(output);
}
expect(exitCode, 0);
});
test('diff fails when an expected file is missing', () {
final String goldenPath = p.join(pkgPath, 'test', 'file_bad_missing.txt');
final String dirPath = p.join(pkgPath, 'test', 'fixtures');
final (int exitCode, String output) = runSync(goldenPath, dirPath);
if (exitCode == 0) {
io.stderr.writeln('Expected non-zero exit code, got $exitCode');
io.stderr.writeln(output);
}
expect(exitCode, 1);
expect(output, contains('+a.txt'));
});
test('diff fails when an unexpected file is present', () {
final String goldenPath = p.join(pkgPath, 'test', 'file_bad_unexpected.txt');
final String dirPath = p.join(pkgPath, 'test', 'fixtures');
final (int exitCode, String output) = runSync(goldenPath, dirPath);
if (exitCode == 0) {
io.stderr.writeln('Expected non-zero exit code, got $exitCode');
io.stderr.writeln(output);
}
expect(exitCode, 1);
expect(output, contains('-c.txt'));
});
}
| engine/tools/dir_contents_diff/test/dir_contents_diff_test.dart/0 | {
"file_path": "engine/tools/dir_contents_diff/test/dir_contents_diff_test.dart",
"repo_id": "engine",
"token_count": 1081
} | 441 |
// 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 '../dependencies.dart';
import 'command.dart';
import 'flags.dart';
/// The root 'fetch' command.
final class FetchCommand extends CommandBase {
/// Constructs the 'fetch' command.
FetchCommand({
required super.environment,
});
@override
String get name => 'fetch';
@override
String get description => "Download the Flutter engine's dependencies";
@override
List<String> get aliases => const <String>['sync'];
@override
Future<int> run() {
final bool verbose = globalResults![verboseFlag] as bool;
return fetchDependencies(environment, verbose: verbose);
}
}
| engine/tools/engine_tool/lib/src/commands/fetch_command.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/commands/fetch_command.dart",
"repo_id": "engine",
"token_count": 233
} | 442 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as path;
import 'package:platform/platform.dart';
import 'package:process_runner/process_runner.dart';
void main() {
final Engine engine;
try {
engine = Engine.findWithin();
} catch (e) {
io.stderr.writeln(e);
io.exitCode = 1;
return;
}
test('The entry points under bin/ work', () async {
const Platform platform = LocalPlatform();
final ProcessRunner runner = ProcessRunner();
final String exe = platform.isWindows ? '.bat' : '';
final String entrypointPath = path.join(
engine.flutterDir.path, 'bin', 'et$exe',
);
final ProcessRunnerResult processResult = await runner.runProcess(
<String>[entrypointPath, 'help'],
failOk: true,
);
if (processResult.exitCode != 0) {
io.stdout.writeln(processResult.stdout);
io.stderr.writeln(processResult.stderr);
}
expect(processResult.exitCode, equals(0));
});
}
| engine/tools/engine_tool/test/entry_point_test.dart/0 | {
"file_path": "engine/tools/engine_tool/test/entry_point_test.dart",
"repo_id": "engine",
"token_count": 437
} | 443 |
# 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/fuchsia/dart/toolchain.gni")
import("//flutter/tools/fuchsia/sdk/sdk_targets.gni")
import("//flutter/tools/fuchsia/toolchain/basic_toolchain.gni")
if (current_toolchain == default_toolchain) {
# A toolchain dedicated to processing and analyzing Dart packages.
# The only targets in this toolchain are action() targets, so it
# has no real tools. But every toolchain needs stamp and copy.
basic_toolchain("dartlang") {
expected_label = dart_toolchain
}
}
if (current_toolchain != default_toolchain) {
sdk_targets("dart_library") {
meta = "$fuchsia_sdk/meta/manifest.json"
}
}
| engine/tools/fuchsia/dart/BUILD.gn/0 | {
"file_path": "engine/tools/fuchsia/dart/BUILD.gn",
"repo_id": "engine",
"token_count": 263
} | 444 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import("//flutter/common/fuchsia_config.gni")
import("//flutter/tools/fuchsia/dart.gni")
import("$dart_src/build/dart/dart_action.gni")
template("dart_kernel") {
prebuilt_dart_action(target_name) {
assert(defined(invoker.main_dart), "main_dart is a required parameter.")
assert(defined(invoker.kernel_platform_files),
"kernel_platform_files target must be defined.")
main_dart = rebase_path(invoker.main_dart)
deps = [ invoker.kernel_platform_files ]
gen_kernel_script = "$dart_src/pkg/vm/bin/gen_kernel.dart"
platform_dill = "$root_out_dir/dart_runner_patched_sdk/platform_strong.dill"
dot_packages = rebase_path("$dart_src/.dart_tool/package_config.json")
inputs = [
platform_dill,
gen_kernel_script,
main_dart,
dot_packages,
]
output = "$target_gen_dir/$target_name.dill"
outputs = [ output ]
depfile = "$output.d"
abs_depfile = rebase_path(depfile)
rebased_output = rebase_path(output, root_build_dir)
vm_args = [
"--depfile=$abs_depfile",
"--depfile_output_filename=$rebased_output",
]
script = gen_kernel_script
args = [
"--packages=" + rebase_path(dot_packages),
"--target=dart_runner",
"--platform=" + rebase_path(platform_dill),
"--output=" + rebase_path(output),
]
if (flutter_runtime_mode == "debug") {
args += [ "--embed-sources" ]
} else {
args += [ "--no-embed-sources" ]
}
if (defined(invoker.aot) && invoker.aot) {
args += [
"--aot",
"--tfa",
]
} else {
# --no-link-platform is only valid when --aot isn't specified
args += [ "--no-link-platform" ]
}
if (defined(invoker.product) && invoker.product) {
# Setting this flag in a non-product release build for AOT (a "profile"
# build) causes the vm service isolate code to be tree-shaken from an app.
# See the pragma on the entrypoint here:
#
# https://github.com/dart-lang/sdk/blob/main/sdk/lib/_internal/vm/bin/vmservice_io.dart#L240
#
# Also, this define excludes debugging and profiling code from Flutter.
args += [ "-Ddart.vm.product=true" ]
} else {
if (flutter_runtime_mode == "profile") {
# The following define excludes debugging code from Flutter.
args += [ "-Ddart.vm.profile=true" ]
}
}
args += [ rebase_path(main_dart) ]
}
}
| engine/tools/fuchsia/dart_kernel.gni/0 | {
"file_path": "engine/tools/fuchsia/dart_kernel.gni",
"repo_id": "engine",
"token_count": 1082
} | 445 |
# 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/fuchsia/fuchsia_debug_symbols.gni")
import("//flutter/tools/fuchsia/fuchsia_libs.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/cmc.gni")
import("//flutter/tools/fuchsia/gn-sdk/src/gn_configs.gni")
# Alias of cmc_compile in gn-sdk/src/cmc.gni
template("_compile_cml") {
assert(defined(invoker.manifest), "_compile_cml must define manifest")
# Create an empty depfile, it's not used in flutter.
write_file("${target_gen_dir}/${target_name}/${target_name}.d",
[],
"list lines")
cmc_compile(target_name) {
forward_variables_from(invoker,
[
"deps",
"manifest",
"testonly",
])
output_file = invoker.output
}
}
# TODO(zijiehe): May use fuchsia_package in gn-sdk if possible. - http://crbug.com/40935282
# Creates a Fuchsia archive (.far) file using PM from the Fuchsia SDK.
#
# binary (required):
# The ELF binary for the archive's program.
# cmx_file (optional):
# The path to the V1 component manifest (.cmx file) for the archive's component.
# Should include the file extension.
# cml_file (optional):
# The path to the V2 component manifest (.cml file) for the archive's component.
# Should include the file extension.
# deps (optional):
# The code dependencies for the archive.
# inputs (optional):
# When these files are changed, the package should be regenerated.
# libraries (optional):
# Paths to .so libraries that should be dynamically linked to the binary.
# resources (optional):
# Files that should be placed into the `data/` directory of the archive.
# testonly (optional):
# Set this to true for archives that are only used for tests.
template("_fuchsia_archive") {
assert(defined(invoker.binary), "package must define binary")
pkg_testonly = defined(invoker.testonly) && invoker.testonly
pkg_target_name = target_name
pkg = {
package_version = "0" # placeholder
forward_variables_from(invoker,
[
"binary",
"deps",
"resources",
"libraries",
])
if (!defined(package_name)) {
package_name = pkg_target_name
}
if (!defined(deps)) {
deps = []
}
if (!defined(resources)) {
resources = []
}
if (!defined(libraries)) {
libraries = []
}
}
far_base_dir = "$root_out_dir/${pkg_target_name}_far"
copy_sources = [ "$root_out_dir/${invoker.binary}" ]
copy_outputs = [ "$far_base_dir/bin/app" ]
foreach(res, pkg.resources) {
copy_sources += [ res.path ]
copy_outputs += [ "$far_base_dir/data/${res.dest}" ]
}
foreach(lib, pkg.libraries) {
output_path = ""
if (defined(lib.output_path)) {
output_path = lib.output_path
}
copy_sources += [ "${lib.path}/${lib.name}" ]
copy_outputs += [ "$far_base_dir/lib/${output_path}${lib.name}" ]
}
pkg_dir_deps = pkg.deps
if (defined(invoker.cmx_file)) {
# cmx files are used for v1 components, only copy it if it is defined
cmx_file = invoker.cmx_file
cmx_target = "$pkg_target_name.copy_cmx"
copy("$cmx_target") {
sources = [ "$cmx_file" ]
outputs = [ "$far_base_dir/meta/${pkg_target_name}.cmx" ]
}
pkg_dir_deps += [ ":$cmx_target" ]
}
write_file("${far_base_dir}/meta/package",
{
name = pkg.package_name
version = pkg.package_version
},
"json")
_dbg_symbols_target = "${target_name}_dbg_symbols"
fuchsia_debug_symbols(_dbg_symbols_target) {
deps = pkg.deps
testonly = pkg_testonly
binary = invoker.binary
}
action("${target_name}_dir") {
script = "//flutter/tools/fuchsia/copy_path.py"
sources = copy_sources
response_file_contents = rebase_path(copy_sources + copy_outputs)
deps = pkg_dir_deps
args = [ "--file-list={{response_file_name}}" ]
outputs = copy_outputs
testonly = pkg_testonly
}
manifest_json_file = "${root_out_dir}/${target_name}_package_manifest.json"
action(target_name) {
script = "//flutter/tools/fuchsia/gen_package.py"
deps = pkg_dir_deps + [
":${target_name}_dir",
":${_dbg_symbols_target}",
]
sources = copy_outputs
inputs = []
if (defined(invoker.inputs)) {
inputs += invoker.inputs
}
args = [
"--pm-bin",
rebase_path("$fuchsia_tool_dir/pm"),
"--package-dir",
rebase_path(far_base_dir),
"--far-name",
target_name,
"--manifest-json-file",
rebase_path(manifest_json_file, root_build_dir),
]
assert(fuchsia_target_api_level != -1,
"Must set a target api level when creating an archive")
if (fuchsia_target_api_level != -1) {
args += [
"--api-level",
"${fuchsia_target_api_level}",
]
}
outputs = [
manifest_json_file,
"${far_base_dir}.manifest",
"$root_out_dir/${target_name}-0.far",
]
testonly = pkg_testonly
}
}
# Creates a Fuchsia archive.
#
# An archive combines an ELF binary and a component manifest to create
# a packaged Fuchsia program that can be deployed to a Fuchsia device.
#
# binary (required):
# The ELF binary for the archive's program.
# cmx_file (required if cml_file is not set):
# The V1 component manifest for the Fuchsia component.
# cml_file (required if cmx_file is not set):
# The V2 component manifest for the Fuchsia component.
# deps (optional):
# The code dependencies for the archive.
# inputs (optional):
# When these files are changed, the package should be regenerated.
# libraries (optional):
# Paths to .so libraries that should be dynamically linked to the binary.
# resources (optional):
# Files that should be placed into the `data/` directory of the archive.
# testonly (optional):
# Set this to true for archives that are only used for tests.
template("fuchsia_archive") {
assert(defined(invoker.cmx_file) || defined(invoker.cml_file),
"must specify either a cmx file, cml file or both")
_deps = []
if (defined(invoker.deps)) {
_deps += invoker.deps
}
if (defined(invoker.cml_file)) {
_far_base_dir = "$root_out_dir/${target_name}_far"
_cml_file_name = get_path_info(invoker.cml_file, "name")
_compile_cml_target = "${target_name}_${_cml_file_name}_compile_cml"
_compile_cml(_compile_cml_target) {
forward_variables_from(invoker, [ "testonly" ])
manifest = invoker.cml_file
output = "$_far_base_dir/meta/${_cml_file_name}.cm"
}
_deps += [ ":$_compile_cml_target" ]
}
_fuchsia_archive(target_name) {
deps = _deps
forward_variables_from(invoker,
[
"binary",
"cmx_file",
"inputs",
"libraries",
"resources",
"testonly",
])
}
}
# Creates a Fuchsia archive (.far) file containing a generated test root
# component and test driver component, using PM from the Fuchsia SDK.
#
# binary (required):
# The binary for the test.
# deps (required):
# Dependencies for the test archive.
# cmx_file (optional):
# A path to the .cmx file for the test archive.
# If not defined, a generated .cml file for the test archive will be used instead.
# cml_file (optional):
# The path to the V2 component manifest (.cml file) for the test archive's component.
# Should include the file extension.
# If not defined, a generated .cml file for the test archive will be used instead.
# libraries (optional):
# Paths to .so libraries that should be dynamically linked to the binary.
# resources (optional):
# Files that should be placed into the `data/` directory of the archive.
template("fuchsia_test_archive") {
assert(defined(invoker.deps), "package must define deps")
_deps = []
if (defined(invoker.deps)) {
_deps += invoker.deps
}
if (defined(invoker.cml_file)) {
_far_base_dir = "$root_out_dir/${target_name}_far"
_cml_file_name = get_path_info(invoker.cml_file, "name")
_compile_cml_target = "${target_name}_${_cml_file_name}_compile_cml"
_compile_cml(_compile_cml_target) {
forward_variables_from(invoker, [ "testonly" ])
manifest = invoker.cml_file
output = "$_far_base_dir/meta/${_cml_file_name}.cm"
}
_deps += [ ":$_compile_cml_target" ]
} else {
# Interpolate test_suite.cml template with the test suite's name.
test_suite = target_name
interpolate_cml_target = "${test_suite}_interpolate_cml"
generated_cml_file = "$root_out_dir/$test_suite.cml"
action(interpolate_cml_target) {
testonly = true
script = "//flutter/tools/fuchsia/interpolate_test_suite.py"
sources = [ "//flutter/testing/fuchsia/meta/test_suite.cml" ]
args = [
"--input",
rebase_path("//flutter/testing/fuchsia/meta/test_suite.cml"),
"--test-suite",
test_suite,
"--output",
rebase_path(generated_cml_file),
]
outputs = [ generated_cml_file ]
}
far_base_dir = "$root_out_dir/${target_name}_far"
# Compile the resulting interpolated test suite's cml.
compile_test_suite_cml_target = "${test_suite}_test_suite_compile_cml"
_compile_cml(compile_test_suite_cml_target) {
testonly = true
deps = [ ":$interpolate_cml_target" ]
manifest = generated_cml_file
output = "$far_base_dir/meta/${test_suite}.cm"
}
_deps += [ ":$compile_test_suite_cml_target" ]
}
_fuchsia_archive(target_name) {
testonly = true
forward_variables_from(invoker,
[
"binary",
"resources",
])
libraries = common_libs
if (defined(invoker.libraries)) {
libraries += invoker.libraries
}
deps = _deps
}
}
| engine/tools/fuchsia/fuchsia_archive.gni/0 | {
"file_path": "engine/tools/fuchsia/fuchsia_archive.gni",
"repo_id": "engine",
"token_count": 4553
} | 446 |
#!/usr/bin/env python3
# Copyright (c) 2013, the Flutter project 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 os
import platform
import subprocess
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), 'test_scripts/test/')))
from common import catch_sigterm, wait_for_sigterm
def Main():
"""
Executes the test-scripts with required environment variables. It acts like
/usr/bin/env, but provides some extra functionality to dynamically set up
the environment variables.
"""
# Ensures the signals can be correctly forwarded to the subprocesses.
catch_sigterm()
os.environ['SRC_ROOT'] = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../'))
# Flutter uses a different repo structure and fuchsia sdk is not in the
# third_party/, so images root and sdk root need to be explicitly set.
os.environ['FUCHSIA_IMAGES_ROOT'] = os.path.join(os.environ['SRC_ROOT'], 'fuchsia/images/')
assert platform.system() == 'Linux', 'Unsupported OS ' + platform.system()
os.environ['FUCHSIA_SDK_ROOT'] = os.path.join(os.environ['SRC_ROOT'], 'fuchsia/sdk/linux/')
os.environ['FUCHSIA_GN_SDK_ROOT'] = os.path.join(
os.environ['SRC_ROOT'], 'flutter/tools/fuchsia/gn-sdk/src'
)
if os.getenv('DOWNLOAD_FUCHSIA_SDK') == 'True':
sdk_path = os.environ['FUCHSIA_SDK_PATH']
assert sdk_path.endswith('/linux-amd64/core.tar.gz')
assert not sdk_path.startswith('/')
os.environ['FUCHSIA_SDK_OVERRIDE'
] = 'gs://fuchsia-artifacts/' + sdk_path[:-len('/linux-amd64/core.tar.gz')]
with subprocess.Popen(sys.argv[1:]) as proc:
try:
proc.wait()
except:
# Use terminate / SIGTERM to allow the subprocess exiting cleanly.
proc.terminate()
return proc.returncode
if __name__ == '__main__':
sys.exit(Main())
| engine/tools/fuchsia/with_envs.py/0 | {
"file_path": "engine/tools/fuchsia/with_envs.py",
"repo_id": "engine",
"token_count": 743
} | 447 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io' as io;
import 'package:githooks/githooks.dart';
Future<void> main(List<String> args) async {
io.exitCode = await run(args);
}
| engine/tools/githooks/bin/main.dart/0 | {
"file_path": "engine/tools/githooks/bin/main.dart",
"repo_id": "engine",
"token_count": 100
} | 448 |
@call vpython3 "%~dp0gn" %*
| engine/tools/gn.bat/0 | {
"file_path": "engine/tools/gn.bat",
"repo_id": "engine",
"token_count": 14
} | 449 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.